import { AuthTokenFetcher, ConvexClient } from 'convex/browser'; import { z } from 'zod'; /** Shared browser-safe memory discovery policy. No inference or authority lives here. */ type MemoryEffort = "fast" | "normal" | "high" | "max"; interface MemoryEffortRequest { effort?: MemoryEffort; maxEntries?: number; maxContextTokens?: number; } interface MemoryEffortPolicyV1 { version: 1; maxDepth?: number; maxEntries?: number; maxContextTokens?: number; maxWork?: number; retrievalDeadlineMs?: number; } interface EffectiveMemoryEffortPolicy { version: 1; policyVersion: "memory-effort-v1"; /** Omission preserves the original immutable snapshot's score ordering. */ evidenceRankingVersion?: 1; /** New snapshots may prove redundant literal and question-source projections. * Omission keeps the historical singleton-only direct lookup rule. */ literalSourceProofVersion?: 1 | 2 | 3; requestedEffort: MemoryEffort; effectiveEffort: MemoryEffort; maxDepth: number | null; maxEntries: number | null; maxContextTokens: number; maxWork: number; maxCandidateBytes: number; pageSize: number; retrievalDeadlineMs: number; targetFirstAnswerMs: number; } type MemoryEffortStopReason = "exhausted" | "depth" | "relevance" | "entries" | "input" | "deadline" | "work" | "cancellation" | "unavailable"; interface MemoryEffortTrace { /** Discovery route only; direct facts do not imply semantic corpus exhaustion. */ retrievalRoute?: "direct-facts-v1" | "semantic-v1"; version: 1; policyVersion: "memory-effort-v1"; requestedEffort: MemoryEffort; effectiveEffort: MemoryEffort; maxDepth: number | null; maxEntries: number | null; maxContextTokens: number; targetFirstAnswerMs: number; reachedDepth: number; visited: number; expanded: number; selected: number; deduplicated: number; entriesByKind: { memory: number; fact: number; pending: number; history: number; }; selectedInputUnits: number; durationMs: number; stopReasons: MemoryEffortStopReason[]; unavailableStages: string[]; } declare const MEMORY_EFFORT_POLICY_V1: Readonly; declare function normalizeMemoryEffortRequest(input?: MemoryEffortRequest): MemoryEffortRequest; declare function resolveMemoryEffortPolicy(request?: MemoryEffortRequest, administrator?: MemoryEffortPolicyV1): EffectiveMemoryEffortPolicy; /** Browser-only v1 contracts. Selectors are verified by the backend, never authority. */ interface RuntimeScope { readonly tenantId: string; readonly memorySpaceId: string; } interface RuntimeSession extends RuntimeScope { readonly version: 1; readonly principalId: string; readonly userId: string; readonly deliveryExpiresAt?: number; } interface TextSubmitV1 { version: 1; agentId: string; agentVersion: number; conversationId?: string; clientRequestId: string; parts: { type: "text"; text: string; }[]; memory?: MemoryEffortRequest; } type RuntimeResponseStatus = "queued" | "waiting_approval" | "running" | "complete" | "failed" | "cancelled"; type RuntimeStageStatus = "pending" | "complete" | "failed" | "not_requested"; interface RuntimeRun { version: 1; runId: string; conversationId: string; agentId: string; agentVersion: number; scope: RuntimeScope; definitionHash: string; queueSequence: number; responseStatus: RuntimeResponseStatus; memoryStatus: RuntimeStageStatus; graphStatus: RuntimeStageStatus; attemptNumber: number; cancellationRequested: boolean; inputMessageIds: string[]; outputMessageIds: string[]; failureCode: string | null; contextCompleteness: "complete" | "incomplete" | null; contextFailureCode: string | null; createdAt: number; updatedAt: number; memoryEffort?: MemoryEffortTrace; } /** Restorable server identity; possession of a handle grants no access. */ interface RuntimeRunHandle extends RuntimeScope { readonly version: 1; readonly principalId: string; readonly runId: string; readonly conversationId: string; readonly agentId: string; readonly agentVersion: number; readonly definitionHash: string; } interface RuntimeStartResult { runId: string; attemptNumber: number; state: "queued" | "ready" | "running" | "waiting_approval" | "finalizing" | "complete" | "failed" | "cancelled" | "unknown"; failureCode?: string; } /** Admission and start metadata from one native transaction. The handle grants no authority. */ interface RuntimeAdmissionResult { handle: RuntimeRunHandle; run: RuntimeRun; start: RuntimeStartResult; } type RuntimePublicPart = { type: "text"; text: string; } | { type: "text-start" | "text-end"; id: string; } | { type: "text-delta"; text: string; id?: string; } | { type: "tool"; toolCallId: string; name: string; phase: "requested" | "approved" | "running" | "succeeded" | "failed"; } | { type: "error"; code: "RUNTIME_OUTPUT_FAILED"; } | { type: "artifact"; artifactId: string; kind: "memory-receipt"; } | { type: "media-job"; version: 1; jobId: string; artifactId: string; kind: "image" | "video"; } | { type: "status"; state: string; }; interface RuntimeToolApproval { operationId: string; toolName: string; requestHash: string; } interface RuntimeOutputCursor { readonly attemptNumber: number; readonly sequence: number; } interface RuntimeObservation { run: RuntimeRun; state: string; parts: { sequence: number; part: RuntimePublicPart; }[]; cursor: number; approvals: RuntimeToolApproval[]; deliveryExpiresAt?: number; } interface RuntimeEmbeddingProfile { profileId: string; modelId: string; dimensions: number; normalization: string; chunking: string; indexName: string; } type RuntimeMemoryStage = "facts" | "vectors" | "graph"; interface RuntimeStageWatermark { readonly cutoff: number; readonly indexedThrough: number; readonly complete: boolean; readonly hole: Readonly<{ sequence: number; state: "pending" | "failed" | "missing"; }> | null; } /** Point-in-time status of captured counters. It does not change an Agent's administrator-selected memory mode. */ interface RuntimeMemoryReadiness { readonly version: 1; readonly cutoff: number; readonly graphCutoff: number; readonly profile: RuntimeEmbeddingProfile; readonly stages: Readonly>>; readonly strictStages: readonly RuntimeMemoryStage[]; } interface RuntimeMemoryReadinessOptions { cutoff?: number; graphCutoff?: number; expectedProfileId?: string; strictStages?: RuntimeMemoryStage[]; } interface RuntimeRecallItem { type: "memory" | "fact"; id: string; content: string; score: number; source: string; /** Additional attributed, public retrieval metadata; never a model request. */ memory?: Readonly>; fact?: Readonly>; retrieval?: { depth: number; path: string[]; }; tenantId?: string; userId?: string; graphContext?: { connectedEntities: string[]; relationshipPath?: string; }; } interface RuntimeRecallRequest { text: string; requestId: string; limit?: number; memory?: MemoryEffortRequest; } interface RuntimeRecallResult { items: RuntimeRecallItem[]; context: string; profileId: string; deliveryExpiresAt?: number; memoryEffort?: MemoryEffortTrace; } /** Capture supplied text once; indexing runs asynchronously under backend policy. */ interface RuntimeRememberInput { conversationId: string; requestId: string; userMessage: string; agentResponse: string; userId?: string; agentId?: string; participantId?: string; userName?: string; expectedRevision?: number; metadata?: Readonly>; } interface RuntimeRememberResult { readonly version: 1; readonly receiptId: string; readonly requestId: string; readonly conversationId: string; readonly scope: RuntimeScope; readonly principalId: string; readonly messageIds: readonly [string, string]; readonly sourceEventIds: readonly [string, string]; readonly historyRevision: number; readonly created: boolean; readonly memoryStatus: "pending" | "complete" | "failed"; readonly profile: RuntimeEmbeddingProfile; readonly stages: Readonly<{ facts: readonly [string, string]; vectors: readonly [string, string]; }>; readonly deliveryExpiresAt?: number; } interface RuntimeTranscriptMessage { id: string; role: "user" | "assistant" | "tool"; parts: Extract[]; order: number; stepOrder: number; status: "pending" | "success" | "failed"; revision: number; } interface RuntimeTranscriptPage { page: RuntimeTranscriptMessage[]; isDone: boolean; continueCursor: string | null; } interface RuntimeDefinition { agentId: string; version: number; definitionHash: string; tools: { toolId: string; toolVersion: number; }[]; memoryMode: string; inputSelectionVersion?: 2; memoryEffortPolicyVersion?: 1; } interface RuntimeConversation { conversationId: string; type: "user-agent" | "agent-agent"; visibility: "private" | "space"; manualWriteLocked: boolean; requireApproval: boolean; historyRevision: number; epoch: number; messageCount: number; participants: string[]; retentionUntil: number | null; createdAt: number; updatedAt: number; } /** Immutable version selectors carry no authority or storage URL. */ interface RuntimeAssetReference { assetId: string; version: number; } interface RuntimeAssetVersion { readonly version: 1; readonly assetId: string; readonly versionId: string; readonly assetVersion: number; readonly contentHash: string; readonly sizeBytes: number; readonly mimeType: string; readonly deliveryExpiresAt?: number; readonly mediaKind: "image" | "video" | "audio" | "document" | "binary"; readonly filename?: string; readonly lineage: Readonly<{ kind: "upload"; requestId: string; } | { kind: "generated"; operationId: string; modelId: string; sourceVersionIds?: readonly string[]; }>; } type RuntimeMediaJobState = "pending" | "submitting" | "submission_unknown" | "processing" | "downloading" | "ready" | "failed" | "cancelled" | "expired"; /** Public durable job metadata; no callback secrets, upstream URLs, encoded output or model overrides. */ interface RuntimeMediaJob { readonly version: 1; readonly jobId: string; readonly artifactId: string; readonly kind: "image" | "video"; readonly state: RuntimeMediaJobState; readonly revision: number; readonly createdAt: number; readonly updatedAt: number; readonly asset?: RuntimeAssetVersion; readonly failureCode?: string; readonly deliveryExpiresAt?: number; readonly costStatus: "reserved" | "incurred_unknown" | "settled"; readonly upstreamCancellation: "not_requested" | "not_supported"; } interface RuntimeMediaSubmit { requestId: string; kind: "image" | "video"; prompt: string; inputAsset?: RuntimeAssetReference; conversationId?: string; } /** Browser projection of a retained artifact. Files remain immutable selectors served through authenticated HTTP. */ interface RuntimeArtifact { readonly contractVersion: 1; readonly artifactId: string; readonly artifactVersion: number; readonly versionPointer: number; readonly kind: "text" | "code" | "sheet" | "image" | "video" | "diagram" | "html" | "custom"; readonly title: string; readonly content?: string; readonly deliveryExpiresAt?: number; readonly streamingState: "draft" | "streaming" | "paused" | "final" | "error"; readonly file?: Readonly; readonly conversationId?: string; readonly createdAt: number; readonly updatedAt: number; } /** Application cap in decoded bytes, independent of Convex/provider protocol limits. */ declare const RUNTIME_ASSET_MAX_BYTES = 20000000; interface RuntimeAssetIoOptions { signal?: AbortSignal; timeoutMs?: number; } interface RuntimeAssetPreview { readonly url: string; readonly mimeType: string; readonly sizeBytes: number; revoke(): void; } interface RuntimeAssetUploadOptions extends RuntimeAssetIoOptions { requestId: string; mimeType: string; filename?: string; } declare class CortexRuntimeError extends Error { readonly code: string; readonly outcome: "not_dispatched" | "uncertain"; readonly retryable: boolean; readonly version = 1; /** Generated ordinary remember intent, when capture outcome needs reconciliation. */ readonly requestId?: string; constructor(code: string, outcome?: "not_dispatched" | "uncertain", retryable?: boolean); } /** Bounded public scalar metadata only; never accepts evidence text or authority. */ declare function runtimeMemoryEffortTrace(input: unknown): MemoryEffortTrace; declare function runtimePublicPart(input: unknown): RuntimePublicPart; /** Closed backend content intents. No model, policy, authority or budget from callers. */ declare const CONTENT_INTENTS: readonly ["title", "text", "code", "sheet", "suggestions"]; type ContentIntent = typeof CONTENT_INTENTS[number]; declare const CONTENT_STATES: readonly ["pending", "running", "ready", "failed", "unknown", "cancelled", "expired"]; type ContentState = typeof CONTENT_STATES[number]; declare const contentSubmitSchema: z.ZodObject<{ version: z.ZodLiteral<1>; requestId: z.ZodString; intent: z.ZodEnum<{ text: "text"; code: "code"; sheet: "sheet"; title: "title"; suggestions: "suggestions"; }>; prompt: z.ZodString; conversationId: z.ZodOptional; sourceMessageId: z.ZodOptional; parentRunId: z.ZodOptional; artifact: z.ZodOptional>; }, z.core.$strict>; type ContentSubmitV1 = z.infer; declare const suggestionSchema: z.ZodObject<{ originalText: z.ZodString; suggestedText: z.ZodString; description: z.ZodString; }, z.core.$strict>; type ContentSuggestionV1 = z.infer & { suggestionId: string; }; interface RuntimeContentJobV1 { version: 1; jobId: string; intent: ContentIntent; state: ContentState; revision: number; createdAt: number; updatedAt: number; conversationId?: string; artifactId?: string; artifactVersion?: number; title?: string; content?: string; suggestions?: ContentSuggestionV1[]; failureCode?: string; deliveryExpiresAt?: number; } type RuntimeClientPort = Pick; /** Metadata only, timed with this client's monotonic clock. RPC end/failed describe * the official port promise; a local deadline may already have suppressed delivery. */ interface RuntimeLatencyEvent { readonly version: 1; readonly phase: "rpc.begin" | "rpc.end" | "rpc.failed" | "auth.begin" | "auth.ready" | "auth.denied" | "watcher.wake"; readonly atMs: number; readonly rpcId?: number; readonly method?: string; readonly durationMs?: number; } interface CortexRuntimeClientOptions { deploymentUrl: string; fetchToken: AuthTokenFetcher; scope?: Partial; /** Explicit owned HTTP-action origin. Tokens are never forwarded to redirects or storage URLs. */ assetHttpUrl?: string; /** Standard HTTP port for assets and the denial-only auth check. Supplying this * also enables that check for a custom borrowed transport. Owned/official * clients use standard fetch by default; HTTP success grants no authority. */ fetch?: typeof globalThis.fetch; onAuthChange?: (authenticated: boolean) => void; /** Optional scalar diagnostics. No arguments, results, credentials or error data are emitted. */ onLatencyEvent?: (event: RuntimeLatencyEvent) => void; /** Bound the official authentication handshake, including providers that never notify rejection. Default 10 seconds. */ authTimeoutMs?: number; /** Bound RPC observation without cancelling or retrying a server mutation. Default 12 seconds. */ requestTimeoutMs?: number; /** An existing official client can be shared; close() then leaves its ownership with the caller. */ client?: RuntimeClientPort; } /** One authenticated Convex connection. JWTs stay inside the host's official fetchToken callback. */ declare class CortexRuntimeClient { private readonly options; private readonly port; private readonly scope; private readonly watchers; private readonly assetRequests; private readonly assetPreviews; private closed; private generation; private authenticated; private fetchToken; private authReady; private rejectAuth?; private stopAuthProbe?; private authProbeSequence; private readonly authProbeTarget; private authTimer?; private sessionTimer?; private deliveryTimer?; private earliestDelivery?; private readonly wakeWatchers; private readonly pendingCalls; private rpcSequence; private latencyAt; constructor(options: CortexRuntimeClientOptions); private latencyNow; private latency; private rpc; private mutation; private action; private installAuth; /** Reinstall the official callback; Convex verifies a fresh token within the bounded handshake. */ refreshAuth(fetchToken?: AuthTokenFetcher): Promise; private expireSession; private sessionDeadline; private trackDelivery; private check; private abortCalls; private call; session(): Promise; private selector; private inSession; private pinned; private handle; submit(request: TextSubmitV1): Promise; /** Native pre-session/admission envelope followed by the independent fresh post-I/O session. */ submitAndStart(request: TextSubmitV1, options?: { streaming?: boolean; }): Promise; attach(runId: string): Promise; start(handle: RuntimeRunHandle, options?: { streaming?: boolean; }): Promise<{ runId: string; attemptNumber: number; state: string; failureCode?: string; }>; get(handle: RuntimeRunHandle): Promise; private observeInSession; observe(handle: RuntimeRunHandle, options?: { cursor?: RuntimeOutputCursor; finalOnly?: boolean; limit?: number; }): Promise; private watch; watchRun(handle: RuntimeRunHandle, onUpdate: (run: RuntimeRun) => void, onError?: (error: CortexRuntimeError) => void): () => void; /** Live cursor pages, including updates while paused for approval. Unsubscribe affects observation only. */ watchObservation(handle: RuntimeRunHandle, onUpdate: (observation: RuntimeObservation) => void, onError?: (error: CortexRuntimeError) => void, options?: { cursor?: RuntimeOutputCursor; finalOnly?: boolean; }): () => void; cancel(handle: RuntimeRunHandle): Promise<{ cancelled: true; }>; approveInput(handle: RuntimeRunHandle): Promise; approveTool(handle: RuntimeRunHandle, approval: RuntimeToolApproval): Promise<{ approved: true; }>; getDefinition(agentId: string, version: number): Promise; messages(conversationId: string, options?: { cursor?: string | null; limit?: number; }): Promise; listConversations(limit?: number): Promise; getDefaultProfile(): Promise<{ version: 1; profile: RuntimeEmbeddingProfile; }>; /** Fresh administrator-selected profile metadata. expectedProfileId is a mismatch guard, never an override. */ getEmbeddingProfile(options?: { operationKey?: "embedding.memory" | "embedding.query"; expectedProfileId?: string; }): Promise<{ version: 1; profile: RuntimeEmbeddingProfile; }>; /** Fresh status, or an explicit strict barrier for only the requested stages. Starts no inference. */ memoryReadiness(options?: RuntimeMemoryReadinessOptions): Promise; recall(input: RuntimeRecallRequest): Promise; /** One canonical capture receipt; pending indexing is not immediate facts/vectors. */ remember(input: RuntimeRememberInput): Promise; /** Fresh receipt/source/profile/readiness, without starting inference. */ rememberStatus(receiptId: string): Promise; /** Admit one backend-owned job and pending artifact. The backend chooses its qualified model and options. */ submitMediaJob(input: RuntimeMediaSubmit): Promise; getMediaJob(jobId: string): Promise; listMediaJobs(options?: { conversationId?: string; limit?: number; }): Promise<{ version: 1; jobs: RuntimeMediaJob[]; }>; /** Local cancellation is honest about unsupported upstream cancellation and any incurred uncertainty. */ cancelMediaJob(jobId: string): Promise; /** Poll/download an existing acknowledged operation; submission-unknown never triggers a new generation. */ reconcileMediaJob(jobId: string): Promise; /** Fresh artifact metadata with a bounded current-version projection and no storage URL or credentials. */ getArtifact(value: string): Promise; private mediaOperation; /** Submit one durable backend content intent; model, budget, tools and memory stay on the backend. */ submitContentJob(input: ContentSubmitV1): Promise; getContentJob(jobId: string): Promise; listContentJobs(options?: { conversationId?: string; limit?: number; }): Promise; cancelContentJob(jobId: string): Promise; /** Recover only the existing operation; an unknown submission is never retried through this API. */ reconcileContentJob(jobId: string): Promise; /** Commit an explicitly selected suggestion against its exact current retained artifact version. */ applyContentSuggestion(input: { jobId: string; suggestionId: string; artifactVersion: number; }): Promise; private contentOperation; private abortAssets; private assetIo; private assetFetch; private currentAsset; /** Metadata is freshly authorized by a mutation; its immutable IDs grant no byte access. */ getAsset(reference: RuntimeAssetReference): Promise; /** Direct bounded raw-byte upload. No client-side storage or presigned URL. */ uploadAsset(input: Uint8Array | Blob, options: RuntimeAssetUploadOptions): Promise; /** Authenticated bytes, verified against the exact current immutable version, suitable for a bounded Blob URL in the UI. */ fetchAsset(reference: RuntimeAssetReference, options?: RuntimeAssetIoOptions): Promise; /** Local bounded Blob URL for image/video/download rendering. Revoke on unmount; auth changes and close also revoke. */ createAssetUrl(reference: RuntimeAssetReference, options?: RuntimeAssetIoOptions): Promise; close(): Promise; } export { type ContentIntent, type ContentState, type ContentSubmitV1, type ContentSuggestionV1, CortexRuntimeClient, type CortexRuntimeClientOptions, CortexRuntimeError, type EffectiveMemoryEffortPolicy, MEMORY_EFFORT_POLICY_V1, type MemoryEffort, type MemoryEffortPolicyV1, type MemoryEffortRequest, type MemoryEffortStopReason, type MemoryEffortTrace, RUNTIME_ASSET_MAX_BYTES, type RuntimeAdmissionResult, type RuntimeArtifact, type RuntimeAssetIoOptions, type RuntimeAssetPreview, type RuntimeAssetReference, type RuntimeAssetUploadOptions, type RuntimeAssetVersion, type RuntimeClientPort, type RuntimeContentJobV1, type RuntimeConversation, type RuntimeDefinition, type RuntimeEmbeddingProfile, type RuntimeLatencyEvent, type RuntimeMediaJob, type RuntimeMediaJobState, type RuntimeMediaSubmit, type RuntimeMemoryReadiness, type RuntimeMemoryReadinessOptions, type RuntimeMemoryStage, type RuntimeObservation, type RuntimeOutputCursor, type RuntimePublicPart, type RuntimeRecallItem, type RuntimeRecallRequest, type RuntimeRecallResult, type RuntimeRememberInput, type RuntimeRememberResult, type RuntimeResponseStatus, type RuntimeRun, type RuntimeRunHandle, type RuntimeScope, type RuntimeSession, type RuntimeStageStatus, type RuntimeStageWatermark, type RuntimeStartResult, type RuntimeToolApproval, type RuntimeTranscriptMessage, type RuntimeTranscriptPage, type TextSubmitV1, normalizeMemoryEffortRequest, resolveMemoryEffortPolicy, runtimeMemoryEffortTrace, runtimePublicPart };