@juspay/neurolink 13.13.0 → 13.13.2
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 -6
- package/dist/auth/tokenStore.d.ts +10 -0
- package/dist/auth/tokenStore.js +36 -0
- package/dist/browser/neurolink.min.js +435 -435
- package/dist/cli/commands/auth.d.ts +14 -1
- package/dist/cli/commands/auth.js +101 -25
- package/dist/cli/factories/authCommandFactory.js +5 -0
- package/dist/core/baseProvider.d.ts +1 -1
- package/dist/core/baseProvider.js +2 -2
- package/dist/core/modules/Utilities.d.ts +1 -1
- package/dist/core/modules/Utilities.js +4 -8
- package/dist/providers/anthropic/client.js +62 -18
- package/dist/providers/ollama/client.d.ts +4 -4
- package/dist/providers/ollama/client.js +5 -5
- package/dist/providers/openaiChatCompletionsBase.js +27 -14
- package/dist/server/routes/codexProxyRoutes.d.ts +2 -2
- package/dist/server/routes/codexProxyRoutes.js +83 -15
- package/dist/types/codex.d.ts +16 -0
- package/dist/types/openaiCompatible.d.ts +2 -0
- package/dist/types/proxy.d.ts +8 -0
- package/dist/types/stream.d.ts +3 -1
- package/dist/utils/timeout.d.ts +8 -0
- package/dist/utils/timeout.js +31 -3
- package/docs-site/static/search-index.json +3 -2
- package/package.json +1 -1
|
@@ -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
|
|
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
|
|
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")
|
|
@@ -835,7 +835,7 @@ export declare abstract class BaseProvider implements AIProvider {
|
|
|
835
835
|
/**
|
|
836
836
|
* Get timeout value in milliseconds - delegated to Utilities
|
|
837
837
|
*/
|
|
838
|
-
getTimeout(options: TextGenerationOptions | StreamOptions): number;
|
|
838
|
+
getTimeout(options: TextGenerationOptions | StreamOptions, operation?: "generate" | "stream"): number;
|
|
839
839
|
/**
|
|
840
840
|
* Check if tool executions should be stored and handle storage
|
|
841
841
|
*/
|
|
@@ -3282,8 +3282,8 @@ export class BaseProvider {
|
|
|
3282
3282
|
/**
|
|
3283
3283
|
* Get timeout value in milliseconds - delegated to Utilities
|
|
3284
3284
|
*/
|
|
3285
|
-
getTimeout(options) {
|
|
3286
|
-
return this.utilities.getTimeout(options);
|
|
3285
|
+
getTimeout(options, operation = "generate") {
|
|
3286
|
+
return this.utilities.getTimeout(options, operation);
|
|
3287
3287
|
}
|
|
3288
3288
|
/**
|
|
3289
3289
|
* Check if tool executions should be stored and handle storage
|
|
@@ -53,7 +53,7 @@ export declare class Utilities {
|
|
|
53
53
|
* Get timeout value in milliseconds from options
|
|
54
54
|
* Supports number or string formats (e.g., '30s', '2m', '1h')
|
|
55
55
|
*/
|
|
56
|
-
getTimeout(options: TextGenerationOptions | StreamOptions): number;
|
|
56
|
+
getTimeout(options: TextGenerationOptions | StreamOptions, operation?: "generate" | "stream"): number;
|
|
57
57
|
/**
|
|
58
58
|
* Get timeout scaled by estimated input token count.
|
|
59
59
|
* For large contexts (>100K tokens), increase timeout proportionally.
|
|
@@ -157,7 +157,7 @@ export class Utilities {
|
|
|
157
157
|
* Get timeout value in milliseconds from options
|
|
158
158
|
* Supports number or string formats (e.g., '30s', '2m', '1h')
|
|
159
159
|
*/
|
|
160
|
-
getTimeout(options) {
|
|
160
|
+
getTimeout(options, operation = "generate") {
|
|
161
161
|
// If caller specified a timeout, use it (supports number ms and string formats)
|
|
162
162
|
if (options.timeout !== undefined && options.timeout !== null) {
|
|
163
163
|
const parsed = parseTimeout(options.timeout);
|
|
@@ -165,13 +165,9 @@ export class Utilities {
|
|
|
165
165
|
return parsed;
|
|
166
166
|
}
|
|
167
167
|
}
|
|
168
|
-
//
|
|
169
|
-
//
|
|
170
|
-
|
|
171
|
-
// infrastructure in BaseProvider.stream(). Both TextGenerationOptions and
|
|
172
|
-
// StreamOptions share the same `input` property, so there is no reliable
|
|
173
|
-
// discriminator to detect streaming at this level.
|
|
174
|
-
const providerDefault = parseTimeout(getDefaultTimeout(this.providerName, "generate"));
|
|
168
|
+
// The caller knows the operation; the two option types share the same
|
|
169
|
+
// shape and cannot be distinguished from their values here.
|
|
170
|
+
const providerDefault = parseTimeout(getDefaultTimeout(this.providerName, operation));
|
|
175
171
|
return providerDefault ?? this.defaultTimeout;
|
|
176
172
|
}
|
|
177
173
|
/**
|
|
@@ -33,7 +33,7 @@ import { resolveRequestKind } from "../../core/resolveRequestKind.js";
|
|
|
33
33
|
import { resolveToolExecutionRecords, toolCallsFromSummaries, } from "../../core/toolExecutionRecorder.js";
|
|
34
34
|
import { transformToolExecutions } from "../../utils/transformationUtils.js";
|
|
35
35
|
import { createAnthropicConfig, getProviderModel, validateApiKey, } from "../../utils/providerConfig.js";
|
|
36
|
-
import { composeAbortSignals, composeAbortSignalsScoped, createTimeoutController, mergeAbortSignals, TimeoutError, } from "../../utils/timeout.js";
|
|
36
|
+
import { composeAbortSignals, composeAbortSignalsScoped, createTimeoutController, mergeAbortSignals, monitorStreamActivity, TimeoutError, } from "../../utils/timeout.js";
|
|
37
37
|
import { pauseDeadlineOf, raceWithAbort } from "../../utils/async/index.js";
|
|
38
38
|
import { normalizeResolvedToolChoice, resolveToolChoice, } from "../../utils/toolChoice.js";
|
|
39
39
|
import { NoOutputGeneratedError } from "../../utils/generationErrors.js";
|
|
@@ -1931,12 +1931,9 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1931
1931
|
// is known good: requestTimeoutMs finite positive, lifetimeTimeoutMs null
|
|
1932
1932
|
// or finite positive or absent.
|
|
1933
1933
|
const control = options.executionControl;
|
|
1934
|
-
//
|
|
1935
|
-
//
|
|
1936
|
-
//
|
|
1937
|
-
// native stream path armed only the provider's own `timeout`, so a caller
|
|
1938
|
-
// asking for a 40-minute turn of 5-minute calls was killed at the shorter
|
|
1939
|
-
// value — and a caller asking for a 200ms turn was not bounded at all.
|
|
1934
|
+
// An explicit turnTimeoutMs remains a whole-turn deadline. Without one,
|
|
1935
|
+
// rely on the resettable stream idle timer; there is no hard lifetime cap.
|
|
1936
|
+
// executionControl keeps its existing lifetime/per-request contract.
|
|
1940
1937
|
const hasValidTurnTimeout = typeof options.turnTimeoutMs === "number" &&
|
|
1941
1938
|
Number.isFinite(options.turnTimeoutMs) &&
|
|
1942
1939
|
options.turnTimeoutMs > 0;
|
|
@@ -1952,13 +1949,24 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1952
1949
|
// that shape removed the turn's ceiling entirely while the caller had said
|
|
1953
1950
|
// nothing at all about it, and TypeScript could not warn because the field
|
|
1954
1951
|
// is `?: number | null`. An absent value means "no opinion", and no
|
|
1955
|
-
// opinion inherits the
|
|
1952
|
+
// opinion inherits the handling below.
|
|
1953
|
+
const idleTimeoutMs = this.getTimeout(options, "stream");
|
|
1956
1954
|
const lifetimeTimeoutMs = control && control.lifetimeTimeoutMs !== undefined
|
|
1957
1955
|
? (control.lifetimeTimeoutMs ?? undefined)
|
|
1958
1956
|
: hasValidTurnTimeout
|
|
1959
1957
|
? options.turnTimeoutMs
|
|
1960
|
-
:
|
|
1958
|
+
: control
|
|
1959
|
+
? this.getTimeout(options)
|
|
1960
|
+
: undefined;
|
|
1961
1961
|
const timeoutController = createTimeoutController(lifetimeTimeoutMs, this.providerName, "stream");
|
|
1962
|
+
// Execution control has its own per-request and lifetime deadline contract.
|
|
1963
|
+
const idleController = control
|
|
1964
|
+
? null
|
|
1965
|
+
: createTimeoutController(idleTimeoutMs, this.providerName, "stream");
|
|
1966
|
+
const cleanupTimeouts = () => {
|
|
1967
|
+
timeoutController?.cleanup();
|
|
1968
|
+
idleController?.cleanup();
|
|
1969
|
+
};
|
|
1962
1970
|
// Consumer-driven abort: fires when the async iterator is closed early
|
|
1963
1971
|
// (caller breaks out of `for await`) so the background loop stops
|
|
1964
1972
|
// reading SSE and running tools.
|
|
@@ -1966,6 +1974,7 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1966
1974
|
const abortSignal = mergeAbortSignals([
|
|
1967
1975
|
options.abortSignal,
|
|
1968
1976
|
timeoutController?.controller.signal,
|
|
1977
|
+
idleController?.controller.signal,
|
|
1969
1978
|
consumerAbortController.signal,
|
|
1970
1979
|
]).signal;
|
|
1971
1980
|
let toolsRecord;
|
|
@@ -2008,7 +2017,7 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2008
2017
|
}
|
|
2009
2018
|
}
|
|
2010
2019
|
catch (setupErr) {
|
|
2011
|
-
|
|
2020
|
+
cleanupTimeouts();
|
|
2012
2021
|
throw this.handleProviderError(setupErr);
|
|
2013
2022
|
}
|
|
2014
2023
|
const modelId = this.modelName || getDefaultAnthropicModel();
|
|
@@ -2040,7 +2049,25 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2040
2049
|
const { push: pushChunk } = channel;
|
|
2041
2050
|
const { usagePromise, finishPromise, resolveUsage, resolveFinish } = createDeferredAnalytics();
|
|
2042
2051
|
let capturedProviderError;
|
|
2043
|
-
|
|
2052
|
+
// The SDK consumes ping events before the adapter sees them. Monitor its
|
|
2053
|
+
// response body so every wire chunk, including heartbeats, resets idle time.
|
|
2054
|
+
const client = idleController
|
|
2055
|
+
? this.client.withOptions({
|
|
2056
|
+
middleware: [
|
|
2057
|
+
...this.client.middleware,
|
|
2058
|
+
async (request, next, context) => {
|
|
2059
|
+
const response = await next(request);
|
|
2060
|
+
return response.ok && context.options?.stream && response.body
|
|
2061
|
+
? new Response(monitorStreamActivity(response.body, idleController.reset), {
|
|
2062
|
+
status: response.status,
|
|
2063
|
+
statusText: response.statusText,
|
|
2064
|
+
headers: response.headers,
|
|
2065
|
+
})
|
|
2066
|
+
: response;
|
|
2067
|
+
},
|
|
2068
|
+
],
|
|
2069
|
+
})
|
|
2070
|
+
: this.client;
|
|
2044
2071
|
// Every attempted call, for the no-output sentinel below; the result
|
|
2045
2072
|
// reports only calls that returned a value, the rule the generate loop
|
|
2046
2073
|
// and Bedrock already follow.
|
|
@@ -2394,12 +2421,29 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2394
2421
|
// The engine's pause for its per-tool deadline goes down too, so
|
|
2395
2422
|
// a confirmation the call waits on does not spend that bound.
|
|
2396
2423
|
const pauseDeadline = pauseDeadlineOf(opts);
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2424
|
+
// No model frames arrive while a tool runs, so the stream idle
|
|
2425
|
+
// timer must not count that time; the tool's own deadline and any
|
|
2426
|
+
// explicit turnTimeoutMs still bound it.
|
|
2427
|
+
const keepAlive = idleController
|
|
2428
|
+
? setInterval(idleController.reset, Math.max(1, Math.min(250, Math.floor(idleTimeoutMs / 2))))
|
|
2429
|
+
: undefined;
|
|
2430
|
+
// A tool that ignores abort and never settles must not keep the
|
|
2431
|
+
// process alive through this timer.
|
|
2432
|
+
keepAlive?.unref();
|
|
2433
|
+
try {
|
|
2434
|
+
return await execute(args, {
|
|
2435
|
+
toolCallId: ctx.toolCallId ?? "",
|
|
2436
|
+
...(ctx.abortSignal ? { abortSignal: ctx.abortSignal } : {}),
|
|
2437
|
+
...(pauseDeadline ? { pauseDeadline } : {}),
|
|
2438
|
+
messages: [],
|
|
2439
|
+
});
|
|
2440
|
+
}
|
|
2441
|
+
finally {
|
|
2442
|
+
if (keepAlive) {
|
|
2443
|
+
clearInterval(keepAlive);
|
|
2444
|
+
}
|
|
2445
|
+
idleController?.reset();
|
|
2446
|
+
}
|
|
2403
2447
|
},
|
|
2404
2448
|
};
|
|
2405
2449
|
}
|
|
@@ -2587,7 +2631,7 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2587
2631
|
pushChunk({ content: output });
|
|
2588
2632
|
}
|
|
2589
2633
|
}
|
|
2590
|
-
|
|
2634
|
+
cleanupTimeouts();
|
|
2591
2635
|
channel.close();
|
|
2592
2636
|
});
|
|
2593
2637
|
loopPromise.catch(() => {
|
|
@@ -37,14 +37,14 @@ export declare class OllamaProvider extends OpenAIChatCompletionsProvider {
|
|
|
37
37
|
*/
|
|
38
38
|
supportsTools(): boolean;
|
|
39
39
|
/**
|
|
40
|
-
* Local models are slow; the base
|
|
41
|
-
*
|
|
42
|
-
* `OLLAMA_TIMEOUT` env override
|
|
40
|
+
* Local models are slow; the base defaults Ollama generation to 5 minutes
|
|
41
|
+
* and streaming idle time to 2 minutes, and honors a per-call `options.timeout`.
|
|
42
|
+
* Preserve the legacy `OLLAMA_TIMEOUT` env override, applied only
|
|
43
43
|
* when no explicit per-call timeout is set. Parsed with the shared
|
|
44
44
|
* `parseTimeout` so both millisecond numbers ("240000") and duration strings
|
|
45
45
|
* ("4m", "30s") work; a malformed value is ignored in favour of the default.
|
|
46
46
|
*/
|
|
47
|
-
getTimeout(options: TextGenerationOptions | StreamOptions): number;
|
|
47
|
+
getTimeout(options: TextGenerationOptions | StreamOptions, operation?: "generate" | "stream"): number;
|
|
48
48
|
/**
|
|
49
49
|
* Health check: probe `/v1/models` and require at least one installed model.
|
|
50
50
|
* A reachable server with zero models would let `resolveModelName()` fall
|
|
@@ -159,14 +159,14 @@ export class OllamaProvider extends OpenAIChatCompletionsProvider {
|
|
|
159
159
|
return isToolCapable;
|
|
160
160
|
}
|
|
161
161
|
/**
|
|
162
|
-
* Local models are slow; the base
|
|
163
|
-
*
|
|
164
|
-
* `OLLAMA_TIMEOUT` env override
|
|
162
|
+
* Local models are slow; the base defaults Ollama generation to 5 minutes
|
|
163
|
+
* and streaming idle time to 2 minutes, and honors a per-call `options.timeout`.
|
|
164
|
+
* Preserve the legacy `OLLAMA_TIMEOUT` env override, applied only
|
|
165
165
|
* when no explicit per-call timeout is set. Parsed with the shared
|
|
166
166
|
* `parseTimeout` so both millisecond numbers ("240000") and duration strings
|
|
167
167
|
* ("4m", "30s") work; a malformed value is ignored in favour of the default.
|
|
168
168
|
*/
|
|
169
|
-
getTimeout(options) {
|
|
169
|
+
getTimeout(options, operation = "generate") {
|
|
170
170
|
if (options.timeout === undefined || options.timeout === null) {
|
|
171
171
|
const envTimeout = process.env.OLLAMA_TIMEOUT?.trim();
|
|
172
172
|
if (envTimeout) {
|
|
@@ -182,7 +182,7 @@ export class OllamaProvider extends OpenAIChatCompletionsProvider {
|
|
|
182
182
|
}
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
|
-
return super.getTimeout(options);
|
|
185
|
+
return super.getTimeout(options, operation);
|
|
186
186
|
}
|
|
187
187
|
/**
|
|
188
188
|
* Health check: probe `/v1/models` and require at least one installed model.
|
|
@@ -34,7 +34,7 @@ import { logger } from "../utils/logger.js";
|
|
|
34
34
|
import { redactUrlCredentials } from "../utils/logSanitize.js";
|
|
35
35
|
import { NoOutputGeneratedError } from "../utils/generationErrors.js";
|
|
36
36
|
import { buildNoOutputSentinel, stampNoOutputSpan, } from "../utils/noOutputSentinel.js";
|
|
37
|
-
import { composeAbortSignalsScoped, createTimeoutController, mergeAbortSignals, TimeoutError, } from "../utils/timeout.js";
|
|
37
|
+
import { composeAbortSignalsScoped, createTimeoutController, getStreamLifetimeTimeout, mergeAbortSignals, monitorStreamActivity, TimeoutError, } from "../utils/timeout.js";
|
|
38
38
|
import { resolveRequestKind } from "../core/resolveRequestKind.js";
|
|
39
39
|
import { appendJsonSchemaInstruction, hasNativeDoGenerate, parseToolInput, resolveStepToolChoice, runNativeGenerateLoop, toNativeToolDeclaration, toPrepareStepRecord, validateToolInput, } from "../core/nativeGenerateLoop.js";
|
|
40
40
|
import { resolveToolExecutionRecords, toolCallsFromSummaries, } from "../core/toolExecutionRecorder.js";
|
|
@@ -728,12 +728,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
728
728
|
// the whole point of the SSE wire is that a slow-but-alive
|
|
729
729
|
// completion keeps the connection (and the timer) fed.
|
|
730
730
|
const monitored = timeoutController
|
|
731
|
-
? res.body.
|
|
732
|
-
transform(chunk, controller) {
|
|
733
|
-
timeoutController.reset();
|
|
734
|
-
controller.enqueue(chunk);
|
|
735
|
-
},
|
|
736
|
-
}))
|
|
731
|
+
? monitorStreamActivity(res.body, timeoutController.reset)
|
|
737
732
|
: res.body;
|
|
738
733
|
const sse = await parseSSEStream(monitored, () => { });
|
|
739
734
|
// Re-shape the aggregate into the JSON-wire response so every
|
|
@@ -1576,8 +1571,13 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
1576
1571
|
async executeStream(options, _analysisSchema) {
|
|
1577
1572
|
this.validateStreamOptions(options);
|
|
1578
1573
|
const startTime = Date.now();
|
|
1579
|
-
const timeout = this.getTimeout(options);
|
|
1574
|
+
const timeout = this.getTimeout(options, "stream");
|
|
1580
1575
|
const timeoutController = createTimeoutController(timeout, this.providerName, "stream");
|
|
1576
|
+
const lifetimeController = createTimeoutController(getStreamLifetimeTimeout(options.turnTimeoutMs), this.providerName, "stream");
|
|
1577
|
+
const cleanupTimeouts = () => {
|
|
1578
|
+
timeoutController?.cleanup();
|
|
1579
|
+
lifetimeController?.cleanup();
|
|
1580
|
+
};
|
|
1581
1581
|
// Consumer-driven abort: fires when the async iterator is closed early
|
|
1582
1582
|
// (caller breaks out of `for await`). Without this the background
|
|
1583
1583
|
// `loopPromise` keeps reading SSE and running tools indefinitely.
|
|
@@ -1585,6 +1585,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
1585
1585
|
const abortSignal = mergeAbortSignals([
|
|
1586
1586
|
options.abortSignal,
|
|
1587
1587
|
timeoutController?.controller.signal,
|
|
1588
|
+
lifetimeController?.controller.signal,
|
|
1588
1589
|
consumerAbortController.signal,
|
|
1589
1590
|
]).signal;
|
|
1590
1591
|
let modelId;
|
|
@@ -1619,7 +1620,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
1619
1620
|
promptMessages = (await this.buildMessagesForStream(options));
|
|
1620
1621
|
}
|
|
1621
1622
|
catch (setupErr) {
|
|
1622
|
-
|
|
1623
|
+
cleanupTimeouts();
|
|
1623
1624
|
throw setupErr;
|
|
1624
1625
|
}
|
|
1625
1626
|
// Structured output rides `response_format`, mirroring the generate
|
|
@@ -1732,6 +1733,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
1732
1733
|
url,
|
|
1733
1734
|
fetchImpl,
|
|
1734
1735
|
abortSignal,
|
|
1736
|
+
onStreamActivity: timeoutController?.reset,
|
|
1735
1737
|
options: sampled,
|
|
1736
1738
|
conversation,
|
|
1737
1739
|
openAITools,
|
|
@@ -1815,7 +1817,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
1815
1817
|
catch (error) {
|
|
1816
1818
|
consumerAbortController.abort();
|
|
1817
1819
|
channel.close();
|
|
1818
|
-
|
|
1820
|
+
cleanupTimeouts();
|
|
1819
1821
|
throw error;
|
|
1820
1822
|
}
|
|
1821
1823
|
// Closure-scoped capture: the runStreamLoop's catch block stashes the
|
|
@@ -1974,7 +1976,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
1974
1976
|
});
|
|
1975
1977
|
resolveFinish("stop");
|
|
1976
1978
|
}
|
|
1977
|
-
|
|
1979
|
+
cleanupTimeouts();
|
|
1978
1980
|
if (!consumerAbortController.signal.aborted) {
|
|
1979
1981
|
consumerAbortController.abort();
|
|
1980
1982
|
}
|
|
@@ -2037,15 +2039,23 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
2037
2039
|
duration: s.endTime.getTime() - s.startTime.getTime(),
|
|
2038
2040
|
}))),
|
|
2039
2041
|
});
|
|
2042
|
+
// The structured-output re-ask runs after the loop settles and is still
|
|
2043
|
+
// inside the turn, so an explicit turnTimeoutMs stays armed until the
|
|
2044
|
+
// stream generator's own cleanup. Only the idle timer ends with the loop.
|
|
2040
2045
|
loopPromise
|
|
2041
|
-
?.finally(() =>
|
|
2046
|
+
?.finally(() => {
|
|
2047
|
+
timeoutController?.cleanup();
|
|
2048
|
+
if (!options.schema) {
|
|
2049
|
+
lifetimeController?.cleanup();
|
|
2050
|
+
}
|
|
2051
|
+
})
|
|
2042
2052
|
.catch((error) => {
|
|
2043
2053
|
captureProviderError(error);
|
|
2044
2054
|
});
|
|
2045
2055
|
return result;
|
|
2046
2056
|
}
|
|
2047
2057
|
async runStreamLoop(args) {
|
|
2048
|
-
const { maxSteps, modelId, url, fetchImpl, abortSignal, options, conversation, openAITools, stepToolChoice, toolsRecord, toolNameFromWire, toolsUsed, toolExecutionSummaries, pushChunk, closeChannel, resolveUsage, resolveFinish, responseFormat, onModelObserved, } = args;
|
|
2058
|
+
const { maxSteps, modelId, url, fetchImpl, abortSignal, options, conversation, openAITools, stepToolChoice, toolsRecord, toolNameFromWire, toolsUsed, toolExecutionSummaries, pushChunk, closeChannel, resolveUsage, resolveFinish, responseFormat, onModelObserved, onStreamActivity, } = args;
|
|
2049
2059
|
// Hoisted above the try so the catch can resolve the usage accumulated
|
|
2050
2060
|
// by steps that completed BEFORE the failure — those steps were billed.
|
|
2051
2061
|
let stepFinish = null;
|
|
@@ -2152,6 +2162,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
2152
2162
|
openAIToolChoice,
|
|
2153
2163
|
pushChunk,
|
|
2154
2164
|
responseFormat,
|
|
2165
|
+
onStreamActivity,
|
|
2155
2166
|
}));
|
|
2156
2167
|
lastObservedPromptTokens = stepResult.usage?.prompt_tokens;
|
|
2157
2168
|
stepFinish = stepResult.finishReason;
|
|
@@ -2382,7 +2393,9 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
2382
2393
|
if (!res.body) {
|
|
2383
2394
|
throw new Error(`${this.providerName}: stream response had no body`);
|
|
2384
2395
|
}
|
|
2385
|
-
return parseSSEStream(
|
|
2396
|
+
return parseSSEStream(args.onStreamActivity
|
|
2397
|
+
? monitorStreamActivity(res.body, args.onStreamActivity)
|
|
2398
|
+
: res.body, (delta) => {
|
|
2386
2399
|
args.pushChunk({ content: delta });
|
|
2387
2400
|
}, (reasoningDelta) => {
|
|
2388
2401
|
// Reasoning rides alongside an empty `content` so plain-text
|
|
@@ -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
|
|
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
|
|
30
|
+
expiresAt: number;
|
|
31
31
|
}>;
|
|
32
32
|
/**
|
|
33
33
|
* Load the Codex account pool from the token store, refreshing expired OAuth
|