import * as react from 'react'; import { O as OkraClient } from '../client-CD1UgTAe.js'; import { a as OkraSession, C as CompletionOptions, a2 as DocumentAssetStatus, b7 as UploadInput, a4 as DocumentConfigUpdate, D as DocumentStatus, c as Page, j as StructuredSchema, i as GenerateResult } from '../types-R6f5p55r.js'; export { b as CompletionEvent } from '../types-R6f5p55r.js'; import { useAgent } from 'agents/react'; import { Effect } from 'effect'; import { S as StructuredSchemaError } from '../structured-schema-BhJIWm_8.js'; import 'effect/Cause'; import 'effect/Types'; import '@okrapdf/component'; import 'zod'; interface Message { id: string; role: 'user' | 'assistant'; content: string; createdAt?: Date; sources?: Array<{ page: number; snippet: string; }>; } interface ChatMessageAdapter { name?: string; toMessage: (message: Message) => TMessage; } interface LibreChatMessage { id: string; messageId: string; role: Message['role']; sender: 'User' | 'Okra'; isCreatedByUser: boolean; text: string; content: Array<{ type: 'text'; text: string; }>; createdAt?: Date; sources?: Message['sources']; } type OkraDocumentStatus = 'resolving' | 'ready' | 'error'; interface UseOkraDocumentReturn { documentId: string | null; session: OkraSession | null; status: OkraDocumentStatus; error: Error | null; isReady: boolean; refetch: () => void; } interface UseOkraQueryReturn$1 { data: T | null; assetStatus: DocumentAssetStatus; error: Error | null; isLoading: boolean; refetch: () => void; } type ChatStatus = 'idle' | 'submitted' | 'streaming' | 'error'; interface UseChatReturn { messages: TMessage[]; okraMessages: Message[]; input: string; handleInputChange: (e: React.ChangeEvent) => void; handleSubmit: (e?: { preventDefault?: () => void; }) => void; isLoading: boolean; status: ChatStatus; stop: () => void; append: (message: Pick) => void; setMessages: React.Dispatch>; } interface ChatConfig { session: OkraSession | null; /** Use streaming (default: true) */ stream?: boolean; /** Forwarded to `session.stream()` / `session.prompt()` without overriding the hook's abort signal. */ completionOptions?: Omit; adapter?: ChatMessageAdapter; onFinish?: (message: Message) => void; onError?: (error: Error) => void; } interface OkraContextValue extends UseOkraDocumentReturn { client: OkraClient; apiKey?: string; registerAsset: (assetId: string) => void; } type OkraClientAuthProps = { client: OkraClient; apiKey?: never; baseUrl?: never; } | { client?: never; apiKey: string; baseUrl?: string; }; type OkraProviderSourceProps = { file: UploadInput; url?: never; documentId?: never; config?: DocumentConfigUpdate; } | { url: string; file?: never; documentId?: never; config?: DocumentConfigUpdate; } | { documentId: string; file?: never; url?: never; config?: never; }; type OkraProviderProps = OkraClientAuthProps & OkraProviderSourceProps & { children: React.ReactNode; }; declare function OkraProvider({ client: providedClient, apiKey, baseUrl, file, url, documentId, config, children, }: OkraProviderProps): react.FunctionComponentElement>; declare function useOkra(): OkraContextValue; declare function useOkraDocument(): UseOkraDocumentReturn; interface UseDocumentStatusOptions { /** Poll interval in ms while processing (default: 2000). 0 to disable. */ pollInterval?: number; /** Skip fetching entirely */ enabled?: boolean; } interface UseDocumentStatusReturn { data: DocumentStatus | null; isLoading: boolean; error: Error | null; isComplete: boolean; isProcessing: boolean; refetch: () => void; } /** * Poll document processing status from the CF Worker. * Accepts either a session object or a raw document ID. * * ```tsx * const { data, isComplete, isProcessing } = useDocumentStatus(session); * // or * const { data } = useDocumentStatus('doc-abc123'); * ``` */ declare function useDocumentStatus(sessionOrId: OkraSession | string | null, options?: UseDocumentStatusOptions): UseDocumentStatusReturn; interface UsePagesOptions { /** Skip fetching (default: true) */ enabled?: boolean; } interface UsePagesReturn { data: Page[]; isLoading: boolean; error: Error | null; refetch: () => void; } /** * Fetch all pages for a document. * * ```tsx * const { data: pages, isLoading } = usePages(session); * // or with a document ID * const { data: pages } = usePages('doc-abc123'); * ``` */ declare function usePages(sessionOrId: OkraSession | string | null, options?: UsePagesOptions): UsePagesReturn; interface UsePageContentOptions { /** Poll interval while content not yet ready (default: 3000). 0 to disable. */ pollInterval?: number; } interface UsePageContentReturn { data: Page | null; content: string; isLoading: boolean; error: Error | null; refetch: () => void; } /** * Fetch a single page's content (markdown + blocks + entities). * Polls until content arrives if the page is still processing. * * ```tsx * const { content, data, isLoading } = usePageContent(session, 1); * ``` */ declare function usePageContent(sessionOrId: OkraSession | string | null, pageNumber: number, options?: UsePageContentOptions): UsePageContentReturn; declare function useChat(config: ChatConfig): UseChatReturn; declare function toLibreChatMessage(message: Message): LibreChatMessage; declare function libreChatAdapter(): ChatMessageAdapter; declare function adaptChatMessages(messages: readonly Message[], adapter: ChatMessageAdapter): TMessage[]; declare function toLibreChatMessages(messages: readonly Message[]): LibreChatMessage[]; declare function useAdaptedChatMessages(messages: readonly Message[], adapter: ChatMessageAdapter): TMessage[]; declare function useLibreChatMessages(messages: readonly Message[]): LibreChatMessage[]; interface UseDocumentQueryOptions { /** Document ID (e.g. "doc-xxx" or "ocr-xxx") */ documentId: string | null; /** The query/prompt to run against the document */ query: string; /** JSON schema or Zod schema for structured output */ schema?: StructuredSchema; /** Skip the query (e.g. while waiting for doc to be ready) */ skip?: boolean; /** Model override */ model?: string; /** Timeout in ms */ timeoutMs?: number; /** How long cached results stay valid in ms (default: 300000 / 5 min) */ cacheTime?: number; } interface UseDocumentQueryReturn { data: T | null; result: GenerateResult | null; isLoading: boolean; error: Error | null; refetch: () => void; } /** * Run a one-shot query against a document, optionally with structured output. * Results are cached in-memory for `cacheTime` ms (default 5 min). * * ```tsx * const { data } = useDocumentQuery({ * documentId: "doc-xxx", * query: "Generate 4 chat suggestions", * schema: z.object({ suggestions: z.array(z.object({ id: z.string(), text: z.string() })) }), * skip: !isReady, * }) * ``` */ declare function useDocumentQuery(options: UseDocumentQueryOptions): UseDocumentQueryReturn; interface UseOkraQueryOptions { asset: string; key?: string; enabled?: boolean; pollInterval?: number; staleTime?: number; } interface UseOkraQueryReturn { data: T | null; assetStatus: DocumentAssetStatus; error: Error | null; isLoading: boolean; refetch: () => void; } declare function useOkraQuery(schema: StructuredSchema, options: UseOkraQueryOptions): UseOkraQueryReturn; /** * Canonical types for the okraPDF `DocumentAgent` running on * `api.okrapdf.com`. Exported so consumers of `@okrapdf/sdk/react` don't have * to redeclare them for every app that calls `createOkraContext()`. * * Mirrors `DocumentState` in `apps/api/server/src/document-agent.ts` * and `documentPhaseSchema` in `@okrapdf/schemas`. The SDK intentionally * inlines the phase union to avoid a workspace-wide dep on `@okrapdf/schemas` * — if the server adds a phase, add it here too. */ type DocumentPhase = 'idle' | 'uploading' | 'parsing' | 'hydrating' | 'verifying' | 'awaiting_review' | 'complete' | 'error'; type DocumentFacetSummary = { phase: 'idle' | 'running' | 'complete' | 'error'; nodes: number; pages: number; duration_ms: number | null; cost_usd: number; error: string | null; payload?: unknown; }; type ParsingIntentKind = 'general_read' | 'question_answering' | 'structured_extract' | 'table_extract' | 'invoice_extract' | 'ocr_repair' | 'compliance_review' | 'engine_compare'; type ParsingPlanStep = { id: string; title: string; detail: string; phase: 'queued' | DocumentPhase; resumable: boolean; status: 'planned'; }; type ParsingLifecyclePlan = { object: 'document_parse_plan'; version: 'okra.parse_plan.v1'; createdAt: string; intent: { raw: string | null; kind: ParsingIntentKind; summary: string; }; workflow: { engine: 'DOC_LIFECYCLE_WORKFLOW'; runner: 'AgentWorkflow'; resumable: true; trigger: 'default_parse' | 'parse_only' | 'render_only' | 'parse_and_render' | 'accept_only'; }; strategy: { processor: string | null; pageImages: 'none' | 'cover' | 'eager'; cache: 'disabled' | 'prefer'; runParse: boolean; runRender: boolean; skipParse: boolean; }; steps: ParsingPlanStep[]; toolPolicy: { free: string[]; requiresGrant: string[]; }; }; type DocumentAgentUiState = { activeTab: 'chat' | 'extract' | 'summary'; currentPage: number; selectedText: string | null; selectedPage: number | null; retryFacet: string | null; }; type DocumentAgentState = { documentId: string | null; phase: DocumentPhase; pagesTotal: number; pagesCompleted: number; pageImagesTotal: number; pageImagesCompleted: number; totalNodes: number; verifiedNodes: number; failedNodes: number; pendingNodes: number; verificationPercent: number; activeVendor: string | null; /** * PDF sha256 (full 64-hex) — content-addressed identifier for the source PDF. * Required for CF Images URL construction via `doc(id, { pdfSha, renderer })`. * Null until the upload workflow computes it (set once, never changes per doc). */ pdfSha256?: string | null; /** * Render backend that produced the page images most recently written for * this document. Clients must pass this through to `doc({ renderer })` so * the emitted `imagedelivery.net` URL's `-{renderer}` tag matches the * actual uploaded image ID (`okra-{env}-{sha12}-p{N}-r{V}-{renderer}`). * * `mupdf150` — MuPDF container @ 150 DPI (server default when bound). * `pdfjs2x` — pdf.js via Browser Rendering @ scale=2 (fallback). * `null` — no pages rendered yet. */ activeRenderer?: 'mupdf150' | 'pdfjs2x' | null; /** Intent-aware parsing plan published by the upload lifecycle. */ parsePlan?: ParsingLifecyclePlan | null; facets?: Record; /** Frontend-owned UI state — written via `setState()`, DO reacts in `onStateChanged()`. */ ui?: DocumentAgentUiState; }; type TriggerRenderParams = { strategy?: 'eager' | 'cover' | 'none'; }; type TriggerParseParams = { vendor?: string; }; type TriggerExtractParams = { schema: unknown; prompt?: string; model?: string; pages?: number[]; monitor?: false | { intervalMs?: number; firstTickMs?: number; }; }; type TriggerExtractResult = { rows: unknown[]; data: unknown; }; type DocumentAgentMethods = { triggerRender(params?: TriggerRenderParams): Promise; triggerParse(params?: TriggerParseParams): Promise; triggerExtract(params: TriggerExtractParams): Promise; }; type QueryObject = Record; type QueryResolver = (name: string) => QueryObject | Promise; type MethodArgs = Methods[K] extends (...args: infer Args) => any ? Args : never; type MethodResult = Methods[K] extends (...args: any[]) => infer Result ? Awaited : never; interface OkraAuthEndpointRequest { docId: string; } interface OkraAuthEndpointResponse { token: string; [key: string]: unknown; } interface CreateOkraContextOptions { host?: string; agent: string; authEndpoint?: string; query?: QueryResolver; cacheTtl?: number; } type OkraDocumentAgent = ReturnType, State>>; declare function createOkraContext(cfg: CreateOkraContextOptions): { useDocument: (name: string | null | undefined) => OkraDocumentAgent; useDocumentSlice: (name: string | null | undefined, selector: (state: State) => T) => T | undefined; useDocumentAction: (name: string | null | undefined, method: K) => (...args: MethodArgs) => Promise>; useDocumentEvents: (name: string | null | undefined, handler: (event: unknown) => void) => void; }; declare function normalizeOkraRpcArgs(args: readonly unknown[]): unknown[]; declare function normalizeOkraRpcArgsEffect(args: readonly unknown[]): Effect.Effect; export { type ChatConfig, type ChatMessageAdapter, type ChatStatus, type CreateOkraContextOptions, type DocumentAgentMethods, type DocumentAgentState, type DocumentAgentUiState, type DocumentFacetSummary, type DocumentPhase, DocumentStatus, GenerateResult, type LibreChatMessage, type Message, type OkraAuthEndpointRequest, type OkraAuthEndpointResponse, type OkraContextValue, type OkraDocumentStatus, OkraProvider, type OkraProviderProps, OkraSession, Page, type TriggerExtractParams, type TriggerExtractResult, type TriggerParseParams, type TriggerRenderParams, type UseChatReturn, type UseDocumentQueryOptions, type UseDocumentQueryReturn, type UseDocumentStatusOptions, type UseDocumentStatusReturn, type UseOkraDocumentReturn, type UseOkraQueryOptions, type UseOkraQueryReturn$1 as UseOkraQueryReturn, type UsePageContentOptions, type UsePageContentReturn, type UsePagesOptions, type UsePagesReturn, adaptChatMessages, createOkraContext, libreChatAdapter, normalizeOkraRpcArgs, normalizeOkraRpcArgsEffect, toLibreChatMessage, toLibreChatMessages, useAdaptedChatMessages, useChat, useDocumentQuery, useDocumentStatus, useLibreChatMessages, useOkra, useOkraDocument, useOkraQuery, usePageContent, usePages };