import * as react from 'react';
import { ReactNode } from 'react';
import { ToolDetailRenderers, ChatUiMessage } from '../web-react/index.js';
import '../contract-CEewO6DI.js';
import '@tangle-network/agent-interface';
import '../plans/index.js';
import '../parts-DIKcC1p6.js';
import '../types-DeEOhQbv.js';
import '../agent-activity-C8ZG0F0M.js';
import '../flow-types-CJxEmaRy.js';
import '../queue-DBkulxW1.js';
import '../sandbox-terminal-ChNEdHF8.js';
import '../catalog/index.js';
import '../harness/index.js';
import '../attachment-validation-yJ6Id4pR.js';
import '../stream-normalizer-DnuqkZvw.js';

/**
 * Wire + UI types for the in-app assistant panel. The wire shapes mirror the
 * SSE contract emitted by `POST /v1/assistant/chat` (platform-api
 * `routes/assistant.ts`). Drift here only mis-renders the client; the server
 * is the source of truth for what it accepts and emits.
 */

/** Define delivery modes for assistant interaction as either steering or queue */
type AssistantDeliveryMode = "steering" | "queue";
/** Request body for `POST /api/v1/assistant/chat`. */
interface ChatRequest {
    message: string;
    /** How to deliver text when a session may already be active. Defaults to steering. */
    deliveryMode?: AssistantDeliveryMode;
    /** Model slug to run this turn against; omit to use the server default. */
    model?: string;
    /** Omit to start a new thread; pass to continue an existing one. */
    threadId?: string;
    /** Per-turn idempotency key — guards against double-charge on retry. */
    turnKey?: string;
}
/** Describe the structure of data representing a thread event with optional model information */
interface ThreadEventData {
    threadId: string;
    turnId: string;
    /** The model slug this turn ran against, when the server reports it. */
    model?: string | null;
}
/** Define data structure representing a delta event with associated text content */
interface DeltaEventData {
    text: string;
}
/** A chunk of the model's reasoning/thinking, streamed BEFORE the answer for
 *  reasoning models. Surfaced as a dim "thinking" block so a long reasoning gap
 *  doesn't read as a frozen panel. Absent for non-reasoning models. */
interface ReasoningEventData {
    text: string;
}
/** Emitted when a read-only tool STARTS running, before its result. Lets the
 *  panel show live "running <tool>…" progress instead of a silent gap. */
interface ToolCallEventData {
    callId: string;
    name: string;
    /** The parsed arguments the agent invoked the tool with. Lets a renderer show
     *  exactly what was called. Omitted by servers predating the field. */
    args?: Record<string, unknown>;
}
/** Describe event data emitted after a tool execution completes with success or error details */
interface ToolResultEventData {
    callId: string;
    name: string;
    ok: boolean;
    output?: unknown;
    error?: {
        code: string;
        message: string;
    };
}
/** What kind of connection a requirement names — drives the card's label and
 *  connect target. "integration" is an OAuth/api-key connection on the
 *  integrations page; "github_app" is the GitHub App installed on the repo (the
 *  event source for a GitHub trigger), connected via the App install flow. */
type ConnectionRequirementKind = "integration" | "github_app";
/** A connection a proposed workflow references, and whether the user has it
 *  connected right now. Surfaced on an authoring proposal so the card can show
 *  what must be connected — and WHERE — before the workflow can be created. */
interface ConnectionRequirement {
    provider: string;
    connected: boolean;
    /** What must be connected. Absent on proposals predating the field — treated
     *  as "integration" by the card. */
    kind?: ConnectionRequirementKind;
    /** Where the user connects this requirement, supplied by the server (the
     *  GitHub App install URL is deploy config the client can't derive). Null when
     *  there's no link to offer (e.g. a github_app requirement on a deploy with no
     *  app slug); the card then shows the requirement without a connect link. */
    connectUrl?: string | null;
}
/**
 * Outcome of a host-driven, in-place connect for a single proposal requirement
 * (see {@link AssistantDockProps.onConnectRequirement}). The host owns the whole
 * connect experience — an OAuth popup, an api-key entry modal, an app install,
 * and any error surfacing — and the assistant stays agnostic to how it happens:
 * the host reports back only whether the requirement is now satisfied, which the
 * card uses to flip that requirement to connected without a reload. `connected:
 * false` (a failed or cancelled connect) leaves the card unchanged so the user
 * can retry.
 */
interface ConnectRequirementResult {
    connected: boolean;
}
/** Describe the data structure for events proposing tool usage with optional integration requirements */
interface ToolProposalEventData {
    /** Null only if the server has no proposal store wired (tools then unusable). */
    proposalId: string | null;
    callId: string;
    name: string;
    args: unknown;
    /** Present on a workflow-authoring proposal: the integrations it references
     *  and their current connection status. Omitted for non-authoring tools. */
    requirements?: ConnectionRequirement[];
}
/** Describe usage event data including tokens, cost, balance, duration, and replay status */
interface UsageEventData {
    promptTokens: number | null;
    completionTokens: number | null;
    costUsd: number | null;
    balanceUsd: number | null;
    /** Wall-clock duration of the turn in milliseconds, when the server measures
     *  it. Drives the renderer's tokens/sec figure. Omitted by older servers. */
    durationMs?: number | null;
    /** True when a completed turn was replayed from storage (no charge). */
    replayed?: boolean;
}
/** Describe the data emitted when a process turn completes including status and optional flags */
interface DoneEventData {
    turnId: string;
    status: string;
    /** True when a mutating tool was proposed and is awaiting confirmation. */
    proposed?: boolean;
    /** True when the agentic loop hit its tool-round cap. */
    capped?: boolean;
}
/** Describe error event data including code and message fields */
interface ErrorEventData {
    code: string;
    message: string;
}
/** Discriminated union the stream reader hands to the reducer. */
type AssistantStreamEvent = {
    type: "thread";
    data: ThreadEventData;
} | {
    type: "delta";
    data: DeltaEventData;
} | {
    type: "reasoning";
    data: ReasoningEventData;
} | {
    type: "tool_call";
    data: ToolCallEventData;
} | {
    type: "tool_result";
    data: ToolResultEventData;
} | {
    type: "tool_proposal";
    data: ToolProposalEventData;
} | {
    type: "usage";
    data: UsageEventData;
} | {
    type: "done";
    data: DoneEventData;
} | {
    type: "error";
    data: ErrorEventData;
};
/** A `tool` message is the inline activity chip for a read-only tool the agent
 *  ran during a turn (e.g. "Validating workflow… ✓"). */
type ChatRole = "user" | "assistant" | "status" | "tool";
/** Live status of a tool-activity chip. */
type ToolActivityStatus = "running" | "ok" | "failed";
/** The outcome of a finished read-only tool, retained on the chip so a renderer
 *  can show the result body (not just the name + status). Mirrors the
 *  `tool_result` event: a success carries the tool's `result`; a failure carries
 *  the error. Absent while the tool is still running. */
type ToolOutcome = {
    ok: true;
    result?: unknown;
} | {
    ok: false;
    error?: {
        code: string;
        message: string;
    };
};
/**
 * The result of a CONFIRMED mutating tool, retained on the resolving `status`
 * message so a host can render it prominently (e.g. a one-time API-key reveal).
 *
 * SECURITY: `output` may carry a one-time secret (e.g. a freshly minted API
 * key). It lives ONLY in the in-memory transcript for the session — the message
 * transcript is deliberately never cached (see `persistence.ts`) and is never
 * sent back to the model (a turn request carries only the new user text, see
 * {@link ChatRequest}). So the secret is shown once and is gone on reload,
 * matching how a dedicated create-key page reveals a key exactly once. A host
 * renderer must uphold the same contract: reveal-on-demand, never persist it.
 */
interface ConfirmedResult {
    /** The confirmed tool's name (e.g. "create_api_key"). */
    name: string;
    /** The tool's raw output. May contain a one-time secret — see the type doc. */
    output: unknown;
    /** The arguments the action was confirmed with, for a renderer that needs them
     *  (e.g. the key's name). */
    args?: unknown;
}
/** Define the structure and properties of a chat message including optional tool activity details */
interface ChatMessage {
    id: string;
    role: ChatRole;
    text: string;
    /** Present only on `tool` messages — the activity's tool name, the arguments it
     *  was called with, its state, and (once finished) its outcome. */
    tool?: {
        name: string;
        status: ToolActivityStatus;
        args?: Record<string, unknown>;
        outcome?: ToolOutcome;
    };
    /** Present only on a `status` message that resolved a confirmed mutating tool
     *  which returned a renderable result — carries that result so the transcript
     *  can render a host-supplied card (e.g. a one-time key reveal) next to the
     *  status line. See {@link ConfirmedResult} for the one-time-secret contract. */
    result?: ConfirmedResult;
}
/** A mutating action the assistant proposed, awaiting the user's confirmation. */
interface PendingProposal {
    proposalId: string | null;
    callId: string;
    name: string;
    args: unknown;
    /** Integration requirements for a workflow-authoring proposal (each provider
     *  + whether it's connected); omitted for non-authoring proposals. */
    requirements?: ConnectionRequirement[];
    /** Inline error shown ON the card after a RETRYABLE confirm failure (an
     *  unconnected integration): the card stays so the user can connect and
     *  confirm again. Null/absent when the card has not failed a retry. */
    retryError?: string | null;
}
/** Describe usage cost, balance, token counts, duration, and replay status for a settled turn */
interface UsageInfo {
    costUsd: number | null;
    balanceUsd: number | null;
    /** Token counts + wall-clock duration for the settled turn, when the server
     *  reports them — drive per-message tokens/sec + cost in a renderer. Optional
     *  so a consumer constructing this on the prior `{ costUsd, balanceUsd,
     *  replayed }` shape stays valid; a renderer treats a missing value as null. */
    promptTokens?: number | null;
    completionTokens?: number | null;
    durationMs?: number | null;
    replayed: boolean;
}
/**
 * The transcript slice handed to a host-supplied `renderTranscript` (see
 * {@link AssistantPanelProps}). It lets a host swap ONLY the conversation
 * rendering — to use its own message renderer — while the panel keeps owning the
 * dock chrome, composer, model picker, history, transport, and proposal
 * orchestration. The bound `renderProposal` returns the panel's own proposal
 * card so the host can place it (e.g. inline after the proposing turn) without
 * re-implementing the confirm/cancel flow.
 */
interface AssistantTranscriptView {
    messages: ChatMessage[];
    /** The current turn's reasoning/thinking text, if any (streamed before the
     *  answer for reasoning models). */
    reasoning: string | null;
    /** Id of the assistant message currently accumulating deltas, if any. */
    streamingId: string | null;
    /** Model slug the current/most-recent turn ran against, or null. */
    model: string | null;
    /** True while a turn is streaming. */
    isStreaming: boolean;
    /** True while the agent is working but has produced no visible output yet
     *  (drives a "thinking" affordance). */
    isThinking: boolean;
    pendingProposals: PendingProposal[];
    /** Cost/tokens/duration for the most recently settled turn, or null before any
     *  turn settles. Optional so a host predating the field stays a valid consumer;
     *  a renderer treats a missing value the same as null. */
    usage?: UsageInfo | null;
    /** The panel's bound proposal card for a pending proposal — render it where the
     *  confirm/cancel UI should appear. */
    renderProposal: (proposal: PendingProposal) => ReactNode;
}

/**
 * Configurable network client for the assistant panel: the chat SSE stream, the
 * model/thread/history reads, and the proposal-confirmation call.
 *
 * The transport is injected via {@link AssistantClientConfig} so the same UI can
 * run in different hosts: a same-origin app authenticates with the session
 * cookie (`credentials: "include"`) and an `X-Requested-With` marker, while a
 * cross-origin host points `baseUrl` at the API and supplies a bearer token via
 * `headers`. The request shapes and the defensive wire parsing are identical
 * across hosts — only the base URL and the auth headers vary.
 */

/** Host-supplied transport configuration for {@link createAssistantClient}. */
interface AssistantClientConfig {
    /**
     * Base URL the five assistant endpoints hang off, with no trailing slash —
     * e.g. `"/api/v1/assistant"` for a same-origin SSR edge, or
     * `"https://id.tangle.tools/api/v1/assistant"` cross-origin. Each method
     * appends its own path (`/chat`, `/models`, `/threads`, …).
     */
    baseUrl: string;
    /**
     * `fetch` credentials mode. Defaults to `"include"` so a same-origin cookie
     * session authenticates; a token-based cross-origin host may pass `"omit"`
     * and carry the credential in {@link AssistantClientConfig.headers}.
     */
    credentials?: RequestCredentials;
    /**
     * Headers applied to every request — the auth token and/or the CSRF marker.
     * Called per request so a rotating token is read fresh, never captured once.
     */
    headers?: () => Record<string, string>;
}
/** Define options for an assistant model including identifier, label, pricing, and context tokens */
interface AssistantModelOption {
    slug: string;
    label: string;
    /** USD per million prompt tokens, when the catalog carries pricing. */
    promptUsdPerMillion?: number;
    /** Context window in tokens, when known. */
    contextTokens?: number;
}
/** Define the structure for assistant model options including a default model slug and available models */
interface AssistantModels {
    /** The slug the server uses when a turn selects no model. */
    default: string | null;
    models: AssistantModelOption[];
}
/** One past conversation in the history switcher. */
interface AssistantThreadSummary {
    id: string;
    /** Truncated first user message; may be null for an untitled thread. */
    title: string | null;
    createdAt: string;
    updatedAt: string;
}
/**
 * Outcome of a model-list fetch. `ok` drives caching: the caller caches on `ok`
 * and retries on `!ok`. An EMPTY list is reported as `!ok` — the server always
 * offers at least the default model when the router is reachable, so an empty
 * menu means the catalog couldn't be loaded and should be retried, not cached
 * for the whole session.
 */
interface AssistantModelsResult {
    ok: boolean;
    data: AssistantModels;
}
/**
 * Outcome of a thread-history restore. The three cases drive different recovery:
 * `ok` rehydrates the transcript; `gone` (the thread 404s — deleted or from a
 * reset DB) tells the caller to drop the dead thread id so the next turn starts
 * fresh; `error` (transient/network/aborted) keeps the thread id and simply
 * doesn't restore, so a later attempt or send still targets the live thread.
 */
type ThreadHistoryResult = {
    status: "ok";
    messages: ChatMessage[];
    proposals: PendingProposal[];
} | {
    status: "gone";
} | {
    status: "error";
};
/** Represent the outcome of a confirmation process with success or failure details */
type ConfirmResult = {
    ok: true;
    output: unknown;
    retryable?: boolean;
} | {
    ok: false;
    error: string;
};
/** Represent invalid client input errors with a specific code INVALID_REQUEST */
declare class AssistantClientInputError extends Error {
    readonly code = "INVALID_REQUEST";
}
/** The assistant network surface, bound to one host's transport config. */
interface AssistantClient {
    fetchModels(signal?: AbortSignal): Promise<AssistantModelsResult>;
    fetchThreads(signal?: AbortSignal): Promise<AssistantThreadSummary[] | null>;
    fetchThreadHistory(threadId: string, signal?: AbortSignal): Promise<ThreadHistoryResult>;
    streamChat(req: ChatRequest, onEvent: (event: AssistantStreamEvent) => void, signal: AbortSignal): Promise<void>;
    confirmProposal(proposalId: string): Promise<ConfirmResult>;
    /** Delete a thread and its server-side turns/proposals. Resolves `{ ok }`; a
     *  404 (already gone) is treated as success so a double-delete is harmless.
     *  Optional so a host with no delete endpoint stays a valid client — the panel
     *  hides the delete affordance when it's absent (see `useAssistantThreads`). */
    deleteThread?(threadId: string): Promise<{
        ok: boolean;
    }>;
}
/**
 * Build an assistant client bound to one host's transport. The returned methods
 * carry no module state, so a host may create one client per config (or share a
 * single same-origin client for the whole app).
 */
declare function createAssistantClient(config: AssistantClientConfig): AssistantClient;

declare function AssistantClientProvider({ client, children, }: {
    client: AssistantClient;
    children: ReactNode;
}): react.JSX.Element;
/**
 * The assistant client for the current host. Throws when no provider is mounted
 * rather than silently falling back to a default transport — a missing provider
 * is a wiring bug, and a hidden default would mask it (and could target the
 * wrong origin).
 */
declare function useAssistantClient(): AssistantClient;

/**
 * Pure state machine driving the assistant panel. Every UI transition — a user
 * message, each streamed SSE event, a stream failure, a confirmed/cancelled
 * proposal, a manual stop — is modeled as an action here, so the panel's
 * behavior can be verified without a DOM or a live stream.
 */

type ChatStatus = "idle" | "streaming" | "awaiting_confirm";
interface AssistantState {
    /** The signed-in user this conversation belongs to. Carried in state so it
     *  moves atomically with the data it labels — persistence keys off it, and a
     *  render whose owner doesn't match the current user is masked (see
     *  `selectVisibleState`), preventing a one-frame cross-account leak. */
    ownerId: string | null;
    /** Persisted across reloads to continue the same server-side thread. */
    threadId: string | null;
    messages: ChatMessage[];
    status: ChatStatus;
    /** Id of the assistant message currently accumulating deltas, if any. Set to
     *  null mid-turn when a tool runs, so the next text delta opens a fresh
     *  assistant bubble — keeping each reasoning segment visually distinct. */
    streamingId: string | null;
    /** Base id for the current turn's assistant bubbles (the `send` assistant id).
     *  Post-tool segments derive a unique id from it; null between turns. */
    streamBaseId: string | null;
    /** How many assistant bubbles the current turn has opened (0 = just the first).
     *  Drives the per-segment bubble id so segments never collide across turns. */
    segmentSeq: number;
    pendingProposals: PendingProposal[];
    /** Cost/balance from the most recently settled turn. */
    usage: UsageInfo | null;
    /** Model slug the current/most-recent turn ran against (from the thread
     *  event), or null before any turn this session. */
    model: string | null;
    /** The current turn's accumulated reasoning/thinking text (reasoning models
     *  stream this before the answer). Shown dim while the answer is still pending;
     *  reset at the start of each turn. Null when the model emits no reasoning. */
    reasoning: string | null;
    error: {
        code: string;
        message: string;
    } | null;
    /** True when the most-recent turn stopped at the per-turn step limit before the
     *  model finished (a partial reply). Drives the one-click "Continue" affordance;
     *  cleared when the next turn starts. */
    capped: boolean;
}

/**
 * React binding for the assistant panel: owns the reducer, drives the chat SSE
 * stream and the proposal-confirmation call, and persists the thread across
 * reloads. All rendering decisions live in the pure reducer + presentation
 * helpers; this hook is the glue between them and the network.
 */

/** Define options for configuring how the assistant sends messages */
interface AssistantSendOptions {
    deliveryMode?: AssistantDeliveryMode;
}
/** Host integration callbacks for {@link useAssistantChat}. */
interface UseAssistantChatOptions {
    /**
     * Called after a workflow-mutating tool (`create_workflow`, `author_workflow`,
     * …) is confirmed successfully — the host re-fetches its workflow list so the
     * result appears without a manual reload. Replaces the in-app cross-module
     * signal the platform used.
     */
    onWorkflowMutation?: () => void;
    /**
     * Called when the user activates a proposal requirement's connect affordance.
     * The host runs whatever connect flow it owns — an OAuth popup, an api-key
     * modal, an app install — and resolves whether the requirement is now
     * satisfied; the card then flips that requirement to connected. Host-agnostic:
     * the assistant never learns how the connection is made, so any host (platform,
     * sandbox, intelligence, …) can supply its own. When omitted, the card falls
     * back to navigating the requirement's connect target (see
     * {@link ProposalCardProps.navigate}).
     */
    onConnectRequirement?: (requirement: ConnectionRequirement) => Promise<ConnectRequirementResult>;
}
/** Define the structure and behavior of an assistant chat session with state, model selection, and message handling */
interface AssistantChat {
    state: AssistantState;
    /** Proposal ids whose confirmation is currently in flight (for disabling). */
    confirmingIds: ReadonlySet<string>;
    /** The user's selected model slug, or null to use the server default. */
    selectedModel: string | null;
    /** Choose the model for subsequent turns (persisted per user). */
    setModel: (model: string | null) => void;
    send: (message: string, options?: AssistantSendOptions) => void;
    stop: () => void;
    confirm: (proposal: PendingProposal) => Promise<void>;
    cancel: (proposal: PendingProposal) => void;
    /** True when the host supplied an in-place connect handler
     *  ({@link UseAssistantChatOptions.onConnectRequirement}); the proposal card
     *  uses this to offer in-place connect instead of navigating away. */
    canConnectRequirement: boolean;
    /** Run the host's in-place connect for one of a proposal's requirements and,
     *  on success, flip that requirement to connected on the card. Resolves (a
     *  no-op) when no host handler is set or the connect didn't complete. */
    connectRequirement: (proposal: PendingProposal, requirement: ConnectionRequirement) => Promise<void>;
    reset: () => void;
    /** Open an existing thread from history, loading its transcript. */
    switchThread: (threadId: string) => void;
    /** True while a switched-to thread's transcript is loading — the composer is
     *  held closed until it resolves so a turn can't run against hidden context. */
    restoring: boolean;
}
/** Manage assistant chat state and interactions for a given user ID with optional configurations */
declare function useAssistantChat(userId: string | null, options?: UseAssistantChatOptions): AssistantChat;

/**
 * The assistant's selectable models for the composer's picker. The list is
 * deployment config (not per-user), so it is fetched once per transport and
 * shared across panel mounts via a cache keyed by the `AssistantClient`.
 *
 * The cache has no TTL: it lives for the page session and is revalidated by a
 * page refresh — acceptable for deployment-config data that changes only on a
 * redeploy. An empty/failed fetch is NOT cached, so it retries on the next mount.
 *
 * Keyed by client so a host that swaps the transport (a tenant/origin/account
 * change) never serves the previous client's catalog or skips the fetch for the
 * new one. A WeakMap lets a discarded client's bucket be collected with it.
 *
 * Client-only by design (a `createRoot` SPA, no React SSR), so the cache lives
 * in one browser tab and is never shared across server requests. Under Strict
 * Mode's double-mount the two effect runs share the one in-flight fetch; the
 * first run's `active = false` makes its callback a no-op, the second commits —
 * dedup holds, no torn state.
 */

/** Resolve and return the current assistant models from the per-client cache with immediate client swap updates */
declare function useAssistantModels(): AssistantModels;

/**
 * The user's recent assistant chat threads for the history switcher. Unlike the
 * model list (deployment config, fetched once), the thread list changes as the
 * user chats, so it is fetched ON DEMAND — call `refresh()` to (re)load it; the
 * panel does so when the history view opens and after a turn settles a new
 * thread into being. It does NOT fetch on mount, so `threads` stays empty and
 * `loaded` false until the first `refresh()`.
 *
 * Self-protective across account AND transport swaps. The list is tagged with the
 * (user, client) it belongs to and is masked to empty on the SAME commit if that
 * no longer matches the current props — so a swap never shows the prior scope's
 * threads for even one frame. In flight, a late result is dropped if either the
 * user or the client changed, and the request is aborted on the swap.
 */

/** Manage and interact with a list of assistant threads including loading, refreshing, and removing threads */
interface AssistantThreads {
    threads: AssistantThreadSummary[];
    loading: boolean;
    /** True once a fetch has settled at least once (drives empty-vs-loading copy). */
    loaded: boolean;
    /** Load (or reload) the thread list. Must be called to populate `threads` —
     *  the hook never fetches on mount (the panel calls this when history opens). */
    refresh: () => void;
    /** Delete a thread. Optimistically drops it from the list (within the current
     *  owner scope); on failure the list is reloaded to restore the true state. A
     *  no-op resolving `{ ok: false }` when the client has no `deleteThread`. */
    remove: (threadId: string) => Promise<{
        ok: boolean;
    }>;
    /** Whether the configured client supports deletion — drives whether a host
     *  shows the delete affordance. */
    canRemove: boolean;
}
/** Resolve and manage assistant threads state for a given user including pending deletions and refresh logic */
declare function useAssistantThreads(userId: string | null): AssistantThreads;

interface AssistantDockProps {
    /** The signed-in user this conversation belongs to (null when signed out). */
    userId: string | null;
    /** Host navigation for error CTAs and connect targets. */
    navigate?: (path: string) => void;
    balanceUsd?: number | null;
    formatMoney?: (usd: number | null) => string;
    /** Render workflow YAML as a node graph in a proposal card. */
    renderGraph?: (yaml: string) => ReactNode;
    /** Render the brand icon for a proposal requirement's integration provider.
     *  The host owns the provider→icon mapping (its integrations catalog); when
     *  absent, the card falls back to its built-in provider mark. */
    renderProviderIcon?: (provider: string) => ReactNode;
    /** Called after a workflow-mutating tool is confirmed (host re-fetches its list). */
    onWorkflowMutation?: () => void;
    /** In-place connect handler for a proposal's integration requirements. The host
     *  runs its own connect flow (OAuth popup, api-key modal, app install) and
     *  resolves whether the requirement is now satisfied; the proposal card then
     *  flips it to connected. Host-agnostic — when omitted, the card falls back to
     *  navigating the requirement's connect target via `navigate`. */
    onConnectRequirement?: (requirement: ConnectionRequirement) => Promise<ConnectRequirementResult>;
    /** Markdown renderer for assistant message content (plain text when absent). */
    renderMarkdown?: (content: string) => ReactNode;
    /** Per-tool custom detail renderers for expanded tool cards in the transcript. */
    toolRenderers?: ToolDetailRenderers;
    /** Render a prominent card for a CONFIRMED tool's result (e.g. a one-time
     *  API-key reveal for `create_api_key`), shown inline after the action's status
     *  line. The result's `output` may carry a one-time secret — see
     *  {@link ConfirmedResult} for the never-persist/never-to-model contract. */
    renderConfirmedResult?: (result: ConfirmedResult) => ReactNode;
    /** Swap the conversation rendering for a host-supplied renderer (see
     *  {@link AssistantPanelProps.renderTranscript}); the dock chrome, composer,
     *  transport, and proposal flow stay owned by the panel. */
    renderTranscript?: (view: AssistantTranscriptView) => ReactNode;
}
declare function AssistantDock({ userId, navigate, balanceUsd, formatMoney, renderGraph, renderProviderIcon, onWorkflowMutation, onConnectRequirement, renderMarkdown, toolRenderers, renderConfirmedResult, renderTranscript, }: AssistantDockProps): react.JSX.Element;

interface AssistantPanelProps {
    chat: AssistantChat;
    userId: string | null;
    onClose: () => void;
    /** Host navigation for error CTAs and connect targets. */
    navigate?: (path: string) => void;
    /** The user's credit balance, for the header tile + low-balance nudge. */
    balanceUsd?: number | null;
    /** Format a USD amount; defaults to Intl currency formatting. */
    formatMoney?: (usd: number | null) => string;
    /** Render workflow YAML as a node graph in a proposal card (the `./workflows`
     *  WorkflowGraph). When absent, proposals show YAML as text. */
    renderGraph?: (yaml: string) => ReactNode;
    /** Render the brand icon for a proposal requirement's integration provider.
     *  When absent, the card falls back to its built-in provider mark. */
    renderProviderIcon?: (provider: string) => ReactNode;
    /** Markdown renderer for assistant message content. When absent, content
     *  renders as plain pre-wrapped text. */
    renderMarkdown?: (content: string) => ReactNode;
    /** Per-tool custom detail renderers for expanded tool cards in the transcript. */
    toolRenderers?: ToolDetailRenderers;
    /** Render a prominent card for a CONFIRMED tool's result (e.g. a one-time
     *  API-key reveal for `create_api_key`), shown inline after the action's status
     *  line. Ignored when a host swaps the whole transcript via `renderTranscript`. */
    renderConfirmedResult?: (result: ConfirmedResult) => ReactNode;
    /** Swap ONLY the conversation rendering for a host-supplied renderer (e.g. a
     *  different chat-message component), while the panel keeps owning the header,
     *  composer, model picker, history, transport, and proposal orchestration.
     *  Receives the transcript slice plus a bound proposal card to place. When
     *  absent, the built-in transcript (web-react `ChatMessages`) renders the
     *  conversation. */
    renderTranscript?: (view: AssistantTranscriptView) => ReactNode;
    /** One-shot composer prefill from the host's launcher (e.g. a page's "Create
     *  with assistant" button passing `openAssistant(seed)`). The panel adopts it
     *  as the composer draft and calls `onComposerSeedApplied` once, so the host
     *  clears its seed state (consume-once). */
    composerSeed?: string | null;
    onComposerSeedApplied?: () => void;
}
declare function AssistantPanel({ chat, userId, onClose, navigate, balanceUsd, formatMoney, renderGraph, renderProviderIcon, renderMarkdown, toolRenderers, renderConfirmedResult, renderTranscript, composerSeed, onComposerSeedApplied, }: AssistantPanelProps): react.JSX.Element;

/**
 * True while a turn is streaming but the model hasn't emitted its first answer
 * token yet — drives the "thinking" affordance so a reasoning gap reads as
 * working, not a frozen panel.
 */
declare function assistantIsThinking(state: AssistantState): boolean;
interface AdaptedTranscript {
    messages: ChatUiMessage[];
    /** The assistant message under which pending proposals should render, or null
     *  when there are none. */
    proposalHostId: string | null;
    /** The current/most-recent turn's assistant message — where the turn cost line
     *  renders (it carries the turn's metrics), or null when there is none. */
    metricsHostId: string | null;
    /** Confirmed-tool results to render under their (system) message, keyed by that
     *  message's id — carried from a `status` message's retained `result` so a host
     *  card (e.g. a one-time API-key reveal) renders inline right after the action. */
    confirmedResults: Map<string, ConfirmedResult>;
}
/**
 * Fold the transcript view into web-react `ChatUiMessage[]`: each user message is
 * 1:1; the assistant/`tool`/`status` messages between two user turns collapse
 * into one assistant message whose ordered `segments` carry the turn's text runs
 * and tool chips IN EMISSION ORDER (with each finished tool's outcome as the chip
 * `result`). The joined text is also kept on `content` — web-react reads it as the
 * "answer has started" signal that gates the reasoning box. The live turn's
 * reasoning preview and model label hang on the last assistant message, and
 * `proposalHostId` names the message the pending proposals render under.
 */
declare function adaptTranscript(view: AssistantTranscriptView): AdaptedTranscript;
interface AssistantTranscriptProps {
    view: AssistantTranscriptView;
    /** Markdown renderer for assistant content; defaults to plain pre-wrapped text. */
    renderMarkdown?: (content: string) => ReactNode;
    /** Per-tool custom detail renderers for expanded tool cards. */
    toolRenderers?: ToolDetailRenderers;
    /** Render a prominent card for a CONFIRMED tool's result, inline after its
     *  status line (e.g. a one-time API-key reveal for `create_api_key`). Return
     *  null to fall back to just the status line. Unlike `toolRenderers` (collapsed
     *  detail for a read-only tool chip), this is shown expanded, so a one-time
     *  secret is visible without a click. See {@link ConfirmedResult}. */
    renderConfirmedResult?: (result: ConfirmedResult) => ReactNode;
    /** Zero-state shown for a fresh, non-streaming thread. */
    emptyState?: ReactNode;
}
/**
 * Render the assistant conversation with web-react's `ChatMessages`. Pending
 * proposals render via the panel's bound `view.renderProposal`, placed inline
 * after the proposing turn through `renderExtras`; the settled turn cost renders
 * once under its assistant bubble.
 */
declare function AssistantTranscript({ view, renderMarkdown, toolRenderers, renderConfirmedResult, emptyState, }: AssistantTranscriptProps): react.JSX.Element;

interface ProposalCardProps {
    proposal: PendingProposal;
    /** True while this proposal's confirmation is in flight (disables the buttons). */
    confirming: boolean;
    onConfirm: () => void;
    onCancel: () => void;
    /** Host navigation for connect targets / the integrations page. */
    navigate?: (path: string) => void;
    /** In-place connect handler for a requirement. When provided, a requirement's
     *  connect affordance calls this (showing a busy state) instead of navigating
     *  to `connectUrl`/the integrations page — the host runs its own connect flow
     *  and the card flips the requirement to connected on success. Host-agnostic;
     *  wired by the panel from {@link UseAssistantChatOptions.onConnectRequirement}. */
    onConnect?: (requirement: ConnectionRequirement) => void | Promise<void>;
    /** Render the workflow YAML as a node graph (the `./workflows` WorkflowGraph).
     *  When absent, the YAML is shown as text. */
    renderGraph?: (yaml: string) => ReactNode;
    /** Render the brand icon for an integration requirement's provider. The host
     *  owns the provider→icon mapping (its integrations catalog); when absent, or
     *  when it returns a nullish node for a provider it doesn't recognize, the row
     *  falls back to the built-in {@link ProviderLogo} mark. */
    renderProviderIcon?: (provider: string) => ReactNode;
}
declare function ProposalCard({ proposal, confirming, onConfirm, onCancel, navigate, onConnect, renderGraph, renderProviderIcon, }: ProposalCardProps): react.JSX.Element;

interface AssistantLauncher {
    /** Whether the assistant drawer is open. */
    open: boolean;
    /** A one-shot starter prompt to prefill the composer with, or null. */
    seed: string | null;
    /** Open the drawer; optionally prefill the composer with `seed`. */
    openAssistant: (seed?: string) => void;
    closeAssistant: () => void;
    /** Clear the pending seed once the composer has applied it (consume-once). */
    clearSeed: () => void;
}
declare function AssistantLauncherProvider({ children, }: {
    children: ReactNode;
}): react.JSX.Element;
declare function useAssistantLauncher(): AssistantLauncher;

export { type AssistantChat, type AssistantClient, type AssistantClientConfig, AssistantClientInputError, AssistantClientProvider, type AssistantDeliveryMode, AssistantDock, type AssistantDockProps, type AssistantLauncher, AssistantLauncherProvider, type AssistantModelOption, type AssistantModels, type AssistantModelsResult, AssistantPanel, type AssistantPanelProps, type AssistantSendOptions, type AssistantStreamEvent, type AssistantThreadSummary, type AssistantThreads, AssistantTranscript, type AssistantTranscriptProps, type AssistantTranscriptView, type ChatMessage, type ChatRequest, type ChatRole, type ConfirmResult, type ConfirmedResult, type ConnectRequirementResult, type ConnectionRequirement, type ConnectionRequirementKind, type DeltaEventData, type DoneEventData, type ErrorEventData, type PendingProposal, ProposalCard, type ProposalCardProps, type ReasoningEventData, type ThreadEventData, type ThreadHistoryResult, type ToolActivityStatus, type ToolCallEventData, type ToolOutcome, type ToolProposalEventData, type ToolResultEventData, type UsageEventData, type UsageInfo, type UseAssistantChatOptions, adaptTranscript, assistantIsThinking, createAssistantClient, useAssistantChat, useAssistantClient, useAssistantLauncher, useAssistantModels, useAssistantThreads };
