Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/api/providers/__tests__/kimi-code.spec.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/api/providers/base-openai-compatible-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ export abstract class BaseOpenAiCompatibleProvider<ModelName extends string>
}
}

protected processUsageMetrics(usage: any, modelInfo?: any): ApiStreamUsageChunk {
protected processUsageMetrics(usage: any, modelInfo?: ModelInfo): ApiStreamUsageChunk {
const inputTokens = usage?.prompt_tokens || 0
const outputTokens = usage?.completion_tokens || 0
const cacheWriteTokens = usage?.prompt_tokens_details?.cache_write_tokens || 0
Expand Down
19 changes: 19 additions & 0 deletions src/api/providers/utils/__tests__/abort-signal.spec.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

141 changes: 140 additions & 1 deletion src/api/providers/utils/__tests__/error-handler.spec.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions src/api/providers/utils/__tests__/request-timeout.spec.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions src/api/providers/utils/abort-signal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,8 @@ export function isRequestAborted(error: unknown, signal?: AbortSignal): boolean
* message "Request was aborted."), so raw SDK abort errors must be
* normalized instead of rethrown.
*/
export function createAbortError(providerName: string): Error {
const abortError = new Error(`The ${providerName} request was aborted`)
export function createAbortError(providerName: string, cause?: unknown): Error {
const abortError = new Error(`The ${providerName} request was aborted`, cause === undefined ? undefined : { cause })
abortError.name = "AbortError"
return abortError
}
Expand Down Expand Up @@ -312,9 +312,10 @@ export function createTimeoutError(providerName: string): Error {
* caller's stop signal.
*/
export function isTimeoutAbort(requestSignal: AbortSignal | undefined): boolean {
// Classify by the merged signal's retained abort reason: if its own timeout fired first, the
// reason stays the TimeoutError even when the caller aborts later, so the failure must still be
// reported as a deadline. A caller-first abort retains the caller's reason instead.
// Classify by the merged signal's retained abort reason: a deadline that fired first keeps the
// TimeoutError reason even if the caller stops later, so this answers only which signal fired
// first. handleOpenAIRequestError answers a caller that also pressed stop with the abort
// contract - error-handler.spec.ts:483-492 pins that answer for the interleaving.
return Boolean(
requestSignal?.aborted && (requestSignal.reason as { name?: string } | undefined)?.name === "TimeoutError",
)
Expand Down
48 changes: 48 additions & 0 deletions src/api/providers/utils/error-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@
* - Enables telemetry and debugging with complete error context
*/

import { APIUserAbortError } from "openai"

import i18n from "../../../i18n/setup"
import { createAbortError, isTimeoutAbort } from "./abort-signal"
import { createTimeoutError } from "./request-timeout"

/**
* Handles API provider errors and transforms them into user-friendly messages
Expand Down Expand Up @@ -163,3 +167,47 @@ export function handleProviderError(
export function handleOpenAIError(error: unknown, providerName: string): Error {
return handleProviderError(error, providerName, { messagePrefix: "completion" })
}

/**
* Handles errors from OpenAI Node SDK request sites with abort awareness.
*
* An abort failure (the external signal already aborted, the SDK's
* APIUserAbortError, or a fetch-level AbortError) is normalized to a fresh
* Error with name "AbortError" and a message ending in "aborted" (the Task.ts
* contract) instead of being wrapped as a regular completion error, which a
* plain rethrow of the SDK abort error would produce.
*
* @internal Exported for the provider request sites that adopt it in the follow-up
* #1311 splits; direct contract tests cover it here (docs/development-quality-checks.md
* "intentional direct-test seam").
*/
export function handleOpenAIRequestError(
error: unknown,
providerName: string,
abortSignal?: AbortSignal,
requestSignal?: AbortSignal,
): Error {
// A terminal HTTP failure keeps its own identity even when the caller stops in the same tick:
// backoff reads the top-level status, so masking a 401/429 as AbortError hides the provider error.
if (hasNumericHttpStatus(error)) return handleOpenAIError(error, providerName)

// The deadline, not the caller's stop, ended this request. Classified before the abort branch so a
// native AbortError raised by the SDK's JSON body read is reported as a timeout as well.
if (!abortSignal?.aborted && isTimeoutAbort(requestSignal)) {
// The abort came from this merged signal's own deadline, not the caller's stop: a timeout
// must stay distinguishable from a user cancellation, so the shared helper's name and
// message are used and the SDK abort is attached as the cause. A caller that pressed stop
// never reaches here - error-handler.spec.ts:483-492 pins the abort for that interleaving.
const timeoutError = createTimeoutError(providerName, "completion request")
timeoutError.cause = error
return timeoutError
}

if (
abortSignal?.aborted ||
(error instanceof Error && (error.name === "AbortError" || error instanceof APIUserAbortError))
) {
return createAbortError(providerName, error)
}
return handleOpenAIError(error, providerName)
}
14 changes: 8 additions & 6 deletions src/api/providers/utils/request-timeout.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import { hasUsableTimeout, toSdkTimeoutMs } from "./abort-signal"

/**
* Returns the value to pass as a client/SDK request timeout option, or undefined.
*
* Per the abort-signal series contract, timeoutMs <= 0, non-finite values
* (or undefined) mean 'no per-request timeout': the option is omitted
* entirely, because some SDKs (e.g. the OpenAI Node SDK) treat timeout: 0 as
* an IMMEDIATE timeout. Finite values are rounded up to whole milliseconds:
* downstream AbortSignal.timeout() validates its delay as uint32 and throws
* for fractions.
* an IMMEDIATE timeout. Values that do survive validation are handed to
* toSdkTimeoutMs, which rounds fractions up (AbortSignal.timeout validates its
* delay as uint32 and throws for fractions) and caps them at the maximum timer
* delay: a Node timer clamps anything past 2^31-1 ms to ~1 ms, which would
* abort the request almost immediately instead of honouring the timeout.
*/
export function getRequestTimeoutMs(timeoutMs?: number): number | undefined {
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
? Math.ceil(timeoutMs)
: undefined
return hasUsableTimeout(timeoutMs) ? toSdkTimeoutMs(timeoutMs) : undefined
}

/**
Expand Down
7 changes: 1 addition & 6 deletions src/eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,6 @@
"count": 1
}
},
"api/providers/__tests__/kimi-code.spec.ts": {
"@typescript-eslint/no-explicit-any": {
"count": 1
}
},
"api/providers/__tests__/lite-llm.spec.ts": {
"@typescript-eslint/no-explicit-any": {
"count": 26
Expand Down Expand Up @@ -191,7 +186,7 @@
},
"api/providers/base-openai-compatible-provider.ts": {
"@typescript-eslint/no-explicit-any": {
"count": 6
"count": 5
}
},
"api/providers/base-provider.ts": {
Expand Down
22 changes: 22 additions & 0 deletions src/test-utils/__tests__/errors.spec.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading