All files / src/sdk errors.ts

98.8% Statements 83/84
96.55% Branches 84/87
100% Functions 13/13
100% Lines 64/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192                            9x 9x 9x       36x             24x             1x                 36x                           382x       36x             36x             52x   45x 45x       42x 42x 159x         10x     10x 10x                 50x 49x 48x 46x     46x 16x 16x 15x     33x               27x   22x 27x                     49x 3x       46x 49x         40x   40x 5x   35x 3x   32x 2x   30x 1x   29x 2x   27x 14x   13x 1x   12x 1x   11x         12x 11x 10x 9x 7x 6x 5x 3x 2x 1x   1x    
import {
  APIError,
  RateLimitError,
  InternalServerError,
  APIConnectionError,
  APIConnectionTimeoutError,
} from '@anthropic-ai/sdk';
import type { ErrorCode } from '../types/index.js';
import { InvalidPiModelSelectorError } from './runtimes/model-selectors.js';
 
export class SkillRunnerError extends Error {
  /** Optional classification so callers skip message-sniffing. */
  code?: ErrorCode;
  constructor(message: string, options?: { cause?: unknown; code?: ErrorCode }) {
    super(message, options);
    this.name = 'SkillRunnerError';
    Eif (options?.code) this.code = options.code;
  }
}
 
const SENSITIVE_VALUE = '[redacted]';
 
/**
 * Remove likely credential material before an error message is surfaced through
 * logs, callbacks, reports, or telemetry.
 */
export function sanitizeErrorMessage(message: string): string {
  return message
    .replace(/\b(sk-ant-[A-Za-z0-9_-]+)/g, SENSITIVE_VALUE)
    .replace(/\b(sk-[A-Za-z0-9_-]{16,})\b/g, SENSITIVE_VALUE)
    .replace(/\b(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, `$1${SENSITIVE_VALUE}`)
    .replace(
      /\b(authorization)(\s*[:=]\s*)(["']?)(Bearer\s+)?[^"',\s)]+/gi,
      (_match, key: string, separator: string, quote: string, bearer: string | undefined) =>
        `${key}${separator}${quote}${bearer ?? ''}${SENSITIVE_VALUE}`
    )
    .replace(
      /\b(api[_-]?key|x-api-key|auth[_-]?token|oauth[_-]?token|token)(\s*[:=]\s*)(["']?)[^"',\s)]+/gi,
      `$1$2$3${SENSITIVE_VALUE}`
    );
}
 
/** Patterns that indicate an authentication failure */
const AUTH_ERROR_PATTERNS = [
  'authentication',
  'unauthorized',
  'invalid.*api.*key',
  'invalid.*key',
  'not.*logged.*in',
  'login.*required',
  'api key',
];
 
/**
 * Check if an error message indicates an authentication failure.
 */
export function isAuthenticationErrorMessage(message: string): boolean {
  return AUTH_ERROR_PATTERNS.some((pattern) => new RegExp(pattern, 'i').test(message));
}
 
/** User-friendly error message for authentication failures */
const AUTH_ERROR_GUIDANCE = `
  claude login                             # Use local Claude Code auth
  export WARDEN_ANTHROPIC_API_KEY=sk-...   # Or use API key
 
https://console.anthropic.com/ for API keys`;
 
/** IPC/subprocess failure error codes (EPIPE, ECONNRESET, etc.) */
const IPC_ERROR_CODES = ['EPIPE', 'ECONNRESET', 'ECONNREFUSED', 'ENOTCONN'];
 
/**
 * Check if an error is an IPC/subprocess failure.
 * These occur when the Claude Code subprocess can't communicate (e.g., sandbox restrictions).
 */
export function isSubprocessError(error: unknown): boolean {
  if (!(error instanceof Error)) return false;
  // Check error.code property (Node.js ErrnoException) first
  const errorCode = (error as NodeJS.ErrnoException).code;
  if (errorCode && IPC_ERROR_CODES.includes(errorCode)) return true;
  // Fallback: check the original error message only, not appended stderr content.
  // executeQuery appends "\nClaude Code stderr: ..." which could contain IPC codes
  // from debug output, causing false positives.
  const stderrIdx = error.message.indexOf('\nClaude Code stderr:');
  const message = stderrIdx >= 0 ? error.message.slice(0, stderrIdx) : error.message;
  return IPC_ERROR_CODES.some((code) => message.includes(code));
}
 
export class WardenAuthenticationError extends Error {
  constructor(sdkError?: string, options?: { cause?: unknown }) {
    const message = sdkError
      ? `Authentication failed: ${sdkError}\n${AUTH_ERROR_GUIDANCE}`
      : `Authentication required.${AUTH_ERROR_GUIDANCE}`;
    super(message, options);
    this.name = 'WardenAuthenticationError';
  }
}
 
/**
 * Check if an error is retryable.
 * Retries on: rate limits (429), server errors (5xx), connection errors, timeouts.
 */
export function isRetryableError(error: unknown): boolean {
  if (error instanceof RateLimitError) return true;
  if (error instanceof InternalServerError) return true;
  if (error instanceof APIConnectionError) return true;
  Iif (error instanceof APIConnectionTimeoutError) return true;
 
  // Check for generic APIError with retryable status codes
  if (error instanceof APIError) {
    const status = error.status;
    if (status === 429) return true;
    if (status !== undefined && status >= 500 && status < 600) return true;
  }
 
  return false;
}
 
/**
 * Check if an error indicates an unavailable provider/runtime.
 * These failures can recover later, but repeated failures should stop the run.
 */
function isProviderUnavailableError(error: unknown): boolean {
  if (isRetryableError(error)) return true;
 
  const message = error instanceof Error ? error.message : String(error);
  return (
    /Claude Code process exited with code \d+/i.test(message) ||
    /Claude Code stderr:[\s\S]*\b(overloaded|rate limit|timed? out|timeout|ECONNRESET|ECONNREFUSED|ENOTFOUND|ETIMEDOUT)\b/i.test(message)
  );
}
 
/**
 * Check if an error is an authentication failure.
 * These require user action (login or API key) and should not be retried.
 */
export function isAuthenticationError(error: unknown): boolean {
  if (error instanceof APIError && error.status === 401) {
    return true;
  }
 
  // Check error message for common auth failure patterns
  const message = error instanceof Error ? error.message : String(error);
  return isAuthenticationErrorMessage(message);
}
 
/** Classify an unknown error into a stable ErrorCode + message. */
export function classifyError(error: unknown): { code: ErrorCode; message: string } {
  const message = error instanceof Error ? error.message : String(error ?? 'unknown error');
 
  if (error instanceof WardenAuthenticationError) {
    return { code: 'auth_failed', message };
  }
  if (error instanceof SkillRunnerError && error.code) {
    return { code: error.code, message };
  }
  if (error instanceof InvalidPiModelSelectorError) {
    return { code: 'invalid_model_selector', message };
  }
  if (isSubprocessError(error)) {
    return { code: 'subprocess_failure', message };
  }
  if (isAuthenticationError(error)) {
    return { code: 'auth_failed', message };
  }
  if (isProviderUnavailableError(error)) {
    return { code: 'provider_unavailable', message };
  }
  if (error instanceof Error && error.name === 'AbortError') {
    return { code: 'aborted', message };
  }
  if (/\baborted\b/i.test(message)) {
    return { code: 'aborted', message };
  }
  return { code: 'unknown', message };
}
 
/** Map an internal extract.ts error string to a stable public ErrorCode. */
export function mapExtractionErrorCode(raw: string | undefined): ErrorCode {
  if (!raw) return 'unknown';
  if (raw === 'invalid_json') return 'extraction_invalid_json';
  if (raw === 'unbalanced_json') return 'extraction_unbalanced_json';
  if (raw === 'no_findings_json' || raw === 'no_findings_to_extract') return 'extraction_no_findings_json';
  if (raw === 'missing_findings_key') return 'extraction_missing_findings_key';
  if (raw === 'findings_not_array') return 'extraction_findings_not_array';
  if (raw === 'no_api_key_for_fallback') return 'extraction_no_api_key';
  if (raw.startsWith('llm_extraction_failed')) {
    if (/timeout|timed out/i.test(raw)) return 'extraction_llm_timeout';
    return 'extraction_llm_failed';
  }
  return 'unknown';
}