@juspay/neurolink 13.12.6 → 13.13.1

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.
@@ -17,7 +17,7 @@
17
17
  * Currently supports:
18
18
  * - Anthropic (API key + OAuth)
19
19
  */
20
- import type { AccountQuota, AuthCommandArgs } from "../../types/index.js";
20
+ import type { AccountQuota, AuthCommandArgs, CodexImportedCredential, CodexImportTokenStore } from "../../types/index.js";
21
21
  /**
22
22
  * Handle the login subcommand
23
23
  * `neurolink auth login <provider>`
@@ -26,6 +26,19 @@ import type { AccountQuota, AuthCommandArgs } from "../../types/index.js";
26
26
  * (e.g., "anthropic:alice") to support multi-account pools.
27
27
  */
28
28
  export declare function handleLogin(argv: AuthCommandArgs): Promise<void>;
29
+ /**
30
+ * Core validation and persistence logic for importing a Codex credential into
31
+ * the account pool. Extracted from handleCodexLogin so import rules, keying,
32
+ * collision avoidance, and --force semantics are directly testable without
33
+ * process.exit.
34
+ */
35
+ export declare function importCodexCredentialToStore(credential: CodexImportedCredential, options?: {
36
+ label?: string;
37
+ force?: boolean;
38
+ }, store?: CodexImportTokenStore): Promise<{
39
+ compoundKey: string;
40
+ label: string;
41
+ }>;
29
42
  /**
30
43
  * Handle Codex (ChatGPT) login by importing the current credential from
31
44
  * `~/.codex/auth.json` into the account pool under a `codex:<label>` key.
@@ -128,6 +128,104 @@ export async function handleLogin(argv) {
128
128
  process.exit(1);
129
129
  }
130
130
  }
131
+ /**
132
+ * Core validation and persistence logic for importing a Codex credential into
133
+ * the account pool. Extracted from handleCodexLogin so import rules, keying,
134
+ * collision avoidance, and --force semantics are directly testable without
135
+ * process.exit.
136
+ */
137
+ export async function importCodexCredentialToStore(credential, options = {}, store = defaultTokenStore) {
138
+ const scopePart = (key, providers, name) => providers[key]?.tokens?.scope
139
+ ?.split(" ")
140
+ .find((part) => part.startsWith(`${name}:`))
141
+ ?.slice(name.length + 1);
142
+ // A key holds "the same account" only on positive identity evidence. When
143
+ // the stored key carries an account id, ids must match. When it does not (a
144
+ // key imported before an account id was available), only a credential that
145
+ // also lacks one can match it, by email. A credential that does carry an
146
+ // account id is NOT matched to an email-only key: the same email can belong
147
+ // to several workspaces, so that overwrite needs --force. Keys the earlier
148
+ // release wrote always include `account:` when the id was known, so the
149
+ // bare-email migration (default login reuses the existing key) is unaffected.
150
+ const sameAccount = (key, providers) => {
151
+ const storedAccount = scopePart(key, providers, "account");
152
+ if (storedAccount) {
153
+ return storedAccount === credential.accountId;
154
+ }
155
+ if (credential.accountId) {
156
+ return false;
157
+ }
158
+ const storedEmail = scopePart(key, providers, "email");
159
+ return Boolean(storedEmail) && storedEmail === credential.email;
160
+ };
161
+ const resolveLabel = (providers) => {
162
+ if (options.label) {
163
+ return options.label;
164
+ }
165
+ if (credential.email && credential.accountId) {
166
+ const combined = `${credential.email}:${credential.accountId}`;
167
+ // Keys written before the account id joined the label are bare emails;
168
+ // keep updating those in place when they belong to this account.
169
+ return !providers[`codex:${combined}`] &&
170
+ providers[`codex:${credential.email}`] &&
171
+ sameAccount(`codex:${credential.email}`, providers)
172
+ ? credential.email
173
+ : combined;
174
+ }
175
+ return (credential.email ??
176
+ credential.accountId ??
177
+ Date.now().toString(36).slice(-6));
178
+ };
179
+ const refuse = (providers, key) => {
180
+ if (options.force) {
181
+ return;
182
+ }
183
+ // Re-importing the same account refreshes its credential; only a key that
184
+ // holds a different account needs --force.
185
+ if (providers[key] && !sameAccount(key, providers)) {
186
+ throw new Error(`Account "${key}" already holds a different Codex account. Pass --force to overwrite.`);
187
+ }
188
+ if (credential.refreshToken) {
189
+ for (const [existingKey, entry] of Object.entries(providers)) {
190
+ if (existingKey.startsWith("codex:") &&
191
+ existingKey !== key &&
192
+ entry.tokens?.refreshToken === credential.refreshToken) {
193
+ throw new Error(`A Codex account with the same refresh token already exists ("${existingKey}"). ` +
194
+ `Sharing a refresh token across multiple accounts causes token rotation invalidations. ` +
195
+ `Pass --force to proceed anyway.`);
196
+ }
197
+ }
198
+ }
199
+ };
200
+ const label = validateAccountLabel(resolveLabel(await store.getProviderSnapshot()));
201
+ const compoundKey = `codex:${label}`;
202
+ const scopeParts = ["codex"];
203
+ if (credential.planType) {
204
+ scopeParts.push(`plan:${credential.planType}`);
205
+ }
206
+ if (credential.email) {
207
+ scopeParts.push(`email:${credential.email}`);
208
+ }
209
+ if (credential.accountId) {
210
+ scopeParts.push(`account:${credential.accountId}`);
211
+ }
212
+ // The checks run again under the store's cross-process lock, so two
213
+ // concurrent imports cannot both pass them and then overwrite each other.
214
+ const saved = await store.saveTokensIf(compoundKey, {
215
+ accessToken: credential.accessToken,
216
+ refreshToken: credential.refreshToken,
217
+ expiresAt: credential.expiresAt ?? Date.now() + 3_600_000,
218
+ tokenType: "Bearer",
219
+ scope: scopeParts.join(" "),
220
+ }, (providers) => {
221
+ refuse(providers, compoundKey);
222
+ return validateAccountLabel(resolveLabel(providers)) === label;
223
+ }, { enable: true });
224
+ if (!saved) {
225
+ throw new Error("Codex accounts changed while importing. Re-run the command.");
226
+ }
227
+ return { compoundKey, label };
228
+ }
131
229
  /**
132
230
  * Handle Codex (ChatGPT) login by importing the current credential from
133
231
  * `~/.codex/auth.json` into the account pool under a `codex:<label>` key.
@@ -141,30 +239,7 @@ export async function handleCodexLogin(argv) {
141
239
  const spinner = ora("Importing Codex (ChatGPT) credential…").start();
142
240
  try {
143
241
  const credential = await importCodexAuthFile();
144
- const rawLabel = argv.label ??
145
- credential.email ??
146
- credential.accountId?.slice(0, 8) ??
147
- Date.now().toString(36).slice(-6);
148
- const label = validateAccountLabel(rawLabel);
149
- const compoundKey = `codex:${label}`;
150
- const scopeParts = ["codex"];
151
- if (credential.planType) {
152
- scopeParts.push(`plan:${credential.planType}`);
153
- }
154
- if (credential.email) {
155
- scopeParts.push(`email:${credential.email}`);
156
- }
157
- if (credential.accountId) {
158
- scopeParts.push(`account:${credential.accountId}`);
159
- }
160
- await defaultTokenStore.saveTokens(compoundKey, {
161
- accessToken: credential.accessToken,
162
- refreshToken: credential.refreshToken,
163
- expiresAt: credential.expiresAt ?? Date.now() + 3_600_000,
164
- tokenType: "Bearer",
165
- scope: scopeParts.join(" "),
166
- });
167
- await defaultTokenStore.markEnabled(compoundKey);
242
+ const { compoundKey } = await importCodexCredentialToStore(credential, { label: argv.label, force: argv.force }, defaultTokenStore);
168
243
  spinner.succeed(`Codex account added to pool: ${chalk.cyan(compoundKey)}`);
169
244
  if (credential.planType) {
170
245
  logger.always(chalk.gray(` plan: ${credential.planType}`));
@@ -572,7 +647,8 @@ export async function handleList(argv) {
572
647
  // every login — reading email from it would show the LATEST login's
573
648
  // email for ALL accounts. The label is the per-account source of truth.
574
649
  if (label && label.includes("@")) {
575
- email = label;
650
+ // Codex labels may be `email:accountId`: drop a trailing id segment.
651
+ email = provider === "codex" ? label.replace(/:[^:@]*$/, "") : label;
576
652
  }
577
653
  // Fall back to credentials file ONLY for the default (unlabeled) account.
578
654
  // Compound-key entries (labeled accounts) must NOT read the shared
@@ -187,6 +187,11 @@ export class AuthCommandFactory {
187
187
  .option("label", {
188
188
  type: "string",
189
189
  description: "Human-readable label for this account (used with --add)",
190
+ })
191
+ .option("force", {
192
+ type: "boolean",
193
+ default: false,
194
+ description: "Codex import: overwrite a label that holds a different account, or reuse a refresh token already registered under another label",
190
195
  })
191
196
  .example("$0 auth login anthropic", "Interactive authentication (choose method)")
192
197
  .example("$0 auth login anthropic --method api-key", "API key authentication")
@@ -153,6 +153,17 @@ export declare const SYSTEM_LIMITS: {
153
153
  DEFAULT_BACKOFF_MULTIPLIER: number;
154
154
  };
155
155
  export declare const DEFAULT_TOOL_ROUTING_TIMEOUT_MS = 15000;
156
+ export declare const JEV_ROUTING_AUDIT_LIMITS: {
157
+ readonly queryCharacters: 6000;
158
+ readonly candidateServers: 64;
159
+ readonly serverIdCharacters: 256;
160
+ readonly capabilityCharacters: 1000;
161
+ readonly serializedInputCharacters: 24000;
162
+ };
163
+ export declare const JEV_ROUTING_AUDIT_OBSERVATION_NAME = "jev-routing-audit";
164
+ export declare const JEV_ROUTING_AUDIT_PROVIDER = "typesafe";
165
+ export declare const JEV_ROUTING_AUDIT_SCHEMA_VERSION = "1";
166
+ export declare const JEV_ROUTING_AUDIT_COMPONENT = "[JevRoutingAudit]";
156
167
  export declare const ENV_DEFAULTS: {
157
168
  maxTokens: number | undefined;
158
169
  temperature: number;
@@ -334,6 +334,17 @@ export const SYSTEM_LIMITS = {
334
334
  };
335
335
  // Pre-call tool routing: hard ceiling for the router LLM call before failing open
336
336
  export const DEFAULT_TOOL_ROUTING_TIMEOUT_MS = 15000;
337
+ export const JEV_ROUTING_AUDIT_LIMITS = {
338
+ queryCharacters: 6000,
339
+ candidateServers: 64,
340
+ serverIdCharacters: 256,
341
+ capabilityCharacters: 1000,
342
+ serializedInputCharacters: 24000,
343
+ };
344
+ export const JEV_ROUTING_AUDIT_OBSERVATION_NAME = "jev-routing-audit";
345
+ export const JEV_ROUTING_AUDIT_PROVIDER = "typesafe";
346
+ export const JEV_ROUTING_AUDIT_SCHEMA_VERSION = "1";
347
+ export const JEV_ROUTING_AUDIT_COMPONENT = "[JevRoutingAudit]";
337
348
  // Environment Variable Support (for future use)
338
349
  export const ENV_DEFAULTS = {
339
350
  maxTokens: (() => {
@@ -1304,6 +1304,9 @@ export declare class NeuroLink {
1304
1304
  * resolver fails open to an empty exclusion list). Accepts both StreamOptions
1305
1305
  * and GenerateOptions since both share the required fields.
1306
1306
  */
1307
+ /** Excluded tools including those a non-empty `toolFilter` leaves out. */
1308
+ private effectiveExcludedTools;
1309
+ private flushJevRoutingAudit;
1307
1310
  private applyToolRoutingExclusions;
1308
1311
  /**
1309
1312
  * Record a tool routing decision on the active span. Telemetry only.
package/dist/neurolink.js CHANGED
@@ -33,7 +33,7 @@ import { emergencyContentTruncation } from "./context/emergencyTruncation.js";
33
33
  import { getContextOverflowProvider, isContextOverflowError, parseProviderOverflowDetails, } from "./context/errorDetection.js";
34
34
  import { ContextBudgetExceededError } from "./context/errors.js";
35
35
  import { repairToolPairs } from "./context/toolPairRepair.js";
36
- import { SYSTEM_LIMITS, DEFAULT_TOOL_ROUTING_TIMEOUT_MS, MIN_RECOVERY_TURN_BUDGET_MS, } from "./core/constants.js";
36
+ import { SYSTEM_LIMITS, DEFAULT_TOOL_ROUTING_TIMEOUT_MS, JEV_ROUTING_AUDIT_PROVIDER, MIN_RECOVERY_TURN_BUDGET_MS, } from "./core/constants.js";
37
37
  import { ConversationMemoryManager } from "./core/conversationMemoryManager.js";
38
38
  import { buildToolRoutingCatalog, buildRoutingQueryFromHistory, resolveToolRoutingExclusions, } from "./core/toolRouting.js";
39
39
  import { ToolRoutingCache } from "./core/toolRoutingCache.js";
@@ -102,6 +102,9 @@ import { assistantMessages } from "./telemetry/chatMessages.js";
102
102
  import { observationLevel, observe, observeTrace, usageDetails, } from "./telemetry/observation.js";
103
103
  import { toolSpanName } from "./telemetry/observationNames.js";
104
104
  import { isNestedOperation, tracers } from "./telemetry/tracers.js";
105
+ import { buildJevRoutingAuditInput, logJevRoutingAuditFailure, } from "./utils/jevRoutingAudit.js";
106
+ import { recordJevRoutingAudit } from "./telemetry/jevRoutingAudit.js";
107
+ const pendingJevRoutingAudits = new WeakMap();
105
108
  import { getConversationMessages, storeConversationTurn, } from "./utils/conversationMemory.js";
106
109
  // Enhanced error handling imports
107
110
  import { CircuitBreaker, ERROR_CODES, ErrorFactory, isAbortError, isCancelledByCaller, isRetriableError, logStructuredError, NeuroLinkError, throwIfSignalAborted, withRetry, withTimeout, } from "./utils/errorHandling.js";
@@ -4386,6 +4389,7 @@ Current user's request: ${currentInput}`;
4386
4389
  await this.applyClassifierRouting(options, options.input?.text ?? originalPrompt ?? "", !options.disableTools &&
4387
4390
  (!!(options.tools && Object.keys(options.tools).length > 0) ||
4388
4391
  this.getCustomTools().size > 0), !!(options.input?.images && options.input.images.length > 0), options.thinkingConfig?.thinkingLevel);
4392
+ this.flushJevRoutingAudit(options);
4389
4393
  await this.maybeApplyGenerateOrchestration(options);
4390
4394
  // Pre-call request router: opt-in, only when the caller did not set both
4391
4395
  // provider+model. Fails open (any router error leaves options unchanged).
@@ -7881,6 +7885,7 @@ Current user's request: ${currentInput}`;
7881
7885
  (!!(options.tools && Object.keys(options.tools).length > 0) ||
7882
7886
  this.getCustomTools().size > 0), !!(options.input?.images && options.input.images.length > 0), options
7883
7887
  .thinking?.thinkingLevel);
7888
+ this.flushJevRoutingAudit(options);
7884
7889
  // Pre-call request router for stream: opt-in, fails open.
7885
7890
  await this.applyRequestRouter(options, originalPrompt, !options.disableTools &&
7886
7891
  (!!(options.tools && Object.keys(options.tools).length > 0) ||
@@ -7974,6 +7979,29 @@ Current user's request: ${currentInput}`;
7974
7979
  * resolver fails open to an empty exclusion list). Accepts both StreamOptions
7975
7980
  * and GenerateOptions since both share the required fields.
7976
7981
  */
7982
+ /** Excluded tools including those a non-empty `toolFilter` leaves out. */
7983
+ effectiveExcludedTools(options, catalog) {
7984
+ const excluded = new Set(options.excludeTools ?? []);
7985
+ const allow = options.toolFilter;
7986
+ if (allow && allow.length > 0) {
7987
+ const allowed = new Set(allow);
7988
+ for (const server of catalog) {
7989
+ for (const name of server.toolNames) {
7990
+ if (!allowed.has(name)) {
7991
+ excluded.add(name);
7992
+ }
7993
+ }
7994
+ }
7995
+ }
7996
+ return [...excluded];
7997
+ }
7998
+ flushJevRoutingAudit(options) {
7999
+ const pending = pendingJevRoutingAudits.get(options);
8000
+ if (pending) {
8001
+ pendingJevRoutingAudits.delete(options);
8002
+ pending();
8003
+ }
8004
+ }
7977
8005
  async applyToolRoutingExclusions(options, userQuery) {
7978
8006
  const routingConfig = this.toolRoutingConfig;
7979
8007
  if (!routingConfig?.enabled || options.disableTools) {
@@ -8086,6 +8114,12 @@ Current user's request: ${currentInput}`;
8086
8114
  }
8087
8115
  let routedExcludeTools;
8088
8116
  let resolvedDecision;
8117
+ let auditEvidence = null;
8118
+ const auditEnabled = routingConfig.audit?.enabled === true;
8119
+ let auditPolicyExclusions = [];
8120
+ if (auditEnabled) {
8121
+ auditPolicyExclusions = this.effectiveExcludedTools(options, catalog);
8122
+ }
8089
8123
  // Intercept the decision so we can store it in the cache.
8090
8124
  const captureDecision = (decision) => {
8091
8125
  resolvedDecision = decision;
@@ -8129,7 +8163,28 @@ Current user's request: ${currentInput}`;
8129
8163
  // Bypass the instance's decision fast-path in that explicit mode.
8130
8164
  decideFn: routingConfig.generateFn
8131
8165
  ? undefined
8132
- : (decisionOptions) => this.siteDecide(decisionOptions, this.decisionSiteContext(options, sessionId || undefined)),
8166
+ : async (decisionOptions) => {
8167
+ let auditInput = null;
8168
+ if (auditEnabled) {
8169
+ auditInput = buildJevRoutingAuditInput(decisionOptions.state);
8170
+ }
8171
+ const result = await this.siteDecide(decisionOptions, this.decisionSiteContext(options, sessionId || undefined));
8172
+ if (auditInput !== null && result !== null) {
8173
+ try {
8174
+ if (result.provider === JEV_ROUTING_AUDIT_PROVIDER) {
8175
+ auditEvidence = {
8176
+ input: auditInput,
8177
+ provider: result.provider,
8178
+ model: result.model,
8179
+ };
8180
+ }
8181
+ }
8182
+ catch (error) {
8183
+ logJevRoutingAuditFailure(error);
8184
+ }
8185
+ }
8186
+ return result;
8187
+ },
8133
8188
  decisionMinDropConfidence: routingConfig.minDropConfidence,
8134
8189
  emitDecision: captureDecision,
8135
8190
  // L2 / ITEM D — only populated when embedding is configured.
@@ -8180,6 +8235,27 @@ Current user's request: ${currentInput}`;
8180
8235
  ...routedExcludeTools,
8181
8236
  ];
8182
8237
  }
8238
+ if (auditEnabled) {
8239
+ // Deferred until the classifier router has narrowed the tools, so the
8240
+ // audit reports the exclusions the request actually runs with.
8241
+ const auditContext = context.active();
8242
+ const evidence = auditEvidence;
8243
+ const decision = resolvedDecision;
8244
+ const policyExclusions = auditPolicyExclusions;
8245
+ pendingJevRoutingAudits.set(options, () => {
8246
+ context.with(auditContext, () => {
8247
+ const finalExcluded = this.effectiveExcludedTools(options, catalog);
8248
+ const policy = new Set(policyExclusions);
8249
+ const routed = new Set(routedExcludeTools);
8250
+ // Exclusions added after JEV ran (classifier) are not JEV's call.
8251
+ const lateExclusions = finalExcluded.filter((name) => !policy.has(name) && !routed.has(name));
8252
+ recordJevRoutingAudit(evidence, decision, catalog, finalExcluded, [
8253
+ ...policyExclusions,
8254
+ ...lateExclusions,
8255
+ ]);
8256
+ });
8257
+ });
8258
+ }
8183
8259
  }
8184
8260
  catch (error) {
8185
8261
  if (isAbortError(error)) {
@@ -1,10 +1,13 @@
1
1
  /**
2
2
  * Enhanced proxy-aware fetch implementation for AI SDK providers
3
- * Supports HTTP/HTTPS, SOCKS4/5, authentication, and NO_PROXY bypass
3
+ * Supports HTTP/HTTPS proxies, authentication, and NO_PROXY bypass.
4
+ * SOCKS proxy URLs are recognized but not supported: a request that selects
5
+ * one falls back to a direct connection, or fails under strict mode
6
+ * (NEUROLINK_PROXY_STRICT, or `createProxyFetch({ strict: true })`).
4
7
  * Lightweight implementation extracted from research of major proxy packages
5
8
  */
6
9
  import type { Dispatcher, ProxyAgent } from "undici";
7
- import type { GoogleGenAIHttpOptions, ProxyTimeouts } from "../types/index.js";
10
+ import type { GoogleGenAIHttpOptions, ProxyTimeouts, ProxyFetchOptions } from "../types/index.js";
8
11
  /**
9
12
  * Classify a fetch failure as a transient network error worth retrying.
10
13
  *
@@ -39,11 +42,32 @@ export declare function getProxyDispatcherForUrl(targetUrl: string, timeouts?: P
39
42
  * The optional dispatcher preserves callers' direct-connection tuning.
40
43
  */
41
44
  export declare function fetchProxyAware(url: string | URL, init?: RequestInit, directDispatcher?: Dispatcher, proxyTimeouts?: ProxyTimeouts): Promise<Response>;
45
+ /**
46
+ * Whether NEUROLINK_PROXY_STRICT asks for "proxy or nothing": `true`, `1`,
47
+ * `yes` or `on` (any case). Any other value, or none, keeps the default of
48
+ * retrying a failed proxy attempt over a direct connection.
49
+ */
50
+ export declare function isProxyStrictMode(): boolean;
51
+ /**
52
+ * The WebSocket clients (`ws`) are built without a proxy agent, so they always
53
+ * connect directly. Call this before opening one: when a proxy is configured
54
+ * for `wsUrl` (and NO_PROXY does not exempt it), strict mode refuses the
55
+ * connection, and otherwise a warning says the socket bypasses the proxy.
56
+ * `label` names the client in the message; the URL itself is never logged,
57
+ * since some carry an API key in the query string.
58
+ */
59
+ export declare function assertWebSocketProxyPolicy(wsUrl: string, label: string): void;
42
60
  /**
43
61
  * Create a proxy-aware fetch function with enhanced capabilities
44
- * Supports HTTP/HTTPS, SOCKS4/5, authentication, and NO_PROXY bypass
62
+ * Supports HTTP/HTTPS proxies, authentication, and NO_PROXY bypass.
63
+ *
64
+ * By default a request whose proxy attempt fails is retried once over a
65
+ * direct connection, with a warning. Strict mode (`options.strict`, or
66
+ * NEUROLINK_PROXY_STRICT when the option is omitted) fails it instead. Strict
67
+ * mode never blocks a request NO_PROXY exempts, or one sent while no proxy is
68
+ * configured: those go direct by design.
45
69
  */
46
- export declare function createProxyFetch(): typeof fetch;
70
+ export declare function createProxyFetch(options?: ProxyFetchOptions): typeof fetch;
47
71
  /**
48
72
  * Mask credentials in a proxy URL for safe logging/reporting.
49
73
  *
@@ -63,6 +87,7 @@ export declare function getProxyStatus(): {
63
87
  allProxy: string | null;
64
88
  socksProxy: string | null;
65
89
  noProxy: string | null;
90
+ strict: boolean;
66
91
  method: string;
67
92
  capabilities: string[];
68
93
  };
@@ -1,6 +1,9 @@
1
1
  /**
2
2
  * Enhanced proxy-aware fetch implementation for AI SDK providers
3
- * Supports HTTP/HTTPS, SOCKS4/5, authentication, and NO_PROXY bypass
3
+ * Supports HTTP/HTTPS proxies, authentication, and NO_PROXY bypass.
4
+ * SOCKS proxy URLs are recognized but not supported: a request that selects
5
+ * one falls back to a direct connection, or fails under strict mode
6
+ * (NEUROLINK_PROXY_STRICT, or `createProxyFetch({ strict: true })`).
4
7
  * Lightweight implementation extracted from research of major proxy packages
5
8
  */
6
9
  import { logger } from "../utils/logger.js";
@@ -285,9 +288,11 @@ function getDefaultPort(protocol) {
285
288
  return 8080;
286
289
  case "https:":
287
290
  return 8080;
291
+ case "socks:":
288
292
  case "socks4:":
289
- return 1080;
293
+ case "socks4a:":
290
294
  case "socks5:":
295
+ case "socks5h:":
291
296
  return 1080;
292
297
  default:
293
298
  return 8080;
@@ -347,10 +352,14 @@ async function createProxyAgent(proxyUrl, timeouts = {}) {
347
352
  return new ProxyAgent({ uri: proxyUrl, ...timeouts });
348
353
  }
349
354
  case "socks4:":
350
- case "socks5:": {
351
- // SOCKS proxy support is not included in the build to avoid optional dependencies
352
- throw new Error(`SOCKS proxy support requires 'proxy-agent' package. ` +
353
- `Install it with: npm install proxy-agent`);
355
+ case "socks4a:":
356
+ case "socks5:":
357
+ case "socks5h:":
358
+ case "socks:": {
359
+ // No SOCKS client ships with the package, and installing one does not
360
+ // change that: this module never loads it.
361
+ throw new Error(`SOCKS proxies (${parsed.protocol}//) are not supported. ` +
362
+ `Use an HTTP(S) proxy, or an HTTP-to-SOCKS bridge in front of the SOCKS proxy`);
354
363
  }
355
364
  default:
356
365
  throw new Error(`Unsupported proxy protocol: ${parsed.protocol}`);
@@ -410,6 +419,46 @@ export async function fetchProxyAware(url, init, directDispatcher, proxyTimeouts
410
419
  }));
411
420
  return response;
412
421
  }
422
+ /**
423
+ * Whether NEUROLINK_PROXY_STRICT asks for "proxy or nothing": `true`, `1`,
424
+ * `yes` or `on` (any case). Any other value, or none, keeps the default of
425
+ * retrying a failed proxy attempt over a direct connection.
426
+ */
427
+ export function isProxyStrictMode() {
428
+ return /^(true|1|yes|on)$/i.test(process.env.NEUROLINK_PROXY_STRICT?.trim() ?? "");
429
+ }
430
+ /**
431
+ * The WebSocket clients (`ws`) are built without a proxy agent, so they always
432
+ * connect directly. Call this before opening one: when a proxy is configured
433
+ * for `wsUrl` (and NO_PROXY does not exempt it), strict mode refuses the
434
+ * connection, and otherwise a warning says the socket bypasses the proxy.
435
+ * `label` names the client in the message; the URL itself is never logged,
436
+ * since some carry an API key in the query string.
437
+ */
438
+ export function assertWebSocketProxyPolicy(wsUrl, label) {
439
+ let host;
440
+ let httpEquivalent;
441
+ try {
442
+ const url = new URL(wsUrl);
443
+ host = url.host;
444
+ url.protocol =
445
+ url.protocol === "wss:" || url.protocol === "https:" ? "https:" : "http:";
446
+ url.search = "";
447
+ httpEquivalent = url.toString();
448
+ }
449
+ catch {
450
+ return;
451
+ }
452
+ if (!selectProxyUrl(httpEquivalent)) {
453
+ return;
454
+ }
455
+ if (isProxyStrictMode()) {
456
+ throw new Error(`[Proxy] ${label} WebSocket to ${host} cannot be sent through the configured proxy, ` +
457
+ `and NEUROLINK_PROXY_STRICT forbids a direct connection`);
458
+ }
459
+ logger.warn(`[Proxy] ${label} WebSocket to ${host} connects directly: WebSocket clients do not use the configured proxy. ` +
460
+ `Set NEUROLINK_PROXY_STRICT=true to refuse the connection instead.`);
461
+ }
413
462
  function sanitizeProxyUrl(url) {
414
463
  return maskProxyUrl(url) ?? "NOT_SET";
415
464
  }
@@ -465,7 +514,7 @@ function createDirectFetchHandler() {
465
514
  }
466
515
  };
467
516
  }
468
- async function executeProxiedFetch(input, init, proxyEnv) {
517
+ async function executeProxiedFetch(input, init, proxyEnv, strict) {
469
518
  const { httpsProxy, httpProxy, allProxy, socksProxy, noProxy } = proxyEnv;
470
519
  init = injectTraceContext(input, init);
471
520
  const requestId = `req-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
@@ -529,10 +578,19 @@ async function executeProxiedFetch(input, init, proxyEnv) {
529
578
  let fetchInit = { ...init };
530
579
  if (input instanceof Request) {
531
580
  fetchInput = input.url;
581
+ // A Request's body is a ReadableStream, and undici refuses a stream
582
+ // body without `duplex: "half"`. Default mode keeps its long-standing
583
+ // behaviour: that TypeError sends the request down the direct
584
+ // fallback. Strict mode has no fallback, so there the stream is sent
585
+ // through the proxy. A caller's own `duplex` in `init` still wins.
586
+ // The Request's own signal rides along so aborting it cancels the
587
+ // proxied attempt; an `init.signal` still wins.
532
588
  fetchInit = {
533
589
  method: input.method,
534
590
  headers: input.headers,
535
591
  body: input.body,
592
+ signal: input.signal,
593
+ ...(strict && input.body ? { duplex: "half" } : {}),
536
594
  ...init,
537
595
  };
538
596
  }
@@ -585,10 +643,23 @@ async function executeProxiedFetch(input, init, proxyEnv) {
585
643
  requestId,
586
644
  error: errorMessage,
587
645
  errorType: error instanceof Error ? error.constructor.name : typeof error,
588
- willFallback: true,
646
+ willFallback: !strict,
589
647
  timestamp: new Date().toISOString(),
590
648
  });
591
- logger.warn(`[Proxy Fetch] Enhanced proxy failed (${errorMessage}), falling back to direct connection`);
649
+ if (strict) {
650
+ let host = "[unknown-host]";
651
+ try {
652
+ host = new URL(targetUrl).host;
653
+ }
654
+ catch {
655
+ // keep the placeholder
656
+ }
657
+ logger.warn(`[Proxy Fetch] Request to ${host} through the proxy failed (${errorMessage}); strict proxy mode is on, so it is not retried over a direct connection`);
658
+ // The original error, unwrapped: callers classify it (abort, transient
659
+ // network codes on `cause`) exactly as they would any fetch failure.
660
+ throw error;
661
+ }
662
+ logger.warn(`[Proxy Fetch] Enhanced proxy failed (${errorMessage}), falling back to direct connection. Set NEUROLINK_PROXY_STRICT=true to fail instead.`);
592
663
  }
593
664
  logger.debug(`[Proxy Fetch] ENHANCED FALLBACK TO STANDARD FETCH`, {
594
665
  requestId,
@@ -630,15 +701,22 @@ async function executeProxiedFetch(input, init, proxyEnv) {
630
701
  throw fallbackError;
631
702
  }
632
703
  }
633
- function createProxiedFetchHandler(proxyEnv) {
634
- return async (input, init) => executeProxiedFetch(input, init, proxyEnv);
704
+ function createProxiedFetchHandler(proxyEnv, strict) {
705
+ return async (input, init) => executeProxiedFetch(input, init, proxyEnv, strict);
635
706
  }
636
707
  // ==================== ENHANCED PROXY FETCH FUNCTION ====================
637
708
  /**
638
709
  * Create a proxy-aware fetch function with enhanced capabilities
639
- * Supports HTTP/HTTPS, SOCKS4/5, authentication, and NO_PROXY bypass
710
+ * Supports HTTP/HTTPS proxies, authentication, and NO_PROXY bypass.
711
+ *
712
+ * By default a request whose proxy attempt fails is retried once over a
713
+ * direct connection, with a warning. Strict mode (`options.strict`, or
714
+ * NEUROLINK_PROXY_STRICT when the option is omitted) fails it instead. Strict
715
+ * mode never blocks a request NO_PROXY exempts, or one sent while no proxy is
716
+ * configured: those go direct by design.
640
717
  */
641
- export function createProxyFetch() {
718
+ export function createProxyFetch(options) {
719
+ const strict = options?.strict ?? isProxyStrictMode();
642
720
  // Detect ALL proxy-related environment variables
643
721
  const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy;
644
722
  const httpProxy = process.env.HTTP_PROXY || process.env.http_proxy;
@@ -683,7 +761,8 @@ export function createProxyFetch() {
683
761
  logger.debug(`[Proxy Fetch] ALL_PROXY: ${sanitizeProxyUrl(allProxy)}`);
684
762
  logger.debug(`[Proxy Fetch] SOCKS_PROXY: ${sanitizeProxyUrl(socksProxy)}`);
685
763
  logger.debug(`[Proxy Fetch] NO_PROXY: ${noProxy || "not set"}`);
686
- return createProxiedFetchHandler(proxyEnv);
764
+ logger.debug(`[Proxy Fetch] Strict mode: ${strict}`);
765
+ return createProxiedFetchHandler(proxyEnv, strict);
687
766
  }
688
767
  /**
689
768
  * Mask credentials in a proxy URL for safe logging/reporting.
@@ -725,11 +804,12 @@ export function getProxyStatus() {
725
804
  allProxy: maskProxyUrl(allProxy),
726
805
  socksProxy: maskProxyUrl(socksProxy),
727
806
  noProxy: noProxy || null,
807
+ strict: isProxyStrictMode(),
728
808
  method: "enhanced-proxy-agent",
729
809
  capabilities: [
730
810
  "HTTP/HTTPS Proxy",
731
- "SOCKS4/SOCKS5 Proxy",
732
811
  "Proxy Authentication",
812
+ "Strict (fail-closed) Mode",
733
813
  "NO_PROXY Bypass",
734
814
  "CIDR Range Matching",
735
815
  "Wildcard Domain Matching",
@@ -21,13 +21,13 @@ import type { AccountQuota, CodexRefreshTokenStore, CodexResponseEnvelope, Codex
21
21
  declare function refreshCodexTokenOnceWithDependencies(key: string, refreshToken: string, store: CodexRefreshTokenStore, refresh: CodexTokenRefresher): Promise<{
22
22
  accessToken: string;
23
23
  refreshToken: string;
24
- expiresAt?: number;
24
+ expiresAt: number;
25
25
  }>;
26
26
  /** Refresh an account's token at most once at a time. */
27
27
  declare function refreshCodexTokenOnce(key: string, refreshToken: string): Promise<{
28
28
  accessToken: string;
29
29
  refreshToken: string;
30
- expiresAt?: number;
30
+ expiresAt: number;
31
31
  }>;
32
32
  /**
33
33
  * Load the Codex account pool from the token store, refreshing expired OAuth