Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

53.8 KB
Raw Blame
import { describe, expect, it } from "vitest";
import { isContextOverflow, type AssistantMessage } from "@earendil-works/pi-ai";
import {
  classifyAgentError,
  describeNetworkFailure,
} from "./agent-errors.js";
import { classifyProviderError } from "./provider-retry.js";

describe("classifyAgentError", () => {
  it.each(["context-validation", "context-estimation", "request-preparation"])(
    "keeps explicitly local %s failures terminal, safe and diagnosable", (phase) => {
      const cause = new TypeError("private prompt api_key=test-secret\nprivate stack");
      const error = Object.assign(new Error("502: fetch failed; prompt is too long", { cause }), {
        code: "LOCAL_REQUEST_ERROR", phase,
      });
      const classified = classifyAgentError(error);
      expect(classified).toMatchObject({
        code: "INTERNAL", retriable: false,
        details: { origin: "local", phase, causeName: "TypeError" },
      });
      expect(classified).toHaveProperty("cause", error);
      expect(error.cause).toBe(cause);
      expect(Object.keys(classified)).not.toContain("cause");
      const serialized = JSON.stringify(classified);
      for (const text of ["private prompt", "test-secret", "private stack", "502", "fetch failed"]) {
        expect(serialized).not.toContain(text);
      }
    },
  );

  it.each(["fetch failed", "429: overloaded", "503: unavailable", "aborted field", "prompt is too long"])(
    "classifies local message metadata before provider wording: %s", (errorMessage) => {
      expect(classifyAgentError({
        role: "assistant", stopReason: "error", errorMessage,
        errorDetails: {
          code: "LOCAL_REQUEST_ERROR", phase: "context-estimation",
          message: "private prompt", causeName: "TypeError", stack: "private stack",
        },
      })).toMatchObject({
        code: "INTERNAL", retriable: false,
        details: { origin: "local", phase: "context-estimation", causeName: "TypeError" },
      });
    },
  );

  it("requires the complete local marker, never error names or wording", () => {
    for (const error of [
      new TypeError("fetch failed"),
      "LOCAL_REQUEST_ERROR context-validation fetch failed",
      Object.assign(new Error("fetch failed"), { name: "LocalRequestError" }),
      { errorMessage: "fetch failed", errorDetails: { code: "LOCAL_REQUEST_ERROR", phase: "remote" } },
      { errorMessage: "fetch failed", errorDetails: { phase: "context-validation", message: "failed" } },
      { errorMessage: "fetch failed", errorDetails: { code: "local_request_error", phase: "context-validation" } },
    ]) {
      expect(classifyAgentError(error)).toMatchObject({ code: "NETWORK_ERROR", retriable: true });
    }
  });

  it("takes pi-ai's code+phase marker as provenance even without a message", () => {
    // Upstream's own reader accepts `code` plus a known `phase`; details that lost
    // their message in transit are still explicit provenance and must not fall
    // through to the transport bucket, which would be retried.
    for (const errorDetails of [
      { code: "LOCAL_REQUEST_ERROR", phase: "context-validation" },
      { code: "LOCAL_REQUEST_ERROR", phase: "request-preparation", causeName: "TypeError" },
    ]) {
      const classified = classifyAgentError({
        role: "assistant", stopReason: "error", errorMessage: "fetch failed", errorDetails,
      });
      expect(classified).toMatchObject({
        code: "INTERNAL", retriable: false,
        details: { origin: "local", phase: errorDetails.phase },
      });
      expect(classified.message).toMatch(/^Local request .* failed\.$/);
      expect(JSON.stringify(classified)).not.toContain("fetch failed");
    }
    // The marker is the whole contract: a message alone is not provenance.
    expect(classifyAgentError({
      errorMessage: "fetch failed",
      errorDetails: { code: "LOCAL_REQUEST_ERROR", phase: "network", message: "fetch failed" },
    })).toMatchObject({ code: "NETWORK_ERROR", retriable: true });
  });

  it("does not expose an arbitrary cause name from local metadata", () => {
    const classified = classifyAgentError({
      errorDetails: {
        code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
        message: "private prompt", causeName: "api_key=test-secret\nprivate stack",
      },
    });
    expect(classified.details).toEqual({ origin: "local", phase: "request-preparation" });
    expect(JSON.stringify(classified)).not.toMatch(/private|test-secret|stack/);
  });

  it("keeps explicit cancellation ahead of local metadata", () => {
    const errorDetails = { code: "LOCAL_REQUEST_ERROR", phase: "context-validation", message: "failed" };
    expect(classifyAgentError({ stopReason: "aborted", errorDetails })).toMatchObject({
      code: "TURN_ABORTED", retriable: false,
    });
    expect(classifyAgentError(Object.assign(new Error("Request aborted"), {
      name: "AbortError", ...errorDetails,
    }))).toMatchObject({ code: "TURN_ABORTED", retriable: false });
  });

  it("keeps a cancelled local cause cancelled however the outer error is named", () => {
    // pi-ai wraps a synchronous AbortError in LocalRequestError before
    // `signal.aborted` flips, so the outer name is not "AbortError": the cause
    // name the marker preserved is the only evidence of the user's Stop.
    const cause = Object.assign(new Error("The operation was aborted"), {
      name: "AbortError",
    });
    const wrapped = Object.assign(new Error("Local request preparation failed."), {
      name: "LocalRequestError", code: "LOCAL_REQUEST_ERROR",
      phase: "request-preparation", cause,
    });
    const classified = classifyAgentError(wrapped);
    expect(classified).toMatchObject({ code: "TURN_ABORTED", retriable: false });
    expect(classified.message).toBe("Request aborted");
    // A cancelled turn is not reported as a local request failure.
    expect(classified.details?.origin).toBeUndefined();
    expect(classified.details?.phase).toBeUndefined();

    // The same cancellation on the wire shape the adapters emit.
    expect(classifyAgentError({
      role: "assistant", stopReason: "error",
      errorMessage: "Local request preparation failed",
      errorDetails: {
        code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
        message: "Local request preparation failed", causeName: "AbortError",
      },
    })).toMatchObject({ code: "TURN_ABORTED", retriable: false });

    // A wrapped, non-abort local failure stays a terminal local failure.
    expect(classifyAgentError(Object.assign(new Error("wrapped setup failure"), {
      name: "LocalRequestError", code: "LOCAL_REQUEST_ERROR",
      phase: "request-preparation", cause: new TypeError("private prompt"),
    }))).toMatchObject({
      code: "INTERNAL", retriable: false,
      details: { origin: "local", phase: "request-preparation", causeName: "TypeError" },
    });
  });

  it("reads the marker through a bounded, cycle-safe cause chain", () => {
    const marker = Object.assign(new Error("Local request context estimation failed."), {
      name: "LocalRequestError", code: "LOCAL_REQUEST_ERROR",
      phase: "context-estimation", cause: new TypeError("private prompt"),
    });
    expect(classifyAgentError(Object.assign(new TypeError("fetch failed"), {
      cause: marker,
    }))).toMatchObject({
      code: "INTERNAL", retriable: false,
      details: { origin: "local", phase: "context-estimation", causeName: "TypeError" },
    });

    // A cycle without the marker stays a transport failure, and it has to
    // terminate instead of being walked forever.
    const first = new TypeError("fetch failed");
    const second = Object.assign(new Error("socket hang up"), { cause: first });
    (first as any).cause = second;
    expect(classifyAgentError(first)).toMatchObject({ code: "NETWORK_ERROR", retriable: true });

    // The same cycle with the marker on the second node is explicit provenance.
    Object.assign(second, { code: "LOCAL_REQUEST_ERROR", phase: "request-preparation" });
    expect(classifyAgentError(first)).toMatchObject({
      code: "INTERNAL", retriable: false,
      details: { origin: "local", phase: "request-preparation" },
    });

    // A self-referencing marker terminates as well.
    const self = Object.assign(new Error("Local request preparation failed."), {
      code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
    });
    (self as any).cause = self;
    expect(classifyAgentError(self)).toMatchObject({
      code: "INTERNAL", retriable: false,
      details: { origin: "local", phase: "request-preparation" },
    });

    // Past the traversal bound the marker is out of reach, so the failure keeps
    // its transport classification rather than claiming local provenance.
    let deep: unknown = Object.assign(new Error("Local request preparation failed."), {
      code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
    });
    for (let depth = 0; depth < 6; depth += 1) {
      deep = Object.assign(new TypeError("fetch failed"), { cause: deep });
    }
    expect(classifyAgentError(deep)).toMatchObject({ code: "NETWORK_ERROR", retriable: true });
  });

  it.each([
    "SELF_SIGNED_CERT_IN_CHAIN",
    "DEPTH_ZERO_SELF_SIGNED_CERT",
    "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
    "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
    "CERT_HAS_EXPIRED",
    "CERT_NOT_YET_VALID",
    "ERR_TLS_CERT_ALTNAME_INVALID",
  ])("makes certificate verification failure %s terminal", (code) => {
    const cause = Object.assign(new Error("certificate verification failed"), { code });
    for (const error of [cause, new Error("Connection error.", { cause }), code]) {
      expect(classifyAgentError(error)).toMatchObject({
        code: "NETWORK_ERROR",
        retriable: false,
        details: { networkCategory: "tls", networkCode: code },
      });
    }
  });

  it.each(["EPROTO", "ERR_SSL_PROTOCOL_ERROR", "ECONNRESET"])(
    "keeps non-certificate transport failure %s retryable", (code) => {
      expect(classifyAgentError(new Error("fetch failed", {
        cause: Object.assign(new Error(code), { code }),
      })).retriable).toBe(true);
    },
  );

  it.each(["UND_ERR_SOCKET", "ERR_PROXY_CONNECTION_FAILED"])(
    "keeps the certificate cause terminal beneath %s", (code) => {
      const error = Object.assign(new Error("fetch failed"), {
        code, cause: Object.assign(new Error("certificate failed"), { code: "CERT_HAS_EXPIRED" }),
      });
      expect(classifyAgentError(error)).toMatchObject({
        retriable: false, details: { networkCode: "CERT_HAS_EXPIRED", networkCategory: "tls" },
      });
    },
  );

  it("classifies auth failures from status fields", () => {
    const err = Object.assign(new Error("Incorrect API key provided"), {
      status: 401,
    });
    expect(classifyAgentError(err)).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
    });
  });

  it("does not treat TLS authentication wording as an API-key rejection", () => {
    expect(classifyAgentError(new Error("mutual TLS authentication failed")))
      .toMatchObject({
        code: "NETWORK_ERROR",
        retriable: true,
        details: { networkCategory: "tls" },
      });

    const handshake = classifyAgentError(
      new Error("authentication handshake timed out"),
    );
    expect(handshake).not.toMatchObject({ code: "PROVIDER_UNAUTHORIZED" });
    expect(handshake.retriable).toBe(true);
    expect(["NETWORK_ERROR", "TIMEOUT"]).toContain(handshake.code);

    expect(classifyAgentError(new Error("Invalid API key"))).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
    });
    expect(classifyAgentError(new Error("unauthorized"))).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
    });
    expect(classifyAgentError(new Error("permission denied"))).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
    });

    // A real credential phrase still names the key or the credentials, and a
    // certificate errno stays terminal even when the text says authentication.
    expect(classifyAgentError(new Error("invalid authentication credentials")))
      .toMatchObject({ code: "PROVIDER_UNAUTHORIZED", retriable: false });
    expect(classifyAgentError(new Error("authentication failed"))).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
    });
    expect(classifyAgentError(Object.assign(
      new Error("mutual TLS authentication failed"),
      { code: "CERT_HAS_EXPIRED" },
    ))).toMatchObject({
      code: "NETWORK_ERROR",
      retriable: false,
      details: { networkCategory: "tls", networkCode: "CERT_HAS_EXPIRED" },
    });
  });

  // OpenAI's classic rejection and Anthropic's header name never say
  // "invalid api key". pi-ai often flattens them to a statusless
  // errorMessage, so the pattern — not only HTTP 401 — must catch them.
  it.each([
    "Incorrect API key provided",
    "Incorrect API key provided: sk-****. You can find your API key at https://platform.openai.com/account/api-keys.",
    "API key expired. Please renew the API key.",
    "invalid x-api-key",
    '{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}',
  ])("classifies statusless Incorrect/expired API-key wording as unauthorized: %s", (message) => {
    expect(classifyAgentError(message)).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
    });
    expect(classifyAgentError(new Error(message))).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
    });
  });


  it("classifies pi-ai '<status>: <body>' errorMessage strings", () => {
    expect(classifyAgentError('429: {"error":{"type":"rate_limit_error"}}'))
      .toMatchObject({ code: "PROVIDER_RATE_LIMITED", retriable: true });
    expect(classifyAgentError('529: {"error":{"type":"overloaded_error"}}'))
      .toMatchObject({ code: "PROVIDER_ERROR", retriable: true });
    expect(classifyAgentError('403 status code (no body)')).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
    });
  });

  it("treats malformed requests as non-retriable provider errors", () => {
    expect(classifyAgentError('400: {"error":"unknown parameter"}'))
      .toMatchObject({ code: "PROVIDER_ERROR", retriable: false });
  });

  it.each([
    ["InvalidParameter: <400> InternalError.Algo.InvalidParameter: Repetitive tool calls detected in the conversation history.", "PROVIDER_ERROR", false, 400],
    ["InvalidParameter: <422> Invalid tool arguments.", "PROVIDER_ERROR", false, 422],
    ["InvalidApiKey: <401> Invalid API key.", "PROVIDER_UNAUTHORIZED", false, 401],
    ["Throttling: <429> Too many requests.", "PROVIDER_RATE_LIMITED", true, 429],
    ["InternalError: <500> The service is temporarily unavailable.", "PROVIDER_ERROR", true, 500],
  ])("classifies DashScope code/status envelopes: %s", (message, code, retriable, status) => {
    expect(classifyAgentError(message)).toMatchObject({
      code, retriable, details: { providerStatus: status },
    });
  });

  it("does not infer an HTTP status from an angle-bracket number in prose", () => {
    expect(classifyAgentError("Provider failed while processing item <400>."))
      .toMatchObject({ code: "PROVIDER_ERROR", retriable: true });
    expect(classifyAgentError("InvalidParameter: <400> Unknown parameter. <429>"))
      .toMatchObject({ code: "PROVIDER_ERROR", retriable: false, details: { providerStatus: 400 } });
    expect(classifyAgentError(Object.assign(
      new Error("InvalidParameter: <400> Unknown parameter."),
      { status: 503 },
    ))).toMatchObject({ code: "PROVIDER_ERROR", retriable: true, details: { providerStatus: 503 } });
  });

  // @google/genai ApiError.message is JSON.stringify(errorBody). pi-ai does
  // not prefix "<status>:", and the Google adapter never records
  // providerResponseStatus, so the main session and subagents classify this
  // assistant message through classifyProviderError with no status argument.
  it.each([
    [
      "400 INVALID_ARGUMENT",
      {
        error: {
          code: 400,
          message: "User location is not supported for the API use.",
          status: "INVALID_ARGUMENT",
        },
      },
      { code: "PROVIDER_ERROR", retriable: false, details: { providerStatus: 400 } },
    ],
    [
      "404 NOT_FOUND",
      {
        error: {
          code: 404,
          message:
            "models/gemini-3-pro-preview is not found for API version v1beta, or is not supported for generateContent. Call ListModels to see the list of available models and their supported methods.",
          status: "NOT_FOUND",
        },
      },
      {
        code: "MODEL_NOT_CONFIGURED",
        retriable: false,
        details: { providerStatus: 404 },
      },
    ],
    [
      "429 RESOURCE_EXHAUSTED",
      {
        error: {
          code: 429,
          message: "Resource has been exhausted (e.g. check quota).",
          status: "RESOURCE_EXHAUSTED",
        },
      },
      {
        code: "PROVIDER_RATE_LIMITED",
        retriable: true,
        details: { providerStatus: 429 },
      },
    ],
    [
      "429 billing exhaustion",
      {
        error: {
          code: 429,
          message:
            "You exceeded your current quota, please check your plan and billing details.",
          status: "RESOURCE_EXHAUSTED",
        },
      },
      { code: "PROVIDER_ERROR", retriable: false, details: { providerStatus: 429 } },
    ],
    [
      "503 UNAVAILABLE",
      {
        error: {
          code: 503,
          message: "The service is currently unavailable.",
          status: "UNAVAILABLE",
        },
      },
      { code: "PROVIDER_ERROR", retriable: true, details: { providerStatus: 503 } },
    ],
    [
      "400 input token count",
      {
        error: {
          code: 400,
          message:
            "The input token count exceeds the maximum number of tokens allowed.",
          status: "INVALID_ARGUMENT",
        },
      },
      {
        code: "CONTEXT_TOO_LARGE",
        retriable: false,
        details: { providerStatus: 400 },
      },
    ],
    [
      "409 unknown 4xx",
      {
        error: {
          code: 409,
          message: "Resource already exists.",
          status: "ALREADY_EXISTS",
        },
      },
      { code: "PROVIDER_ERROR", retriable: true, details: { providerStatus: 409 } },
    ],
  ])(
    "classifies an unprefixed Gemini JSON %s body",
    (_label, body, expected) => {
      const errorMessage = JSON.stringify(body);
      const message = { role: "assistant", stopReason: "error", errorMessage };
      expect(classifyAgentError(errorMessage)).toMatchObject(expected);
      expect(classifyAgentError(new Error(errorMessage))).toMatchObject(expected);
      expect(classifyAgentError(message)).toMatchObject(expected);
      expect(classifyProviderError(message)).toMatchObject(expected);
    },
  );

  // Gemini's native API and some OpenAI-compatible gateways reject a bad key
  // with HTTP 400, not 401. The status table must still call that a
  // credential failure. A 400 that only says "permission denied" or
  // "unauthorized" stays a malformed request.
  it("classifies an HTTP 400 API-key rejection as unauthorized", () => {
    const errorMessage = JSON.stringify({
      error: {
        code: 400,
        message: "API key not valid. Please pass a valid API key.",
        status: "INVALID_ARGUMENT",
        details: [
          {
            "@type": "type.googleapis.com/google.rpc.ErrorInfo",
            reason: "API_KEY_INVALID",
            domain: "googleapis.com",
          },
        ],
      },
    });
    const expected = {
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
      details: { providerStatus: 400 },
    };
    const message = { role: "assistant", stopReason: "error", errorMessage };
    expect(classifyAgentError(errorMessage)).toMatchObject(expected);
    expect(classifyAgentError(new Error(errorMessage))).toMatchObject(expected);
    expect(classifyAgentError(message)).toMatchObject(expected);
    expect(classifyProviderError(message)).toMatchObject(expected);
    expect(classifyAgentError(`400: ${errorMessage}`)).toMatchObject(expected);
    expect(classifyProviderError({
      role: "assistant",
      stopReason: "error",
      errorMessage: "400: API key not valid. Please pass a valid API key.",
    })).toMatchObject(expected);
    expect(classifyAgentError("400: Invalid API key")).toMatchObject(expected);
    expect(classifyAgentError('400: {"reason":"API_KEY_INVALID"}')).toMatchObject(expected);
    expect(classifyAgentError("422: invalid_api_key")).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
      details: { providerStatus: 422 },
    });

    for (const ordinary of [
      "400: Invalid value at 'contents'",
      "400: permission denied",
      "422: unauthorized",
      "400: unknown parameter",
    ]) {
      expect(classifyAgentError(ordinary)).toMatchObject({
        code: "PROVIDER_ERROR",
        retriable: false,
      });
    }
    expect(classifyAgentError(
      "400: The input token count exceeds the maximum number of tokens allowed.",
    )).toMatchObject({ code: "CONTEXT_TOO_LARGE", retriable: false });
  });

  it("does not treat a non-HTTP JSON code as a provider status", () => {
    const cases = [
      JSON.stringify({ error: { code: 123, message: "not an http status" } }),
      JSON.stringify({ code: 400, message: "plain code is not an http status" }),
      JSON.stringify({
        error: {
          code: "400",
          message: "string code is not an http status",
          status: "INVALID_ARGUMENT",
        },
      }),
    ];
    for (const errorMessage of cases) {
      const classified = classifyProviderError({
        role: "assistant",
        stopReason: "error",
        errorMessage,
      });
      expect(classified).toMatchObject({
        code: "PROVIDER_ERROR",
        retriable: true,
      });
      expect(classified.details?.providerStatus).toBeUndefined();
    }
  });

  it("treats a request option an adapter refuses as non-retriable", () => {
    expect(
      classifyAgentError(
        "Custom fetch is not supported by the Google Generative AI adapter",
      ),
    ).toMatchObject({ code: "PROVIDER_ERROR", retriable: false });
    expect(
      classifyAgentError(
        "Custom fetch is not supported by the Google Vertex adapter",
      ),
    ).toMatchObject({ code: "PROVIDER_ERROR", retriable: false });
    // A status some layer attached to the same message must not re-arm the
    // transient retry budget for a request the adapter will refuse again.
    expect(
      classifyAgentError(
        "502: Custom fetch is not supported by the Google Generative AI adapter",
      ),
    ).toMatchObject({ code: "PROVIDER_ERROR", retriable: false });
  });

  it("detects context overflow from 400 bodies and bare messages", () => {
    expect(
      classifyAgentError(
        "400: This model's maximum context length is 128000 tokens",
      ),
    ).toMatchObject({ code: "CONTEXT_TOO_LARGE", retriable: false });
    expect(classifyAgentError("prompt is too long: 210000 tokens"))
      .toMatchObject({ code: "CONTEXT_TOO_LARGE" });
  });

  // Ollama's MLX runner returns this as HTTP 500, and other gateways wrap the
  // same upstream overflow as 502/503. pi-ai's LiteLLM rule wants "(8192)" or
  // " of 8192 tokens", so "(8192 tokens)" is invisible to isContextOverflow.
  // The status table must not retry it as a generic 5xx.
  it("classifies a 5xx-wrapped context overflow as terminal CONTEXT_TOO_LARGE", () => {
    const body =
      "input length (9000 tokens) exceeds the model's maximum context length (8192 tokens)";
    const json = (status: number) =>
      `${status} {"error":{"message":"${body}"}}`;
    const assistant = (errorMessage: string) =>
      ({ role: "assistant", stopReason: "error", errorMessage }) as AssistantMessage;

    expect(isContextOverflow(assistant(body))).toBe(false);
    expect(isContextOverflow(assistant(json(500)))).toBe(false);

    expect(classifyAgentError(json(500))).toMatchObject({
      code: "CONTEXT_TOO_LARGE",
      retriable: false,
      details: { providerStatus: 500 },
    });
    expect(classifyAgentError(Object.assign(new Error(body), { status: 500 }))).toMatchObject({
      code: "CONTEXT_TOO_LARGE",
      retriable: false,
      details: { providerStatus: 500 },
    });
    expect(classifyProviderError(assistant(json(500)))).toMatchObject({
      code: "CONTEXT_TOO_LARGE",
      retriable: false,
      details: { providerStatus: 500 },
    });
    for (const status of [502, 503]) {
      expect(classifyAgentError(json(status))).toMatchObject({
        code: "CONTEXT_TOO_LARGE",
        retriable: false,
        details: { providerStatus: status },
      });
    }
  });

  it("keeps ordinary and rate-limited 5xx responses retryable", () => {
    for (const message of [
      "500 Internal Server Error",
      "500: Internal Server Error",
      "502: upstream connect error or disconnect/reset before headers",
      "503 Service Unavailable",
      "503: Service Unavailable",
      "503: overloaded",
      "503: Too many requests",
      "503: rate limit exceeded",
      // CONTEXT_PATTERN matches "too many tokens", but this is a throttle.
      // pi-ai excludes "rate limit"; the 5xx branch must not undo that.
      "503: Throttling error: Too many tokens, please wait before trying again.",
      "503: rate limit: too many tokens, please wait before trying again.",
    ]) {
      const classified = classifyAgentError(message);
      expect(classified.code, message).not.toBe("CONTEXT_TOO_LARGE");
      expect(classified, message).toMatchObject({
        code: "PROVIDER_ERROR",
        retriable: true,
      });
    }
    expect(classifyAgentError(Object.assign(
      new Error("Internal Server Error"),
      { status: 500 },
    ))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: true,
      details: { providerStatus: 500 },
    });
    expect(classifyAgentError(Object.assign(
      new Error("Service Unavailable"),
      { status: 503 },
    ))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: true,
      details: { providerStatus: 503 },
    });
    expect(classifyAgentError(Object.assign(
      new Error("upstream connect error or disconnect/reset before headers"),
      { status: 502 },
    ))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: true,
      details: { providerStatus: 502 },
    });
  });

  // Each message is what pi-ai 1.1.0 reports for that provider's overflow:
  // OpenAI-compatible bodies arrive as "<status>: <body>", Bedrock as its
  // exception prefix. pi-ai's `isContextOverflow` already sends every one of
  // them to overflow recovery, so the terminal code has to agree.
  it.each([
    ["DashScope/Qwen", '400: {"code":"invalid_parameter_error","type":"invalid_request_error","message":"Range of input length should be [1, 98304]"}'],
    ["z.ai", '400: {"code":"1261","message":"Prompt exceeds max length"}'],
    ["xAI", "400: {\"message\":\"This model's maximum prompt length is 131072 but the request contains 537812 tokens.\"}"],
    ["Groq", '400: {"message":"Please reduce the length of the messages or completion.","type":"invalid_request_error"}'],
    ["llama.cpp", '400: {"code":400,"message":"the request exceeds the available context size, try increasing it","type":"exceed_context_size_error"}'],
    ["Bedrock", "Validation error: Input is too long for requested model."],
  ])("classifies the %s overflow pi-ai recovers from as CONTEXT_TOO_LARGE", (_provider, errorMessage) => {
    const message = { role: "assistant", stopReason: "error", errorMessage };
    expect(isContextOverflow(message as AssistantMessage)).toBe(true);
    expect(classifyAgentError(message)).toMatchObject({
      code: "CONTEXT_TOO_LARGE",
      retriable: false,
    });
    expect(classifyProviderError(message)).toMatchObject({
      code: "CONTEXT_TOO_LARGE",
      retriable: false,
    });
  });

  it("classifies Bedrock's token throttle as rate limiting, not an overflow", () => {
    const message = {
      role: "assistant",
      stopReason: "error",
      errorMessage: "Throttling error: Too many tokens, please wait before trying again.",
    };
    expect(isContextOverflow(message as AssistantMessage)).toBe(false);
    expect(classifyAgentError(message)).toMatchObject({
      code: "PROVIDER_RATE_LIMITED",
      retriable: true,
    });
  });

  // Spending, credit, billing, and disk quotas do not recover by backing off.
  // A bare "quota" match used to mark them PROVIDER_RATE_LIMITED and retriable.
  it.each([
    "Your organization has exceeded its monthly spending quota",
    "Your credit quota is exhausted. Please top up.",
    "Billing quota exceeded for this project",
    "disk quota exceeded",
    "insufficient_quota",
    '429: {"error":{"message":"You exceeded your current quota, please check your plan and billing details.","type":"insufficient_quota","code":"insufficient_quota"}}',
    '429: {"error":{"code":"organization_spend_limit_exceeded"}}',
    '429: {"error":{"code":"organization_usage_limit_exceeded"}}',
    "429: Billing quota exceeded",
  ])("does not retry exhausted account or disk quota: %s", (message) => {
    const classified = classifyAgentError(new Error(message));
    expect(classified).not.toMatchObject({
      code: "PROVIDER_RATE_LIMITED",
      retriable: true,
    });
    expect(classified).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
    });
  });

  // Zhipu/Z.ai code 1308 is the plan usage cap, sent as 429; it resets after
  // hours, so the rate-limit budget must not replay it (pi #11537).
  it.each([
    '429 {"error":{"code":"1308","message":"已达到 5 小时的使用上限。您的限额将在 2026-11-06 23:00:00 重置。"}}',
    '429: {"error":{"code":1308,"message":"Usage limit reached for 5 hour."}}',
  ])("does not retry the Zhipu usage-limit code: %s", (message) => {
    expect(classifyAgentError(Object.assign(new Error(message), { status: 429 }))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
    });
  });

  it("keeps a 429 that only mentions 1308 elsewhere retryable", () => {
    expect(classifyAgentError(Object.assign(
      new Error('429 {"error":{"code":"1302","message":"rate limit, request 13080"}}'),
      { status: 429 },
    ))).toMatchObject({ code: "PROVIDER_RATE_LIMITED", retriable: true });
  });

  it("classifies structured 429 quota errors before generic status handling", () => {
    expect(classifyAgentError(Object.assign(
      new Error("429: rate limit response"),
      { status: 429, code: "credit_balance_exhausted" },
    ))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
    });
  });

  // OpenRouter reports an empty balance as HTTP 402. Backing off cannot add
  // credits, so the same-turn transient budget must not replay the request.
  it.each([
    "402 Insufficient credits. Add more using https://openrouter.ai/settings/credits",
    "402 Payment Required",
    "402 status code (no body)",
    "402: gateway said something unexpected",
    "This request requires more credits, or fewer max_tokens. You requested up to 65536 tokens, but can only afford 1000.",
    "Insufficient credits",
    "Payment Required",
    '429: {"error":{"message":"Insufficient credits"}}',
    // DeepSeek / SiliconFlow / MiniMax use "balance", not "credits".
    "Insufficient Balance",
    "Sorry, your account balance is insufficient",
    "insufficient balance of the account",
    '{"code":30001,"message":"Sorry, your account balance is insufficient","data":null}',
  ])("treats HTTP 402 and credit-exhaustion wording as terminal: %s", (message) => {
    expect(classifyAgentError(new Error(message))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
    });
  });

  // Anthropic bills an empty wallet as HTTP 400 with this sentence. DashScope
  // uses code Arrearage, sometimes with only the "good standing" sentence
  // left. pi-ai often drops the status, and a gateway may relabel the same
  // text 429. Backing off cannot add credits.
  it.each([
    "Your credit balance is too low to access the Anthropic API. Please go to Plans & Billing to upgrade or purchase credits.",
    '{"code":"Arrearage","message":"Access denied, please make sure your account is in good standing.","type":"Arrearage"}',
    "Arrearage",
    "Access denied, please make sure your account is in good standing.",
  ])(
    "treats Anthropic credit-balance and DashScope Arrearage wording as terminal: %s",
    (message) => {
      expect(classifyAgentError(message)).toMatchObject({
        code: "PROVIDER_ERROR",
        retriable: false,
      });
      expect(classifyAgentError(new Error(message))).toMatchObject({
        code: "PROVIDER_ERROR",
        retriable: false,
      });
      expect(classifyAgentError(Object.assign(new Error(message), { status: 429 }))).toMatchObject({
        code: "PROVIDER_ERROR",
        retriable: false,
      });
      expect(classifyAgentError(Object.assign(new Error(message), { status: 400 }))).toMatchObject({
        code: "PROVIDER_ERROR",
        retriable: false,
      });
    },
  );

  it("treats a structured Arrearage code as terminal even when the message omits the word", () => {
    expect(classifyAgentError(Object.assign(
      new Error("Access denied"),
      { code: "Arrearage" },
    ))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
    });
  });

  it("does not treat nearby balance or access wording as account exhaustion", () => {
    for (const message of [
      "insufficient credentials",
      "balance",
      "credits",
      "Access denied",
      "Your account is in good standing.",
    ]) {
      expect(classifyAgentError(new Error(message))).toMatchObject({
        code: "PROVIDER_ERROR",
        retriable: true,
      });
    }
    expect(classifyAgentError(Object.assign(new Error("Access denied"), { status: 429 }))).toMatchObject({
      code: "PROVIDER_RATE_LIMITED",
      retriable: true,
    });
    expect(classifyAgentError(Object.assign(
      new Error("Your account is in good standing."),
      { status: 429 },
    ))).toMatchObject({
      code: "PROVIDER_RATE_LIMITED",
      retriable: true,
    });
  });

  it("treats a structured HTTP 402 as a terminal provider error", () => {
    expect(classifyAgentError(Object.assign(
      new Error("Payment Required"),
      { status: 402 },
    ))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
      details: { providerStatus: 402 },
    });
  });

  // pi-ai often keeps only the OpenAI SDK string "Error code: <status> - <body>"
  // and drops err.status. The prefix is the HTTP status; a bare business code is not.
  it.each([
    [
      "Error code: 402 - {'error': {'message': 'Insufficient Balance', 'type': 'invalid_request_error'}}",
      "PROVIDER_ERROR",
      false,
      402,
    ],
    [
      "Error code: 401 - Incorrect API key provided",
      "PROVIDER_UNAUTHORIZED",
      false,
      401,
    ],
    [
      "Error code: 429 - Rate limit reached for model",
      "PROVIDER_RATE_LIMITED",
      true,
      429,
    ],
    [
      "Error code: 404 - The model does not exist",
      "MODEL_NOT_CONFIGURED",
      false,
      404,
    ],
    [
      "Error code: 402 - see note (500)",
      "PROVIDER_ERROR",
      false,
      402,
    ],
  ])(
    "reads an OpenAI SDK Error code prefix as the HTTP status: %s",
    (message, code, retriable, status) => {
      expect(classifyAgentError(new Error(message))).toMatchObject({
        code,
        retriable,
        details: { providerStatus: status },
      });
    },
  );

  it("does not read a business code or prose as an OpenAI Error code status", () => {
    const silicon = classifyAgentError(new Error("Error code: 30001 - account balance"));
    expect(silicon.details?.providerStatus).toBeUndefined();
    expect(silicon).toMatchObject({ code: "PROVIDER_ERROR", retriable: true });

    const bare = classifyAgentError(new Error("provider said code: 401"));
    expect(bare.details?.providerStatus).toBeUndefined();
    expect(bare).toMatchObject({ code: "PROVIDER_ERROR", retriable: true });

    const prose = classifyAgentError(new Error("see the error code: 500 in the handbook"));
    expect(prose.details?.providerStatus).toBeUndefined();
    expect(prose).toMatchObject({ code: "PROVIDER_ERROR", retriable: true });

    const zhipu = classifyAgentError(
      '{"error":{"code":"1308","message":"Usage limit reached"}}',
    );
    expect(zhipu.details?.providerStatus).toBeUndefined();
    expect(zhipu).toMatchObject({ code: "PROVIDER_ERROR", retriable: false });
  });

  it("keeps a structured status ahead of an OpenAI Error code prefix", () => {
    expect(classifyAgentError(Object.assign(
      new Error("Error code: 402 - Payment failed upstream"),
      { status: 503 },
    ))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: true,
      details: { providerStatus: 503 },
    });
  });

  it("does not treat a bare credits mention or a 429 rate limit as credit exhaustion", () => {
    expect(classifyAgentError(new Error("credits"))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: true,
    });
    expect(classifyAgentError(new Error("credits remaining will reset"))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: true,
    });
    // "credentials" shares a prefix with "credits" and must stay out of the
    // exhaustion matcher.
    expect(classifyAgentError(new Error("insufficient credentials"))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: true,
    });
    expect(classifyAgentError(
      '429: {"error":{"type":"rate_limit_error","message":"credits remaining"}}',
    )).toMatchObject({
      code: "PROVIDER_RATE_LIMITED",
      retriable: true,
    });
    expect(classifyAgentError(new Error("429: Too many requests"))).toMatchObject({
      code: "PROVIDER_RATE_LIMITED",
      retriable: true,
    });
  });

  // Volcengine Ark reports an overdue account as AccountOverdueError
  // ("your account has an overdue balance"). pi-ai often drops the HTTP 403
  // and leaves the message, a JSON body, or error.code. Backing off cannot
  // clear the balance, so those shapes are terminal before the status table.
  // A bare "overdue" / "account" / "forbidden" is not this failure.
  it.each([
    "The request failed because your account has an overdue balance.",
    "AccountOverdueError: The request failed because your account has an overdue balance.",
    JSON.stringify({
      error: {
        code: "AccountOverdueError",
        message: "The request failed because your account has an overdue balance.",
        type: "Forbidden",
      },
    }),
  ])("treats statusless Volcengine overdue-balance text as terminal: %s", (message) => {
    expect(classifyAgentError(message)).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
    });
    expect(classifyAgentError(new Error(message))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
    });
  });

  it("treats a structured AccountOverdueError code as terminal billing exhaustion", () => {
    expect(classifyAgentError(Object.assign(
      new Error("The request failed because your account has an overdue balance."),
      { code: "AccountOverdueError" },
    ))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
      details: { providerCode: "AccountOverdueError" },
    });
    // The code alone is enough when the message text was replaced.
    expect(classifyAgentError(Object.assign(
      new Error("request rejected"),
      { code: "AccountOverdueError" },
    ))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
      details: { providerCode: "AccountOverdueError" },
    });
  });

  it.each([429, 400])(
    "does not retry AccountOverdueError when HTTP %s is still attached",
    (status) => {
      expect(classifyAgentError(Object.assign(
        new Error("The request failed because your account has an overdue balance."),
        { status, code: "AccountOverdueError" },
      ))).toMatchObject({
        code: "PROVIDER_ERROR",
        retriable: false,
        details: { providerStatus: status, providerCode: "AccountOverdueError" },
      });
    },
  );

  it("does not retry an overdue-balance message reported as HTTP 429", () => {
    expect(classifyAgentError(Object.assign(
      new Error("The request failed because your account has an overdue balance."),
      { status: 429 },
    ))).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
      details: { providerStatus: 429 },
    });
  });

  // Exhaustion is probed before the 403 branch, so a body that still carries
  // 403 and the overdue wording is billing-terminal. A plain 403 is not.
  it("classifies a 403 AccountOverdueError body as terminal billing exhaustion", () => {
    expect(classifyAgentError(
      "Error code: 403 - { 'error': { 'code': 'AccountOverdueError', 'message': 'The request failed because your account has an overdue balance.', 'type': 'Forbidden' } }",
    )).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: false,
      details: { providerStatus: 403 },
    });
  });

  it("does not treat unrelated overdue, account, or forbidden wording as billing exhaustion", () => {
    for (const message of [
      "overdue library book",
      "overdue",
      "account",
      "balance",
      "credits",
      "insufficient credentials",
      "Forbidden",
      "account has overdue",
    ]) {
      expect(classifyAgentError(message)).toMatchObject({
        code: "PROVIDER_ERROR",
        retriable: true,
      });
    }
    expect(classifyAgentError("403 Forbidden")).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
    });
    expect(classifyAgentError(Object.assign(
      new Error("permission denied"),
      { status: 403 },
    ))).toMatchObject({
      code: "PROVIDER_UNAUTHORIZED",
      retriable: false,
    });
  });

  it.each([
    "Rate limit exceeded",
    "Too many requests",
    "quota exceeded",
  ])("keeps throughput quota wording retryable: %s", (message) => {
    expect(classifyAgentError(new Error(message))).toMatchObject({
      code: "PROVIDER_RATE_LIMITED",
      retriable: true,
    });
  });

  it("keeps context checkpoint failures distinct from provider failures", () => {
    expect(
      classifyAgentError(
        "CONTEXT_COMPACTION_FAILED: unable to create a checkpoint before the next model request",
      ),
    ).toMatchObject({
      code: "CONTEXT_COMPACTION_FAILED",
      retriable: false,
      details: { origin: "local" },
    });
  });

  it("classifies network failures via the cause chain", () => {
    const err = new Error("fetch failed");
    (err as any).cause = Object.assign(new Error("connect ECONNREFUSED"), {
      code: "ECONNREFUSED",
    });
    expect(classifyAgentError(err)).toMatchObject({
      code: "NETWORK_ERROR",
      retriable: true,
      details: { networkCategory: "refused", networkCode: "ECONNREFUSED" },
    });
    expect(classifyAgentError("getaddrinfo ENOTFOUND api.example.com"))
      .toMatchObject({
        code: "NETWORK_ERROR",
        details: {
          networkCategory: "dns",
          networkCode: "ENOTFOUND",
          networkHost: "api.example.com",
        },
      });
  });

  it("names the failing layer behind a nested DNS cause", () => {
    const err = new TypeError("fetch failed");
    (err as any).cause = Object.assign(
      new Error("getaddrinfo ENOTFOUND api.example.com"),
      {
        code: "ENOTFOUND",
        syscall: "getaddrinfo",
        hostname: "api.example.com",
      },
    );

    // `providerCode` repeats the same errno, so it is folded into the
    // network-namespaced key instead of being logged twice.
    expect(classifyAgentError(err).details).toEqual({
      networkCategory: "dns",
      networkCode: "ENOTFOUND",
      networkSyscall: "getaddrinfo",
      networkHost: "api.example.com",
    });
  });

  it("reads the errno out of an undici aggregate cause", () => {
    const aggregate = new AggregateError(
      [
        Object.assign(new Error("connect ECONNREFUSED ::1:443"), {
          code: "ECONNREFUSED",
        }),
        Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:443"), {
          code: "ECONNREFUSED",
        }),
      ],
      "all connection attempts failed",
    );
    const err = Object.assign(new TypeError("fetch failed"), {
      cause: aggregate,
    });

    expect(classifyAgentError(err)).toMatchObject({
      code: "NETWORK_ERROR",
      details: { networkCategory: "refused", networkCode: "ECONNREFUSED" },
    });
  });

  it("separates TLS, timeout and dropped-socket causes", () => {
    const tls = Object.assign(new TypeError("fetch failed"), {
      cause: Object.assign(new Error("self signed certificate"), {
        code: "DEPTH_ZERO_SELF_SIGNED_CERT",
      }),
    });
    const tlsProto = Object.assign(new TypeError("fetch failed"), {
      cause: Object.assign(new Error("write EPROTO"), { code: "EPROTO" }),
    });
    const timeout = Object.assign(new TypeError("fetch failed"), {
      cause: Object.assign(new Error("Connect Timeout Error"), {
        code: "UND_ERR_CONNECT_TIMEOUT",
      }),
    });
    const reset = Object.assign(new TypeError("fetch failed"), {
      cause: Object.assign(new Error("other side closed"), {
        code: "UND_ERR_SOCKET",
      }),
    });
    const proxy = Object.assign(new TypeError("fetch failed"), {
      cause: Object.assign(new Error("proxy connection failed"), {
        code: "ERR_PROXY_CONNECTION_FAILED",
      }),
    });

    expect(classifyAgentError(tls).details).toMatchObject({
      networkCategory: "tls",
      networkCode: "DEPTH_ZERO_SELF_SIGNED_CERT",
    });
    expect(classifyAgentError(tlsProto).details).toMatchObject({
      networkCategory: "tls",
      networkCode: "EPROTO",
    });
    expect(classifyAgentError(timeout).details).toMatchObject({
      networkCategory: "timeout",
      networkCode: "UND_ERR_CONNECT_TIMEOUT",
    });
    expect(classifyAgentError(reset).details).toMatchObject({
      networkCategory: "reset",
      networkCode: "UND_ERR_SOCKET",
    });
    expect(classifyAgentError(proxy).details).toMatchObject({
      networkCategory: "proxy",
      networkCode: "ERR_PROXY_CONNECTION_FAILED",
    });
  });

  it("says the layer is unknown rather than guessing when no cause survives", () => {
    // The reporter's shape: a bare `fetch failed` with no cause chain kept.
    expect(classifyAgentError(new TypeError("fetch failed"))).toMatchObject({
      code: "NETWORK_ERROR",
      retriable: true,
      details: { networkCategory: "unknown" },
    });
  });

  it("never leaks credentials through network diagnostics", () => {
    const err = Object.assign(new TypeError("fetch failed"), {
      cause: Object.assign(
        new Error(
          "connect ECONNRESET https://api.example.com/v1/chat?api_key=sk-live-secret Authorization: Bearer token-secret",
        ),
        { code: "ECONNRESET", hostname: "user:[email protected]" },
      ),
    });
    const classified = classifyAgentError(err);
    const serialized = JSON.stringify(classified);

    expect(serialized).not.toContain("sk-live-secret");
    expect(serialized).not.toContain("token-secret");
    expect(serialized).not.toContain("user:pass");
    expect(serialized).not.toContain("?api_key");
    // Only the errno survives: no hostname, no port, no URL, no query.
    expect(classified.details).toEqual({
      networkCategory: "reset",
      networkCode: "ECONNRESET",
    });
  });

  it("classifies aborts, timeouts and unknown errors", () => {
    const abortErr = new Error("The operation was aborted");
    abortErr.name = "AbortError";
    expect(classifyAgentError(abortErr)).toMatchObject({
      code: "TURN_ABORTED",
      retriable: false,
    });
    expect(classifyAgentError("agent.prompt timeout")).toMatchObject({
      code: "TIMEOUT",
      retriable: true,
    });
    expect(classifyAgentError("something unexpected")).toMatchObject({
      code: "PROVIDER_ERROR",
      retriable: true,
    });
  });

  it("lets an abort win over a compaction failure it caused", () => {
    const abortErr = new Error(
      "CONTEXT_COMPACTION_FAILED: unable to create a checkpoint before the next model request",
    );
    abortErr.name = "AbortError";
    expect(classifyAgentError(abortErr)).toMatchObject({ code: "TURN_ABORTED" });
    expect(classifyAgentError("Turn aborted while compacting context")).toMatchObject({
      code: "TURN_ABORTED",
      retriable: false,
    });
  });

  it("does not treat transport abort wording as a user Stop", () => {
    // Socket and stream failures say "abort" without being a cancellation.
    // They must stay retriable so provider retry runs and the UI does not
    // show Stop.
    expect(classifyAgentError(new Error("software caused connection abort"))).toMatchObject({
      code: "NETWORK_ERROR",
      retriable: true,
      details: { networkCategory: "reset" },
    });
    expect(classifyAgentError(new Error("connection aborted"))).toMatchObject({
      code: "NETWORK_ERROR",
      retriable: true,
      details: { networkCategory: "reset" },
    });
    expect(classifyAgentError(new Error("stream aborted"))).toMatchObject({
      code: "STREAM_FAILED",
      retriable: true,
    });
    expect(classifyAgentError(new Error("provider aborted the stream"))).toMatchObject({
      code: "STREAM_FAILED",
      retriable: true,
    });

    expect(classifyAgentError("Request aborted")).toMatchObject({
      code: "TURN_ABORTED",
      retriable: false,
    });
    expect(classifyAgentError("The operation was aborted")).toMatchObject({
      code: "TURN_ABORTED",
      retriable: false,
    });
    expect(classifyAgentError("Turn aborted while compacting context")).toMatchObject({
      code: "TURN_ABORTED",
      retriable: false,
    });
    const abortErr = Object.assign(new Error("The operation was aborted"), {
      name: "AbortError",
    });
    expect(classifyAgentError(abortErr)).toMatchObject({
      code: "TURN_ABORTED",
      retriable: false,
    });
  });

  it("classifies a provider termination as a retryable stream failure", () => {
    expect(classifyAgentError("terminated")).toMatchObject({
      code: "STREAM_FAILED",
      retriable: true,
    });
  });

  it("keeps provider diagnostics bounded to status and safe error codes", () => {
    const classified = classifyAgentError(
      Object.assign(new Error("terminated"), {
        status: 200,
        code: "ERR_STREAM_PREMATURE_CLOSE",
      }),
    );
    expect(classified.details).toEqual({
      providerStatus: 200,
      providerCode: "ERR_STREAM_PREMATURE_CLOSE",
    });

    const unsafe = classifyAgentError(
      Object.assign(new Error("terminated"), {
        code: "Bearer secret-token",
      }),
    );
    expect(unsafe.details).toBeUndefined();
  });

  it("redacts secrets before exposing provider error details", () => {
    const classified = classifyAgentError(
      '401: {"api_key":"sk-secret","Authorization":"Bearer token-secret"}',
    );

    expect(classified.message).not.toContain("sk-secret");
    expect(classified.message).not.toContain("token-secret");
    expect(classified.message).toContain("[REDACTED]");
  });

  it("truncates oversized provider bodies", () => {
    const { message } = classifyAgentError(`500: ${"x".repeat(5000)}`);
    expect(message.length).toBeLessThan(700);
  });

  it("keeps a pseudo errno out of the reported network code", () => {
    // A long errno-shaped run inside a provider body must not become an
    // unbounded detail: the message is untrusted text.
    const flood = `EDNS${"A".repeat(3_000)}`;
    expect(describeNetworkFailure(flood, flood).code).toBeUndefined();
    expect(classifyAgentError(flood).details).not.toHaveProperty("networkCode");

    // A body word that merely contains "proxy" is not a proxy layer either.
    const bodyWord = Object.assign(new TypeError("fetch failed"), {
      cause: Object.assign(new Error("blocked EBLOCKEDBYPROXY"), {
        code: "EBLOCKEDBYPROXY",
      }),
    });
    const details = classifyAgentError(bodyWord).details ?? {};
    expect(details.networkCategory).toBe("unknown");
    expect(details).not.toHaveProperty("networkCode");
  });

  it("reads a proxy failure as a proxy failure wherever the errno sits", () => {
    // undici reports the proxy's own socket errno as the deeper cause; the
    // proxy is still the layer that failed.
    const err = Object.assign(new TypeError("fetch failed"), {
      cause: Object.assign(new Error("proxy connect ECONNREFUSED"), {
        code: "ERR_PROXY_CONNECTION_FAILED",
        cause: Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:7890"), {
          code: "ECONNREFUSED",
        }),
      }),
    });

    expect(classifyAgentError(err).details).toEqual({
      networkCategory: "proxy",
      networkCode: "ERR_PROXY_CONNECTION_FAILED",
    });
  });

  it("does not turn a credential-shaped message token into a hostname", () => {
    const token = classifyAgentError(
      "getaddrinfo ENOTFOUND sk-live-abcdef012345",
    );
    expect(token.details).toMatchObject({
      networkCategory: "dns",
      networkCode: "ENOTFOUND",
    });
    expect(token.details).not.toHaveProperty("networkHost");

    // Truncating `user:pass@host` at the colon must not report `user` as the
    // host either.
    expect(
      classifyAgentError(
        "getaddrinfo ENOTFOUND user:[email protected]?api_key=sk-1",
      ).details,
    ).not.toHaveProperty("networkHost");
  });

  it("classifies host capacity exhaustion and timeout distinctly from provider failures (#1071)", () => {
    // Error caused by host RPC slot exhaustion during credential/config resolution
    const overloadError = new Error(
      "API key auth failed for provider chatgpt: host RPC capacity is exhausted",
    );
    expect(classifyAgentError(overloadError)).toMatchObject({
      code: "HOST_OVERLOADED",
      retriable: true,
      details: { origin: "host" },
    });

    const typedOverload = Object.assign(new Error("RPC failed"), {
      errorCode: "HOST_OVERLOADED",
    });
    expect(classifyAgentError(typedOverload)).toMatchObject({
      code: "HOST_OVERLOADED",
      retriable: true,
      details: { origin: "host" },
    });

    const unavailableError = new Error("host RPC timeout: session.appendMessage");
    expect(classifyAgentError(unavailableError)).toMatchObject({
      code: "HOST_UNAVAILABLE",
      retriable: true,
      details: { origin: "host" },
    });
  });
});