import { ZodType } from 'zod'; interface OkraEvent { v: number; type: string; timestamp: number; data: Record; } interface DocumentEvent extends OkraEvent { v: 1; type: `document.${string}`; documentId: string; } type DocumentEventType = 'document.phase_changed' | 'document.vendor_started' | 'document.vendor_completed' | 'document.vendor_failed' | 'document.parse_complete' | 'document.hydrated' | 'document.verification_progress' | 'document.ready' | 'document.error' | 'document.thumbnail_ready' | 'document.node_verified' | 'document.page_resolved' | 'document.extraction_started'; type DocumentEventHandler = (event: DocumentEvent) => void; interface DocumentEventStreamOptions { /** Filter to specific event types. Omit or null = all public events. */ events?: DocumentEventType[]; signal?: AbortSignal; /** Maximum unread iterator events, default 1024. Overflow closes and rejects the iterator. */ bufferSize?: number; } /** * Lightweight WebSocket event stream for document lifecycle events. * * Usage: * const stream = new DocumentEventStream(wsUrl); * stream.on('document.ready', (evt) => console.log('Done!', evt.data)); * stream.connect(); * // or: for await (const evt of stream) { ... } */ declare class DocumentEventStream { #private; constructor(url: string, options?: DocumentEventStreamOptions); /** Open once. Repeated calls do not replace the owned socket. */ connect(): void; /** Subscribe to live callbacks without retaining an iterator backlog. */ on(type: DocumentEventType | '*', handler: DocumentEventHandler): () => void; /** Close the socket, detach listeners and discard unread iterator events. */ close(): void; get connected(): boolean; /** * Subscribe at iterator creation; create it before connect() to receive initial frames. * Callbacks alone retain no backlog. One shared iterator buffers at most bufferSize * events and fails explicitly on overflow. Remote close drains accepted events; * close(), abort and iterator return discard them and release pending pulls. */ [Symbol.asyncIterator](): AsyncGenerator; } type JsonSchema = Record; type StructuredOutputErrorCode = 'SCHEMA_VALIDATION_FAILED' | 'EXTRACTION_FAILED' | 'TIMEOUT' | 'DOCUMENT_NOT_FOUND'; type RuntimeErrorCode = StructuredOutputErrorCode | 'INVALID_REQUEST' | 'UNAUTHORIZED' | 'HTTP_ERROR' | 'NOT_FOUND' | 'NOT_IMPLEMENTED' | 'INVALID_RESPONSE'; interface OkraClientOptions { /** Hosted default points at api.okrapdf.com. */ baseUrl?: string; /** Bearer API key (okra_...). */ apiKey?: string; /** Alternative auth header (e.g. worker-to-worker shared secret). */ sharedSecret?: string; /** Inject custom fetch implementation for tests or runtime overrides. */ fetch?: typeof globalThis.fetch; } interface UploadRedactPiiOptions { preset?: string; patterns?: string[]; includeNames?: boolean; includeAddresses?: boolean; customPatterns?: Array>; [key: string]: unknown; } interface UploadRedactOptions { pii?: UploadRedactPiiOptions; publicFieldAllowlist?: string[]; [key: string]: unknown; } interface UploadOptions { /** Cancel the upload and its progress subscription. Accepted remote work may continue. */ signal?: AbortSignal; /** Provide your own document ID. Default: auto-generated `doc-*`. */ documentId?: string; /** Optional filename hint for binary uploads. */ fileName?: string; /** Initial document spec seeded at upload/create time. */ config?: DocumentSpec; /** Free-text parsing goal used to build the upload-time parse plan. */ intent?: string; /** Processing capability hints forwarded to the worker. */ capabilities?: ProcessingCapabilities; /** Document visibility. 'private' (default) requires auth; 'public' auto-publishes on completion. */ visibility?: 'public' | 'private'; /** BYOK vendor keys passed through to extraction (e.g. { llamaparse: 'llx-...' }). Stateless — never stored. */ vendorKeys?: Record; /** OpenRedact policy forwarded to upload and enforced at read/query/completion surfaces. */ redact?: UploadRedactOptions; /** * Vendor-specific options passed through to the parsing vendor API. * Follows the AI SDK providerOptions pattern — keys are vendor API fields. * @example { model: 'gemini-3.1-pro', parse_mode: 'parse_page_with_agent' } */ vendorOptions?: Record; /** Live progress through processing; closes on terminal progress, upload failure, or signal abort. */ onProgress?: (event: DocumentEvent) => void; } type WorkflowPhase = 'ocr' | 'enhance' | 'metadata' | 'verify'; type WorkflowTier = 'fast' | 'standard' | 'premium'; type InvoiceExtractionQuality = 'fast' | 'balanced' | 'high'; type InvoiceExtractionInput = string | { fileId?: string; file_id?: string; }; interface InvoiceExtractionRunOptions { inputs: InvoiceExtractionInput[]; tableId?: string; quality?: InvoiceExtractionQuality; signal?: AbortSignal; } interface InvoiceExtractionRunListOptions { limit?: number; cursor?: string; signal?: AbortSignal; } interface InvoiceExtractionRun { id: string; runId: string; status: string; workflowName: 'invoice-extraction'; workflowLabel: string; workflowVersion: number; quality: InvoiceExtractionQuality; tableId: string; agentId?: string | null; inputs: Array<{ fileId: string; }>; /** Absent on the deprecated POST response (#1389); present on GET responses. */ eventsUrl?: string; /** Absent on the deprecated POST response (#1389); present on GET responses. */ streamUrl?: string; /** Absent on the deprecated POST response (#1389); present on GET responses. */ rowsUrl?: string; /** Absent on the deprecated POST response (#1389); present on GET responses. */ exports?: { csvUrl: string; jsonUrl: string; xmlUrl?: string; xlsxUrl?: string; [key: string]: unknown; }; createdAt: string; } interface InvoiceExtractionRunList { data: InvoiceExtractionRun[]; hasMore: boolean; nextCursor: string | null; } interface InvoiceExtractionException { id: string; runId: string; tableId: string; rowId?: string | null; fileId?: string | null; field?: string | null; code: 'missing_required_field' | 'document_parse_failed' | 'empty_result' | 'run_failed' | 'validation_warning'; severity: 'warning' | 'error'; status: 'open' | 'resolved'; message: string; value?: unknown; sourcePage?: number | null; sourceBbox?: string | null; createdAt: string; } interface InvoiceExtractionExceptionList { data: InvoiceExtractionException[]; hasMore?: boolean; nextCursor?: string | null; } interface InvoiceExtractionResolveExceptionOptions { rowId: string; field?: string; value?: unknown; action?: 'approve' | 'correct'; signal?: AbortSignal; } interface InvoiceExtractionExceptionResolution { id: string; runId: string; tableId: string; rowId: string; status: 'resolved'; } interface WorkflowPhaseConfig { vendor?: string; tier?: WorkflowTier; enabled?: boolean; } /** * Processing capability shape used by upload/config/key-workflow surfaces. * Includes well-known flags and allows forward-compatible custom keys. */ interface ProcessingCapabilities { vlm_qwen?: boolean; structural_check?: boolean; sandbox_verify?: boolean; search?: boolean; phases?: Partial>; middleware?: Array<{ name: string; [key: string]: unknown; }>; [key: string]: unknown; } type DocumentAction = 'admin' | 'read_meta' | 'read_content' | 'query' | 'download_pdf' | 'update_config' | 'trigger_extract' | 'create_link' | 'list_links' | 'publish'; type PrincipalRef = { type: 'owner'; } | { type: 'public'; } | { type: 'user'; id: string; } | { type: 'org'; id: string; } | { type: 'project'; id: string; }; interface DocumentGrantConstraints { redaction_role?: 'admin' | 'viewer' | 'public'; expires_at?: string; not_before?: string; output_allowlist?: string[]; } interface DocumentGrant { grant_id?: string; principal: PrincipalRef; actions: DocumentAction[]; constraints?: DocumentGrantConstraints; } interface DocumentAccessRoleProfile { pii?: Record; [key: string]: unknown; } interface DocumentAccess { default_effect: 'deny'; grants: DocumentGrant[]; redaction_roles?: { viewer?: DocumentAccessRoleProfile; public?: DocumentAccessRoleProfile; }; } type PageImageStrategy = 'none' | 'cover' | 'eager' | 'lazy'; interface DocumentExtract { page_image_strategy: PageImageStrategy; provider: string | null; provider_options?: Record; } interface DocumentFeatureFlags { vlm_qwen: boolean; structural_check: boolean; sandbox_verify: boolean; search: boolean; } interface DocumentRuntime { self_heal: boolean; workflow_watchdog_timeout_ms: number; max_auto_reparse: number; } interface DocumentPluginSpec { name: string; provider?: string; model?: string; providerOptions?: Record; } interface DocumentAgentModelEndpoint { provider?: string; model?: string; } interface DocumentAgentModelConfig { chat?: DocumentAgentModelEndpoint; query?: DocumentAgentModelEndpoint; } interface DocumentAgentToolPolicies { get_job_metadata?: string; get_live_status?: string; query_sql?: string; query_document?: string; view_page_region?: string; } interface DocumentAgentToolsConfig { builtinAllowlist?: string[]; builtinToolPolicies?: DocumentAgentToolPolicies; completionToolMode?: string; userToolPolicy?: string; } interface DocumentAgentContextConfig { mode?: string; } interface DocumentAgentSecurityConfig { redactionRole?: 'admin' | 'viewer' | 'public'; sqlReadOnly?: boolean; allowReparseTool?: boolean; } interface DocumentAgentRuntimeConfig { maxToolRounds?: number; cacheDefault?: boolean; stream?: boolean; } interface DocumentAgentConfig { agent_id: string; instructions?: string; model?: DocumentAgentModelConfig; tools?: DocumentAgentToolsConfig; context?: DocumentAgentContextConfig; security?: DocumentAgentSecurityConfig; runtime?: DocumentAgentRuntimeConfig; eval?: Record; } interface DocumentSpec { version: 1; access: DocumentAccess; extract: DocumentExtract; features: DocumentFeatureFlags; runtime: DocumentRuntime; agent: DocumentAgentConfig; plugins: DocumentPluginSpec[]; } interface DocumentSpecRecord { document_id: string | null; spec_version: number; spec: DocumentSpec; } interface DocumentSpecDiff { accessChanged: boolean; extractChanged: boolean; agentChanged: boolean; pluginChanged: boolean; changed: boolean; } type DocumentConfigUpdate = DocumentSpec; interface DocumentConfigResult extends DocumentSpecRecord { diff?: DocumentSpecDiff; phase?: string; maxPass?: number; workflowId?: string; reparsed?: boolean; } interface ReparseOptions { strategy?: 'auto' | 'textlayer'; signal?: AbortSignal; } interface ReparseResult extends DocumentStatus { message?: string; workflowId?: string; strategy?: string; } type VerifyVerdict = 'supported' | 'contradicted' | 'not_visible'; interface VerifyBbox { x: number; y: number; w: number; h: number; } interface VerifyParams { claim: string; page: number; bbox?: VerifyBbox; signal?: AbortSignal; } interface VerifyResult { verdict: VerifyVerdict; page: number; bbox: VerifyBbox | null; evidence_snippet: string; page_image_url: string; confidence: number; model: string; } interface ApplyWorkflowOptions { capabilities: ProcessingCapabilities; reparse?: boolean; strategy?: ReparseOptions['strategy']; signal?: AbortSignal; } interface ApplyWorkflowResult { config: DocumentConfigResult; reparse?: ReparseResult; } interface ApiKeyWorkflowConfigResponse { key_id: string; user_id: string; default_capabilities: ProcessingCapabilities | null; created_at: string | null; updated_at: string | null; } type UploadInput = string | ArrayBuffer | Uint8Array | Blob; type ParsePageSelection = string | number[] | { from?: number; to?: number; }; interface ParseParserConfig { /** Parser id. See `GET /v1/vendors`. */ id: string; /** Parser preset/model variant, forwarded to provider options when supported. */ variant?: string; /** Parser-local options. */ options?: Record; /** AI-SDK-style provider options. */ vendorOptions?: Record; /** Snake-case alias accepted for raw API parity. */ vendor_options?: Record; } interface ParseOptions { /** PDF bytes, local path (Node), Blob, or ArrayBuffer/Uint8Array. */ file?: UploadInput; /** Reuse a previously-uploaded file by id (skip re-encoding). */ fileId?: string; /** Parser id or parser config. See `GET /v1/vendors`. Defaults to `textlayer` if omitted. */ parser?: string | ParseParserConfig; /** Parser preset/model variant, forwarded to provider options when supported. */ variant?: string; /** Page selection, e.g. `1-3`, `[1, 3]`, or `{ from: 1, to: 3 }`. */ pages?: ParsePageSelection; /** Requested output projections, e.g. `{ html: true, markdown: true }`. */ outputs?: string[] | Record; /** Publish/export options for derived assets. */ publish?: boolean | Record; /** Vendor-specific options forwarded as `VendorInput.parameters`. */ options?: Record; /** AI-SDK-style providerOptions forwarded as `VendorInput.vendorOptions`. */ vendorOptions?: Record; /** Request metadata copied onto the resulting job. */ metadata?: Record; /** Optional JSON schema for structured extraction (Gemini-style `responseSchema`). */ schema?: JsonSchema; /** Optional file name hint, surfaces in vendor logs. */ fileName?: string; /** Cancel input preparation and the client request; accepted server jobs continue. */ signal?: AbortSignal; } type JobStatus = 'queued' | 'running' | 'rendering' | 'publishing' | 'succeeded' | 'failed' | 'cancelled' | 'idle' | 'awaiting_user_input' | 'completed' | 'completed_with_errors'; interface JobError { message: string; code?: string; } interface JobProgress { phase: string; current: number; total: number; pages_done: number; pages_completed: number; pages_failed: number; pages_running: number; pages_pending: number; pages_total: number; chunks_completed: number; chunks_total: number; percent: number | null; [key: string]: unknown; } type JobErrorCode = 'quota_exceeded' | 'invalid_file' | 'parse_timeout' | 'provider_failure' | 'auth_failure' | 'job_failed' | string; interface JobListOptions { type?: string; status?: JobStatus; documentId?: string; limit?: number; signal?: AbortSignal; } interface CreateJobOptions { type: 'document.parse' | 'document.reparse' | string; documentId?: string; document_id?: string; document?: string; strategy?: string; engine?: string; processor?: string; parser?: Record | string; parser_profile?: Record | string; signal?: AbortSignal; [key: string]: unknown; } interface OkraJob { id: string; object: 'job'; type: string; status: JobStatus; internal_status?: string; terminal?: boolean; next_poll_after_ms?: number | null; retryable?: boolean; created?: number; completed?: number | null; created_at?: number; updated_at?: number; completed_at?: number | null; livemode?: boolean; url?: string; status_url?: string; job_id?: string; job_type?: string; job_label?: string | null; document_id?: string | null; file_name?: string | null; run_id?: string | null; workflow_name?: string | null; workflow_id?: string | null; engine_id?: string | null; provider?: string | null; model?: string | null; prompt_id?: string | null; prompt_version?: string | number | null; confidence_kind?: string | null; cost_usd?: number | null; progress_current?: number; progress_total?: number; progress?: JobProgress | null; pages_completed?: number; pages_failed?: number; pages_running?: number; pages_pending?: number; pages_total?: number; chunks_completed?: number; chunks_total?: number; duration_ms?: number | null; error_code?: JobErrorCode | null; user_message?: string | null; error?: string | null; latest_error?: string | null; usage?: Record | null; request?: unknown; result: Result | null; metadata?: Record; last_error: JobError | null; } interface JobListResponse { object: 'list'; data: OkraJob[]; has_more: boolean; next_cursor?: string | null; } interface ParseUsage { pages: number; duration_ms?: number | null; } interface ParseExtraction { data: unknown; schema_valid: boolean; } interface ParseArtifact { object: 'artifact'; type: string; url: string; format?: ParseOutputFormat; hash?: string; [key: string]: unknown; } type ParseOutputFormat = 'nodes' | 'markdown' | 'text' | 'html' | 'json'; type ParseNodeRole = 'text' | 'heading' | 'section_heading' | 'table' | 'row' | 'cell' | 'figure' | 'header' | 'footer' | 'key_value' | 'list' | 'unknown'; interface ParseNode { id: string; page: number; role: ParseNodeRole; text: string; bbox?: { x: number; y: number; w: number; h: number; }; confidence?: number; label?: string; type?: string; parent_id?: string; vendor_payload_ref?: { sha256: string; uri?: string; }; children?: ParseNode[]; } interface ParseNodesFormat { object: 'parse_format'; format: 'nodes'; pages: Array<{ page: number; width?: number; height?: number; nodes: ParseNode[]; }>; } interface ParseMarkdownFormat { object: 'parse_format'; format: 'markdown'; content: string; pages: Array<{ page: number; content: string; }>; } interface ParseTextFormat { object: 'parse_format'; format: 'text'; content: string; pages: Array<{ page: number; content: string; }>; } interface ParseJsonFormat { object: 'parse_format'; format: 'json'; page_count: number; pages: Array>; } interface ParseResultFormats { nodes?: ParseNodesFormat; markdown?: ParseMarkdownFormat; text?: ParseTextFormat; html?: ParseArtifact; json?: ParseJsonFormat; } interface CanonicalParseBlock { type: string; label?: string; value?: string; bbox?: { x: number; y: number; w: number; h: number; }; confidence?: number; children?: CanonicalParseBlock[]; } interface CanonicalParsePage { pageNumber: number; width?: number; height?: number; blocks: CanonicalParseBlock[]; } interface CanonicalParseOutput { pages: CanonicalParsePage[]; metadata: { vendor: string; model?: string; durationMs: number; confidence: number | null; pageCount: number; }; } interface ParseResult { object: 'parse_result'; job: string; file?: { name?: string | null; source?: 'inline' | 'file_id' | null; }; usage: ParseUsage; formats?: ParseResultFormats; extracted?: ParseExtraction | null; extraction_error?: string | null; artifacts?: Record | null; artifact_error?: string | null; } type ParseJob = OkraJob; type FileUploadTransport = 'auto' | 'multipart' | 'direct'; interface FileUploadOptions { /** Optional filename hint for binary uploads. Defaults to `document.pdf`. */ fileName?: string; /** Optional document spec to seed before first parse. */ config?: DocumentSpec; /** Transport hint. `auto` uses multipart for small PDFs and direct-to-R2 for larger ones. */ transport?: FileUploadTransport; signal?: AbortSignal; } interface FileListOptions { limit?: number; cursor?: string; signal?: AbortSignal; } interface OkraFileUrls { bytes: string; document: string; } interface OkraFile { id: string; file_id: string; object: 'file'; name: string; mime: string; size: number; bytes: number; sha256: string; upload_mode: 'multipart' | 'presigned'; created_at: string; updated_at: string; workflow_bound: false; urls: OkraFileUrls; } interface OkraFileListResponse { object: 'list'; data: OkraFile[]; has_more: boolean; next_cursor: string | null; } interface DeleteFileResult { deleted: boolean; fileId: string; } interface OkraFiles { /** Upload a passive PDF asset. Does not start parsing or bind to a workflow. */ upload(input: UploadInput, options?: FileUploadOptions): Promise; /** Fetch a passive PDF asset by id. */ get(fileId: string, signal?: AbortSignal): Promise; /** List passive PDF assets for the authenticated user. */ list(options?: FileListOptions): Promise; /** Delete a passive PDF asset if it has not been materialized as a document surface. */ delete(fileId: string, signal?: AbortSignal): Promise; /** Deterministic PDF bytes URL for the passive file asset. */ downloadUrl(fileId: string): string; } type ApiResourceAuthMode = 'required' | 'optional' | 'public'; interface ApiResourceOperation { method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'; path: string; action: string; description: string; auth: ApiResourceAuthMode; returns?: string; } interface ApiResource { object: 'api_resource'; name: string; path: string; description: string; aliases: string[]; related_actions: string[]; operations: ApiResourceOperation[]; } interface ApiAction { object: 'api_action'; name: string; path: string; description: string; primary_resource: string; returns: string; operations: ApiResourceOperation[]; } interface ApiResourceCatalog { object: 'api_resource_catalog'; version: string; data: ApiResource[]; actions: ApiAction[]; usage_hint: string; } interface DocumentStatus { phase: string; pagesTotal?: number; pagesCompleted?: number; totalNodes?: number; verifiedNodes?: number; failedNodes?: number; pendingNodes?: number; plugins?: DocumentPluginState[]; [key: string]: unknown; } interface WaitOptions { /** Per-stage deadline, including HTTP reads and polling sleeps. Default: 5 minutes. */ timeoutMs?: number; pollIntervalMs?: number; signal?: AbortSignal; /** Try WebSocket progress first; a timeout starts a fresh polling window. Default: false. */ realtime?: boolean; /** Progress callback (fires for each lifecycle event when realtime: true). */ onProgress?: (event: DocumentEvent) => void; } interface CitationBbox { x: number; y: number; w: number; h: number; } /** Standalone SDK mirror of the server's Anthropic page_location citation contract. */ interface PageLocationCitation { type: 'page_location'; cited_text: string; start_page_number: number; end_page_number: number; document_index?: number; document_title?: string; citation_url: string; match: 'exact' | 'fuzzy'; field?: string; bbox?: CitationBbox; /** 'node' = real element box from the parse; 'page' = page-level fallback (#507). */ bbox_source?: 'node' | 'page'; block_id?: string; } /** One grounded citation in the opt-in Anthropic-shaped form (#505). */ interface ExtractCitation extends PageLocationCitation { field: string; block_id: string; } interface StructuredOutputMeta { confidence: number; model: string; durationMs: number; /** * Default = regex page citations `{ page, text }`. When the request opts in * with `cite: true`, this is instead the Anthropic-shaped grounded citation * array (#505): one `ExtractCitation` per grounded field with `cited_text`, * `start/end_page_number`, plus okra `bbox` + `field` + `match`. */ citations?: Array<{ page: number; text: string; } | ExtractCitation>; } type StructuredSchema = JsonSchema | ZodType; interface PageBlock { text: string; bbox?: { x: number; y: number; width: number; height: number; }; confidence?: number; } interface PageEntity { id: string; type: string; label: string | null; } interface Page { page: number; content: string; blocks: PageBlock[]; entities: PageEntity[]; } interface Entity { id: string; type: string; label: string | null; value: string | null; page_number: number | null; status: string; bbox_x?: number | null; bbox_y?: number | null; bbox_w?: number | null; bbox_h?: number | null; metadata?: string | null; } interface EntitiesResponse { nodes: Entity[]; total?: number; limit?: number; offset?: number; } interface QueryResult { rows: Record[]; columns: string[]; } interface LogEntry { seq: number; event: string; actor_type: string; actor_id: string; target_id: string | null; detail: string; created_at: number; prev_hash: string; chain_hash: string; } interface LogsOptions { limit?: number; signal?: AbortSignal; } /** Events yielded by `session.stream()` / `client.stream()`. */ type CompletionEvent = { type: 'text_delta'; text: string; } | { type: 'done'; answer: string; costUsd?: number; sources?: Array<{ page: number; snippet: string; }>; } | { type: 'error'; message: string; }; interface CompletionOptions { stream?: boolean; model?: string; /** Maximum server-side tool round-trips before forcing a final answer. */ maxSteps?: number; signal?: AbortSignal; } interface GenerateOptions { schema?: StructuredSchema; model?: string; /** Maximum server-side tool round-trips before forcing a final answer. */ maxSteps?: number; timeoutMs?: number; signal?: AbortSignal; /** Opt-in source grounding (#505): when true, `meta.citations` is the * Anthropic-shaped grounded array (each field → source page + bbox). */ cite?: boolean; } interface GenerateResult { answer: string; sources?: Array<{ page: number; snippet: string; }>; costUsd?: number; /** Present when schema is provided. */ data?: T; /** Present when schema is provided. */ meta?: StructuredOutputMeta; } interface SessionCreateOptions { /** Wait for extraction to complete before returning the session handle. Default: true */ wait?: boolean; /** Default model used by prompt()/stream() unless overridden per call. */ model?: string; /** Upload options used when source is URL/path/file (not an existing doc ID). */ upload?: UploadOptions; /** Wait options used when `wait` is enabled. */ waitOptions?: WaitOptions; } interface SessionAttachOptions { /** Default model used by prompt()/stream() unless overridden per call. */ model?: string; } interface SessionState { id: string; model?: string; modelEndpoint: string; } interface DocumentPluginState { plugin_name: string; desired_spec_version: number; desired_fingerprint: string | null; applied_spec_version: number | null; applied_fingerprint: string | null; status: 'pending' | 'running' | 'completed' | 'failed'; trigger: 'ready' | 'config_changed' | 'delete' | null; workflow_id: string | null; output: Record | null; error: string | null; last_run_at: number | null; completed_at: number | null; created_at: number; updated_at: number; } type DocumentAssetStatus = DocumentPluginState['status']; interface TocItem { id: string; title: string; page: number; level: number; } interface TocAssetData { items: TocItem[]; pageCount: number; generatedAt: number; } interface DocumentAsset> { assetId: string; status: DocumentAssetStatus; data: T | null; error: string | null; updatedAt: number; raw: DocumentPluginState; } interface OkraSession { readonly id: string; readonly modelEndpoint: string; readonly model?: string; state(): SessionState; setModel(model: string): Promise; status(signal?: AbortSignal): Promise; wait(options?: WaitOptions): Promise; pages(options?: { range?: string; signal?: AbortSignal; }): Promise; page(pageNumber: number, signal?: AbortSignal): Promise; entities(options?: { type?: string; limit?: number; offset?: number; signal?: AbortSignal; }): Promise; downloadUrl(): string; query(sql: string, signal?: AbortSignal): Promise; logs(options?: LogsOptions): Promise; publish(signal?: AbortSignal): Promise; shareLink(options?: ShareLinkOptions): Promise; assets(signal?: AbortSignal): Promise; asset>(assetId: string, signal?: AbortSignal): Promise | null>; prompt(query: string, options?: GenerateOptions & { schema?: undefined; }): Promise; prompt(query: string, options: GenerateOptions & { schema: StructuredSchema; }): Promise>; stream(query: string, options?: CompletionOptions): AsyncGenerator; } interface PublishResult { published: boolean; documentId: string; version: string; publicUrl: string; /** Immutable public URL: https://api.okrapdf.com/v1/documents/{id} */ url: string; hash: string; slug: string; canonicalPath: string; } interface ShareLinkOptions { /** Link role: 'viewer' (redacted/PDF access), 'admin' (full access), or 'ask' (public completion). */ role?: 'viewer' | 'ask' | 'admin'; label?: string; expiresInMs?: number; maxViews?: number; signal?: AbortSignal; } interface ShareLinkLinks { markdown: string | null; pdf: string | null; completion: string | null; } interface ShareLinkCapabilities { canViewPdf: boolean; } interface ShareLinkResult { documentId: string; token: string; tokenHint: string; links: ShareLinkLinks; capabilities: ShareLinkCapabilities; role: string; expiresAt: number; maxViews: number | null; } /** NDJSON events emitted by `client.collections.query()`. * Mirrors `CollectionQueryEvent` in `@okrapdf/schemas`. */ type CollectionQueryEvent = { type: 'start'; query_id: string; prompt: string; doc_count: number; } | { type: 'text_delta'; query_id: string; doc_id: string; text: string; } | { type: 'result'; query_id: string; doc_id: string; status: 'fulfilled' | 'failed' | 'timeout'; answer: string; error?: string; data?: Record; citations?: PageLocationCitation[]; usage: { cost_usd: number; }; duration_ms: number; } | { type: 'done'; query_id: string; completed: number; failed: number; total_cost_usd: number; } | { type: 'error'; query_id: string; error: string; }; /** Options for `client.collections.query()` — the map-reduce fan-out path. */ interface CollectionQueryOptions { /** Experimental: JSON Schema or Zod schema for structured extraction per document. * When provided, each result includes a typed `data` field. * Structured collection fan-out is not part of the stable v0.14 surface. */ schema?: StructuredSchema; /** Opt-in per-field source citations for structured collection extraction. */ cite?: boolean; /** Subset of document IDs to query. Omit to query all docs in collection. */ docIds?: string[]; signal?: AbortSignal; } /** Per-document answer in a gathered collection query result. */ interface DocumentAnswer { docId: string; status: 'fulfilled' | 'failed' | 'timeout'; /** Free-text answer (empty string for structured-only queries). */ answer: string; /** Structured extraction output — present when query included a schema. */ data?: T; /** Anthropic page_location citations returned when query included `cite: true`. */ citations?: PageLocationCitation[]; costUsd: number; durationMs: number; error?: string; } /** Aggregated result from `CollectionQueryStream.gather()`. */ interface CollectionQueryResult { queryId: string; prompt: string; answers: Map>; totalCostUsd: number; durationMs: number; completed: number; failed: number; } /** * Lazy stream handle returned by `client.collections.query()`. * * Two consumption modes: * - Iterate for real-time per-doc events (spreadsheet UIs) * - `.gather()` to await all results (scripts, pipelines) */ interface CollectionQueryStream extends AsyncIterable { /** Wait for all documents to complete and return the aggregated result. */ gather(): Promise>; /** Cancel the in-flight query. */ abort(): void; /** Expose the underlying NDJSON body as a ReadableStream (for proxying). */ toReadableStream(): ReadableStream; } /** A document summary inside a collection listing. */ interface CollectionDocument { id: string; file_name: string; phase: string; pages_total: number; total_nodes: number; added_at: string; source: string; } /** Full collection metadata returned by `client.collections.get()`. */ interface Collection { id: string; name: string; description: string | null; document_count: number; visibility: 'public' | 'private'; user_id: string; created_at: string; documents: CollectionDocument[]; } /** Summary row returned by `client.collections.list()`. */ interface CollectionSummary { id: string; name: string; description: string | null; document_count: number; } interface MarkdownPage { pageNumber: number; content: string; vendor: string; } interface DocumentMarkdownExport { docId: string; fileName: string | null; pageCount: number; pages: MarkdownPage[]; } type CollectionExportEvent = { type: 'start'; doc_count: number; format: string; } | { type: 'result'; doc_id: string; file_name: string; page_count: number; pages: MarkdownPage[]; } | { type: 'done'; completed: number; failed: number; total_pages: number; } | { type: 'error'; error: string; }; type CollectionExportFormat = 'markdown' | 'zip'; interface CollectionExportOptions { format?: CollectionExportFormat; signal?: AbortSignal; } interface CollectionMarkdownExport { collectionId: string; collectionName: string; documents: DocumentMarkdownExport[]; totalDocuments: number; totalPages: number; exportedAt: string; } interface OkraCollections { /** List all collections for the authenticated user. */ list(signal?: AbortSignal): Promise; /** Get a single collection with its documents. */ get(collectionId: string, signal?: AbortSignal): Promise; /** Unstructured fan-out — each doc answers independently via NDJSON stream. */ query(collectionId: string, prompt: string, options?: CollectionQueryOptions): CollectionQueryStream; /** Experimental structured fan-out — each doc extracts typed data matching the schema. * This schema-based collection path is not part of the stable v0.14 surface. */ query(collectionId: string, prompt: string, options: CollectionQueryOptions & { schema: StructuredSchema; }): CollectionQueryStream; /** Streaming completion — collection acts as a single model endpoint. * Returns the same `CompletionEvent` stream as `session.stream()`, * so it plugs directly into AI SDK providers. */ stream(collectionId: string, query: string, options?: CompletionOptions): AsyncGenerator; /** Non-streaming completion — returns a single synthesized answer. */ prompt(collectionId: string, query: string, options?: GenerateOptions & { schema?: undefined; }): Promise; /** Non-streaming structured completion — returns typed data. */ prompt(collectionId: string, query: string, options: GenerateOptions & { schema: StructuredSchema; }): Promise>; /** Export pre-computed markdown for all documents in the collection (NDJSON parsed to JSON). */ exportMarkdown(collectionId: string, signal?: AbortSignal): Promise; /** Export with declarative format options (`markdown` or `zip`). */ exportMarkdown(collectionId: string, options: CollectionExportOptions & { format: 'zip'; }): Promise; exportMarkdown(collectionId: string, options: CollectionExportOptions & { format?: 'markdown'; }): Promise; } /** Delivery transform options for image resizing/processing (maps to CF Image Resizing). */ interface DeliveryTransform { w?: number; h?: number; dpr?: number; q?: number; f?: 'auto' | 'webp' | 'avif' | 'jpeg' | 'png'; md?: 'copyright' | 'keep' | 'none'; c?: 'scale-down' | 'contain' | 'cover' | 'crop' | 'pad' | 'squeeze'; g?: 'auto' | 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center'; zm?: number; bl?: number; sh?: number; br?: number; co?: number; sa?: number; r?: number; fl?: 'h' | 'v' | 'hv'; bg?: string; anim?: boolean; seg?: 'foreground'; } interface UrlBuilderOptions { format?: 'json' | 'csv' | 'html' | 'markdown' | 'png'; include?: string[]; /** Provider transformation — changes extraction source, e.g. 'llamaparse', 'googleocr'. */ provider?: string; /** Delivery transform for image resizing/processing. */ transform?: DeliveryTransform; } /** A document summary returned by `client.listDocuments()`. */ interface DocumentListItem { id: string; file_name: string | null; phase: string; pages_total: number | null; total_nodes: number | null; visibility: 'public' | 'private'; created_at: string; } interface DocumentListResponse { documents: DocumentListItem[]; } interface ReadDocumentOptions { /** Page range in "1-5" format. Omit for full document. */ pages?: string; signal?: AbortSignal; } interface ReadDocumentResult { documentId: string; markdown: string; } interface DeleteDocumentResult { deleted: boolean; documentId: string; } interface DocUrlOptions { /** * Original source filename used to build friendly artifact URLs, e.g. * /.../invoice.json */ fileName?: string; /** * Default provider transformation applied to all URLs from this builder, * e.g. `/t_llamaparse/pages/1.md` vs `/t_googleocr/pages/1.json`. */ provider?: string; /** * Default image placeholder type when page image is not yet available. * Inserts `/d_{type}/` segment. e.g. 'shimmer' → `/d_shimmer/pages/1/image.png` */ defaultImage?: string; /** * Friendly alias for `defaultImage`. Placeholder for images not yet rendered. * 'shimmer' | 'auto' | 'color:hex'. Inserts `/d_{placeholder}/` segment. */ placeholder?: string; /** Output schema name — inserts `/o_{schema}/` segment. */ output?: string; /** * Switches the origin path from `/document/:id/` (session-cookie auth) * to `/v1/documents/:id/` (public). Required for `` tags and any * browser request that won't carry an auth cookie. Default: `false`. */ public?: boolean; /** * @deprecated Use `pdfSha` + `renderer` to emit `imagedelivery.net` URLs instead. * When `true`, image URLs are wrapped with `/cdn-cgi/image//`. * Will be removed in v0.16.x once all consumers migrate. */ cdnImage?: boolean; /** * PDF sha256 (full 64-hex). When provided together with `renderer`, image * URLs target `imagedelivery.net//okra-{env}-{pdfSha12}-p{N}-r{V}-{renderer}/{variant}` * — content-addressed, dedup'd, cache-immutable per ID. * * Without `pdfSha`, image URLs fall back to the origin path (legacy). * Fetch `pdfSha` from the existing `/status` endpoint or use `resolveDoc(id)`. */ pdfSha?: string; /** * Render backend that produced the bytes: `mupdf150` (MuPDF container @ 150 DPI) * or `pdfjs2x` (pdf.js via Browser Rendering @ scale=2). Encoded in the image ID * so backend-divergent bytes cannot collide under one ID. */ renderer?: 'mupdf150' | 'pdfjs2x' | (string & {}); /** * Environment prefix for CF Images IDs — prevents cross-env collisions when * prod/staging/dev share a CF account. Default: `'prod'`. */ env?: 'prod' | 'staging' | 'dev' | (string & {}); /** * CF Images account hash — the path prefix on `imagedelivery.net//...`. * Public value, safe to bake into client bundles. When omitted, image URLs * fall back to the origin path. */ accountHash?: string; /** * Base URL for `imagedelivery.net`. Override for self-hosted CF Images or * custom delivery domains. Default: `'https://imagedelivery.net'`. */ imagesBaseUrl?: string; /** * Render schema version encoded in the ID (`-r{V}`). Bumps when render * params change (pdf.js version, DPI, anti-aliasing). Default: `1`. */ renderVersion?: number; /** * Sha-prefix width in hex chars. Default: `12` (48 bits, ~10⁻⁵ collision p at 100K). * Auto-escalates to `16` on observed collision; bump account-wide at 1M-PDF milestone. */ pdfShaLength?: number; } export { type DocumentAgentToolPolicies as $, type ApiKeyWorkflowConfigResponse as A, type CollectionQueryResult as B, type CompletionOptions as C, type DocumentStatus as D, type EntitiesResponse as E, type CollectionQueryStream as F, type GenerateOptions as G, type CollectionSummary as H, type DeleteDocumentResult as I, type DeleteFileResult as J, type DocUrlOptions as K, type LogsOptions as L, type DocumentAccess as M, type DocumentAccessRoleProfile as N, type OkraClientOptions as O, type ProcessingCapabilities as P, type QueryResult as Q, type RuntimeErrorCode as R, type SessionState as S, type DocumentAction as T, type DocumentAgentConfig as U, type DocumentAgentContextConfig as V, type WaitOptions as W, type DocumentAgentModelConfig as X, type DocumentAgentModelEndpoint as Y, type DocumentAgentRuntimeConfig as Z, type DocumentAgentSecurityConfig as _, type OkraSession as a, type ReparseResult as a$, type DocumentAgentToolsConfig as a0, type DocumentAnswer as a1, type DocumentAssetStatus as a2, type DocumentConfigResult as a3, type DocumentConfigUpdate as a4, type DocumentEvent as a5, type DocumentEventHandler as a6, DocumentEventStream as a7, type DocumentEventStreamOptions as a8, type DocumentEventType as a9, type InvoiceExtractionRunOptions as aA, type JobError as aB, type JobListOptions as aC, type JobListResponse as aD, type JobStatus as aE, type JsonSchema as aF, type MarkdownPage as aG, type OkraCollections as aH, type OkraEvent as aI, type OkraFile as aJ, type OkraFileListResponse as aK, type OkraFileUrls as aL, type OkraFiles as aM, type OkraJob as aN, type PageBlock as aO, type PageEntity as aP, type PageImageStrategy as aQ, type ParseArtifact as aR, type ParseExtraction as aS, type ParseJob as aT, type ParseOptions as aU, type ParseResult as aV, type ParseUsage as aW, type PrincipalRef as aX, type ReadDocumentOptions as aY, type ReadDocumentResult as aZ, type ReparseOptions as a_, type DocumentExtract as aa, type DocumentFeatureFlags as ab, type DocumentGrant as ac, type DocumentGrantConstraints as ad, type DocumentListItem as ae, type DocumentListResponse as af, type DocumentMarkdownExport as ag, type DocumentPluginSpec as ah, type DocumentPluginState as ai, type DocumentRuntime as aj, type DocumentSpec as ak, type DocumentSpecDiff as al, type DocumentSpecRecord as am, type Entity as an, type FileListOptions as ao, type FileUploadOptions as ap, type FileUploadTransport as aq, type InvoiceExtractionException as ar, type InvoiceExtractionExceptionList as as, type InvoiceExtractionExceptionResolution as at, type InvoiceExtractionInput as au, type InvoiceExtractionQuality as av, type InvoiceExtractionResolveExceptionOptions as aw, type InvoiceExtractionRun as ax, type InvoiceExtractionRunList as ay, type InvoiceExtractionRunListOptions as az, type CompletionEvent as b, type SessionAttachOptions as b0, type SessionCreateOptions as b1, type ShareLinkCapabilities as b2, type ShareLinkLinks as b3, type StructuredOutputMeta as b4, type TocAssetData as b5, type TocItem as b6, type UploadInput as b7, type UploadOptions as b8, type UploadRedactOptions as b9, type UploadRedactPiiOptions as ba, type UrlBuilderOptions as bb, type VerifyBbox as bc, type VerifyParams as bd, type VerifyResult as be, type VerifyVerdict as bf, type WorkflowPhase as bg, type WorkflowPhaseConfig as bh, type WorkflowTier as bi, type DeliveryTransform as bj, type ApiResourceCatalog as bk, type ApiResource as bl, type ApiAction as bm, type CreateJobOptions as bn, type Page as c, type LogEntry as d, type PublishResult as e, type ShareLinkOptions as f, type ShareLinkResult as g, type DocumentAsset as h, type GenerateResult as i, type StructuredSchema as j, type StructuredOutputErrorCode as k, type PageLocationCitation as l, type ApplyWorkflowOptions as m, type ApplyWorkflowResult as n, type CanonicalParseBlock as o, type CanonicalParseOutput as p, type CanonicalParsePage as q, type CitationBbox as r, type Collection as s, type CollectionDocument as t, type CollectionExportEvent as u, type CollectionExportFormat as v, type CollectionExportOptions as w, type CollectionMarkdownExport as x, type CollectionQueryEvent as y, type CollectionQueryOptions as z };