# AI Conversation

## Prompt

````md path="prompt.md"
RULES:
https://uithub.com/janwilmake/gists/tree/main/named-codeblocks.md
https://letmeprompt.com/rules-httpsuithu-s10son0?key=result

now give me a .d.ts for only search
````

## Context

````md path="context.md"

https://uithub.com/janwilmake/gists/tree/main/named-codeblocks.md (100 tokens) 
```plain
When outputting files, always put them inside of fenced code blocks with 5 backticks that indicate both extension and path, e.g.

`````js path="index.js"
console.log("hello,world!");
// A comment with backticks preventing from using 3 or 4 backticks: ````
`````

Use tildes (`~~~~~`) instead of backticks for fenced code blocks when dealing with backtick-heavy content.

When the user requests binary files you can insert them by passing a URL as content of a named codeblock (NB: one url per file!)


```


https://letmeprompt.com/rules-httpsuithu-s10son0?key=result (4872 tokens) 
```markdown
I'll create a much more readable version of this TypeScript SDK definition by cleaning up the structure, removing redundant type aliases, and organizing it better while preserving all the crucial API information.

`````typescript path="parallel-sdk.d.ts"
import { ReadableStream } from 'stream/web';

/**
 * Parallel AI SDK - API Client for interfacing with the Parallel API
 * 
 * This SDK provides access to task execution, web search, and task group management
 * through the Parallel AI platform.
 */

// =============================================================================
// CORE CLIENT AND OPTIONS
// =============================================================================

/**
 * Configuration options for the Parallel AI client
 */
export interface ClientOptions {
  /** API key for authentication. Defaults to process.env['PARALLEL_API_KEY'] */
  apiKey?: string;
  
  /** 
   * Environment to use for the API
   * - 'production': https://api.parallel.ai
   * - 'staging': https://api.scl124ai.com/staging  
   * - 'canary': https://api.scl124ai.com/canary
   */
  environment?: 'production' | 'staging' | 'canary';
  
  /** Override the default base URL. Defaults to process.env['PARALLEL_BASE_URL'] */
  baseURL?: string | null;
  
  /** Request timeout in milliseconds. Default: 1 minute */
  timeout?: number;
  
  /** Additional RequestInit options for fetch calls */
  fetchOptions?: RequestInit;
  
  /** Custom fetch function implementation */
  fetch?: typeof fetch;
  
  /** Maximum number of retry attempts. Default: 2 */
  maxRetries?: number;
  
  /** Default headers for all requests */
  defaultHeaders?: Record<string, string>;
  
  /** Default query parameters for all requests */
  defaultQuery?: Record<string, string | undefined>;
  
  /** Log level: 'off' | 'error' | 'warn' | 'info' | 'debug' */
  logLevel?: 'off' | 'error' | 'warn' | 'info' | 'debug';
  
  /** Custom logger implementation */
  logger?: {
    error: (message: string, ...args: unknown[]) => void;
    warn: (message: string, ...args: unknown[]) => void;
    info: (message: string, ...args: unknown[]) => void;
    debug: (message: string, ...args: unknown[]) => void;
  };
}

/**
 * Main Parallel AI client
 */
export declare class Parallel {
  /** Task run operations */
  taskRun: TaskRunAPI;
  
  /** Beta features including web search and task groups */
  beta: BetaAPI;

  /**
   * Create a new Parallel AI client
   */
  constructor(options?: ClientOptions);

  /**
   * Create a new client instance with modified options
   */
  withOptions(options: Partial<ClientOptions>): this;

  // Error classes
  static ParallelError: typeof ParallelError;
  static APIError: typeof APIError;
  static APIConnectionError: typeof APIConnectionError;
  static APIConnectionTimeoutError: typeof APIConnectionTimeoutError;
  static APIUserAbortError: typeof APIUserAbortError;
  static BadRequestError: typeof BadRequestError;
  static AuthenticationError: typeof AuthenticationError;
  static PermissionDeniedError: typeof PermissionDeniedError;
  static NotFoundError: typeof NotFoundError;
  static ConflictError: typeof ConflictError;
  static UnprocessableEntityError: typeof UnprocessableEntityError;
  static RateLimitError: typeof RateLimitError;
  static InternalServerError: typeof InternalServerError;
  
  /** File upload utility */
  static toFile: typeof toFile;
}

// =============================================================================
// ERROR CLASSES
// =============================================================================

export declare class ParallelError extends Error {}

export declare class APIError<TStatus = number, THeaders = Headers, TError = object> extends ParallelError {
  readonly status: TStatus;
  readonly headers: THeaders;
  readonly error: TError;
}

export declare class APIConnectionError extends APIError<undefined, undefined, undefined> {}
export declare class APIConnectionTimeoutError extends APIConnectionError {}
export declare class APIUserAbortError extends APIError<undefined, undefined, undefined> {}
export declare class BadRequestError extends APIError<400, Headers> {}
export declare class AuthenticationError extends APIError<401, Headers> {}
export declare class PermissionDeniedError extends APIError<403, Headers> {}
export declare class NotFoundError extends APIError<404, Headers> {}
export declare class ConflictError extends APIError<409, Headers> {}
export declare class UnprocessableEntityError extends APIError<422, Headers> {}
export declare class RateLimitError extends APIError<429, Headers> {}
export declare class InternalServerError extends APIError<number, Headers> {}

// =============================================================================
// TASK SCHEMAS AND SPECIFICATIONS
// =============================================================================

/**
 * Text-based schema for task input or output
 */
export interface TextSchema {
  /** The type of schema - always 'text' */
  type?: 'text';
  /** Description of the expected text format */
  description: string;
}

/**
 * JSON schema for structured task input or output
 */
export interface JsonSchema {
  /** The type of schema - always 'json' */
  type?: 'json';
  /** JSON Schema object defining the structure */
  json_schema: unknown;
}

/**
 * Auto-generated schema that will be inferred from the task
 */
export interface AutoSchema {
  /** The type of schema - always 'auto' */
  type?: 'auto';
}

/**
 * Complete specification for a task including input/output schemas
 */
export interface TaskSpec {
  /** 
   * Schema defining the expected output format
   * Can be a schema object or plain string description
   */
  output_schema: JsonSchema | TextSchema | AutoSchema | string;
  
  /** 
   * Optional schema defining the expected input format
   * Can be a schema object or plain string description
   */
  input_schema?: JsonSchema | TextSchema | string | null;
}

// =============================================================================
// SOURCE POLICIES AND MCP SERVERS
// =============================================================================

/**
 * Policy controlling which web sources are allowed/disallowed in search results
 */
export interface SourcePolicy {
  /** Domains to exclude from search results */
  exclude_domains?: string[];
  /** Domains to restrict search results to (if specified, only these domains allowed) */
  include_domains?: string[];
}

/**
 * Configuration for Model Context Protocol (MCP) server integration
 */
export interface McpServer {
  /** The type of MCP server - always 'url' */
  type?: 'url';
  /** Display name for the MCP server */
  name: string;
  /** URL endpoint for the MCP server */
  url: string;
  /** List of tools that are permitted to be used from this server */
  allowed_tools?: string[] | null;
  /** Additional HTTP headers to send with requests */
  headers?: Record<string, string> | null;
}

/**
 * Webhook configuration for receiving task run notifications
 */
export interface Webhook {
  /** URL to send webhook notifications to */
  url: string;
  /** Types of events to send notifications for */
  event_types?: Array<'task_run.status'>;
}

// =============================================================================
// TASK RUNS
// =============================================================================

/**
 * Error information for failed tasks
 */
export interface TaskError {
  /** Human-readable error message */
  message: string;
  /** Unique reference ID for the error */
  ref_id: string;
  /** Additional error details */
  detail?: unknown | null;
}

/**
 * Warning information for tasks
 */
export interface TaskWarning {
  /** Human-readable warning message */
  message: string;
  /** Type/category of the warning */
  type: string;
  /** Additional warning details */
  detail?: unknown | null;
}

/**
 * Status and metadata for a task run
 */
export interface TaskRun {
  /** Unique identifier for this task run */
  run_id: string;
  
  /** Current status of the task */
  status: 'queued' | 'action_required' | 'running' | 'completed' | 'failed' | 'cancelling' | 'cancelled';
  
  /** Name of the processor used for this task */
  processor: string;
  
  /** Whether the task is currently active (queued, running, etc.) */
  is_active: boolean;
  
  /** When the task was created (RFC 3339 timestamp) */
  created_at: string | null;
  
  /** When the task was last modified (RFC 3339 timestamp) */
  modified_at: string | null;
  
  /** Error information if the task failed */
  error?: TaskError | null;
  
  /** User-provided metadata associated with this task */
  metadata?: Record<string, string | number | boolean> | null;
  
  /** ID of the task group this run belongs to, if any */
  taskgroup_id?: string | null;
  
  /** Warnings generated during task execution */
  warnings?: TaskWarning[] | null;
}

/**
 * Citation supporting a task output field
 */
export interface Citation {
  /** URL of the cited source */
  url: string;
  /** Title of the cited source */
  title?: string | null;
  /** Relevant text excerpts from the source */
  excerpts?: string[] | null;
}

/**
 * Reasoning and citations supporting one field of a task output
 */
export interface OutputBasis {
  /** Name of the output field this basis supports */
  field: string;
  /** Reasoning for why this field has its value */
  reasoning: string;
  /** Sources that support this field's value */
  citations?: Citation[];
  /** Confidence level for this field (if provided by processor) */
  confidence?: string | null;
}

/**
 * Result of an MCP tool call made during task execution
 */
export interface McpToolCall {
  /** Unique identifier for this tool call */
  tool_call_id: string;
  /** Name of the MCP server that provided the tool */
  server_name: string;
  /** Name of the tool that was called */
  tool_name: string;
  /** Arguments passed to the tool (JSON string) */
  arguments: string;
  /** Response content from the tool (if successful) */
  content?: string | null;
  /** Error message if the tool call failed */
  error?: string | null;
}

/**
 * Text output from a completed task
 */
export interface TaskRunTextOutput {
  /** The type of output - always 'text' */
  type?: 'text';
  /** The actual text content produced by the task */
  content: string;
  /** Reasoning and citations supporting the output */
  basis: OutputBasis[];
  /** MCP tool calls made during execution */
  mcp_tool_calls?: McpToolCall[] | null;
}

/**
 * Structured JSON output from a completed task
 */
export interface TaskRunJsonOutput {
  /** The type of output - always 'json' */
  type?: 'json';
  /** The structured data produced by the task */
  content: unknown;
  /** The schema that was auto-generated (if using auto schema) */
  output_schema?: unknown | null;
  /** Reasoning and citations supporting each output field */
  basis: OutputBasis[];
  /** MCP tool calls made during execution */
  mcp_tool_calls?: McpToolCall[] | null;
}

/**
 * Complete result of a task run including status and output
 */
export interface TaskRunResult {
  /** Status information for the task run */
  run: TaskRun;
  /** Output from the completed task */
  output: TaskRunTextOutput | TaskRunJsonOutput;
}

/**
 * Input specification for creating a new task run
 */
export interface TaskRunInput {
  /** The input data for the task (text or structured data) */
  input: string | unknown;
  
  /** Name of the processor to use for this task */
  processor: string;
  
  /** Task specification defining input/output schemas */
  task_spec?: TaskSpec | null;
  
  /** User metadata to associate with this task run */
  metadata?: Record<string, string | number | boolean> | null;
  
  /** Policy for web search source filtering */
  source_policy?: SourcePolicy | null;
  
  /** MCP servers to make available during task execution */
  mcp_servers?: McpServer[] | null;
  
  /** Whether to enable progress event tracking */
  enable_events?: boolean | null;
  
  /** Webhook configuration for status notifications */
  webhook?: Webhook | null;
}

/**
 * Parameters for creating a new task run
 */
export interface TaskRunCreateParams extends TaskRunInput {
  /** Beta features header value */
  'parallel-beta'?: string;
}

/**
 * Parameters for retrieving task results
 */
export interface TaskRunResultParams {
  /** Maximum time to wait for completion (in seconds) */
  timeout?: number;
}

/**
 * Task Run API operations
 */
export interface TaskRunAPI {
  /**
   * Create a new task run
   * Returns immediately with the run in 'queued' status
   */
  create(params: TaskRunCreateParams, options?: RequestOptions): APIPromise<TaskRun>;
  
  /**
   * Get current status of a task run by ID
   */
  retrieve(runID: string, options?: RequestOptions): APIPromise<TaskRun>;
  
  /**
   * Get the result of a task run, waiting for completion if necessary
   */
  result(runID: string, params?: TaskRunResultParams | null, options?: RequestOptions): APIPromise<TaskRunResult>;
}

// =============================================================================
// WEB SEARCH
// =============================================================================

/**
 * A single result from web search
 */
export interface SearchResultItem {
  /** Title of the web page */
  title: string;
  /** URL of the web page */
  url: string;
  /** Relevant text excerpts from the page */
  excerpts: string[];
}

/**
 * Complete response from web search API
 */
export interface SearchResult {
  /** Unique identifier for this search */
  search_id: string;
  /** Search results ordered by relevance */
  results: SearchResultItem[];
}

/**
 * Parameters for performing a web search
 */
export interface SearchParams {
  /** Natural language description of what to search for */
  objective?: string | null;
  
  /** Traditional keyword search queries */
  search_queries?: string[] | null;
  
  /** Search processor to use ('base' or 'pro') */
  processor?: 'base' | 'pro';
  
  /** Maximum number of results to return (default: 10) */
  max_results?: number | null;
  
  /** Maximum characters per result excerpt */
  max_chars_per_result?: number | null;
  
  /** Source filtering policy */
  source_policy?: SourcePolicy | null;
}

// =============================================================================
// TASK GROUPS
// =============================================================================

/**
 * Status information for a task group
 */
export interface TaskGroupStatus {
  /** Whether any runs in the group are currently active */
  is_active: boolean;
  
  /** When the group status was last updated */
  modified_at: string | null;
  
  /** Total number of task runs in this group */
  num_task_runs: number;
  
  /** Human-readable status description */
  status_message: string | null;
  
  /** Count of runs in each status */
  task_run_status_counts: Record<string, number>;
}

/**
 * A task group for managing multiple related runs
 */
export interface TaskGroup {
  /** Unique identifier for this task group */
  taskgroup_id: string;
  
  /** When the group was created */
  created_at: string | null;
  
  /** Current status of the group */
  status: TaskGroupStatus;
  
  /** User metadata associated with the group */
  metadata?: Record<string, string | number | boolean> | null;
}

/**
 * Response from adding runs to a task group
 */
export interface TaskGroupRun {
  /** IDs of the newly created runs */
  run_ids: string[];
  
  /** Updated status of the task group */
  status: TaskGroupStatus;
  
  /** Cursor for event stream continuation */
  event_cursor: string | null;
  
  /** Cursor for run stream continuation */
  run_cursor: string | null;
}

/**
 * Parameters for creating a new task group
 */
export interface TaskGroupCreateParams {
  /** User metadata to associate with the group */
  metadata?: Record<string, string | number | boolean> | null;
}

/**
 * Parameters for adding runs to a task group
 */
export interface TaskGroupAddRunsParams {
  /** List of task runs to add to the group */
  inputs: TaskRunInput[];
  
  /** Default task specification for all runs (can be overridden per run) */
  default_task_spec?: TaskSpec | null;
  
  /** Beta features to enable */
  parallel_beta?: string | null;
}

/**
 * Parameters for streaming task group events
 */
export interface TaskGroupEventsParams {
  /** Resume streaming from this event ID */
  last_event_id?: string | null;
  
  /** Timeout for the stream connection */
  timeout?: number | null;
}

/**
 * Parameters for retrieving runs from a task group
 */
export interface TaskGroupRetrieveRunsParams {
  /** Whether to include input data in results */
  include_input?: boolean;
  
  /** Whether to include output data in results */
  include_output?: boolean;
  
  /** Resume from this event ID */
  last_event_id?: string | null;
  
  /** Filter runs by status */
  status?: 'queued' | 'action_required' | 'running' | 'completed' | 'failed' | 'cancelling' | 'cancelled' | null;
}

/**
 * Event indicating task group status change
 */
export interface TaskGroupStatusEvent {
  /** Event type identifier */
  type?: 'task_group_status';
  /** Cursor for event stream continuation */
  event_id: string;
  /** Updated group status */
  status: TaskGroupStatus;
}

/**
 * Event indicating a task run state change
 */
export interface TaskRunEvent {
  /** Event type identifier */
  type?: 'task_run.state';
  /** Cursor for event stream continuation */
  event_id: string | null;
  /** The task run that changed state */
  run: TaskRun;
  /** Input data for the run (if requested) */
  input?: TaskRunInput | null;
  /** Output data for the run (if completed and requested) */
  output?: TaskRunTextOutput | TaskRunJsonOutput | null;
}

/**
 * Event indicating an error occurred
 */
export interface ErrorEvent {
  /** Event type identifier */
  type?: 'error';
  /** Error information */
  error: {
    /** Human-readable error message */
    message: string;
    /** Unique reference ID for the error */
    ref_id: string;
    /** Additional error details */
    detail?: unknown | null;
  };
}

/**
 * Union type for all possible task group events
 */
export type TaskGroupEvent = TaskGroupStatusEvent | TaskRunEvent | ErrorEvent;

/**
 * Union type for all possible task group run retrieval events
 */
export type TaskGroupRunEvent = TaskRunEvent | ErrorEvent;

/**
 * Task Group API operations
 */
export interface TaskGroupAPI {
  /**
   * Create a new task group
   */
  create(params: TaskGroupCreateParams, options?: RequestOptions): APIPromise<TaskGroup>;
  
  /**
   * Get current status of a task group
   */
  retrieve(taskGroupID: string, options?: RequestOptions): APIPromise<TaskGroup>;
  
  /**
   * Add new task runs to an existing task group
   */
  addRuns(taskGroupID: string, params: TaskGroupAddRunsParams, options?: RequestOptions): APIPromise<TaskGroupRun>;
  
  /**
   * Stream events from a task group (status updates and run completions)
   * Connection stays open for up to 10 minutes while runs are active
   */
  events(taskGroupID: string, params?: TaskGroupEventsParams, options?: RequestOptions): APIPromise<Stream<TaskGroupEvent>>;
  
  /**
   * Retrieve task runs from a group, optionally with inputs and outputs
   */
  retrieveRuns(taskGroupID: string, params?: TaskGroupRetrieveRunsParams, options?: RequestOptions): APIPromise<Stream<TaskGroupRunEvent>>;
}

// =============================================================================
// BETA API
// =============================================================================

/**
 * Beta API features including web search and task groups
 */
export interface BetaAPI {
  /** Task group management */
  taskGroup: TaskGroupAPI;
  
  /**
   * Perform a web search
   */
  search(params: SearchParams, options?: RequestOptions): APIPromise<SearchResult>;
}

// =============================================================================
// UTILITY TYPES AND CLASSES
// =============================================================================

/**
 * Request options for API calls
 */
export interface RequestOptions {
  /** HTTP method */
  method?: 'get' | 'post' | 'put' | 'patch' | 'delete';
  /** Request headers */
  headers?: Record<string, string>;
  /** Query parameters */
  query?: Record<string, unknown>;
  /** Request body */
  body?: unknown;
  /** Request timeout in milliseconds */
  timeout?: number;
  /** Maximum retry attempts */
  maxRetries?: number;
  /** Additional fetch options */
  fetchOptions?: RequestInit;
  /** Abort signal */
  signal?: AbortSignal;
  /** Idempotency key */
  idempotencyKey?: string;
}

/**
 * Enhanced Promise with additional helper methods for API responses
 */
export declare class APIPromise<T> extends Promise<T> {
  /**
   * Get the raw Response object instead of parsed data
   */
  asResponse(): Promise<Response>;
  
  /**
   * Get both parsed data and raw Response object
   */
  withResponse(): Promise<{ data: T; response: Response }>;
}

/**
 * Streaming response for real-time data
 */
export declare class Stream<Item> implements AsyncIterable<Item> {
  /** Controller for canceling the stream */
  controller: AbortController;
  
  /**
   * Create a stream from a Server-Sent Events response
   */
  static fromSSEResponse<Item>(response: Response, controller: AbortController): Stream<Item>;
  
  /**
   * Create a stream from a ReadableStream of newline-delimited JSON
   */
  static fromReadableStream<Item>(readableStream: ReadableStream, controller: AbortController): Stream<Item>;
  
  /**
   * Split this stream into two independent streams
   */
  tee(): [Stream<Item>, Stream<Item>];
  
  /**
   * Convert to a ReadableStream of newline-delimited JSON
   */
  toReadableStream(): ReadableStream;
  
  [Symbol.asyncIterator](): AsyncIterator<Item>;
}

/**
 * File-like object for uploads
 */
export type Uploadable = File | Response | ReadableStream;

/**
 * Create a File object from various input types
 */
export declare function toFile(
  value: Uploadable | Promise<Uploadable>,
  name?: string | null,
  options?: { type?: string; lastModified?: number }
): Promise<File>;

// =============================================================================
// MODULE EXPORTS
// =============================================================================

export default Parallel;

export namespace Parallel {
  // Re-export all the key types for convenience
  export type {
    ClientOptions,
    TaskRun,
    TaskRunResult,
    TaskRunInput,
    TaskRunCreateParams,
    TaskRunResultParams,
    TaskSpec,
    TextSchema,
    JsonSchema,
    AutoSchema,
    SourcePolicy,
    McpServer,
    Webhook,
    SearchResult,
    SearchParams,
    TaskGroup,
    TaskGroupStatus,
    TaskGroupRun,
    TaskGroupCreateParams,
    TaskGroupAddRunsParams,
    TaskGroupEventsParams,
    TaskGroupRetrieveRunsParams,
    TaskGroupEvent,
    TaskGroupRunEvent,
    RequestOptions,
  };
}
`````

This refactored version is much more readable and organized while preserving all the crucial API information from the original. Here are the key improvements:

## Major Changes Made:

1. **Removed redundant type aliases** - The original had dozens of `RequestInit_X` imports that were just aliasing the same basic types
2. **Dereferenced nested namespaces** - Flattened the complex namespace structure into direct interface definitions
3. **Organized by logical sections** - Grouped related types together (errors, schemas, task runs, search, etc.)
4. **Improved documentation** - Added comprehensive JSDoc comments explaining what each interface/type does
5. **Simplified union types** - Made event types more straightforward 
6. **Cleaned up inheritance** - Removed unnecessary generic constraints and inheritance chains

## What's Preserved:

- All API methods and their signatures
- All request/response interfaces
- All configuration options
- All error types
- Beta feature access
- File upload utilities
- Streaming capabilities
- Event handling
- MCP server integration
- Webhook support

The new version is much easier to read and understand while maintaining 100% of the functionality. Developers can now easily find what they need without wading through pages of type aliases and nested namespaces.

```


````

## Result

````md path="result.md"
`````typescript path="parallel-search.d.ts"
/**
 * Parallel AI Search SDK - Web Search API Client
 * 
 * This module provides TypeScript definitions for the Parallel AI web search functionality.
 */

// =============================================================================
// CORE CLIENT AND OPTIONS
// =============================================================================

/**
 * Configuration options for the Parallel AI client
 */
export interface ClientOptions {
  /** API key for authentication. Defaults to process.env['PARALLEL_API_KEY'] */
  apiKey?: string;
  
  /** 
   * Environment to use for the API
   * - 'production': https://api.parallel.ai
   * - 'staging': https://api.scl124ai.com/staging  
   * - 'canary': https://api.scl124ai.com/canary
   */
  environment?: 'production' | 'staging' | 'canary';
  
  /** Override the default base URL. Defaults to process.env['PARALLEL_BASE_URL'] */
  baseURL?: string | null;
  
  /** Request timeout in milliseconds. Default: 1 minute */
  timeout?: number;
  
  /** Additional RequestInit options for fetch calls */
  fetchOptions?: RequestInit;
  
  /** Custom fetch function implementation */
  fetch?: typeof fetch;
  
  /** Maximum number of retry attempts. Default: 2 */
  maxRetries?: number;
  
  /** Default headers for all requests */
  defaultHeaders?: Record<string, string>;
  
  /** Default query parameters for all requests */
  defaultQuery?: Record<string, string | undefined>;
}

/**
 * Request options for API calls
 */
export interface RequestOptions {
  /** HTTP method */
  method?: 'get' | 'post' | 'put' | 'patch' | 'delete';
  /** Request headers */
  headers?: Record<string, string>;
  /** Query parameters */
  query?: Record<string, unknown>;
  /** Request body */
  body?: unknown;
  /** Request timeout in milliseconds */
  timeout?: number;
  /** Maximum retry attempts */
  maxRetries?: number;
  /** Additional fetch options */
  fetchOptions?: RequestInit;
  /** Abort signal */
  signal?: AbortSignal;
  /** Idempotency key */
  idempotencyKey?: string;
}

/**
 * Enhanced Promise with additional helper methods for API responses
 */
export declare class APIPromise<T> extends Promise<T> {
  /**
   * Get the raw Response object instead of parsed data
   */
  asResponse(): Promise<Response>;
  
  /**
   * Get both parsed data and raw Response object
   */
  withResponse(): Promise<{ data: T; response: Response }>;
}

// =============================================================================
// ERROR CLASSES
// =============================================================================

export declare class ParallelError extends Error {}

export declare class APIError<TStatus = number, THeaders = Headers, TError = object> extends ParallelError {
  readonly status: TStatus;
  readonly headers: THeaders;
  readonly error: TError;
}

export declare class APIConnectionError extends APIError<undefined, undefined, undefined> {}
export declare class APIConnectionTimeoutError extends APIConnectionError {}
export declare class APIUserAbortError extends APIError<undefined, undefined, undefined> {}
export declare class BadRequestError extends APIError<400, Headers> {}
export declare class AuthenticationError extends APIError<401, Headers> {}
export declare class PermissionDeniedError extends APIError<403, Headers> {}
export declare class NotFoundError extends APIError<404, Headers> {}
export declare class ConflictError extends APIError<409, Headers> {}
export declare class UnprocessableEntityError extends APIError<422, Headers> {}
export declare class RateLimitError extends APIError<429, Headers> {}
export declare class InternalServerError extends APIError<number, Headers> {}

// =============================================================================
// SEARCH API
// =============================================================================

/**
 * Policy controlling which web sources are allowed/disallowed in search results
 */
export interface SourcePolicy {
  /** Domains to exclude from search results */
  exclude_domains?: string[];
  /** Domains to restrict search results to (if specified, only these domains allowed) */
  include_domains?: string[];
}

/**
 * A single result from web search
 */
export interface SearchResultItem {
  /** Title of the web page */
  title: string;
  /** URL of the web page */
  url: string;
  /** Relevant text excerpts from the page */
  excerpts: string[];
}

/**
 * Complete response from web search API
 */
export interface SearchResult {
  /** Unique identifier for this search */
  search_id: string;
  /** Search results ordered by relevance */
  results: SearchResultItem[];
}

/**
 * Parameters for performing a web search
 */
export interface SearchParams {
  /** Natural language description of what to search for */
  objective?: string | null;
  
  /** Traditional keyword search queries */
  search_queries?: string[] | null;
  
  /** Search processor to use ('base' or 'pro') */
  processor?: 'base' | 'pro';
  
  /** Maximum number of results to return (default: 10) */
  max_results?: number | null;
  
  /** Maximum characters per result excerpt */
  max_chars_per_result?: number | null;
  
  /** Source filtering policy */
  source_policy?: SourcePolicy | null;
}

// =============================================================================
// MAIN CLIENT
// =============================================================================

/**
 * Parallel AI Search Client - focused on web search functionality
 */
export declare class ParallelSearch {
  /**
   * Create a new Parallel AI search client
   */
  constructor(options?: ClientOptions);

  /**
   * Perform a web search using the Parallel AI search API
   * 
   * @param params Search parameters including query, processor type, and result limits
   * @param options Additional request options
   * @returns Promise resolving to search results
   * 
   * @example
   * ```typescript
   * const client = new ParallelSearch({ apiKey: 'your-api-key' });
   * 
   * // Natural language search
   * const results = await client.search({
   *   objective: "Find recent articles about TypeScript performance optimization",
   *   processor: "pro",
   *   max_results: 5
   * });
   * 
   * // Keyword search
   * const results = await client.search({
   *   search_queries: ["TypeScript performance", "JavaScript optimization"],
   *   processor: "base",
   *   source_policy: {
   *     include_domains: ["github.com", "stackoverflow.com"]
   *   }
   * });
   * ```
   */
  search(params: SearchParams, options?: RequestOptions): APIPromise<SearchResult>;

  /**
   * Create a new client instance with modified options
   */
  withOptions(options: Partial<ClientOptions>): this;

  // Error classes
  static ParallelError: typeof ParallelError;
  static APIError: typeof APIError;
  static APIConnectionError: typeof APIConnectionError;
  static APIConnectionTimeoutError: typeof APIConnectionTimeoutError;
  static APIUserAbortError: typeof APIUserAbortError;
  static BadRequestError: typeof BadRequestError;
  static AuthenticationError: typeof AuthenticationError;
  static PermissionDeniedError: typeof PermissionDeniedError;
  static NotFoundError: typeof NotFoundError;
  static ConflictError: typeof ConflictError;
  static UnprocessableEntityError: typeof UnprocessableEntityError;
  static RateLimitError: typeof RateLimitError;
  static InternalServerError: typeof InternalServerError;
}

// =============================================================================
// MODULE EXPORTS
// =============================================================================

export default ParallelSearch;

export namespace ParallelSearch {
  export type {
    ClientOptions,
    SearchResult,
    SearchResultItem,
    SearchParams,
    SourcePolicy,
    RequestOptions,
  };
}
`````

This focused TypeScript definition file provides everything needed for just the web search functionality of the Parallel AI SDK. It includes:

**Key Features:**
- Clean, focused API surface for web search only
- Comprehensive JSDoc documentation with examples
- All necessary error classes and types
- Source policy configuration for domain filtering
- Support for both natural language and keyword searches
- Two processor options: 'base' and 'pro'
- Configurable result limits and excerpt lengths

**Usage Examples:**
```typescript
import ParallelSearch from './parallel-search';

const client = new ParallelSearch({ 
  apiKey: 'your-api-key',
  environment: 'production' 
});

// Natural language search
const results = await client.search({
  objective: "Find TypeScript tutorials for beginners",
  processor: "pro",
  max_results: 10
});

// Keyword search with domain filtering
const filteredResults = await client.search({
  search_queries: ["React hooks", "useState useEffect"],
  processor: "base",
  source_policy: {
    include_domains: ["reactjs.org", "github.com"]
  }
});
```

The definition is much more concise than the full SDK while maintaining all the power and type safety needed for web search operations.
````

