import { RequestMetadata } from '@vscode/copilot-api';
import { Raw } from '@vscode/prompt-tsx';
import type { CancellationToken } from 'vscode';
import { ITokenizer, TokenizerType } from '../../../util/common/tokenizer';
import { AsyncIterableObject } from '../../../util/vs/base/common/async';
import { Source } from '../../chat/common/chatMLFetcher';
import type { ChatLocation, ChatResponse } from '../../chat/common/commonTypes';
import { ICAPIClientService } from '../../endpoint/common/capiClient';
import { CustomModel, EndpointEditToolName } from '../../endpoint/common/endpointProvider';
import { ILogService } from '../../log/common/logService';
import { ITelemetryService, TelemetryProperties } from '../../telemetry/common/telemetry';
import { TelemetryData } from '../../telemetry/common/telemetryData';
import { AnthropicMessagesTool, FinishedCallback, OpenAiFunctionTool, OpenAiResponsesFunctionTool, OptionalChatRequestParams, Prediction } from './fetch';
import { FetcherId, FetchOptions, IAbortController, IFetcherService, PaginationOptions, Response } from './fetcherService';
import { ChatCompletion, RawMessageConversionCallback } from './openai';
/**
 * Encapsulates all the functionality related to making GET/POST requests using
 * different libraries (and in the future, different environments like web vs
 * node).
 */
export interface IFetcher {
    getUserAgentLibrary(): string;
    fetch(url: string, options: FetchOptions): Promise<Response>;
    disconnectAll(): Promise<unknown>;
    makeAbortController(): IAbortController;
    isAbortError(e: any): boolean;
    isInternetDisconnectedError(e: any): boolean;
    isFetcherError(err: any): boolean;
    getUserMessageForFetcherError(err: any): string;
    fetchWithPagination<T>(baseUrl: string, options: PaginationOptions<T>): Promise<T[]>;
}
export declare const userAgentLibraryHeader = "X-VSCode-User-Agent-Library-Version";
export type ReqHeaders = {
    [key: string]: string;
};
/**
 * The HeaderContributor provides the interface which allows implmentors
 * to decorate a request's `headers` object with additional key / value pairs.
 */
export interface HeaderContributor {
    contributeHeaderValues(headers: ReqHeaders): void;
}
/**
 * Rough shape of an endpoint body. A superset of the parameters of any request,
 * but provided to at least have rough typings.
 */
export interface IEndpointBody {
    /** General or completions: */
    tools?: (OpenAiFunctionTool | OpenAiResponsesFunctionTool | AnthropicMessagesTool)[];
    model?: string;
    previous_response_id?: string;
    max_tokens?: number;
    max_output_tokens?: number;
    max_completion_tokens?: number;
    temperature?: number;
    top_p?: number;
    stream?: boolean;
    prediction?: Prediction;
    messages?: any[];
    n?: number;
    reasoning?: {
        effort?: string;
        summary?: string;
    };
    tool_choice?: OptionalChatRequestParams['tool_choice'] | {
        type: 'function';
        name: string;
    };
    top_logprobs?: number;
    intent?: boolean;
    intent_threshold?: number;
    state?: 'enabled';
    snippy?: {
        enabled: boolean;
    };
    stream_options?: {
        include_usage?: boolean;
    };
    prompt?: string;
    /** Embeddings endpoints only: */
    dimensions?: number;
    embed?: boolean;
    /** Chunking endpoints: */
    qos?: any;
    content?: string;
    path?: string;
    local_hashes?: string[];
    language_id?: number;
    /** docs search */
    query?: string;
    scopingQuery?: string;
    limit?: number;
    similarity?: number;
    /** Code search: */
    scoping_query?: string;
    /** Responses API: */
    input?: readonly any[];
    truncation?: 'auto' | 'disabled';
    include?: ['reasoning.encrypted_content'];
    store?: boolean;
    text?: {
        verbosity?: 'low' | 'medium' | 'high';
    };
    /** Messages API */
    thinking?: {
        type: 'enabled' | 'disabled';
        budget_tokens?: number;
    };
}
export interface IEndpointFetchOptions {
    suppressIntegrationId?: boolean;
}
export interface IEndpoint {
    readonly urlOrRequestMetadata: string | RequestMetadata;
    getExtraHeaders?(): Record<string, string>;
    getEndpointFetchOptions?(): IEndpointFetchOptions;
    interceptBody?(body: IEndpointBody | undefined): void;
    acquireTokenizer(): ITokenizer;
    readonly modelMaxPromptTokens: number;
    readonly name: string;
    readonly version: string;
    readonly family: string;
    readonly tokenizer: TokenizerType;
}
export declare function stringifyUrlOrRequestMetadata(urlOrRequestMetadata: string | RequestMetadata): string;
export interface IEmbeddingsEndpoint extends IEndpoint {
    readonly maxBatchSize: number;
}
export interface IMakeChatRequestOptions {
    /** The debug name for this request */
    debugName: string;
    /** The array of chat messages to send */
    messages: Raw.ChatMessage[];
    ignoreStatefulMarker?: boolean;
    /** Streaming callback for each response part. */
    finishedCb: FinishedCallback | undefined;
    /** Location where the chat message is being sent. */
    location: ChatLocation;
    /** Optional source of the chat request */
    source?: Source;
    /** Additional request options */
    requestOptions?: Omit<OptionalChatRequestParams, 'n'>;
    /** Indicates if the request was user-initiated */
    userInitiatedRequest?: boolean;
    /** (CAPI-only) Optional telemetry properties for analytics */
    telemetryProperties?: IChatRequestTelemetryProperties;
    /** Enable retrying the request when it was filtered due to snippy. Note- if using finishedCb, requires supporting delta.retryReason, eg with clearToPreviousToolInvocation */
    enableRetryOnFilter?: boolean;
    /** Enable retrying the request when it failed. Defaults to enableRetryOnFilter. Note- if using finishedCb, requires supporting delta.retryReason, eg with clearToPreviousToolInvocation */
    enableRetryOnError?: boolean;
    /** Which fetcher to use, overrides the default. */
    useFetcher?: FetcherId;
}
export type IChatRequestTelemetryProperties = {
    requestId?: string;
    messageId?: string;
    conversationId?: string;
    messageSource?: string;
    associatedRequestId?: string;
    retryAfterErrorCategory?: string;
    retryAfterError?: string;
    connectivityTestError?: string;
    retryAfterFilterCategory?: string;
};
export interface ICreateEndpointBodyOptions extends IMakeChatRequestOptions {
    requestId: string;
    postOptions: OptionalChatRequestParams;
}
export interface IChatEndpoint extends IEndpoint {
    readonly maxOutputTokens: number;
    /** The model ID- this may change and will be `copilot-base` for the base model. Use `family` to switch behavior based on model type. */
    readonly model: string;
    readonly apiType?: string;
    readonly supportsThinkingContentInHistory?: boolean;
    readonly supportsToolCalls: boolean;
    readonly supportsVision: boolean;
    readonly supportsPrediction: boolean;
    readonly supportedEditTools?: readonly EndpointEditToolName[];
    readonly showInModelPicker: boolean;
    readonly isPremium?: boolean;
    readonly degradationReason?: string;
    readonly multiplier?: number;
    readonly restrictedToSkus?: string[];
    readonly isDefault: boolean;
    readonly isFallback: boolean;
    readonly customModel?: CustomModel;
    readonly isExtensionContributed?: boolean;
    readonly policy: 'enabled' | {
        terms: string;
    };
    /**
     * Handles processing of responses from a chat endpoint. Each endpoint can have different response formats.
     * @param telemetryService The telemetry service
     * @param logService The log service
     * @param response The response from the chat endpoint
     * @param expectedNumChoices The expected number of choices in the response
     * @param finishCallback A finish callback to indicate when the response should be complete
     * @param telemetryData GH telemetry data from the originating request, will be extended with request information
     * @param cancellationToken A cancellation tokenf for cancelling the request
     * @returns An async iterable object of chat completions
     */
    processResponseFromChatEndpoint(telemetryService: ITelemetryService, logService: ILogService, response: Response, expectedNumChoices: number, finishCallback: FinishedCallback, telemetryData: TelemetryData, cancellationToken?: CancellationToken): Promise<AsyncIterableObject<ChatCompletion>>;
    /**
     * Accepts the chat policy for the given endpoint, enabling its usage.
     * @returns A promise that resolves to true if the chat policy was accepted, false otherwise.
     */
    acceptChatPolicy(): Promise<boolean>;
    /**
     * Flights a request from the chat endpoint returning a chat response.
     * Most of the time this is ChatMLFetcher#fetchOne, but it can be overridden for special cases.
     * TODO @lramos15 - Support multiple completions in the future, we don't use this at the moment.
     *
     * @param userInitiatedRequest Is only applicable to CAPI requests
     * @param telemetryProperties An object containing various properties for telemetry, e.g., can contain a field `requestId` that sets the header request ID
     */
    makeChatRequest(debugName: string, messages: Raw.ChatMessage[], finishedCb: FinishedCallback | undefined, token: CancellationToken, location: ChatLocation, source?: Source, requestOptions?: Omit<OptionalChatRequestParams, 'n'>, userInitiatedRequest?: boolean, telemetryProperties?: TelemetryProperties): Promise<ChatResponse>;
    /**
     * Flights a request from the chat endpoint returning a chat response.
     * Most of the time this is ChatMLFetcher#fetchOne, but it can be overridden for special cases.
     */
    makeChatRequest2(options: IMakeChatRequestOptions, token: CancellationToken): Promise<ChatResponse>;
    /**
     * Creates the request body to be sent to the endpoint based on the request.
     */
    createRequestBody(options: ICreateEndpointBodyOptions): IEndpointBody;
    cloneWithTokenOverride(modelMaxPromptTokens: number): IChatEndpoint;
}
/** Function to create a standard request body for CAPI completions */
export declare function createCapiRequestBody(options: ICreateEndpointBodyOptions, model: string, callback?: RawMessageConversionCallback): IEndpointBody;
export declare function canRetryOnceNetworkError(reason: any): boolean;
export declare function postRequest(fetcherService: IFetcherService, telemetryService: ITelemetryService, capiClientService: ICAPIClientService, endpointOrUrl: IEndpoint | string | RequestMetadata, secretKey: string, hmac: string | undefined, intent: string, requestId: string, body?: IEndpointBody, additionalHeaders?: Record<string, string>, cancelToken?: CancellationToken, useFetcher?: FetcherId): Promise<Response>;
export declare function getRequest(fetcherService: IFetcher, telemetryService: ITelemetryService, capiClientService: ICAPIClientService, endpointOrUrl: IEndpoint | string | RequestMetadata, secretKey: string, hmac: string | undefined, intent: string, requestId: string, body?: IEndpointBody, additionalHeaders?: Record<string, string>, cancelToken?: CancellationToken): Promise<Response>;
export declare const IHeaderContributors: import("../../../util/common/services").ServiceIdentifier<HeaderContributors>;
export interface IHeaderContributors {
    readonly _serviceBrand: undefined;
    add(contributor: HeaderContributor): void;
    remove(contributor: HeaderContributor): void;
    contributeHeaders(headers: ReqHeaders): void;
    size(): number;
}
export declare class HeaderContributors implements IHeaderContributors {
    readonly _serviceBrand: undefined;
    private readonly contributors;
    add(contributor: HeaderContributor): void;
    remove(contributor: HeaderContributor): void;
    contributeHeaders(headers: ReqHeaders): void;
    size(): number;
}
//# sourceMappingURL=networking.d.ts.map