@juspay/neurolink 12.7.3 → 12.7.5
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.
- package/CHANGELOG.md +2 -2
- package/dist/browser/neurolink.min.js +399 -399
- package/dist/cli/commands/auth.js +252 -125
- package/dist/cli/commands/proxy.js +110 -91
- package/dist/cli/factories/authCommandFactory.js +8 -11
- package/dist/memory/memoryRetrievalTools.d.ts +5 -2
- package/dist/memory/memoryRetrievalTools.js +11 -3
- package/dist/neurolink.js +5 -4
- package/dist/proxy/codexAccountUsage.d.ts +1 -1
- package/dist/proxy/codexAccountUsage.js +13 -1
- package/dist/proxy/proxyActivity.js +12 -1
- package/dist/proxy/usageStats.d.ts +2 -2
- package/dist/proxy/usageStats.js +66 -10
- package/dist/server/routes/claudeProxyRoutes.d.ts +2 -1
- package/dist/server/routes/claudeProxyRoutes.js +62 -12
- package/dist/server/routes/codexProxyRoutes.d.ts +8 -2
- package/dist/server/routes/codexProxyRoutes.js +191 -58
- package/dist/types/cli.d.ts +37 -5
- package/dist/types/proxy.d.ts +37 -0
- package/package.json +2 -2
|
@@ -24,8 +24,10 @@ import { loadAccountQuotas, saveAccountQuota, } from "../../proxy/accountQuota.j
|
|
|
24
24
|
import { createCodexUsageTap } from "../../proxy/codexUsage.js";
|
|
25
25
|
import { CODEX_ACCOUNT_PREFIX, parseCodexRateLimitHeaders, } from "../../proxy/codexAccountUsage.js";
|
|
26
26
|
import { buildClientAttribution } from "../../proxy/clientAttribution.js";
|
|
27
|
-
import {
|
|
27
|
+
import { trackProxyResponse } from "../../proxy/proxyActivity.js";
|
|
28
|
+
import { logRequest, logRequestAttempt } from "../../proxy/requestLogger.js";
|
|
28
29
|
import { parseRetryAfterMs } from "../../proxy/routingPolicy.js";
|
|
30
|
+
import { recordAttempt, recordAttemptError, recordFinalError, recordFinalSuccess, } from "../../proxy/usageStats.js";
|
|
29
31
|
import { sanitizeForLog } from "../../utils/logSanitize.js";
|
|
30
32
|
import { logger } from "../../utils/logger.js";
|
|
31
33
|
const CODEX_UPSTREAM_TIMEOUT_MS = 15 * 60 * 1000; // 15 min, matches Claude path
|
|
@@ -33,6 +35,32 @@ const DEFAULT_TRANSIENT_COOLDOWN_MS = 60_000;
|
|
|
33
35
|
const MAX_TRANSIENT_COOLDOWN_MS = 15 * 60 * 1000;
|
|
34
36
|
/** Brief park after a refresh attempt that never reached a verdict. */
|
|
35
37
|
const CODEX_AUTH_COOLDOWN_MS = 60_000;
|
|
38
|
+
const CODEX_ACCOUNT_TYPE = "codex-oauth";
|
|
39
|
+
const CODEX_FALLBACK_METADATA_KEY = "neurolink.codexFallback";
|
|
40
|
+
function getCodexTransportErrorCode(error) {
|
|
41
|
+
if (!error || typeof error !== "object") {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
const directCode = error.code;
|
|
45
|
+
if (typeof directCode === "string") {
|
|
46
|
+
return directCode;
|
|
47
|
+
}
|
|
48
|
+
const cause = error.cause;
|
|
49
|
+
if (!cause || typeof cause !== "object") {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
const causeCode = cause.code;
|
|
53
|
+
return typeof causeCode === "string" ? causeCode : undefined;
|
|
54
|
+
}
|
|
55
|
+
function codexTransportScope(error) {
|
|
56
|
+
const code = getCodexTransportErrorCode(error);
|
|
57
|
+
return code === "ENOTFOUND" || code === "EAI_AGAIN"
|
|
58
|
+
? "shared_provider_transport"
|
|
59
|
+
: "connection_transport";
|
|
60
|
+
}
|
|
61
|
+
function summarizeCodexUpstreamError(errorText, fallback) {
|
|
62
|
+
return sanitizeForLog(errorText).slice(0, 200) || fallback;
|
|
63
|
+
}
|
|
36
64
|
/**
|
|
37
65
|
* In-flight proactive refreshes, keyed by account.
|
|
38
66
|
*
|
|
@@ -43,8 +71,7 @@ const CODEX_AUTH_COOLDOWN_MS = 60_000;
|
|
|
43
71
|
* that is perfectly healthy.
|
|
44
72
|
*/
|
|
45
73
|
const codexRefreshInFlight = new Map();
|
|
46
|
-
|
|
47
|
-
async function refreshCodexTokenOnce(key, refreshToken) {
|
|
74
|
+
async function refreshCodexTokenOnceWithDependencies(key, refreshToken, store, refresh) {
|
|
48
75
|
const existing = codexRefreshInFlight.get(key);
|
|
49
76
|
if (existing) {
|
|
50
77
|
return existing;
|
|
@@ -54,20 +81,36 @@ async function refreshCodexTokenOnce(key, refreshToken) {
|
|
|
54
81
|
// request that captured the pool just before a previous refresh completed
|
|
55
82
|
// holds a token that has since been rotated; using it would spend a real
|
|
56
83
|
// attempt on a grant the server has already invalidated.
|
|
57
|
-
const latest = await
|
|
84
|
+
const latest = await store.peekTokens(key).catch(() => null);
|
|
58
85
|
const current = latest?.refreshToken ?? refreshToken;
|
|
59
|
-
const refreshed = await
|
|
60
|
-
|
|
86
|
+
const refreshed = await refresh(current);
|
|
87
|
+
const resolved = {
|
|
61
88
|
accessToken: refreshed.accessToken,
|
|
62
89
|
refreshToken: refreshed.refreshToken ?? current,
|
|
63
|
-
expiresAt: refreshed.expiresAt,
|
|
90
|
+
expiresAt: refreshed.expiresAt ?? latest?.expiresAt ?? Date.now() + 3_600_000,
|
|
64
91
|
};
|
|
92
|
+
// Hold the single-flight slot through persistence. Releasing it after the
|
|
93
|
+
// OAuth response but before this write lets a third request read the old
|
|
94
|
+
// rotating refresh token, receive an invalid_grant, and disable an account
|
|
95
|
+
// another request has already healed.
|
|
96
|
+
if (latest) {
|
|
97
|
+
await store.saveTokens(key, {
|
|
98
|
+
...resolved,
|
|
99
|
+
tokenType: "Bearer",
|
|
100
|
+
...(latest.scope ? { scope: latest.scope } : {}),
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
return resolved;
|
|
65
104
|
})().finally(() => {
|
|
66
105
|
codexRefreshInFlight.delete(key);
|
|
67
106
|
});
|
|
68
107
|
codexRefreshInFlight.set(key, pending);
|
|
69
108
|
return pending;
|
|
70
109
|
}
|
|
110
|
+
/** Refresh an account's token at most once at a time. */
|
|
111
|
+
async function refreshCodexTokenOnce(key, refreshToken) {
|
|
112
|
+
return refreshCodexTokenOnceWithDependencies(key, refreshToken, tokenStore, refreshCodexToken);
|
|
113
|
+
}
|
|
71
114
|
// Headers we never forward upstream (hop-by-hop, client creds, or things we
|
|
72
115
|
// re-derive). The client's own auth is replaced with the pooled account's.
|
|
73
116
|
const BLOCKED_UPSTREAM_HEADERS = new Set([
|
|
@@ -114,13 +157,6 @@ async function loadCodexProxyAccounts() {
|
|
|
114
157
|
const refreshed = await refreshCodexTokenOnce(key, tokens.refreshToken);
|
|
115
158
|
accessToken = refreshed.accessToken;
|
|
116
159
|
expiresAt = refreshed.expiresAt ?? expiresAt;
|
|
117
|
-
await tokenStore.saveTokens(key, {
|
|
118
|
-
accessToken,
|
|
119
|
-
refreshToken: refreshed.refreshToken,
|
|
120
|
-
expiresAt: expiresAt ?? Date.now() + 3_600_000,
|
|
121
|
-
tokenType: "Bearer",
|
|
122
|
-
scope: tokens.scope,
|
|
123
|
-
});
|
|
124
160
|
}
|
|
125
161
|
catch (error) {
|
|
126
162
|
// Keep the stale token; a 401 upstream will trigger rotation.
|
|
@@ -241,7 +277,11 @@ export async function handleCodexResponsesRequest(ctx) {
|
|
|
241
277
|
const model = typeof body.model === "string"
|
|
242
278
|
? body.model
|
|
243
279
|
: "-";
|
|
244
|
-
|
|
280
|
+
// A Codex call made as an inner Anthropic fallback is an upstream attempt,
|
|
281
|
+
// not an independently final client request. The parent fallback owns the
|
|
282
|
+
// final status and can still recover with a later provider.
|
|
283
|
+
const isFallbackRequest = ctx.metadata?.[CODEX_FALLBACK_METADATA_KEY] === true;
|
|
284
|
+
const writeFinalLog = (account, responseStatus, extra = {}) => logRequest({
|
|
245
285
|
timestamp: new Date().toISOString(),
|
|
246
286
|
requestId: ctx.requestId,
|
|
247
287
|
method: ctx.method,
|
|
@@ -251,16 +291,63 @@ export async function handleCodexResponsesRequest(ctx) {
|
|
|
251
291
|
toolCount: Array.isArray(body.tools)
|
|
252
292
|
? body.tools.length
|
|
253
293
|
: 0,
|
|
254
|
-
account,
|
|
255
|
-
|
|
294
|
+
account: account?.label ?? "",
|
|
295
|
+
...(account ? { accountKey: account.key } : {}),
|
|
296
|
+
accountType: account ? CODEX_ACCOUNT_TYPE : "",
|
|
297
|
+
// This is the cost provider. accountKey and the response header identify
|
|
298
|
+
// the actual Codex pool that supplied the credential.
|
|
299
|
+
provider: "openai",
|
|
256
300
|
...buildClientAttribution(ctx.headers),
|
|
257
301
|
responseStatus,
|
|
258
302
|
responseTimeMs: Date.now() - requestStartTime,
|
|
259
303
|
...extra,
|
|
260
304
|
});
|
|
305
|
+
let finalOutcomeRecorded = false;
|
|
306
|
+
const recordFinalOutcome = async (account, responseStatus, extra = {}) => {
|
|
307
|
+
if (isFallbackRequest || finalOutcomeRecorded) {
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
finalOutcomeRecorded = true;
|
|
311
|
+
if (responseStatus >= 400) {
|
|
312
|
+
recordFinalError(responseStatus, account?.label, account ? CODEX_ACCOUNT_TYPE : undefined, {
|
|
313
|
+
requestId: ctx.requestId,
|
|
314
|
+
...(account ? { accountKey: account.key } : {}),
|
|
315
|
+
errorType: extra.errorType,
|
|
316
|
+
terminalOutcome: extra.terminalOutcome ?? "handler_error",
|
|
317
|
+
message: extra.errorMessage,
|
|
318
|
+
errorCode: extra.errorCode,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
recordFinalSuccess(account?.label, account ? CODEX_ACCOUNT_TYPE : undefined);
|
|
323
|
+
}
|
|
324
|
+
await writeFinalLog(account, responseStatus, extra);
|
|
325
|
+
};
|
|
326
|
+
const writeAttempt = (account, attempt, startedAt, responseStatus, extra = {}) => {
|
|
327
|
+
void logRequestAttempt({
|
|
328
|
+
timestamp: new Date().toISOString(),
|
|
329
|
+
requestId: ctx.requestId,
|
|
330
|
+
attempt,
|
|
331
|
+
method: ctx.method,
|
|
332
|
+
path: ctx.path,
|
|
333
|
+
model,
|
|
334
|
+
stream: true,
|
|
335
|
+
toolCount: Array.isArray(body.tools)
|
|
336
|
+
? body.tools.length
|
|
337
|
+
: 0,
|
|
338
|
+
account: account.label,
|
|
339
|
+
accountKey: account.key,
|
|
340
|
+
accountType: CODEX_ACCOUNT_TYPE,
|
|
341
|
+
provider: "openai",
|
|
342
|
+
responseStatus,
|
|
343
|
+
responseTimeMs: Date.now() - requestStartTime,
|
|
344
|
+
attemptDurationMs: Date.now() - startedAt,
|
|
345
|
+
...extra,
|
|
346
|
+
}).catch(() => undefined);
|
|
347
|
+
};
|
|
261
348
|
const accounts = await loadCodexProxyAccounts();
|
|
262
349
|
if (accounts.length === 0) {
|
|
263
|
-
await
|
|
350
|
+
await recordFinalOutcome(undefined, 401, {
|
|
264
351
|
errorType: "no_accounts",
|
|
265
352
|
errorMessage: "No Codex accounts",
|
|
266
353
|
});
|
|
@@ -280,7 +367,7 @@ export async function handleCodexResponsesRequest(ctx) {
|
|
|
280
367
|
const retryAfterSec = soonest
|
|
281
368
|
? Math.max(1, Math.ceil((soonest - now) / 1000))
|
|
282
369
|
: 60;
|
|
283
|
-
await
|
|
370
|
+
await recordFinalOutcome(undefined, 429, {
|
|
284
371
|
errorType: "all_accounts_cooling",
|
|
285
372
|
errorMessage: "All Codex accounts are rate-limited",
|
|
286
373
|
});
|
|
@@ -300,11 +387,15 @@ export async function handleCodexResponsesRequest(ctx) {
|
|
|
300
387
|
let attempt = 0;
|
|
301
388
|
let lastErrorMessage = "All Codex accounts failed";
|
|
302
389
|
let lastErrorStatus = 502;
|
|
390
|
+
let lastAttemptedAccount;
|
|
303
391
|
for (const account of eligible) {
|
|
304
|
-
attempt += 1;
|
|
305
392
|
let authRetried = false;
|
|
306
393
|
// Same-account loop only re-runs once, for a post-401 token refresh.
|
|
307
394
|
for (;;) {
|
|
395
|
+
attempt += 1;
|
|
396
|
+
const attemptStartedAt = Date.now();
|
|
397
|
+
lastAttemptedAccount = account;
|
|
398
|
+
recordAttempt(account.label, CODEX_ACCOUNT_TYPE);
|
|
308
399
|
let upstream;
|
|
309
400
|
try {
|
|
310
401
|
upstream = await fetch(CODEX_RESPONSES_URL, {
|
|
@@ -320,6 +411,17 @@ export async function handleCodexResponsesRequest(ctx) {
|
|
|
320
411
|
// can act on. Keep the detail in the log and return a fixed string, so
|
|
321
412
|
// internal topology never reaches the client.
|
|
322
413
|
logger.debug(`Codex upstream fetch failed (${account.label}): ${sanitizeForLog(error instanceof Error ? error.message : String(error))}`);
|
|
414
|
+
const errorMessage = summarizeCodexUpstreamError(error instanceof Error ? error.message : String(error), "Codex upstream request failed");
|
|
415
|
+
const errorCode = getCodexTransportErrorCode(error);
|
|
416
|
+
const transportScope = codexTransportScope(error);
|
|
417
|
+
recordAttemptError(account.label, CODEX_ACCOUNT_TYPE, 502);
|
|
418
|
+
writeAttempt(account, attempt, attemptStartedAt, 502, {
|
|
419
|
+
errorType: "network_error",
|
|
420
|
+
errorMessage,
|
|
421
|
+
...(errorCode ? { errorCode } : {}),
|
|
422
|
+
transportScope,
|
|
423
|
+
retryable: true,
|
|
424
|
+
});
|
|
323
425
|
lastErrorMessage = "Codex upstream request failed";
|
|
324
426
|
lastErrorStatus = 502;
|
|
325
427
|
break; // rotate to next account
|
|
@@ -336,50 +438,72 @@ export async function handleCodexResponsesRequest(ctx) {
|
|
|
336
438
|
clearAccountCooldown(account.key, account.expiredCooldownUntil).catch(() => undefined);
|
|
337
439
|
}
|
|
338
440
|
publishCodexHeaders(ctx, account, attempt, quota);
|
|
339
|
-
|
|
441
|
+
writeAttempt(account, attempt, attemptStartedAt, upstream.status);
|
|
340
442
|
const headers = {
|
|
341
443
|
"content-type": upstream.headers.get("content-type") ?? "text/event-stream",
|
|
342
444
|
"cache-control": "no-cache",
|
|
343
445
|
connection: "keep-alive",
|
|
344
446
|
...(ctx.responseHeaders ?? {}),
|
|
345
447
|
};
|
|
346
|
-
// Tap the relay for token usage. The log above is written first and
|
|
347
|
-
// unconditionally so a request is never lost when a client hangs up
|
|
348
|
-
// mid-stream; this emits a second record for the same requestId
|
|
349
|
-
// carrying the counts, which proxyAnalysis merges. If the stream shape
|
|
350
|
-
// is not recognised, usage resolves null and nothing extra is written —
|
|
351
|
-
// i.e. exactly the previous behaviour.
|
|
352
448
|
if (!upstream.body) {
|
|
449
|
+
await recordFinalOutcome(account, upstream.status, {
|
|
450
|
+
terminalOutcome: "bodyless",
|
|
451
|
+
});
|
|
353
452
|
return new Response(upstream.body, {
|
|
354
453
|
status: upstream.status,
|
|
355
454
|
headers,
|
|
356
455
|
});
|
|
357
456
|
}
|
|
358
457
|
const { stream: usageTap, usage: usageSeen } = createCodexUsageTap();
|
|
359
|
-
|
|
360
|
-
.then((usage) => {
|
|
361
|
-
if (!usage) {
|
|
362
|
-
return;
|
|
363
|
-
}
|
|
364
|
-
return writeLog(account.label, upstream.status, {
|
|
365
|
-
provider: "openai",
|
|
366
|
-
inputTokens: usage.inputTokens,
|
|
367
|
-
outputTokens: usage.outputTokens,
|
|
368
|
-
cacheReadTokens: usage.cacheReadTokens,
|
|
369
|
-
cacheCreationTokens: usage.cacheCreationTokens,
|
|
370
|
-
});
|
|
371
|
-
})
|
|
372
|
-
.catch(() => undefined);
|
|
373
|
-
return new Response(upstream.body.pipeThrough(usageTap), {
|
|
458
|
+
const relay = new Response(upstream.body.pipeThrough(usageTap), {
|
|
374
459
|
status: upstream.status,
|
|
375
460
|
headers,
|
|
376
461
|
});
|
|
462
|
+
return trackProxyResponse(relay, () => undefined, {
|
|
463
|
+
onTerminal: ({ outcome }) => {
|
|
464
|
+
void usageSeen
|
|
465
|
+
.then((usage) => {
|
|
466
|
+
const usageExtra = usage
|
|
467
|
+
? {
|
|
468
|
+
inputTokens: usage.inputTokens,
|
|
469
|
+
outputTokens: usage.outputTokens,
|
|
470
|
+
cacheReadTokens: usage.cacheReadTokens,
|
|
471
|
+
cacheCreationTokens: usage.cacheCreationTokens,
|
|
472
|
+
}
|
|
473
|
+
: {};
|
|
474
|
+
if (outcome === "completed" || outcome === "bodyless") {
|
|
475
|
+
return recordFinalOutcome(account, upstream.status, {
|
|
476
|
+
terminalOutcome: outcome,
|
|
477
|
+
...usageExtra,
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
return recordFinalOutcome(account, outcome === "client_cancelled" ? 499 : 502, {
|
|
481
|
+
errorType: outcome === "client_cancelled"
|
|
482
|
+
? "client_cancelled"
|
|
483
|
+
: "stream_error",
|
|
484
|
+
errorMessage: outcome === "client_cancelled"
|
|
485
|
+
? "Client cancelled Codex stream"
|
|
486
|
+
: "Codex upstream stream failed",
|
|
487
|
+
terminalOutcome: outcome,
|
|
488
|
+
...usageExtra,
|
|
489
|
+
});
|
|
490
|
+
})
|
|
491
|
+
.catch(() => undefined);
|
|
492
|
+
},
|
|
493
|
+
});
|
|
377
494
|
}
|
|
378
495
|
const errText = await upstream.text().catch(() => "");
|
|
379
496
|
// 401/403 → try a forced token refresh once, then rotate.
|
|
380
497
|
if ((upstream.status === 401 || upstream.status === 403) &&
|
|
381
498
|
!authRetried &&
|
|
382
499
|
account.refreshToken) {
|
|
500
|
+
const errorMessage = summarizeCodexUpstreamError(errText, "Codex authentication rejected upstream");
|
|
501
|
+
recordAttemptError(account.label, CODEX_ACCOUNT_TYPE, upstream.status);
|
|
502
|
+
writeAttempt(account, attempt, attemptStartedAt, upstream.status, {
|
|
503
|
+
errorType: "authentication_error",
|
|
504
|
+
errorMessage,
|
|
505
|
+
retryable: true,
|
|
506
|
+
});
|
|
383
507
|
authRetried = true;
|
|
384
508
|
const staleTokens = {
|
|
385
509
|
accessToken: account.token,
|
|
@@ -387,17 +511,11 @@ export async function handleCodexResponsesRequest(ctx) {
|
|
|
387
511
|
expiresAt: account.expiresAt ?? 0,
|
|
388
512
|
};
|
|
389
513
|
try {
|
|
390
|
-
const refreshed = await
|
|
514
|
+
const refreshed = await refreshCodexTokenOnce(account.key, account.refreshToken);
|
|
391
515
|
account.token = refreshed.accessToken;
|
|
392
516
|
account.refreshToken = refreshed.refreshToken ?? account.refreshToken;
|
|
393
517
|
account.expiresAt = refreshed.expiresAt ?? account.expiresAt;
|
|
394
518
|
account.accountId = resolveCodexAccountId(refreshed.accessToken);
|
|
395
|
-
await tokenStore.saveTokens(account.key, {
|
|
396
|
-
accessToken: account.token,
|
|
397
|
-
refreshToken: account.refreshToken,
|
|
398
|
-
expiresAt: account.expiresAt ?? Date.now() + 3_600_000,
|
|
399
|
-
tokenType: "Bearer",
|
|
400
|
-
});
|
|
401
519
|
continue; // retry same account with the fresh token
|
|
402
520
|
}
|
|
403
521
|
catch (error) {
|
|
@@ -432,6 +550,16 @@ export async function handleCodexResponsesRequest(ctx) {
|
|
|
432
550
|
const retryAfterMs = parseRetryAfterMs(upstream.headers.get("retry-after"));
|
|
433
551
|
const plan = planCodexCooldown(quota, retryAfterMs, Date.now());
|
|
434
552
|
await saveAccountCooldown(account.key, plan.coolingUntil, plan.reason).catch(() => undefined);
|
|
553
|
+
const rateLimitKind = plan.reason === "transient" ? "transient" : "quota";
|
|
554
|
+
const errorMessage = summarizeCodexUpstreamError(errText, "Codex account rate-limited");
|
|
555
|
+
recordAttemptError(account.label, CODEX_ACCOUNT_TYPE, upstream.status, rateLimitKind);
|
|
556
|
+
writeAttempt(account, attempt, attemptStartedAt, upstream.status, {
|
|
557
|
+
errorType: "rate_limit_error",
|
|
558
|
+
errorMessage,
|
|
559
|
+
retryable: true,
|
|
560
|
+
rateLimitKind,
|
|
561
|
+
cooldownReason: plan.reason,
|
|
562
|
+
});
|
|
435
563
|
lastErrorStatus = 429;
|
|
436
564
|
lastErrorMessage = "Codex account rate-limited";
|
|
437
565
|
break; // rotate
|
|
@@ -443,12 +571,22 @@ export async function handleCodexResponsesRequest(ctx) {
|
|
|
443
571
|
// of letting it stay first in line with unknown quota.
|
|
444
572
|
await saveAccountCooldown(account.key, Date.now() + CODEX_AUTH_COOLDOWN_MS, "auth").catch(() => undefined);
|
|
445
573
|
}
|
|
574
|
+
const errorMessage = summarizeCodexUpstreamError(errText, "Codex error");
|
|
575
|
+
const errorType = upstream.status === 401 || upstream.status === 403
|
|
576
|
+
? "authentication_error"
|
|
577
|
+
: "api_error";
|
|
578
|
+
recordAttemptError(account.label, CODEX_ACCOUNT_TYPE, upstream.status);
|
|
579
|
+
writeAttempt(account, attempt, attemptStartedAt, upstream.status, {
|
|
580
|
+
errorType,
|
|
581
|
+
errorMessage,
|
|
582
|
+
retryable: upstream.status >= 500,
|
|
583
|
+
});
|
|
446
584
|
lastErrorStatus = upstream.status >= 500 ? 502 : upstream.status;
|
|
447
|
-
lastErrorMessage =
|
|
585
|
+
lastErrorMessage = errorMessage;
|
|
448
586
|
break; // rotate
|
|
449
587
|
}
|
|
450
588
|
}
|
|
451
|
-
await
|
|
589
|
+
await recordFinalOutcome(lastAttemptedAccount, lastErrorStatus, {
|
|
452
590
|
errorType: "all_accounts_failed",
|
|
453
591
|
errorMessage: lastErrorMessage,
|
|
454
592
|
});
|
|
@@ -529,18 +667,12 @@ async function handleCodexModelsRequest(ctx) {
|
|
|
529
667
|
if (!authRetried && account.refreshToken) {
|
|
530
668
|
authRetried = true;
|
|
531
669
|
try {
|
|
532
|
-
const refreshed = await
|
|
670
|
+
const refreshed = await refreshCodexTokenOnce(account.key, account.refreshToken);
|
|
533
671
|
account.token = refreshed.accessToken;
|
|
534
672
|
account.refreshToken =
|
|
535
673
|
refreshed.refreshToken ?? account.refreshToken;
|
|
536
674
|
account.expiresAt = refreshed.expiresAt ?? account.expiresAt;
|
|
537
675
|
account.accountId = resolveCodexAccountId(refreshed.accessToken);
|
|
538
|
-
await tokenStore.saveTokens(account.key, {
|
|
539
|
-
accessToken: account.token,
|
|
540
|
-
refreshToken: account.refreshToken,
|
|
541
|
-
expiresAt: account.expiresAt ?? Date.now() + 3_600_000,
|
|
542
|
-
tokenType: "Bearer",
|
|
543
|
-
});
|
|
544
676
|
continue; // retry this account with the fresh token
|
|
545
677
|
}
|
|
546
678
|
catch {
|
|
@@ -605,5 +737,6 @@ export const __testHooks = {
|
|
|
605
737
|
buildCodexUpstreamHeaders,
|
|
606
738
|
planCodexCooldown,
|
|
607
739
|
refreshCodexTokenOnce,
|
|
740
|
+
refreshCodexTokenOnceWithDependencies,
|
|
608
741
|
codexRefreshInFlightSize: () => codexRefreshInFlight.size,
|
|
609
742
|
};
|
package/dist/types/cli.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ import type { PPTGenerationResult } from "./ppt.js";
|
|
|
11
11
|
import type { AvatarResult } from "./avatar.js";
|
|
12
12
|
import type { MusicResult } from "./music.js";
|
|
13
13
|
import type { OAuthTokens } from "./auth.js";
|
|
14
|
-
import type { AccountQuota } from "./proxy.js";
|
|
14
|
+
import type { AccountQuota, ProxyPassthroughAccount } from "./proxy.js";
|
|
15
15
|
import type { ClaudeSubscriptionTier } from "./subscription.js";
|
|
16
16
|
import type { ServerFramework } from "./server.js";
|
|
17
17
|
import type { AuthProviderType } from "./auth.js";
|
|
@@ -954,7 +954,7 @@ export type AuthCommandArgs = BaseCommandArgs & {
|
|
|
954
954
|
label?: string;
|
|
955
955
|
account?: string;
|
|
956
956
|
force?: boolean;
|
|
957
|
-
/** `auth list --refresh`: fetch fresh limits
|
|
957
|
+
/** `auth list --refresh`: fetch fresh provider limits before listing */
|
|
958
958
|
refresh?: boolean;
|
|
959
959
|
/** Path to the proxy config YAML, used by set-/get-/clear-primary */
|
|
960
960
|
config?: string;
|
|
@@ -969,12 +969,44 @@ export type AuthCommandArgs = BaseCommandArgs & {
|
|
|
969
969
|
/** Yargs positional arguments */
|
|
970
970
|
_?: (string | number)[];
|
|
971
971
|
};
|
|
972
|
+
/** Refresh state for a provider-qualified account. */
|
|
973
|
+
export type AuthListRefreshStatus = "refreshed" | "snapshot" | "unavailable" | "not_supported";
|
|
974
|
+
/** Fresh-limit result for one provider-qualified account. */
|
|
975
|
+
export type AuthListRefreshAccountResult = {
|
|
976
|
+
/** Provider prefix parsed from the configured account key. */
|
|
977
|
+
provider: string;
|
|
978
|
+
/** A missing limit is explicit rather than being rendered as an unexplained dash. */
|
|
979
|
+
status: AuthListRefreshStatus;
|
|
980
|
+
error?: string;
|
|
981
|
+
};
|
|
982
|
+
/** One direct quota-adapter result used by `auth list --refresh`. */
|
|
983
|
+
export type AuthListDirectQuotaRefreshResult = {
|
|
984
|
+
status: "refreshed";
|
|
985
|
+
quota: AccountQuota;
|
|
986
|
+
} | {
|
|
987
|
+
status: "unavailable" | "not_supported";
|
|
988
|
+
error?: string;
|
|
989
|
+
};
|
|
990
|
+
/** Provider-specific quota capability used by the generic auth-list refresh. */
|
|
991
|
+
export type AuthListQuotaRefreshAdapter = {
|
|
992
|
+
/** A successful local proxy `/limits` response is authoritative for this provider. */
|
|
993
|
+
supportsProxyRefresh?: boolean;
|
|
994
|
+
listAccounts: () => Promise<ProxyPassthroughAccount[]>;
|
|
995
|
+
priorQuotaKeys: (account: ProxyPassthroughAccount) => readonly string[];
|
|
996
|
+
refreshAccount: (account: ProxyPassthroughAccount, options: {
|
|
997
|
+
prior: AccountQuota | null;
|
|
998
|
+
}) => Promise<AuthListDirectQuotaRefreshResult>;
|
|
999
|
+
};
|
|
1000
|
+
/** Applies one account's explicit auth-list refresh state. */
|
|
1001
|
+
export type AuthListRefreshResultSetter = (key: string, status: AuthListRefreshStatus, error?: string) => void;
|
|
972
1002
|
/** Outcome of the `auth list --refresh` fresh-limit fetch. */
|
|
973
1003
|
export type AuthListRefreshOutcome = {
|
|
974
1004
|
/** How the fresh limits were obtained ("none" when every path failed). */
|
|
975
|
-
via: "proxy" | "direct" | "none";
|
|
976
|
-
/** Freshly fetched quotas keyed by account
|
|
1005
|
+
via: "proxy" | "direct" | "mixed" | "none";
|
|
1006
|
+
/** Freshly fetched quotas keyed by provider-qualified account key. */
|
|
977
1007
|
quotas: Record<string, AccountQuota> | null;
|
|
1008
|
+
/** Per-account refresh status, also keyed by provider-qualified account key. */
|
|
1009
|
+
accounts: Record<string, AuthListRefreshAccountResult>;
|
|
978
1010
|
/** Per-account and transport errors, already formatted for display. */
|
|
979
1011
|
errors: string[];
|
|
980
1012
|
};
|
|
@@ -1220,7 +1252,7 @@ export type ProviderSetupConfig = {
|
|
|
1220
1252
|
endpoint?: string;
|
|
1221
1253
|
isReconfiguring?: boolean;
|
|
1222
1254
|
};
|
|
1223
|
-
/** Providers
|
|
1255
|
+
/** Providers with first-class credential flows implemented by `neurolink auth`. */
|
|
1224
1256
|
export type SupportedProvider = "anthropic" | "codex";
|
|
1225
1257
|
/** Arguments for `neurolink autoresearch init`. */
|
|
1226
1258
|
export type AutoresearchInitArgs = {
|
package/dist/types/proxy.d.ts
CHANGED
|
@@ -21,6 +21,7 @@ import type { ProxyTracer } from "../proxy/proxyTracer.js";
|
|
|
21
21
|
import type { ACCOUNT_COOLING_REASONS, PROXY_ACCOUNT_TYPES, PROXY_ACCOUNT_ROUTING_MODES, PROXY_ACCOUNT_ROUTING_REASONS, PROXY_ACCOUNT_ROUTING_STRATEGIES } from "../proxy/routingEvidence.js";
|
|
22
22
|
import type { FallbackEntry, ModelMapping, ProxyRoutingConfig, CloakingConfig } from "./subscription.js";
|
|
23
23
|
import type { RouteDeprecation } from "./server.js";
|
|
24
|
+
import type { StoredOAuthTokens } from "./auth.js";
|
|
24
25
|
/**
|
|
25
26
|
* Type describing the ModelRouter contract.
|
|
26
27
|
* Defined here to avoid a circular dependency between types and implementation.
|
|
@@ -557,6 +558,8 @@ export type RequestLogEntry = {
|
|
|
557
558
|
stream: boolean;
|
|
558
559
|
toolCount: number;
|
|
559
560
|
account: string;
|
|
561
|
+
/** Provider-qualified account key for collision-free reconstruction. */
|
|
562
|
+
accountKey?: string;
|
|
560
563
|
accountType: string;
|
|
561
564
|
responseStatus: number;
|
|
562
565
|
responseTimeMs: number;
|
|
@@ -576,6 +579,8 @@ export type RequestLogEntry = {
|
|
|
576
579
|
* cross-provider model lookup rather than assuming Anthropic.
|
|
577
580
|
*/
|
|
578
581
|
provider?: string;
|
|
582
|
+
/** Terminal state of the client-facing response when known. */
|
|
583
|
+
terminalOutcome?: "completed" | "bodyless" | "client_cancelled" | "stream_error" | "handler_error";
|
|
579
584
|
/**
|
|
580
585
|
* Which CLI made the request, derived from User-Agent, and the raw header it
|
|
581
586
|
* was derived from.
|
|
@@ -605,6 +610,8 @@ export type RequestAttemptLogEntry = {
|
|
|
605
610
|
stream: boolean;
|
|
606
611
|
toolCount: number;
|
|
607
612
|
account: string;
|
|
613
|
+
/** Provider-qualified account key for collision-free reconstruction. */
|
|
614
|
+
accountKey?: string;
|
|
608
615
|
accountType: string;
|
|
609
616
|
responseStatus: number;
|
|
610
617
|
/** End-to-end request age when this attempt completed. */
|
|
@@ -627,11 +634,28 @@ export type RequestAttemptLogEntry = {
|
|
|
627
634
|
outputTokens?: number;
|
|
628
635
|
cacheCreationTokens?: number;
|
|
629
636
|
cacheReadTokens?: number;
|
|
637
|
+
/** Provider that received this upstream attempt. */
|
|
638
|
+
provider?: string;
|
|
630
639
|
/** OTel trace ID for correlation with distributed traces */
|
|
631
640
|
traceId?: string;
|
|
632
641
|
/** OTel span ID for correlation with distributed traces */
|
|
633
642
|
spanId?: string;
|
|
634
643
|
};
|
|
644
|
+
/** Additional fields recorded when a Codex response becomes client-final. */
|
|
645
|
+
export type CodexFinalLogExtra = Partial<Pick<RequestLogEntry, "errorType" | "errorMessage" | "errorCode" | "transportScope" | "inputTokens" | "outputTokens" | "cacheReadTokens" | "cacheCreationTokens" | "terminalOutcome">>;
|
|
646
|
+
/** Additional fields recorded for each upstream Codex account attempt. */
|
|
647
|
+
export type CodexAttemptLogExtra = Partial<Pick<RequestAttemptLogEntry, "errorType" | "errorMessage" | "errorCode" | "transportScope" | "retryable" | "rateLimitKind" | "cooldownReason">>;
|
|
648
|
+
/** Minimal persistence contract needed by Codex rotating-token refreshes. */
|
|
649
|
+
export type CodexRefreshTokenStore = {
|
|
650
|
+
peekTokens(provider: string): Promise<StoredOAuthTokens | null>;
|
|
651
|
+
saveTokens(provider: string, tokens: StoredOAuthTokens): Promise<void>;
|
|
652
|
+
};
|
|
653
|
+
/** Result contract for a Codex OAuth refresh operation. */
|
|
654
|
+
export type CodexTokenRefresher = (refreshToken: string) => Promise<{
|
|
655
|
+
accessToken: string;
|
|
656
|
+
refreshToken?: string;
|
|
657
|
+
expiresAt?: number;
|
|
658
|
+
}>;
|
|
635
659
|
export type ProxyBodyCaptureInput = {
|
|
636
660
|
phase: string;
|
|
637
661
|
headers?: Record<string, string>;
|
|
@@ -880,6 +904,8 @@ export type ProxyTerminalErrorSummary = {
|
|
|
880
904
|
category: ProxyTerminalErrorCategory;
|
|
881
905
|
requestId?: string;
|
|
882
906
|
account?: string;
|
|
907
|
+
/** Provider-qualified account identity when the failure was attributable. */
|
|
908
|
+
accountKey?: string;
|
|
883
909
|
accountType?: string;
|
|
884
910
|
errorType?: string;
|
|
885
911
|
errorCode?: string;
|
|
@@ -889,12 +915,20 @@ export type ProxyTerminalErrorSummary = {
|
|
|
889
915
|
/** Optional terminal context supplied when a final request error is recorded. */
|
|
890
916
|
export type ProxyTerminalErrorDetails = {
|
|
891
917
|
requestId?: string;
|
|
918
|
+
/** Exact provider-qualified account key when the caller has it. */
|
|
919
|
+
accountKey?: string;
|
|
892
920
|
errorType?: string;
|
|
893
921
|
errorCode?: string;
|
|
894
922
|
terminalOutcome?: string;
|
|
895
923
|
message?: string;
|
|
896
924
|
};
|
|
897
925
|
export type AccountStats = {
|
|
926
|
+
/**
|
|
927
|
+
* Provider-qualified account identity for rows written by current builds.
|
|
928
|
+
* Omitted only by legacy snapshots whose bare map keys are intentionally
|
|
929
|
+
* treated as unattributed rather than guessed at during status rendering.
|
|
930
|
+
*/
|
|
931
|
+
key?: string;
|
|
898
932
|
label: string;
|
|
899
933
|
type: string;
|
|
900
934
|
attemptCount: number;
|
|
@@ -2611,6 +2645,9 @@ export type StatusStats = {
|
|
|
2611
2645
|
/** Whether this status response reconciled shared state or used local memory. */
|
|
2612
2646
|
snapshotSource?: "reconciled" | "memory";
|
|
2613
2647
|
accounts?: {
|
|
2648
|
+
/** Provider-qualified key; null for explicitly unattributed legacy rows. */
|
|
2649
|
+
key?: string | null;
|
|
2650
|
+
provider?: "anthropic" | "codex" | "other" | "unknown";
|
|
2614
2651
|
label: string;
|
|
2615
2652
|
type: string;
|
|
2616
2653
|
attempts?: number;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "12.7.
|
|
3
|
+
"version": "12.7.5",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
|
|
6
6
|
"author": {
|
|
@@ -407,7 +407,7 @@
|
|
|
407
407
|
"zod-to-json-schema": "^3.25.1"
|
|
408
408
|
},
|
|
409
409
|
"peerDependencies": {
|
|
410
|
-
"@juspay/hippocampus": ">=0.1.
|
|
410
|
+
"@juspay/hippocampus": ">=0.1.8",
|
|
411
411
|
"@opentelemetry/api": "^1.9.0",
|
|
412
412
|
"@opentelemetry/sdk-trace-node": "^2.6.0",
|
|
413
413
|
"react": ">=18.0.0",
|