import EventEmitter from 'eventemitter3';
import z$1, { Schema, ZodTypeAny, z, ZodSchema } from 'zod';
import { Image as Image$1 } from '@boundaryml/baml';
import sharp, { Sharp } from 'sharp';
import { Page, BrowserContext, PageScreenshotOptions, Browser, LaunchOptions, BrowserContextOptions } from 'playwright';
import { PostHog } from 'posthog-node';
import pino from 'pino';

type Base64Image = `data:image/${'jpeg' | 'png' | 'gif'};base64,${string}`;
type WebAction = NavigateWebAction | ClickWebAction | TypeWebAction | ScrollWebAction | SwitchTabWebAction;
interface NavigateWebAction {
    variant: 'load';
    url: string;
}
interface ClickWebAction {
    variant: 'click';
    x: number;
    y: number;
}
interface TypeWebAction {
    variant: 'type';
    x: number;
    y: number;
    content: string;
}
interface ScrollWebAction {
    variant: 'scroll';
    x: number;
    y: number;
    deltaX: number;
    deltaY: number;
}
type SwitchTabWebAction = {
    variant: 'tab';
    index: number;
};
interface PixelCoordinate {
    x: number;
    y: number;
}

/**
 * "Intents" are natural language descriptors that align 1:1 with executable web actions.
 * Micro converts intents into web actions.
 */

interface Action {
    variant: string;
    [key: string]: any;
}
type ActionIntent = ClickIntent | TypeIntent | ScrollIntent | SwitchTabIntent;
type Intent = ActionIntent | CheckIntent;
interface ClickIntent {
    variant: 'click';
    target: string;
}
interface TypeIntent {
    variant: 'type';
    target: string;
    content: string;
}
interface ScrollIntent {
    variant: 'scroll';
    target: string;
    deltaX: number;
    deltaY: number;
}
type SwitchTabIntent = SwitchTabWebAction;
interface CheckIntent {
    variant: 'check';
    checks: string[];
}

/*************************************************************************************************

Welcome to Baml! To use this generated code, please run one of the following:

$ npm install @boundaryml/baml
$ yarn add @boundaryml/baml
$ pnpm add @boundaryml/baml

*************************************************************************************************/

interface ConnectorInstructions {
    connectorId: string;
    instructions: string;
}
interface ModularMemoryContext {
    instructions?: string | null;
    observationContent: (string | Image$1)[];
    connectorInstructions: ConnectorInstructions[];
}

type LLMClient = AnthropicClient | BedrockClient | GoogleAIClient | GoogleVertexClient | OpenAIClient | OpenAIGenericClient | AzureOpenAIClient;
type GroundingClient = MoondreamClient;
interface AnthropicClient {
    provider: 'anthropic';
    options: {
        model: string;
        apiKey?: string;
        temperature?: number;
    };
}
interface BedrockClient {
    provider: 'aws-bedrock';
    options: {
        model: string;
        temperature?: number;
    };
}
interface GoogleAIClient {
    provider: 'google-ai';
    options: {
        model: string;
        apiKey?: string;
        temperature?: number;
        baseUrl?: string;
    };
}
interface GoogleVertexClient {
    provider: 'vertex-ai';
    options: {
        model: string;
        location: string;
        baseUrl?: string;
        projectId?: string;
        credentials?: string | object;
        temperature?: number;
    };
}
interface OpenAIClient {
    provider: 'openai';
    options: {
        model: string;
        apiKey?: string;
        temperature?: number;
    };
}
interface AzureOpenAIClient {
    provider: 'azure-openai';
    options: {
        resourceName: string;
        deploymentId: string;
        apiVersion: string;
        apiKey: string;
    };
}
interface OpenAIGenericClient {
    provider: 'openai-generic';
    options: {
        model: string;
        baseUrl: string;
        apiKey?: string;
        temperature?: number;
        headers?: Record<string, string>;
    };
}
interface MoondreamClient {
    provider: 'moondream';
    options: {
        baseUrl?: string;
        apiKey?: string;
    };
}
interface LLMClientIdentifier {
    provider: string;
    model: string;
}
interface ModelUsage {
    llm: LLMClientIdentifier;
    inputTokens: number;
    outputTokens: number;
}

/**
 * Convert observations to form that can be passed as BAML context, rendered as a custom XML-like structure.
 */

type BamlRenderable = Image$1 | string;

type StoredMedia = {
    type: 'media';
    format: string;
    storage: 'base64';
    base64: string;
};
interface StoredPrimitive {
    type: 'primitive';
    content: string | boolean | number;
}
type MultiMediaPrimitive = StoredMedia | StoredPrimitive | undefined | null;
type MultiMediaArray = Array<MultiMediaJson>;
type MultiMediaObject = {
    [key: string]: MultiMediaJson;
};
type MultiMediaJson = MultiMediaPrimitive | MultiMediaArray | MultiMediaObject;

declare class Image {
    /**
     * Wrapper for a Sharp image with conveniences to go to/from base64, convert to BAML, or serialize as JSON
     */
    private img;
    constructor(img: Sharp);
    static fromBase64(base64: string): Image;
    getFormat(): Promise<keyof sharp.FormatEnum>;
    /**
     * Convert the image to a JSON representation
     */
    toJson(): Promise<StoredMedia>;
    toBase64(): Promise<string>;
    toBaml(): Promise<Image$1>;
    getDimensions(): Promise<{
        width: number;
        height: number;
    }>;
    resize(width: number, height: number): Promise<Image>;
}

type ObservableDataPrimitive = Image | string | number | boolean | null | undefined;
type ObservableDataArray = Array<ObservableData>;
type ObservableDataObject = {
    [key: string]: ObservableData;
};
type ObservableData = ObservableDataPrimitive | ObservableDataArray | ObservableDataObject;
interface ObservationOptions {
    type: string;
    limit?: number;
    dedupe?: boolean;
}
type ObservationSource = `connector:${string}` | `action:taken:${string}` | `action:result:${string}` | `thought`;
declare class Observation {
    readonly source: ObservationSource;
    readonly timestamp: number;
    readonly data: ObservableData;
    readonly options?: ObservationOptions;
    constructor(source: ObservationSource, data: ObservableData, options?: ObservationOptions);
    static fromConnector(connectorId: string, data: ObservableData, options?: ObservationOptions): Observation;
    static fromActionTaken(actionId: string, data: ObservableData, options?: ObservationOptions): Observation;
    static fromActionResult(actionId: string, data: ObservableData, options?: ObservationOptions): Observation;
    static fromThought(data: ObservableData, options?: ObservationOptions): Observation;
    toString(): string;
    toJson(): Promise<MultiMediaJson>;
    toContext(): Promise<BamlRenderable[]>;
    hash(): Promise<string>;
    equals(obs: Observation): Promise<boolean>;
}

interface ActionDefinition<T> {
    name: string;
    description?: string;
    schema: Schema<T>;
    resolver: ({ input, agent }: {
        input: T;
        agent: Agent;
    }) => Promise<void | ObservableData>;
    render: (action: T) => string;
}
declare function createAction<S extends ZodTypeAny>(action: {
    name: string;
    description?: string;
    schema?: S;
    resolver: ({ input, agent }: {
        input: z.infer<S>;
        agent: Agent;
    }) => Promise<void | ObservableData>;
    render?: (action: z.infer<S>) => string;
}): ActionDefinition<z.infer<S>>;
type ActionPayload<A extends ActionDefinition<any>> = {
    name: A['name'];
} & z.infer<A['schema']>;

interface ModelHarnessOptions {
    llm: LLMClient;
}
interface ModelHarnessEvents {
    'tokensUsed': (usage: ModelUsage) => {};
}
declare class ModelHarness {
    /**
     * Strong reasoning agent for high level strategy and planning.
     */
    readonly events: EventEmitter<ModelHarnessEvents>;
    private options;
    private collector;
    private cr;
    private baml;
    private logger;
    private prevTotalInputTokens;
    private prevTotalOutputTokens;
    constructor(options: {
        llm: LLMClient;
    } & Partial<ModelHarnessOptions>);
    reportUsage(): void;
    createPartialRecipe<T>(context: ModularMemoryContext, // Changed to ModularMemoryContext
    task: string, actionVocabulary: ActionDefinition<T>[]): Promise<{
        reasoning: string;
        actions: Action[];
    }>;
    extract<T extends Schema>(instructions: string, schema: T, screenshot: Image, domContent: string): Promise<z.infer<T>>;
    query<T extends Schema>(context: ModularMemoryContext, query: string, schema: T): Promise<z.infer<T>>;
}

interface AgentEvents {
    'start': () => void;
    'stop': () => void;
    'thought': (thought: string) => void;
    'actStarted': (task: string, options: ActOptions) => void;
    'actDone': (task: string, options: ActOptions) => void;
    'actionStarted': (action: Action) => void;
    'actionDone': (action: Action) => void;
    'tokensUsed': (usage: ModelUsage) => void;
}

interface AgentConnector {
    id: string;
    onStart?(): Promise<void>;
    onStop?(): Promise<void>;
    getActionSpace?(): ActionDefinition<any>[];
    collectObservations?(): Promise<Observation[]>;
    getInstructions?(): Promise<void | string>;
}

interface SerializedAgentMemory {
    instructions?: string;
    observations: {
        source: ObservationSource;
        timestamp: number;
        data: MultiMediaJson;
        options?: ObservationOptions;
    }[];
}
declare class AgentMemory {
    readonly instructions: string | null;
    private observations;
    constructor(instructions?: string);
    isEmpty(): boolean;
    recordThought(content: string): void;
    recordObservation(obs: Observation): void;
    getLastThoughtMessage(): string | null;
    buildContext(activeConnectors: AgentConnector[]): Promise<ModularMemoryContext>;
    toJSON(): Promise<SerializedAgentMemory>;
}

interface AgentOptions {
    llm?: LLMClient;
    connectors?: AgentConnector[];
    actions?: ActionDefinition<any>[];
    prompt?: string | null;
    telemetry?: boolean;
}
interface ActOptions {
    prompt?: string;
    data?: string | Record<string, string>;
}
declare class Agent {
    private options;
    private connectors;
    private actions;
    readonly model: ModelHarness;
    readonly events: EventEmitter<AgentEvents>;
    private doneActing;
    protected latestTaskMemory: AgentMemory;
    constructor(baseConfig?: Partial<AgentOptions>);
    getConnector<C extends AgentConnector>(connectorClass: new (...args: any[]) => C): C | undefined;
    require<C extends AgentConnector>(connectorClass: new (...args: any[]) => C): C;
    start(): Promise<void>;
    identifyAction(action: Action): ActionDefinition<any>;
    exec(action: Action, memory?: AgentMemory): Promise<void>;
    protected _recordConnectorObservations(memory: AgentMemory): Promise<void>;
    get memory(): AgentMemory;
    act(taskOrSteps: string | string[], options?: ActOptions): Promise<void>;
    _traceAct(task: string, memory: AgentMemory, options?: ActOptions): Promise<void>;
    _act(description: string, memory: AgentMemory, options?: ActOptions): Promise<void>;
    query<T extends z$1.Schema>(query: string, schema: T): Promise<z$1.infer<T>>;
    queueDone(): Promise<void>;
    stop(): Promise<void>;
}

declare class ActionVisualizer {
    /**
     * Manages the visual indicator for actions on a page
     */
    private page;
    private visualElementId;
    private lastPosition;
    constructor();
    setActivePage(page: Page): void;
    visualizeAction(x: number, y: number): Promise<void>;
    redrawLastPosition(): Promise<void>;
    private _drawVisual;
}

interface TabState {
    activeTab: number;
    tabs: {
        title: string;
        url: string;
    }[];
}

interface WebHarnessOptions {
    virtualScreenDimensions?: {
        width: number;
        height: number;
    };
}
declare class WebHarness {
    /**
     * Executes web actions on a page
     * Not responsible for browser lifecycle
     */
    readonly context: BrowserContext;
    private options;
    private stability;
    readonly visualizer: ActionVisualizer;
    private transformer;
    private tabs;
    constructor(context: BrowserContext, options?: WebHarnessOptions);
    retrieveTabState(): Promise<TabState>;
    start(): Promise<void>;
    get page(): Page;
    screenshot(options?: PageScreenshotOptions): Promise<Image>;
    _type(content: string): Promise<void>;
    transformCoordinates({ x, y }: {
        x: number;
        y: number;
    }): {
        x: number;
        y: number;
    };
    click({ x, y }: {
        x: number;
        y: number;
    }): Promise<void>;
    rightClick({ x, y }: {
        x: number;
        y: number;
    }): Promise<void>;
    doubleClick({ x, y }: {
        x: number;
        y: number;
    }): Promise<void>;
    drag({ x1, y1, x2, y2 }: {
        x1: number;
        y1: number;
        x2: number;
        y2: number;
    }): Promise<void>;
    type({ content }: {
        content: string;
    }): Promise<void>;
    clickAndType({ x, y, content }: {
        x: number;
        y: number;
        content: string;
    }): Promise<void>;
    scroll({ x, y, deltaX, deltaY }: {
        x: number;
        y: number;
        deltaX: number;
        deltaY: number;
    }): Promise<void>;
    switchTab({ index }: {
        index: number;
    }): Promise<void>;
    newTab(): Promise<void>;
    navigate(url: string): Promise<void>;
    selectAll(): Promise<void>;
    enter(): Promise<void>;
    backspace(): Promise<void>;
    tab(): Promise<void>;
    goBack(): Promise<void>;
    executeAction(action: WebAction): Promise<void>;
    waitForStability(timeout?: number): Promise<void>;
}

type BrowserOptions = ({
    instance: Browser;
} | {
    cdp: string;
} | {
    launchOptions?: LaunchOptions;
}) & {
    contextOptions?: BrowserContextOptions;
};
declare class BrowserProvider {
    private activeBrowsers;
    private logger;
    private constructor();
    static getInstance(): BrowserProvider;
    private _launchOrReuseBrowser;
    _createAndTrackContext(options: BrowserOptions): Promise<BrowserContext>;
    newContext(options?: BrowserOptions): Promise<BrowserContext>;
    private _applyEmulationSettings;
}

interface GroundingServiceConfig {
    client?: GroundingClient;
}
interface GroundingServiceInfo {
    provider: string;
    numCalls: number;
}
declare class GroundingService {
    /**
     * Small, fast, vision agent to translate high level web actions to precise, executable actions.
     * Uses Moondream for pixel precision pointing.
     */
    private config;
    private info;
    private logger;
    private moondream;
    constructor(config: GroundingServiceConfig);
    getInfo(): GroundingServiceInfo;
    locateTarget(screenshot: Image, target: string): Promise<PixelCoordinate>;
    _locateTarget(screenshot: Image, target: string): Promise<PixelCoordinate>;
}

interface BrowserConnectorOptions {
    browser?: BrowserOptions;
    url?: string;
    grounding?: GroundingClient;
    virtualScreenDimensions?: {
        width: number;
        height: number;
    };
}
interface BrowserConnectorStateData {
    screenshot: Image;
    tabs: TabState;
}
declare class BrowserConnector implements AgentConnector {
    readonly id: string;
    private harness;
    private options;
    private browser?;
    private context;
    private logger;
    private grounding?;
    constructor(options?: BrowserConnectorOptions);
    requireGrounding(): GroundingService;
    onStart(): Promise<void>;
    onStop(): Promise<void>;
    getActionSpace(): ActionDefinition<any>[];
    getHarness(): WebHarness;
    private captureCurrentState;
    transformScreenshot(screenshot: Image): Promise<Image>;
    getLastScreenshot(): Promise<Image>;
    collectObservations(): Promise<Observation[]>;
    getInstructions(): Promise<void | string>;
}

declare function startBrowserAgent(options?: AgentOptions & BrowserConnectorOptions & {
    narrate?: boolean;
}): Promise<BrowserAgent>;
type ExtractedOutput = string | number | boolean | bigint | Date | null | undefined | {
    [key: string]: ExtractedOutput;
} | ExtractedOutput[];
interface BrowserAgentEvents {
    'nav': (url: string) => void;
    'extractStarted': (instructions: string, schema: ZodSchema) => void;
    'extractDone': (instructions: string, data: ExtractedOutput) => void;
}
declare class BrowserAgent extends Agent {
    readonly browserAgentEvents: EventEmitter<BrowserAgentEvents>;
    constructor({ agentOptions, browserOptions }: {
        agentOptions?: Partial<AgentOptions>;
        browserOptions?: BrowserConnectorOptions;
    });
    get page(): Page;
    get context(): BrowserContext;
    nav(url: string): Promise<void>;
    extract<T extends Schema>(instructions: string, schema: T): Promise<z$1.infer<T>>;
}

interface AgentErrorOptions {
    variant?: string;
    adaptable?: boolean;
}
declare class AgentError extends Error {
    readonly options: Required<AgentErrorOptions>;
    constructor(message: string, options?: AgentErrorOptions);
}

/**
 * Represents any reason why a test case could have failed, for example:
 * - Step could not be completed
 * - Check did not pass
 * - Could not navigate to starting URL
 * - Time or action based timeout
 * - Operation cancelled by signal
 * - ...
 */
type FailureDescriptor = BugDetectedFailure | MisalignmentFailure | NetworkFailure | BrowserFailure | RateLimitFailure | ApiKeyFailure | UnknownFailure | CancelledFailure;
type BugSeverity = 'critical' | 'high' | 'medium' | 'low';
/**
 * Step and check failures are classified into one of:
 * BugDetectedFailure: seems to be something wrong with the application itself
 * MisalignmentFailure: seems to be a discrepency between the test case and the interface
 *    OR the agent did not properly recognize the relationship between test case and interface
 */
interface BugDetectedFailure {
    variant: 'bug';
    title: string;
    expectedResult: string;
    actualResult: string;
    severity: BugSeverity;
}
interface MisalignmentFailure {
    /**
     * Major misalignment: when a step/check fails due to:
     * 1. Poorly written step/check that is completely unrelated to the interface
     * 2. Or interface has changed so much that step/check no longer applicable
     * 3. Planner did not do good enough job adjusting recipe for minor misalignment
     * Misalignment could be due to a poorly written test case OR bad agent behavior.
     */
    variant: 'misalignment';
    message: string;
}
interface NetworkFailure {
    /**
     * For example, failure to connect to starting URL, or any other network errors
     * that would completely prevent the test from executing.
     */
    variant: 'network';
    message: string;
}
interface BrowserFailure {
    /**
     * E.g. something goes wrong with playwright interactions, any DOM manipulation, etc.
     */
    variant: 'browser';
    message: string;
}
interface RateLimitFailure {
    variant: 'rate_limit';
    message: string;
}
interface ApiKeyFailure {
    variant: 'api_key';
    message: string;
}
interface UnknownFailure {
    variant: 'unknown';
    message: string;
}
interface CancelledFailure {
    /**
     * Operation was cancelled, typically by an AbortSignal from a controlling process (e.g., test runner pool).
     */
    variant: 'cancelled';
}

declare function retryOnError<T>(fnToRetry: () => Promise<T>, errorSubstrings: string[], retryLimit: number, delayMs?: number): Promise<T>;
/**
 * Performs a deep comparison between two values to determine if they are equivalent.
 *
 * @param a The first value to compare.
 * @param b The second value to compare.
 * @param cache A WeakMap to handle circular references. Should not be provided by the caller.
 * @returns `true` if the values are deeply equal, `false` otherwise.
 */
declare function deepEquals(a: any, b: any, cache?: WeakMap<object, WeakSet<object>>): boolean;

interface TestDataEntry {
    key: string;
    value: string;
    sensitive: boolean;
}
interface TestData {
    data?: TestDataEntry[];
    other?: string;
}
interface TestStepDefinition {
    description: string;
    checks: string[];
    testData: TestData;
}
interface TestCaseDefinition {
    url: string;
    steps: TestStepDefinition[];
    recipe?: Intent[];
}
type TestCaseResult = SuccessfulTestCaseResult | FailedTestCaseResult;
interface SuccessfulTestCaseResult {
    passed: true;
    recipe: Intent[];
}
interface FailedTestCaseResult {
    passed: false;
    failure: FailureDescriptor;
}

declare const createId: () => string;
declare const posthog: PostHog;
declare function getMachineId(): string;
declare function getCodebaseId(): string | undefined;
declare function sendTelemetry(eventName: string, properties: Record<string, any>): Promise<void>;

declare function buildDefaultBrowserAgentOptions({ agentOptions, browserOptions }: {
    agentOptions: AgentOptions;
    browserOptions: BrowserConnectorOptions;
}): {
    agentOptions: AgentOptions;
    browserOptions: BrowserConnectorOptions;
};

declare const logger: pino.Logger<never, boolean>;

export { type ActOptions, type Action, type ActionDefinition, type ActionIntent, type ActionPayload, Agent, type AgentConnector, AgentError, type AgentErrorOptions, type AgentEvents, type AgentOptions, type AnthropicClient, type ApiKeyFailure, type AzureOpenAIClient, type Base64Image, type BedrockClient, BrowserAgent, BrowserConnector, type BrowserConnectorOptions, type BrowserConnectorStateData, type BrowserFailure, type BrowserOptions, BrowserProvider, type BugDetectedFailure, type BugSeverity, type CancelledFailure, type CheckIntent, type ClickIntent, type ClickWebAction, type FailedTestCaseResult, type FailureDescriptor, type GoogleAIClient, type GoogleVertexClient, type GroundingClient, type Intent, type LLMClient, type LLMClientIdentifier, type MisalignmentFailure, type ModelUsage, type MoondreamClient, type NavigateWebAction, type NetworkFailure, type OpenAIClient, type OpenAIGenericClient, type PixelCoordinate, type RateLimitFailure, type ScrollIntent, type ScrollWebAction, type SuccessfulTestCaseResult, type SwitchTabIntent, type SwitchTabWebAction, type TestCaseDefinition, type TestCaseResult, type TestData, type TestDataEntry, type TestStepDefinition, type TypeIntent, type TypeWebAction, type UnknownFailure, type WebAction, buildDefaultBrowserAgentOptions, createAction, createId, deepEquals, getCodebaseId, getMachineId, logger, posthog, retryOnError, sendTelemetry, startBrowserAgent };
