Compare commits
6 Commits
main
...
worktree-t
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d45ffa4fa | ||
|
|
ada094c6de | ||
|
|
18651ae5ec | ||
|
|
1101999dae | ||
|
|
436c41fb19 | ||
|
|
fe6c8bd5d6 |
@ -1262,6 +1262,17 @@ const SETTINGS_SCHEMA = {
|
||||
parentKey: 'generationConfig',
|
||||
showInDialog: false,
|
||||
},
|
||||
bodyTimeout: {
|
||||
type: 'number',
|
||||
label: 'Body Timeout',
|
||||
category: 'Generation Configuration',
|
||||
requiresRestart: false,
|
||||
default: 0,
|
||||
description:
|
||||
'Streaming body timeout in milliseconds. Maximum idle time allowed between data chunks during streaming. Set to 0 (default) to disable the body timeout, which prevents timeout errors with slow local model servers (Ollama, mlx_lm.server). Set a positive value to impose a safety timeout between chunks.',
|
||||
parentKey: 'generationConfig',
|
||||
showInDialog: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@ -177,12 +177,10 @@ export class AnthropicContentGenerator implements ContentGenerator {
|
||||
const useProxyIdentity = !isAnthropicNativeBaseUrl(contentGeneratorConfig);
|
||||
const defaultHeaders = this.buildHeaders(useProxyIdentity);
|
||||
const baseURL = contentGeneratorConfig.baseUrl;
|
||||
// Configure fetch options for proxy support and timeout handling.
|
||||
// With proxy, dispatcher timeouts are disabled so SDK timeout controls the
|
||||
// request; without proxy, no custom dispatcher is installed.
|
||||
const runtimeOptions = buildRuntimeFetchOptions(
|
||||
'anthropic',
|
||||
this.cliConfig.getProxy(),
|
||||
{ bodyTimeout: this.contentGeneratorConfig.bodyTimeout },
|
||||
);
|
||||
|
||||
// IdeaLab-style Anthropic proxies expect `Authorization: Bearer <token>`
|
||||
|
||||
@ -80,7 +80,8 @@ export type ContentGeneratorConfig = {
|
||||
authType?: AuthType | undefined;
|
||||
enableOpenAILogging?: boolean;
|
||||
openAILoggingDir?: string;
|
||||
timeout?: number; // Timeout configuration in milliseconds
|
||||
timeout?: number; // Total request timeout in milliseconds (hard deadline from request start)
|
||||
bodyTimeout?: number; // Inter-chunk idle timeout for streaming (ms). 0 = disabled (default).
|
||||
maxRetries?: number; // Maximum retries for rate-limit errors
|
||||
retryErrorCodes?: number[]; // Additional error codes that trigger rate-limit retry
|
||||
enableCacheControl?: boolean; // Enable cache control for DashScope providers
|
||||
|
||||
@ -74,7 +74,7 @@ describe('DashScopeOpenAICompatibleProvider', () => {
|
||||
buildRuntimeFetchOptions as unknown as MockedFunction<
|
||||
(sdkType: 'openai', proxyUrl?: string) => OpenAIRuntimeFetchOptions
|
||||
>;
|
||||
mockedBuildRuntimeFetchOptions.mockReturnValue(undefined);
|
||||
mockedBuildRuntimeFetchOptions.mockReturnValue({});
|
||||
|
||||
// Mock ContentGeneratorConfig
|
||||
mockContentGeneratorConfig = {
|
||||
|
||||
@ -140,12 +140,10 @@ export class DashScopeOpenAICompatibleProvider extends DefaultOpenAICompatiblePr
|
||||
maxRetries = DEFAULT_MAX_RETRIES,
|
||||
} = this.contentGeneratorConfig;
|
||||
const defaultHeaders = this.buildHeaders();
|
||||
// Configure fetch options for proxy support and timeout handling.
|
||||
// With proxy, dispatcher timeouts are disabled so SDK timeout controls the
|
||||
// request; without proxy, no custom dispatcher is installed.
|
||||
const runtimeOptions = buildRuntimeFetchOptions(
|
||||
'openai',
|
||||
this.cliConfig.getProxy(),
|
||||
{ bodyTimeout: this.contentGeneratorConfig.bodyTimeout },
|
||||
);
|
||||
return new OpenAI({
|
||||
apiKey,
|
||||
@ -153,7 +151,7 @@ export class DashScopeOpenAICompatibleProvider extends DefaultOpenAICompatiblePr
|
||||
timeout,
|
||||
maxRetries,
|
||||
defaultHeaders,
|
||||
...(runtimeOptions || {}),
|
||||
...runtimeOptions,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -47,7 +47,7 @@ describe('DefaultOpenAICompatibleProvider', () => {
|
||||
buildRuntimeFetchOptions as unknown as MockedFunction<
|
||||
(sdkType: 'openai', proxyUrl?: string) => OpenAIRuntimeFetchOptions
|
||||
>;
|
||||
mockedBuildRuntimeFetchOptions.mockReturnValue(undefined);
|
||||
mockedBuildRuntimeFetchOptions.mockReturnValue({});
|
||||
|
||||
// Mock ContentGeneratorConfig
|
||||
mockContentGeneratorConfig = {
|
||||
|
||||
@ -81,12 +81,10 @@ export class DefaultOpenAICompatibleProvider
|
||||
maxRetries = DEFAULT_MAX_RETRIES,
|
||||
} = this.contentGeneratorConfig;
|
||||
const defaultHeaders = this.buildHeaders();
|
||||
// Configure fetch options for proxy support and timeout handling.
|
||||
// With proxy, dispatcher timeouts are disabled so SDK timeout controls the
|
||||
// request; without proxy, no custom dispatcher is installed.
|
||||
const runtimeOptions = buildRuntimeFetchOptions(
|
||||
'openai',
|
||||
this.cliConfig.getProxy(),
|
||||
{ bodyTimeout: this.contentGeneratorConfig.bodyTimeout },
|
||||
);
|
||||
return new OpenAI({
|
||||
apiKey,
|
||||
@ -94,7 +92,7 @@ export class DefaultOpenAICompatibleProvider
|
||||
timeout,
|
||||
maxRetries,
|
||||
defaultHeaders,
|
||||
...(runtimeOptions || {}),
|
||||
...runtimeOptions,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -31,6 +31,7 @@ export const MODEL_GENERATION_CONFIG_FIELDS = [
|
||||
'extra_body',
|
||||
'modalities',
|
||||
'splitToolMedia',
|
||||
'bodyTimeout',
|
||||
] as const satisfies ReadonlyArray<keyof ContentGeneratorConfig>;
|
||||
|
||||
/**
|
||||
|
||||
@ -39,6 +39,7 @@ export type ModelGenerationConfig = Pick<
|
||||
| 'contextWindowSize'
|
||||
| 'modalities'
|
||||
| 'splitToolMedia'
|
||||
| 'bodyTimeout'
|
||||
>;
|
||||
|
||||
/**
|
||||
|
||||
@ -77,14 +77,29 @@ describe('buildRuntimeFetchOptions (node runtime)', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
it('returns undefined for OpenAI when no proxy is set', () => {
|
||||
it('returns dispatcher with bodyTimeout=0 for OpenAI when no proxy is set', () => {
|
||||
const result = buildRuntimeFetchOptions('openai');
|
||||
expect(result).toBeUndefined();
|
||||
expect(result).toBeDefined();
|
||||
const dispatcher = (
|
||||
result as { fetchOptions?: { dispatcher?: { options?: UndiciOptions } } }
|
||||
).fetchOptions?.dispatcher;
|
||||
expect(dispatcher?.options).toMatchObject({
|
||||
bodyTimeout: 0,
|
||||
headersTimeout: 0,
|
||||
keepAliveTimeout: 60_000,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns empty object for Anthropic when no proxy is set', () => {
|
||||
it('returns dispatcher with bodyTimeout=0 for Anthropic when no proxy is set', () => {
|
||||
const result = buildRuntimeFetchOptions('anthropic');
|
||||
expect(result).toEqual({});
|
||||
expect(result).toBeDefined();
|
||||
const dispatcher = (
|
||||
result as { fetchOptions?: { dispatcher?: { options?: UndiciOptions } } }
|
||||
).fetchOptions?.dispatcher;
|
||||
expect(dispatcher?.options).toMatchObject({
|
||||
bodyTimeout: 0,
|
||||
headersTimeout: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('uses ProxyAgent with disabled timeouts when proxy is set', () => {
|
||||
@ -139,22 +154,113 @@ describe('buildRuntimeFetchOptions (node runtime)', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('does not inject a fetch override when no proxy is set', () => {
|
||||
// No-proxy path must stay on the runtime's built-in fetch — see the
|
||||
// comment in buildFetchOptionsWithDispatcher() in runtimeFetchOptions.ts
|
||||
// about avoiding version-mismatch issues on code paths
|
||||
// that don't need a custom dispatcher.
|
||||
it('pins fetch to undici when no proxy is set (dispatcher version compatibility)', () => {
|
||||
const openaiResult = buildRuntimeFetchOptions('openai');
|
||||
expect(openaiResult).toBeUndefined();
|
||||
expect((openaiResult as { fetch?: unknown }).fetch).toBe(mockUndiciFetch);
|
||||
|
||||
const anthropicResult = buildRuntimeFetchOptions('anthropic');
|
||||
expect((anthropicResult as { fetch?: unknown }).fetch).toBeUndefined();
|
||||
expect((anthropicResult as { fetch?: unknown }).fetch).toBe(
|
||||
mockUndiciFetch,
|
||||
);
|
||||
});
|
||||
|
||||
it('returns undefined for OpenAI when dispatcher creation fails', () => {
|
||||
it('ignores custom bodyTimeout when proxy is set (proxy hardcodes bodyTimeout: 0)', () => {
|
||||
const result = buildRuntimeFetchOptions('openai', 'http://proxy.local', {
|
||||
bodyTimeout: 60000,
|
||||
});
|
||||
const dispatcher = (
|
||||
result as { fetchOptions?: { dispatcher?: { options?: UndiciOptions } } }
|
||||
).fetchOptions?.dispatcher;
|
||||
expect(dispatcher?.options).toMatchObject({
|
||||
uri: 'http://proxy.local',
|
||||
bodyTimeout: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('respects custom bodyTimeout option in no-proxy path', () => {
|
||||
const result = buildRuntimeFetchOptions('openai', undefined, {
|
||||
bodyTimeout: 60000,
|
||||
});
|
||||
const dispatcher = (
|
||||
result as { fetchOptions?: { dispatcher?: { options?: UndiciOptions } } }
|
||||
).fetchOptions?.dispatcher;
|
||||
expect(dispatcher?.options).toMatchObject({
|
||||
bodyTimeout: 60000,
|
||||
headersTimeout: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('caches no-proxy dispatchers by bodyTimeout value', () => {
|
||||
const result1 = buildRuntimeFetchOptions('openai', undefined, {
|
||||
bodyTimeout: 0,
|
||||
});
|
||||
const result2 = buildRuntimeFetchOptions('openai', undefined, {
|
||||
bodyTimeout: 0,
|
||||
});
|
||||
const dispatcher1 = (
|
||||
result1 as {
|
||||
fetchOptions?: { dispatcher?: { options?: UndiciOptions } };
|
||||
}
|
||||
).fetchOptions?.dispatcher;
|
||||
const dispatcher2 = (
|
||||
result2 as {
|
||||
fetchOptions?: { dispatcher?: { options?: UndiciOptions } };
|
||||
}
|
||||
).fetchOptions?.dispatcher;
|
||||
expect(dispatcher1).toBe(dispatcher2);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ input: -1, expected: 0, label: 'negative', shouldWarn: true },
|
||||
{ input: 3.14, expected: 0, label: 'float', shouldWarn: true },
|
||||
{ input: NaN, expected: 0, label: 'NaN', shouldWarn: true },
|
||||
{ input: Infinity, expected: 0, label: 'Infinity', shouldWarn: true },
|
||||
{ input: undefined, expected: 0, label: 'undefined', shouldWarn: false },
|
||||
{ input: 0, expected: 0, label: 'zero', shouldWarn: false },
|
||||
{
|
||||
input: 60000,
|
||||
expected: 60000,
|
||||
label: 'positive integer',
|
||||
shouldWarn: false,
|
||||
},
|
||||
])(
|
||||
'sanitizes invalid bodyTimeout ($label → $expected)',
|
||||
({ input, expected, shouldWarn }) => {
|
||||
const result = buildRuntimeFetchOptions('openai', undefined, {
|
||||
bodyTimeout: input as number,
|
||||
});
|
||||
const dispatcher = (
|
||||
result as {
|
||||
fetchOptions?: { dispatcher?: { options?: UndiciOptions } };
|
||||
}
|
||||
).fetchOptions?.dispatcher;
|
||||
expect(dispatcher?.options).toMatchObject({
|
||||
bodyTimeout: expected,
|
||||
headersTimeout: 0,
|
||||
});
|
||||
if (shouldWarn) {
|
||||
expect(mockWarn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Invalid bodyTimeout'),
|
||||
);
|
||||
} else {
|
||||
expect(mockWarn).not.toHaveBeenCalledWith(
|
||||
expect.stringContaining('Invalid bodyTimeout'),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('falls back to no-proxy dispatcher when proxy creation fails (OpenAI)', () => {
|
||||
const result = buildRuntimeFetchOptions('openai', 'http://invalid-proxy');
|
||||
// Should fallback to undefined (no dispatcher) on error
|
||||
expect(result).toBeUndefined();
|
||||
// Should fallback to a no-proxy Agent with bodyTimeout preserved
|
||||
expect(result).toBeDefined();
|
||||
const dispatcher = (
|
||||
result as { fetchOptions?: { dispatcher?: { options?: UndiciOptions } } }
|
||||
).fetchOptions?.dispatcher;
|
||||
expect(dispatcher?.options).toMatchObject({
|
||||
bodyTimeout: 0,
|
||||
headersTimeout: 0,
|
||||
});
|
||||
// Should log the failure for visibility
|
||||
expect(mockWarn).toHaveBeenCalledOnce();
|
||||
expect(mockWarn).toHaveBeenCalledWith(
|
||||
@ -167,13 +273,20 @@ describe('buildRuntimeFetchOptions (node runtime)', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('returns empty object for Anthropic when dispatcher creation fails', () => {
|
||||
it('falls back to no-proxy dispatcher when proxy creation fails (Anthropic)', () => {
|
||||
const result = buildRuntimeFetchOptions(
|
||||
'anthropic',
|
||||
'http://invalid-proxy',
|
||||
);
|
||||
// Should fallback to empty object on error
|
||||
expect(result).toEqual({});
|
||||
// Should fallback to a no-proxy Agent with bodyTimeout preserved
|
||||
expect(result).toBeDefined();
|
||||
const dispatcher = (
|
||||
result as { fetchOptions?: { dispatcher?: { options?: UndiciOptions } } }
|
||||
).fetchOptions?.dispatcher;
|
||||
expect(dispatcher?.options).toMatchObject({
|
||||
bodyTimeout: 0,
|
||||
headersTimeout: 0,
|
||||
});
|
||||
// Should log the failure for visibility
|
||||
expect(mockWarn).toHaveBeenCalledOnce();
|
||||
expect(mockWarn).toHaveBeenCalledWith(
|
||||
@ -186,11 +299,39 @@ describe('buildRuntimeFetchOptions (node runtime)', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves custom bodyTimeout in proxy-failure fallback', () => {
|
||||
const result = buildRuntimeFetchOptions('openai', 'http://invalid-proxy', {
|
||||
bodyTimeout: 60000,
|
||||
});
|
||||
const dispatcher = (
|
||||
result as { fetchOptions?: { dispatcher?: { options?: UndiciOptions } } }
|
||||
).fetchOptions?.dispatcher;
|
||||
expect(dispatcher?.options).toMatchObject({
|
||||
bodyTimeout: 60000,
|
||||
headersTimeout: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns different dispatchers for different bodyTimeout values', () => {
|
||||
const result0 = buildRuntimeFetchOptions('openai', undefined, {
|
||||
bodyTimeout: 0,
|
||||
});
|
||||
const result60k = buildRuntimeFetchOptions('openai', undefined, {
|
||||
bodyTimeout: 60000,
|
||||
});
|
||||
const dispatcher0 = (result0 as { fetchOptions?: { dispatcher?: unknown } })
|
||||
.fetchOptions?.dispatcher;
|
||||
const dispatcher60k = (
|
||||
result60k as { fetchOptions?: { dispatcher?: unknown } }
|
||||
).fetchOptions?.dispatcher;
|
||||
expect(dispatcher0).not.toBe(dispatcher60k);
|
||||
});
|
||||
|
||||
it('redacts credentials from proxy URL in error message', () => {
|
||||
// http://invalid-proxy triggers dispatcher failure whose error message
|
||||
// contains credentials that should be redacted
|
||||
const result = buildRuntimeFetchOptions('openai', 'http://invalid-proxy');
|
||||
expect(result).toBeUndefined();
|
||||
expect(result).toBeDefined();
|
||||
// Should redact credentials in the log message
|
||||
expect(mockWarn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('<redacted>'),
|
||||
|
||||
@ -4,7 +4,12 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { ProxyAgent, fetch as undiciFetch, type Dispatcher } from 'undici';
|
||||
import {
|
||||
Agent,
|
||||
ProxyAgent,
|
||||
fetch as undiciFetch,
|
||||
type Dispatcher,
|
||||
} from 'undici';
|
||||
|
||||
import { createDebugLogger } from './debugLogger.js';
|
||||
|
||||
@ -31,21 +36,14 @@ export function detectRuntime(): Runtime {
|
||||
/**
|
||||
* Runtime fetch options for OpenAI SDK
|
||||
*/
|
||||
export type OpenAIRuntimeFetchOptions =
|
||||
| {
|
||||
fetchOptions?: {
|
||||
dispatcher?: Dispatcher;
|
||||
timeout?: false;
|
||||
};
|
||||
// Optional fetch override. When a custom dispatcher is being passed,
|
||||
// we pin this to the bundled undici's fetch so the dispatcher and
|
||||
// fetch share a single undici version — otherwise Node's built-in
|
||||
// fetch (newer undici) rejects a ProxyAgent from the bundled undici
|
||||
// (e.g. v6) with `invalid onError method`.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
fetch?: any;
|
||||
}
|
||||
| undefined;
|
||||
export type OpenAIRuntimeFetchOptions = {
|
||||
fetchOptions?: {
|
||||
dispatcher?: Dispatcher;
|
||||
timeout?: false;
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
fetch?: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* Runtime fetch options for Anthropic SDK
|
||||
@ -63,12 +61,21 @@ export type AnthropicRuntimeFetchOptions = {
|
||||
*/
|
||||
export type SDKType = 'openai' | 'anthropic';
|
||||
|
||||
/**
|
||||
* Options for configuring fetch behavior.
|
||||
*/
|
||||
export interface RuntimeFetchBehaviorOptions {
|
||||
/** Streaming body timeout in ms. 0 = disabled (default). */
|
||||
bodyTimeout?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build runtime-specific fetch options for OpenAI SDK
|
||||
*/
|
||||
export function buildRuntimeFetchOptions(
|
||||
sdkType: 'openai',
|
||||
proxyUrl?: string,
|
||||
options?: RuntimeFetchBehaviorOptions,
|
||||
): OpenAIRuntimeFetchOptions;
|
||||
/**
|
||||
* Build runtime-specific fetch options for Anthropic SDK
|
||||
@ -76,6 +83,7 @@ export function buildRuntimeFetchOptions(
|
||||
export function buildRuntimeFetchOptions(
|
||||
sdkType: 'anthropic',
|
||||
proxyUrl?: string,
|
||||
options?: RuntimeFetchBehaviorOptions,
|
||||
): AnthropicRuntimeFetchOptions;
|
||||
/**
|
||||
* Build runtime-specific fetch options based on the detected runtime and SDK type
|
||||
@ -83,22 +91,29 @@ export function buildRuntimeFetchOptions(
|
||||
* across Node.js and Bun, ensuring user-configured timeout works as expected.
|
||||
*
|
||||
* @param sdkType - The SDK type ('openai' or 'anthropic') to determine return type
|
||||
* @param proxyUrl - Optional proxy URL
|
||||
* @param options - Optional behavior configuration (bodyTimeout, etc.)
|
||||
* @returns Runtime-specific options compatible with the specified SDK
|
||||
*/
|
||||
export function buildRuntimeFetchOptions(
|
||||
sdkType: SDKType,
|
||||
proxyUrl?: string,
|
||||
options?: RuntimeFetchBehaviorOptions,
|
||||
): OpenAIRuntimeFetchOptions | AnthropicRuntimeFetchOptions {
|
||||
const runtime = detectRuntime();
|
||||
|
||||
// When using a custom dispatcher (proxy mode), disable undici timeouts (set to 0)
|
||||
// to let SDK's timeout parameter control the total request time. This ensures
|
||||
// user-configured timeouts work as expected for long-running requests.
|
||||
// When no proxy is configured, the runtime's built-in fetch is used with its
|
||||
// default timeout behavior.
|
||||
// All Node.js paths use a custom undici dispatcher with configurable bodyTimeout.
|
||||
// With proxy: ProxyAgent with bodyTimeout=0 (SDK timeout controls the request).
|
||||
// Without proxy: plain Agent with configurable bodyTimeout (default 0 = disabled).
|
||||
// Bun: uses its own timeout: false mechanism.
|
||||
|
||||
switch (runtime) {
|
||||
case 'bun': {
|
||||
if (options?.bodyTimeout && options.bodyTimeout > 0) {
|
||||
debugLogger.warn(
|
||||
`bodyTimeout setting (${options.bodyTimeout}ms) is not supported on Bun runtime (all timeouts are disabled via timeout: false).`,
|
||||
);
|
||||
}
|
||||
if (sdkType === 'openai') {
|
||||
// Bun: Disable built-in 300s timeout to let OpenAI SDK timeout control
|
||||
// This ensures user-configured timeout works as expected without interference
|
||||
@ -130,15 +145,15 @@ export function buildRuntimeFetchOptions(
|
||||
}
|
||||
|
||||
case 'node': {
|
||||
// Node.js: Use a custom undici dispatcher only when a proxy is configured.
|
||||
// Proxy dispatchers disable undici timeouts so SDK timeout controls the
|
||||
// total request time; no-proxy calls use the runtime's built-in fetch.
|
||||
return buildFetchOptionsWithDispatcher(sdkType, proxyUrl);
|
||||
// Node.js: Use a custom undici dispatcher to control body timeout.
|
||||
// With proxy: routes through ProxyAgent with bodyTimeout disabled.
|
||||
// Without proxy: uses plain Agent with configurable bodyTimeout.
|
||||
return buildFetchOptionsWithDispatcher(sdkType, proxyUrl, options);
|
||||
}
|
||||
|
||||
default: {
|
||||
// Unknown runtime: treat as Node.js-like environment.
|
||||
return buildFetchOptionsWithDispatcher(sdkType, proxyUrl);
|
||||
return buildFetchOptionsWithDispatcher(sdkType, proxyUrl, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -149,21 +164,32 @@ export function buildRuntimeFetchOptions(
|
||||
*/
|
||||
const dispatcherCache = new Map<string, Dispatcher>();
|
||||
|
||||
/**
|
||||
* Cache of no-proxy Agent dispatchers keyed by bodyTimeout value.
|
||||
*/
|
||||
const noProxyDispatcherCache = new Map<number, Dispatcher>();
|
||||
|
||||
function getOrCreateNoProxyDispatcher(bodyTimeout: number): Dispatcher {
|
||||
const cached = noProxyDispatcherCache.get(bodyTimeout);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const dispatcher = new Agent({
|
||||
bodyTimeout,
|
||||
headersTimeout: 0,
|
||||
keepAliveTimeout: 60_000,
|
||||
});
|
||||
|
||||
noProxyDispatcherCache.set(bodyTimeout, dispatcher);
|
||||
return dispatcher;
|
||||
}
|
||||
|
||||
/**
|
||||
* Proxy dispatcher creation failure counts keyed by sanitized host.
|
||||
*/
|
||||
const proxyFailureCounts = new Map<string, number>();
|
||||
|
||||
/**
|
||||
* Fallback return value when no custom dispatcher is used.
|
||||
* OpenAI SDK accepts `undefined` for fetchOptions to use runtime built-in fetch;
|
||||
* Anthropic SDK requires an empty object `{}`.
|
||||
*/
|
||||
const NO_DISPATCHER_FALLBACK = {
|
||||
openai: undefined,
|
||||
anthropic: {},
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Get or create a shared undici dispatcher for the given proxy configuration.
|
||||
* The dispatcher is cached so that preconnect and subsequent SDK requests
|
||||
@ -195,6 +221,7 @@ export function getOrCreateSharedDispatcher(proxyUrl: string): Dispatcher {
|
||||
*/
|
||||
export function resetDispatcherCache(): void {
|
||||
dispatcherCache.clear();
|
||||
noProxyDispatcherCache.clear();
|
||||
proxyFailureCounts.clear();
|
||||
}
|
||||
|
||||
@ -587,36 +614,46 @@ function recordProxyFailure(hostname: string): number {
|
||||
return failureCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize bodyTimeout to a value accepted by undici Agent constructor.
|
||||
* undici requires a non-negative integer; invalid values default to 0 (disabled).
|
||||
*/
|
||||
function sanitizeBodyTimeout(value: number | undefined): number {
|
||||
if (value === undefined || value === null) {
|
||||
return 0;
|
||||
}
|
||||
if (!Number.isInteger(value) || value < 0) {
|
||||
debugLogger.warn(
|
||||
`Invalid bodyTimeout value ${value} (must be a non-negative integer). Defaulting to 0 (disabled).`,
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function buildFetchOptionsWithDispatcher(
|
||||
sdkType: SDKType,
|
||||
_sdkType: SDKType,
|
||||
proxyUrl?: string,
|
||||
options?: RuntimeFetchBehaviorOptions,
|
||||
): OpenAIRuntimeFetchOptions | AnthropicRuntimeFetchOptions {
|
||||
// When no proxy is configured, skip the custom dispatcher and let the SDK
|
||||
// use the runtime's built-in fetch. This avoids version-mismatch issues
|
||||
// between the project's bundled undici and the Node.js built-in undici.
|
||||
// Re-verify compatibility if the bundled undici version changes.
|
||||
const resolvedBodyTimeout = sanitizeBodyTimeout(options?.bodyTimeout);
|
||||
|
||||
if (!proxyUrl) {
|
||||
return NO_DISPATCHER_FALLBACK[sdkType];
|
||||
// Create a plain Agent with configurable bodyTimeout to prevent undici's
|
||||
// default 300s idle timeout from killing streaming connections to slow
|
||||
// local model servers (Ollama, mlx_lm.server) during tool call generation.
|
||||
// Pin fetch to bundled undici to avoid version-mismatch with the dispatcher.
|
||||
const dispatcher = getOrCreateNoProxyDispatcher(resolvedBodyTimeout);
|
||||
return { fetchOptions: { dispatcher }, fetch: undiciFetch };
|
||||
}
|
||||
|
||||
// Note: Without a custom dispatcher, Node.js built-in fetch uses its default
|
||||
// 300s bodyTimeout. This is sufficient for all current model streaming responses.
|
||||
try {
|
||||
const dispatcher = getOrCreateSharedDispatcher(proxyUrl);
|
||||
// Pin fetch to undici's own implementation so the dispatcher and fetch
|
||||
// come from the same undici version. Node's bundled undici may differ in
|
||||
// major version from the project's bundled one (e.g. v8 vs v6), which
|
||||
// breaks dispatcher handler-interface checks (`invalid onError method`).
|
||||
// The no-proxy branch above intentionally skips this so the runtime's
|
||||
// built-in fetch continues to be used when no dispatcher is involved.
|
||||
// Pin fetch to bundled undici so dispatcher and fetch share a version.
|
||||
// Node's built-in undici may differ in major version (e.g. v8 vs v6),
|
||||
// which breaks dispatcher handler-interface checks (`invalid onError method`).
|
||||
return { fetchOptions: { dispatcher }, fetch: undiciFetch };
|
||||
} catch (error) {
|
||||
// Log dispatcher creation failure - requests will fallback to direct connection
|
||||
// bypassing the configured proxy. This is important for environments requiring
|
||||
// proxy for security controls (TLS inspection, traffic logging).
|
||||
// Log only the hostname (without credentials) to avoid credential leakage,
|
||||
// and do not deduplicate so that administrators can see each credential change
|
||||
// attempt's failure when debugging proxy issues.
|
||||
const hostname = extractHostnameFromProxyUrl(proxyUrl);
|
||||
const failureCount = recordProxyFailure(hostname);
|
||||
const failureLabel =
|
||||
@ -625,11 +662,10 @@ function buildFetchOptionsWithDispatcher(
|
||||
const redactedMessage = redactProxyCredentials(errorMessage);
|
||||
const logMessage = `Failed to create proxy dispatcher for ${hostname} (${failureLabel}), falling back to direct connection: ${redactedMessage}`;
|
||||
debugLogger.warn(logMessage);
|
||||
// Dual logging: debugLogger writes to ~/.qwen/debug/ (for local debugging),
|
||||
// console.error writes to stderr (captured by container orchestrators and log aggregators).
|
||||
// This ensures visibility in production even when debug sessions are inactive.
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`[RUNTIME_FETCH] ${logMessage}`);
|
||||
return NO_DISPATCHER_FALLBACK[sdkType];
|
||||
// Fall back to a no-proxy Agent so bodyTimeout protection is preserved
|
||||
const dispatcher = getOrCreateNoProxyDispatcher(resolvedBodyTimeout);
|
||||
return { fetchOptions: { dispatcher }, fetch: undiciFetch };
|
||||
}
|
||||
}
|
||||
|
||||
@ -546,6 +546,11 @@
|
||||
"contextWindowSize": {
|
||||
"description": "Overrides the default context window size for the selected model. Use this setting when a provider's effective context limit differs from Qwen Code's default. This value defines the model's assumed maximum context capacity, not a per-request token limit.",
|
||||
"type": "number"
|
||||
},
|
||||
"bodyTimeout": {
|
||||
"description": "Streaming body timeout in milliseconds. Maximum idle time allowed between data chunks during streaming. Set to 0 (default) to disable the body timeout, which prevents timeout errors with slow local model servers (Ollama, mlx_lm.server). Set a positive value to impose a safety timeout between chunks.",
|
||||
"type": "number",
|
||||
"default": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user