File size: 1,941 Bytes
461e15a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
 * Turn an inference failure into the one-line message the chat UI shows.
 *
 * Provider errors (AI SDK `APICallError`) carry the HTTP status of the
 * Inference Providers router. We keep it as an `HTTP <code>:` prefix so the
 * client can map 401 / 402 / 429 to an actionable message without parsing
 * provider-specific wording, and we pull the human part out of JSON bodies.
 */
export function formatStreamError(error: unknown): string {
  const status = statusOf(error);
  const message = cleanMessage(error);
  return status ? `HTTP ${status}: ${message}` : message;
}

function statusOf(error: unknown): number | null {
  if (!error || typeof error !== "object") return null;
  const e = error as { statusCode?: unknown; status?: unknown; cause?: unknown };
  const code = typeof e.statusCode === "number" ? e.statusCode : typeof e.status === "number" ? e.status : null;
  if (code) return code;
  return e.cause && e.cause !== error ? statusOf(e.cause) : null;
}

function cleanMessage(error: unknown): string {
  if (!error) return "Stream error";
  const e = error as { message?: unknown; responseBody?: unknown };
  const body = typeof e.responseBody === "string" ? fromJson(e.responseBody) : null;
  if (body) return body;
  const raw = typeof e.message === "string" && e.message ? e.message : String(error);
  return fromJson(raw) ?? raw;
}

function fromJson(text: string): string | null {
  const trimmed = text.trim();
  if (!trimmed.startsWith("{")) return null;
  try {
    const parsed = JSON.parse(trimmed) as { error?: unknown; message?: unknown };
    const inner = parsed.error;
    if (typeof inner === "string") return inner;
    if (inner && typeof inner === "object" && typeof (inner as { message?: unknown }).message === "string") {
      return (inner as { message: string }).message;
    }
    if (typeof parsed.message === "string") return parsed.message;
  } catch {
    return null;
  }
  return null;
}