import { TracedFSM, type TracedFSMStateSpanOptions, type TracedFSMTagProviderFactory } from "./traced-fsm.js";
import type { FSMOnTransitionParams, FSMTransitionHandlerFactory } from "./fsm.js";
import type { OperationQueue } from "../../util/operation-queue.js";
import type { EntityPermissionStore } from "../agent/tools2/entity-permissions.js";
import type { ToolRegistry } from "../agent/tools2/registry.js";
import type { AccessControlContext, Tool } from "../agent/tools2/types.js";
import type { FileSystemInterface } from "../app-interface/file-system-interface.js";
import type { AppShell } from "../app-interface/shell.js";
import type { ChatSessionStore } from "../chat/chat-session-store.js";
import type { AppContextStore } from "../context/app-context.js";
import type { KnowledgeManager } from "../facts/knowledge-manager.js";
import type { AiServiceFeatureFlags } from "../features.js";
import type { IntegrationStore } from "../integrations/store.js";
import type { ChaosOptions } from "../llm/chaos-fetch.js";
import type { LLMClient, LLMClientStreamTextOptions } from "../llm/client.js";
import type { ContextManagerV2 } from "../llm/context-v2/manager.js";
import type { LLMProviderError } from "../llm/error.js";
import type { StreamTextResult } from "../llm/interaction/provider.js";
import type { LLMProvider } from "../llm/types.js";
import type { LLMObsNamedSpanOptions } from "../llmobs/index.js";
import type { PlaywrightMcpServerManager } from "../mcp/playwright-server.js";
import type { ClarkProfiler } from "../profiler/clark-profiler.js";
import type { PromptInterpretTask } from "../prompt-builder-service/classifiers/prompt-interpret-task.js";
import type { RecordingManager } from "../recording/index.js";
import type { TemplateRenderer } from "../template-renderer.js";
import type { AiServiceConfig, AiServiceEvents, ArtifactProcessor, ChangeInfo, EditorClient, FileArtifact, UserChange } from "../types.js";
import type { LanguageModelV2 } from "@ai-sdk/provider";
import type { AiGenerateRequest, Attachment, LLMProviderConfig, PromptContextIntegration, PromptContext, PromptContextEntity, RememberFactCandidate, RuntimeErrorData, AiMode, PlanContext, AiMessagePush, AiGenerationState, AiToolPermission, BrowserContext, ConsoleLogEntry, ApiRunRecord } from "@superblocksteam/library-shared/types";
import type { TracedEventEmitter } from "@superblocksteam/shared";
import type { FinishReason } from "ai";
import type { ViteDevServer } from "vite";
declare const $: {
    readonly Idle: "Idle";
    readonly AgentPlanning: "AgentPlanning";
    readonly LLMGenerating: "LLMGenerating";
    readonly AwaitingUser: "AwaitingUser";
    readonly PostProcessing: "PostProcessing";
    readonly RuntimeReviewing: "RuntimeReviewing";
    readonly Dead: "Dead";
};
export declare const ClarkStateNames: {
    readonly Idle: "Idle";
    readonly AgentPlanning: "AgentPlanning";
    readonly LLMGenerating: "LLMGenerating";
    readonly AwaitingUser: "AwaitingUser";
    readonly PostProcessing: "PostProcessing";
    readonly RuntimeReviewing: "RuntimeReviewing";
    readonly Dead: "Dead";
};
export type ClarkState = keyof typeof $;
export declare const USER_SENT_PROMPT = "userSentPrompt";
export declare const USER_ACCEPTED_DRAFT = "userAcceptedDraft";
export declare const USER_REJECTED_DRAFT = "userRejectedDraft";
export declare const USER_CANCELED = "userCanceled";
export declare const AGENT_PLANNED = "agentPlanned";
export declare const AGENT_REPORTED_ERROR_TO_USER = "agentReportedErrorToUser";
export declare const AGENT_NEEDS_USER_INPUT = "agentNeedsUserInput";
export declare const AGENT_GAVE_UP = "agentGaveUp";
export declare const AGENT_CANCELED = "agentCanceled";
export declare const LLM_REQUESTED_CONTEXT = "llmRequestedContext";
export declare const LLM_FINISHED_UNEXPECTEDLY = "llmFinishedUnexpectedly";
export declare const LLM_ERRORED = "llmErrored";
export declare const LLM_FINISHED = "llmFinished";
export declare const POST_PROCESSING_ERRORED = "postProcessingErrored";
export declare const POST_PROCESSING_FINISHED = "postProcessingFinished";
export declare const RUNTIME_REVIEW_FINISHED = "runtimeReviewFinished";
export declare const APP_RUNTIME_UPDATED_WITHOUT_EDITS = "appRuntimeUpdatedWithoutEdits";
export declare const RUNTIME_REVIEW_ERRORED = "runtimeReviewErrored";
export declare const BUILD_SYSTEM_ERRORED = "buildSystemErrored";
export declare const SERVICE_STARTED_WITH_DRAFT = "serviceStartedWithDraft";
export declare const V3_AGENT_FINISHED = "v3AgentFinished";
export type ClarkEvent = {
    type: typeof USER_SENT_PROMPT;
    request: AiGenerateRequest;
    peer: EditorClient;
    peerId: string;
} | {
    type: typeof USER_ACCEPTED_DRAFT;
    silently?: boolean;
} | {
    type: typeof USER_REJECTED_DRAFT;
    silently?: boolean;
} | {
    type: typeof USER_CANCELED;
} | {
    type: typeof AGENT_PLANNED;
    userPrompt: string;
    promptContext?: PromptContext;
    debugging?: boolean;
    /** True if this is an original user prompt (not a response to interactive message). Defaults to true. */
    isUserPrompt?: boolean;
    knowledgeMessageId?: string;
} | {
    type: typeof AGENT_REPORTED_ERROR_TO_USER;
    error: Error;
} | {
    type: typeof AGENT_NEEDS_USER_INPUT;
    advice?: string;
} | {
    type: typeof AGENT_GAVE_UP;
} | {
    type: typeof AGENT_CANCELED;
    advice?: string;
} | {
    type: typeof LLM_REQUESTED_CONTEXT;
    prompt: string;
} | {
    type: typeof LLM_FINISHED_UNEXPECTEDLY;
    finishReason: FinishReason;
} | {
    type: typeof LLM_ERRORED;
    error: LLMProviderError;
} | {
    type: typeof LLM_FINISHED;
    files: FileArtifact[];
} | {
    type: typeof POST_PROCESSING_ERRORED;
    error: Error;
} | {
    type: typeof POST_PROCESSING_FINISHED;
    files: FileArtifact[];
} | {
    type: typeof RUNTIME_REVIEW_FINISHED;
} | {
    type: typeof APP_RUNTIME_UPDATED_WITHOUT_EDITS;
} | {
    type: typeof RUNTIME_REVIEW_ERRORED;
    tsErrorsByPath: Record<string, string[]>;
    lintErrorsByPath: Record<string, string[]>;
    integrationErrorsByPath: Record<string, string[]>;
} | {
    type: typeof BUILD_SYSTEM_ERRORED;
    error: Error;
} | {
    type: typeof SERVICE_STARTED_WITH_DRAFT;
} | {
    type: typeof V3_AGENT_FINISHED;
};
export declare const transitions: {
    readonly Idle: {
        readonly userSentPrompt: "AgentPlanning";
        readonly serviceStartedWithDraft: "AwaitingUser";
        readonly appRuntimeUpdatedWithoutEdits: "Idle";
    };
    readonly AgentPlanning: {
        readonly agentPlanned: "LLMGenerating";
        readonly agentNeedsUserInput: "AwaitingUser";
        readonly v3AgentFinished: "AwaitingUser";
        readonly agentGaveUp: "Dead";
        readonly agentCanceled: "Idle";
        readonly userCanceled: "Idle";
    };
    readonly LLMGenerating: {
        readonly llmFinished: "PostProcessing";
        readonly llmErrored: "AgentPlanning";
        readonly llmFinishedUnexpectedly: "AgentPlanning";
        readonly llmRequestedContext: "AgentPlanning";
        readonly appRuntimeUpdatedWithoutEdits: "Idle";
        readonly userCanceled: "Idle";
        readonly agentCanceled: "Idle";
        readonly postProcessingErrored: "AgentPlanning";
        readonly v3AgentFinished: "AwaitingUser";
        readonly agentNeedsUserInput: "AwaitingUser";
    };
    readonly PostProcessing: {
        readonly postProcessingFinished: "RuntimeReviewing";
        readonly postProcessingErrored: "AgentPlanning";
        readonly userCanceled: "Idle";
        readonly agentCanceled: "Idle";
        readonly appRuntimeUpdatedWithoutEdits: "Idle";
    };
    readonly RuntimeReviewing: {
        readonly runtimeReviewErrored: "AgentPlanning";
        readonly buildSystemErrored: "AgentPlanning";
        readonly runtimeReviewFinished: "AwaitingUser";
        readonly appRuntimeUpdatedWithoutEdits: "Idle";
        readonly userCanceled: "Idle";
        readonly agentCanceled: "Idle";
    };
    readonly AwaitingUser: {
        readonly userAcceptedDraft: "Idle";
        readonly userRejectedDraft: "RuntimeReviewing";
        readonly userSentPrompt: "AgentPlanning";
        readonly userCanceled: "Idle";
        readonly agentCanceled: "Idle";
    };
    readonly Dead: {};
};
export type $Idle = typeof $.Idle;
export type $AgentPlanning = typeof $.AgentPlanning;
export type $LLMGenerating = typeof $.LLMGenerating;
export type $AwaitingUser = typeof $.AwaitingUser;
export type $PostProcessing = typeof $.PostProcessing;
export type $RuntimeReviewing = typeof $.RuntimeReviewing;
export type $Dead = typeof $.Dead;
export type ClarkTransitionHandlerFactory = FSMTransitionHandlerFactory<ClarkState, ClarkEvent>;
export type ClarkTagProviderFactory = TracedFSMTagProviderFactory<ClarkState, ClarkEvent, ClarkContext>;
export declare class Clark extends TracedFSM<ClarkState, ClarkEvent, ClarkContext> {
    constructor(config: {
        initialContext: ClarkContext;
        createTransitionHandler: ClarkTransitionHandlerFactory;
        sessionId?: string;
        createTagProvider?: ClarkTagProviderFactory;
    });
    getAccessControl(flags: AiServiceFeatureFlags): AccessControlContext;
    resetContext(): void;
    protected getRootSpanOptions(_initialEvent: ClarkEvent): LLMObsNamedSpanOptions;
    protected getStateSpanOptions(state: ClarkState): TracedFSMStateSpanOptions;
    protected sanitizeEvent(event: ClarkEvent): Partial<ClarkEvent>;
    /**
     * High-level streamText interface with middleware support.
     *
     * Automatically composes:
     * - Context management (acquires lock, manages conversation history)
     * - Logging middleware (logs full conversation to artifact)
     * - LLMObs middleware (tracing and observability)
     *
     * Only `user` message is required - all other options have smart defaults.
     *
     * @param services - Service dependencies (contextManager, profiler, etc.)
     * @param options - Stream options including model, user message, tools, etc.
     * @returns Promise resolving to stream result
     *
     * @example
     * ```typescript
     * // Minimal usage - only user message required
     * const result = await clark.streamText(services, {
     *   user: { role: "user", content: "Hello!" }
     * });
     *
     * // With overrides
     * const result = await clark.streamText(services, {
     *   user: { role: "user", content: userPrompt },
     *   model: myCustomModel,
     *   system: systemPrompt,
     *   tools: actualTools,
     *   context: { contextOptions: { maxTokens: 150000 } },
     *   logging: { conversationId: "custom-id" }
     * });
     * ```
     */
    streamText<TOOLS extends Record<string, Tool>>(services: ClarkStateHandlerParams, options: ClarkStreamTextOptions<TOOLS>): Promise<StreamTextResult<TOOLS>>;
    private pushContextUsed;
}
export type ClarkTransition = FSMOnTransitionParams<ClarkState, ClarkEvent>;
export type ClarkStateHandlerFactory = (clark: Clark, params: ClarkStateHandlerParams) => (transition: ClarkTransition) => Promise<void>;
export type ClarkStateHandlerFactories = {
    [K in ClarkState]: ClarkStateHandlerFactory;
};
export type ValidEventsForState<S extends ClarkState> = keyof (typeof transitions)[S] extends never ? never : {
    [K in keyof (typeof transitions)[S]]: Extract<ClarkEvent, {
        type: K;
    }>;
}[keyof (typeof transitions)[S]];
/**
 * Consolidated state for API testing lifecycle.
 *
 * An API moves between sets as events occur:
 *   buildApi succeeds  → untested
 *   testApi succeeds   → passed  (removed from untested/failed)
 *   testApi fails      → failed  (removed from untested/passed)
 *   buildApi rebuilds  → untested (removed from failed/passed)
 *   deleteFile         → removed from all sets
 */
export interface ApiTestingState {
    /** APIs built in this session that have never had testApi called */
    untested: Set<string>;
    /** APIs where testApi ran and returned errors */
    failed: Set<string>;
    /** APIs where testApi ran successfully */
    passed: Set<string>;
}
export type ClarkContext = {
    peer?: EditorClient;
    peerId?: string;
    hasSuggestions?: boolean;
    summaryMessages?: {
        role: "user" | "assistant";
        isDebugging: boolean;
        content: string;
    }[];
    abortController?: AbortController;
    initialElementIds?: string[];
    initialFilePaths?: {
        apis: string[];
        components: string[];
    };
    generatedChangeInfo?: Record<string, ChangeInfo>;
    peerChannelQueue?: OperationQueue;
    usedDebugging?: boolean;
    runTimestamp?: string;
    jwt?: string;
    promptId?: string;
    chatmessageId?: string;
    availableIntegrations?: PromptContextIntegration[];
    promptInterpretTask?: PromptInterpretTask;
    debugToolCalled?: boolean;
    lastDebugTimestamp?: number;
    lastDebugHadTypeErrors?: boolean;
    lastFileModificationTime?: number;
    debugAttemptCount?: number;
    useMockGeneration?: boolean;
    buildSystemErrors?: Error[];
    runtimeErrors?: RuntimeErrorData[];
    consoleLogs?: ConsoleLogEntry[];
    apiRunRecords?: Array<ApiRunRecord & {
        apiId: string;
        _size?: number;
    }>;
    requiredFileReads?: Set<string>;
    checklist?: {
        items: {
            id: string;
            content: string;
            status: "pending" | "in_progress" | "completed" | "cancelled";
            createdAt: string;
            updatedAt?: string;
        }[];
        lastUpdated: string;
    };
    llmConfig?: LLMProviderConfig;
    usedCacheBreakpoints?: Record<string, number>;
    currentMode?: AiMode;
    planContext?: PlanContext;
    taggedEntities?: PromptContextEntity[];
    chaosOptions?: ChaosOptions;
    retryCount?: number;
    workflowFailed?: boolean;
    workflowMetrics?: {
        toolCallCount: number;
        stepCount: number;
        linesAdded: number;
        linesEdited: number;
        linesRemoved: number;
        workflowStartedAt?: string;
    };
    planSize?: "small" | "medium" | "large" | "extra large";
    lastGenerationState?: {
        state: AiGenerationState;
        hasSuggestions?: boolean;
    };
    activeInteractiveMessage?: {
        id: string;
        payload: AiMessagePush;
    };
    pendingToolPermissionRequest?: {
        messageId: string;
        toolName: string;
        actionName?: {
            future: string;
            present: string;
            past: string;
        };
        formattedInput?: {
            targets: string[];
            details?: string;
            summary?: string;
        };
        rawInput: any;
        permissions?: AiToolPermission[];
        toolCallId?: string;
        signature?: string;
        /** Timestamp of the assistant message containing the tool call - used to truncate stale error on approval */
        toolCallTimestamp?: number;
    };
    skippedToolPermissionRequests?: Set<string>;
    userChanges?: UserChange[];
    /** Consolidated API testing state tracking */
    apiTestingState?: ApiTestingState;
    /** APIs that failed to build - must be fixed and rebuilt before finalizing */
    failedApiBuilds?: Set<string>;
    /** Browser context for Playwright automation - contains iframe URL and init/bootstrap data */
    browserContext?: BrowserContext;
    /** Current test run ID */
    currentTestRunId?: string;
    /** Current test cases for the active test run */
    currentTestCases?: Array<{
        id: string;
        name: string;
        description?: string;
    }>;
    /** Tracked statuses of test cases (source of truth for reconciliation) */
    testCaseStatuses?: Map<string, "not_started" | "running" | "passed" | "failed" | "skipped">;
    /** Test case ID that should be skipped (set by user skip request) */
    skipRequestedForTestCase?: string;
    partialResponse?: {
        text: string;
        lastUpdatedAt: number;
    };
    interruptedPreviousGeneration?: boolean;
    interruptOriginalPrompt?: string;
    isInterruptAbort?: boolean;
    /** Set to true when Clark calls the rememberFacts tool in the current turn */
    explicitRememberIntentForTurn?: boolean;
    /** Mode to restore after FACT-mode approval flow completes */
    modeBeforeFactCapture?: AiMode;
    /** Candidate facts staged by the rememberFacts tool, awaiting user approval */
    rememberFactsCandidatesForTurn?: RememberFactCandidate[];
    /** The active pending approval for app facts — contains the interactive message ID */
    pendingAppFacts?: {
        messageId: string;
        facts: RememberFactCandidate[];
    };
    /** Attachments buffered before context was loaded — flushed to AttachmentsStore once context is available */
    pendingAttachments?: {
        attachments: Attachment[];
        originalMessage?: string;
    };
};
export type ClarkStateHandlerParams = AiServiceConfig & {
    templateRenderer: TemplateRenderer;
    artifactProcessor: ArtifactProcessor;
    appShell: AppShell;
    signals: TracedEventEmitter<AiServiceEvents>;
    fileSystemInterface: FileSystemInterface;
    integrationStore: IntegrationStore;
    knowledgeManager: KnowledgeManager;
    appContextStore: AppContextStore;
    llmProvider: LLMProvider;
    chatSessionStore: ChatSessionStore;
    clarkProfiler: ClarkProfiler;
    contextManagerV2: ContextManagerV2;
    toolRegistry: ToolRegistry;
    entityPermissionStore: EntityPermissionStore;
    llmClient: LLMClient;
    mcpServerManager: PlaywrightMcpServerManager;
    viteServer?: ViteDevServer;
    recordingManager?: RecordingManager;
};
/**
 * Options for Clark.streamText().
 *
 * Extends StreamTextOptions with Clark-specific middleware configuration.
 * Only `user` message is required - all other options have smart defaults.
 * providerConfig and enableFallback are populated from Clark's context.llmConfig.
 */
export interface ClarkStreamTextOptions<TOOLS extends Record<string, Tool>> extends Omit<LLMClientStreamTextOptions<TOOLS>, "model" | "providerConfig"> {
    /** Language model to use. Defaults to services.llmProvider.modelForTask("generateBroadEdit"). */
    model?: LanguageModelV2;
}
export {};
//# sourceMappingURL=clark-fsm.d.ts.map