Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

13.0 KB
Raw Blame
import { AgentRuntimeErrorType, ChatErrorType, type ChatMessageError } from '@lobechat/types';

import { isRecord } from '../utils/object';
import { refineErrorCode } from './refine';
import { getErrorCodeSpec } from './specs';

/** Pull a usable HTTP status out of the nested upstream error object. */
const extractHttpStatus = (body: unknown): number | undefined => {
  if (!body || typeof body !== 'object') return undefined;
  const b = body as { error?: { status?: unknown }; status?: unknown; statusCode?: unknown };
  if (typeof b.status === 'number') return b.status;
  if (typeof b.statusCode === 'number') return b.statusCode;
  if (b.error && typeof b.error === 'object' && typeof b.error.status === 'number') {
    return b.error.status;
  }
  return undefined;
};

const extractProvider = (body: unknown): string | undefined => {
  if (!body || typeof body !== 'object') return undefined;
  const p = (body as { provider?: unknown }).provider;
  return typeof p === 'string' ? p : undefined;
};

/**
 * Find the first human-readable message in an error value, walking the nested `error`,
 * `_responseBody` and `body` layers that runtime payloads use.
 */
export const extractErrorMessage = (value: unknown, depth = 0): string | undefined => {
  if (typeof value === 'string') return value.trim() ? value : undefined;
  if (!isRecord(value) || depth > 5) return undefined;
  if (typeof value.message === 'string' && value.message.trim() && value.message !== 'error') {
    return value.message;
  }
  for (const nested of [value.error, value._responseBody, value.body]) {
    const message = extractErrorMessage(nested, depth + 1);
    if (message) return message;
  }
};

interface ChatCompletionErrorPayloadLike {
  _responseBody?: unknown;
  body?: unknown;
  budget?: unknown;
  error?: unknown;
  errorType: ChatMessageError['type'];
  message?: string;
  provider?: unknown;
}

const mergePayloadError = (
  sourceBody: Record<string, unknown>,
  payload: ChatCompletionErrorPayloadLike,
): unknown | undefined => {
  if (
    payload.body !== undefined ||
    payload._responseBody === undefined ||
    payload.error === undefined
  )
    return undefined;
  if (!('error' in sourceBody)) return payload.error;
  if (isRecord(sourceBody.error) && isRecord(payload.error)) {
    return { ...payload.error, ...sourceBody.error };
  }
};

const buildPayloadBody = (
  payload: ChatCompletionErrorPayloadLike,
  originalError: unknown,
  message: string,
): unknown => {
  // Runtime payloads often keep UI context (for example quota hints) next to
  // `error`, while `error` itself only carries the display message. Merge both
  // layers so normalizing `{ errorType, error }` does not drop the fields the
  // chat error renderer needs later.
  const sourceBody = payload.body ?? payload._responseBody ?? payload.error ?? originalError;
  /**
   * Error hooks attach display fields such as `traceId` through `_responseBody`. A stream error
   * already carries the provider `body`, which would otherwise hide them from the error card.
   */
  const displayFields =
    payload.body !== undefined &&
    isRecord(payload._responseBody) &&
    payload._responseBody !== payload.body
      ? payload._responseBody
      : undefined;
  const context: Record<string, unknown> = {};

  if (payload.budget !== undefined) context.budget = payload.budget;
  if (typeof payload.provider === 'string') context.provider = payload.provider;

  if (isRecord(sourceBody)) {
    const payloadError = mergePayloadError(sourceBody, payload);

    return {
      ...sourceBody,
      ...displayFields,
      // `_responseBody` is the display-facing body, but gateway/model-runtime
      // still carries status/provider details in `error` for some failures:
      // `{ _responseBody: { error: { message } }, error: { status: 402 } }`.
      ...(payloadError === undefined ? {} : { error: payloadError }),
      ...(payload.budget !== undefined && !('budget' in sourceBody)
        ? { budget: payload.budget }
        : {}),
      ...(typeof payload.provider === 'string' && !('provider' in sourceBody)
        ? { provider: payload.provider }
        : {}),
      ...('message' in sourceBody ? {} : { message }),
    };
  }

  return {
    ...context,
    ...(sourceBody === undefined ? {} : { error: sourceBody }),
    message,
  };
};

/**
 * Cap a stack before it lands in `agent_operations.error` / trace snapshots.
 * The top frames identify the throw site; the rest is runtime plumbing that
 * would only bloat every stored error row.
 */
const STACK_MAX_CHARS = 1000;

const truncateStack = (stack: string | undefined): string | undefined => {
  if (!stack) return undefined;
  return stack.length > STACK_MAX_CHARS ? `${stack.slice(0, STACK_MAX_CHARS)}…` : stack;
};

/**
 * Merge classification metadata from `ERROR_CODE_SPECS` onto a normalized
 * `ChatMessageError`. Codes that aren't in the spec table (fallbacks like
 * `InternalServerError`, or numeric ChatErrorType values) pass through
 * unchanged β€” every classification field stays optional.
 *
 * Keeping enrichment in one place means downstream consumers (`agent_operations.error`
 * JSONB, S3 trace snapshots, agent-gateway WS push, dashboards) all get the
 * same shape without re-running pattern matching themselves.
 */
/** The model gateway's message for a model tier the user's plan does not include. */
const PLAN_GATE_PATTERN = /available on paid plans only/i;

/**
 * Classification for a platform admission refusal that arrives as a bare HTTP 403.
 *
 * The model gateway rejects a call it will not serve before any provider sees it, either
 * because the user's plan does not include the model tier or because a usage-security gate
 * holds the account (`body.reason`). Both carry the numeric `Forbidden` type, which has no
 * spec, so they were stored with no category and read as unknown failures. Both are the
 * account's state, not a runtime fault, so they are classified as user-side. The `type`
 * stays as is, because the chat error renderer picks its card from it.
 *
 * A bare `Forbidden` with neither marker is left unclassified on purpose: the refusal lost
 * its explanation somewhere upstream, which is a defect to fix rather than a user state.
 */
const classifyForbidden = (formatted: ChatMessageError): ChatMessageError | undefined => {
  if (String(formatted.type) !== String(ChatErrorType.Forbidden)) return undefined;
  const reason = isRecord(formatted.body) ? formatted.body.reason : undefined;
  const category =
    typeof reason === 'string' && reason
      ? 'auth'
      : PLAN_GATE_PATTERN.test(formatted.message ?? '')
        ? 'quota'
        : undefined;
  if (!category) return undefined;

  return {
    ...formatted,
    attribution: 'user',
    category,
    countAsFailure: false,
    httpStatus: 403,
    isFallback: false,
    retryable: false,
    severity: 'warning',
  };
};

const enrichWithSpec = (formatted: ChatMessageError): ChatMessageError => {
  // Generic `ProviderBizError` is re-derived from the message / HTTP status into
  // a more specific code before enrichment, so the catch-all doesn't swallow
  // rate-limits, network drops, quota, etc. Specific codes pass through.
  const refined = refineErrorCode({
    errorType: String(formatted.type),
    httpStatus: extractHttpStatus(formatted.body),
    message: formatted.message,
    provider: extractProvider(formatted.body),
  });
  const type = (refined ?? formatted.type) as ChatMessageError['type'];

  // `getErrorCodeSpec` is keyed by `ILobeAgentRuntimeErrorType` strings; coerce
  // because `ChatMessageError['type']` widens to include numeric `ChatErrorType`
  // values, which simply miss the lookup and pass through unenriched.
  const spec = getErrorCodeSpec(String(type));
  if (!spec) return classifyForbidden(formatted) ?? formatted;

  return {
    ...formatted,
    attribution: spec.attribution,
    category: spec.category,
    countAsFailure: spec.countAsFailure,
    httpStatus: spec.httpStatus,
    isFallback: spec.isFallback ?? false,
    numericId: spec.numericId,
    retryable: spec.retryable,
    severity: spec.severity,
    type,
  };
};

/**
 * Normalize an arbitrary thrown value into `ChatMessageError`, then attach
 * classification metadata from `ERROR_CODE_SPECS` so the resulting object
 * is self-describing for everything downstream of the runtime catch block.
 *
 * Handles four input shapes:
 *
 * 1. `ChatCompletionErrorPayload` β€” what `model-runtime` throws on LLM
 *    failures: `{ errorType, error, provider?, message? }`.
 * 2. Already-normalized `ChatMessageError` (`{ type, message?, body? }`)
 *    β€” re-enriched in place so the helper is safe to call twice (the inner
 *    `runtime.step()` non-throwing error path and the outer `executeStep`
 *    catch can both run through here without double-wrapping).
 * 3. Standard `Error` instance β€” wrapped as `InternalServerError`.
 * 4. Anything else β€” a loosely-typed `{ message }` body (e.g. a heterogeneous CLI
 *    agent's wire `error` event data `{ code, message, stderr }`) or a raw string β€”
 *    mapped to `AgentRuntimeError` with a real extracted message. This branch is
 *    the single canonical replacement for the hetero-specific `toChatMessageError`.
 */
export const normalizeChatMessageError = (error: unknown): ChatMessageError => {
  if (
    isRecord(error) &&
    (typeof error.errorType === 'string' || typeof error.errorType === 'number')
  ) {
    const payload: ChatCompletionErrorPayloadLike = {
      ...error,
      errorType: error.errorType as ChatMessageError['type'],
      message: typeof error.message === 'string' ? error.message : undefined,
    };
    const message =
      (payload.message && payload.message !== 'error' ? payload.message : undefined) ??
      extractErrorMessage(payload.body) ??
      extractErrorMessage(payload._responseBody) ??
      extractErrorMessage(payload.error) ??
      String(payload.errorType);

    return enrichWithSpec({
      body: buildPayloadBody(payload, error, message),
      message,
      type: payload.errorType,
    });
  }

  // Path 2: already-normalized ChatMessageError shape β€” has `type` but not
  // `errorType`, and isn't a thrown Error instance. Common when the inner
  // runtime.step() catch has already stuffed a partial ChatMessageError into
  // `newState.error` and the outer service is just topping it up.
  if (
    error &&
    typeof error === 'object' &&
    !(error instanceof Error) &&
    'type' in error &&
    (typeof (error as { type: unknown }).type === 'string' ||
      typeof (error as { type: unknown }).type === 'number')
  ) {
    const { _responseBody: responseBody, ...formatted } = error as ChatMessageError & {
      _responseBody?: unknown;
    };
    const message = extractErrorMessage(formatted);
    // Error hooks attach display fields such as `traceId` through `_responseBody`, including on
    // a typed provider stream error that fails a router's last channel mid-stream.
    const body =
      isRecord(responseBody) && responseBody !== formatted.body
        ? { ...(isRecord(formatted.body) ? formatted.body : {}), ...responseBody }
        : formatted.body;
    return enrichWithSpec({
      ...formatted,
      ...(body === undefined ? {} : { body }),
      ...(message ? { message } : {}),
    });
  }

  if (error instanceof Error) {
    // Unclassified harness throw: nothing upstream recognized it, so `name` +
    // `message` are all the triage signal there is β€” and for a `SyntaxError`
    // out of some `JSON.parse` those two say nothing about WHERE it blew up.
    // Persist a bounded stack so a recurring 500 is locatable from the stored
    // operation instead of needing a live repro.
    // Error hooks attach display fields such as `traceId` through `_responseBody` β€” also on
    // plain Errors, e.g. a provider stream that fails with `TypeError: terminated`.
    const responseBody = (error as { _responseBody?: unknown })._responseBody;
    return enrichWithSpec({
      body: {
        ...(isRecord(responseBody) ? responseBody : {}),
        name: error.name,
        stack: truncateStack(error.stack),
      },
      message: error.message,
      type: ChatErrorType.InternalServerError,
    });
  }

  // Path 4: arbitrary thrown value. A loosely-typed object (no `errorType`, no
  // string/number `type`) keeps its body and contributes its `.message` rather
  // than being stringified to '[object Object]' β€” this is what the heterogeneous
  // CLI agents emit on the wire (`{ code, message, stderr }`). A raw string or any
  // other primitive becomes a `{ message }` body. Mirrors the former
  // `toChatMessageError`, then runs through `enrichWithSpec` so even these get
  // classification (the bare hetero formatter never did).
  if (isRecord(error)) {
    return enrichWithSpec({
      body: error,
      message: extractErrorMessage(error) ?? 'Agent runtime error',
      type:
        typeof error.code === 'string'
          ? (getErrorCodeSpec(error.code)?.code ?? AgentRuntimeErrorType.AgentRuntimeError)
          : AgentRuntimeErrorType.AgentRuntimeError,
    });
  }

  const message = typeof error === 'string' ? error : 'Agent runtime error';
  return enrichWithSpec({
    body: { message },
    message,
    type: AgentRuntimeErrorType.AgentRuntimeError,
  });
};