import { BaseCheckpointSaver, CheckpointTuple, CheckpointListOptions, Checkpoint, CheckpointMetadata, PendingWrite } from '@langchain/langgraph-checkpoint'; import * as _kortyx_core from '@kortyx/core'; import { InterruptInput, GraphState, WorkflowDefinition, NodeFn, RuntimeEnvelope } from '@kortyx/core'; import { RunnableConfig } from '@langchain/core/runnables'; import postgres from 'postgres'; import { KortyxError } from '@kortyx/core/errors'; import * as _kortyx_prompts from '@kortyx/prompts'; import * as _kortyx_hooks from '@kortyx/hooks'; import { ReasonTraceAdapter, KortyxTelemetryConfig } from '@kortyx/hooks'; import { GetProviderFn } from '@kortyx/providers'; declare function getCheckpointer(key: string): BaseCheckpointSaver; type PruneRuntimeOptions = { /** Defaults to wall-clock time; future timestamps are rejected. */ now?: Date; /** Maximum parent records removed per table. Default: 500, maximum: 1000. */ batchSize?: number; }; type PruneRuntimeResult = { skipped: boolean; hasMore: boolean; deleted: { pendingRequests: number; sessionCheckpoints: number; graphCheckpoints: number; sessions: number; runs: number; }; }; type RuntimeMaintenance = { /** Explicit, idempotent backend setup. Complete before serving requests. */ setup: () => Promise; /** App-scheduled cleanup. Redis uses native TTL; memory uses lazy expiry/count limits. */ prune: (options?: PruneRuntimeOptions) => Promise; }; /** Internal: A submitted answer is addressed to an occurrence, never its value. */ type ResumeDelivery = { id: string; nodeId: string; position: number; value: unknown; delivered: boolean; engineInterruptId?: string | undefined; }; /** Internal: Legacy imports infer the outstanding occurrence from saved replay history. */ declare function createResumeDelivery(id: string, nodeId: string, request: Pick, value: unknown, snapshot?: GraphSnapshotBundle): ResumeDelivery; /** Address the engine wake-up too; an empty/false/null answer remains a response. */ declare function resumeDeliveryInput(delivery: ResumeDelivery): unknown; /** Internal: Called only after the addressed response has entered its replay owner. */ declare function acknowledgeResumeDelivery(delivery: ResumeDelivery | undefined, nodeId: string, position: number): void; /** A self-contained, JSON snapshot, including pending writes needed for replay. */ type GraphSnapshotBundle = CheckpointTuple & { /** Kortyx-owned continuation state; absent in legacy engine snapshots. */ suspension?: { version: 1; response?: ResumeDelivery; }; }; /** Preserve readable legacy pauses; never guess whether an old command was consumed. */ declare function prepareSuspensionSnapshot(snapshot: GraphSnapshotBundle): GraphSnapshotBundle; declare function captureGraphSnapshot(saver: BaseCheckpointSaver, threadId: string, checkpointId?: string, suspension?: { runtimePatch?: Record | undefined; response?: ResumeDelivery | undefined; }): Promise; declare function restoreGraphSnapshot(saver: BaseCheckpointSaver, snapshot: GraphSnapshotBundle, threadId: string): Promise; type HumanInputKind = "choice" | "multi-choice" | "text" | "custom"; interface HumanInputOption { id: string; label: string; description?: string; value?: unknown; } interface PendingRequestRecord { ready?: boolean; responseCompleted?: boolean; token: string; requestId: string; sessionId?: string | undefined; /** * Framework run identifier used by the checkpointer (thread_id). * This must be stable across interrupt/resume, but should not be reused for new messages. */ runId: string; /** * LangGraph checkpoint id for the paused interrupt within the run thread. * Used to resume from the correct interrupt after session rollback. */ graphCheckpointId?: string | undefined; graphSnapshot?: GraphSnapshotBundle; workflow: string; node: string; state?: GraphState; schema: { kind: HumanInputKind; multiple: boolean; question?: string; id?: string; schemaId?: string; schemaVersion?: string; contract?: string; request?: unknown; meta?: Record; }; options: HumanInputOption[]; createdAt: number; ttlMs: number; } interface PendingRequestStore { list?: () => Promise; take?: (token: string) => Promise; save: (rec: PendingRequestRecord) => Promise; get: (token: string) => Promise; delete: (token: string) => Promise; update: (token: string, patch: Partial) => Promise; } declare function createInMemoryPendingRequestStore(): PendingRequestStore & { pruneExpired: (now: number, batchSize: number) => number; }; /** Internal cache capability. It is separate from authoritative framework stores. */ type FrameworkPayloadCache = { get: (key: string) => Promise; set: (key: string, value: string, ttlMs: number) => Promise; close?: () => Promise; }; type CreateCachingFrameworkAdapterOptions = { /** Authoritative storage. Currently supports the PostgreSQL adapter. */ storage: T; /** Payload cache provider. Currently supports the Redis adapter. */ cache: FrameworkAdapter; /** Cache operation budget. Default: 25 ms, maximum: 1000 ms. */ timeoutMs?: number; }; /** Attaches caching to storage before traffic, preserving every storage method and its identity. * The returned adapter owns shutdown of both inputs. Do not use the cache input as another storage backend. */ declare function createCachingFrameworkAdapter(options: CreateCachingFrameworkAdapterOptions): T; type RedisFrameworkStore = { close?: () => Promise; list?: (prefix: string) => Promise; take?: (key: string) => Promise; get: (key: string) => Promise; set: (key: string, value: string, ttlMs: number) => Promise; del: (key: string) => Promise; hset: (key: string, field: string, value: string) => Promise; hsetnx: (key: string, field: string, value: string) => Promise; writeHash?: (key: string, writes: Array<{ field: string; value: string; overwrite: boolean; }>, ttlMs: number) => Promise; hgetall: (key: string) => Promise>; expire: (key: string, ttlMs: number) => Promise; scanKeys: (prefix: string) => Promise; delRaw: (keys: string[]) => Promise; }; type RuntimeSql = postgres.Sql | postgres.TransactionSql; type RuntimeRetentionPolicy = { /** Rolling history window. The current head and live runs are protected. Default: 30. */ checkpointHistoryDays?: number; /** Inactivity window for a session. Unexpired interrupts and live runs protect it. Default: 30. */ inactiveSessionDays?: number; }; /** Internal relational storage. Redis never controls visibility or token consumption. */ declare class PostgresRuntimeStore { private cache?; private cacheTtlMs; private cacheTimeoutMs; readonly sql: postgres.Sql; readonly scope: string; readonly historyMs: number; readonly sessionMs: number; private readonly cachePrefix; private cacheRetryAfter; private cacheClosed; private readonly cachePopulations; constructor(connectionString: string, namespace: string, retention: RuntimeRetentionPolicy, cache?: Pick, cacheTtlMs?: number, cacheTimeoutMs?: number); get cacheEnabled(): boolean; attachCache(cache: FrameworkPayloadCache, ttlMs: number, timeoutMs: number): void; setup(): Promise; query(query: PromiseLike): Promise; transaction(operation: (sql: postgres.TransactionSql) => Promise): Promise; liveSession(sql: RuntimeSql, now: number): postgres.PendingQuery; liveCheckpoint(sql: RuntimeSql, now: number): postgres.PendingQuery; liveRun(sql: RuntimeSql, now: number): postgres.PendingQuery; touchRun(sql: postgres.TransactionSql, runId: string): Promise; touchSession(sql: postgres.TransactionSql, sessionId: string): Promise; payload(key: unknown[], load: () => Promise): Promise; private cacheCall; close(): Promise; } /** Kortyx-owned checkpoint format and relational persistence, independent of LangGraph saver packages. */ declare class PostgresCheckpointSaver extends BaseCheckpointSaver { private readonly store; constructor(store: PostgresRuntimeStore); getTuple(config: RunnableConfig): Promise; list(config: RunnableConfig, options?: CheckpointListOptions): AsyncGenerator; put(config: RunnableConfig, checkpoint: Checkpoint, metadata: CheckpointMetadata, _newVersions: Record): Promise; putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string): Promise; deleteThread(runId: string): Promise; deleteCheckpointWrites(runId: string, ns: string, id: string): Promise; getLatestCheckpointId(runId: string, ns?: string): Promise; } type CreatePostgresFrameworkAdapterOptions = { connectionString: string; /** Isolates applications sharing the runtime tables. Default: "default". */ namespace?: string; /** Interrupt lifetime, independent of checkpoint retention. Default: 15 minutes. */ ttlMs?: number; retention?: RuntimeRetentionPolicy; }; type PostgresFrameworkAdapter = ManagedFrameworkAdapter & { kind: "postgres"; checkpointer: PostgresCheckpointSaver; /** Closes owned connections. Call after in-flight executions have completed. */ close: () => Promise; }; declare function createPostgresFrameworkAdapter(options: CreatePostgresFrameworkAdapterOptions): PostgresFrameworkAdapter; type CheckpointId = string; type CheckpointSummary = { id: CheckpointId; sessionId: string; turnIndex: number; createdAt: number; nodes: string[]; workflow: string; label?: string; parentCheckpointId?: string; parentSessionId?: string; forkedFrom?: string; workflowVersion?: string; buildId?: string; /** PostgreSQL retains abandoned branches until their history window expires. */ branchStatus?: "active" | "abandoned"; }; type SessionCheckpointRecord = CheckpointSummary & { runId: string; graphCheckpointId?: string; state: GraphState; effects: { structuredStreamIds: string[]; interruptTokens: string[]; }; activePendingRequests: PendingRequestRecord[]; }; /** Exhaustive execution-field registry: additions to full records must be classified. */ declare const sessionCheckpointPayloadFields: readonly string[]; type AppendSessionCheckpointArgs = { sessionId: string; runId: string; graphCheckpointId?: string; workflow: string; state: GraphState; nodes?: string[]; structuredStreamIds?: string[]; pendingRequests?: PendingRequestRecord[]; label?: string; workflowVersion?: string; buildId?: string; }; type RollbackSessionCheckpointResult = { sessionId: string; head: CheckpointId; invalidatedStructuredStreamIds: string[]; invalidatedInterruptTokens: string[]; activePendingRequests: PendingRequestRecord[]; }; type ForkSessionCheckpointResult = { sessionId: string; parentSessionId: string; forkedFrom: CheckpointId; checkpoint: SessionCheckpointRecord; }; type SessionCheckpointStore = { /** The store publishes pending requests in the same transaction as the session transition. */ managesPendingRequests?: boolean; list: (sessionId: string) => Promise; get: (id: CheckpointId) => Promise; getHead: (sessionId: string) => Promise; append: (args: AppendSessionCheckpointArgs) => Promise; rollbackTo: (id: CheckpointId, options?: { preparePendingRequests?: (requests: PendingRequestRecord[]) => void; }) => Promise; fork: (id: CheckpointId, options?: { newSessionId?: string; preparePendingRequests?: (requests: PendingRequestRecord[]) => void; }) => Promise; }; type SessionCheckpointStoreOptions = { maxCheckpointsPerSession?: number; }; declare function createInMemorySessionCheckpointStore(options?: SessionCheckpointStoreOptions): SessionCheckpointStore; type FrameworkAdapter = { kind: "in-memory" | "redis" | "postgres"; pendingRequests: PendingRequestStore; sessionCheckpoints: SessionCheckpointStore; checkpointer: BaseCheckpointSaver; ttlMs: number; /** Optional for legacy custom adapters; required on every built-in adapter. */ maintenance?: RuntimeMaintenance; /** Optional for legacy custom adapters; closes owned connections. */ close?: () => Promise; /** Protects execution from concurrent retention cleanup. Released after the entire outcome is persisted. */ acquireRunLease?: (args: { runId: string; sessionId?: string; onLost: (cause: unknown) => void; }) => Promise<() => Promise>; /** * Best-effort cleanup for ephemeral framework state for a single run. * Called when a workflow completes without pausing for an interrupt. */ cleanupRun?: (runId: string, namespaces: string[]) => Promise; }; /** Shared lifecycle contract implemented by every built-in adapter. * FrameworkAdapter remains available for existing custom implementations. */ type ManagedFrameworkAdapter = FrameworkAdapter & { maintenance: RuntimeMaintenance; /** Close owned connections after in-flight executions finish. */ close: () => Promise; }; type CreateInMemoryFrameworkAdapterOptions = { ttlMs?: number; maxSessionCheckpoints?: number; }; declare function createInMemoryFrameworkAdapter(options?: CreateInMemoryFrameworkAdapterOptions): ManagedFrameworkAdapter; type CreateRedisFrameworkAdapterOptions = { url: string; ttlMs?: number; prefix?: string; maxSessionCheckpoints?: number; }; declare function createRedisFrameworkAdapter(options: CreateRedisFrameworkAdapterOptions): ManagedFrameworkAdapter; declare function createFrameworkAdapterFromEnv(env?: Record): (ManagedFrameworkAdapter & { kind: "in-memory" | "redis"; }) | PostgresFrameworkAdapter; type EvalExecutionState = "queued" | "running" | "completed" | "cancelled" | "unknown"; type EvalExecutionLimits = { maxActiveRuns: number; maxActiveAttempts: number; maxQueuedExecutions: number; }; type EvalExecutionJob = { id: string; scope: string; fingerprint: string; group: string; concurrency: number; weight: number; reserved: boolean; payload: Record; state: EvalExecutionState; createdAt: number; expiresAt: number; leaseOwner: string | null; leaseUntil: number; cancelRequested: boolean; sequence: number; bytes: number; }; type EvalExecutionEvent = { sequence: number; event: Record; }; type EvalExecutionSubmission = Pick & { queued: boolean; }; /** Admission and claims must be atomic across every handler/replica sharing a store. */ interface EvalExecutionStore { /** Renewal cadence; configure leases comfortably above scheduling/network delays. */ readonly heartbeatIntervalMs: number; /** Changes whenever deduplication history is lost; stable across durable replicas. */ generation(): Promise; submit(job: EvalExecutionSubmission, limits: EvalExecutionLimits): Promise; claim(owner: string, scope: string, limits: EvalExecutionLimits): Promise; /** Bounded snapshot of queued identities in this scope, after maintenance. */ queued?(scope: string): Promise; /** Atomic claim restricted to the retirement snapshot; never claim newer work. */ claimQueued?(owner: string, scope: string, limits: EvalExecutionLimits, ids: readonly string[]): Promise; get(id: string): Promise; status(id: string): Promise | undefined>; events(id: string, after: number): Promise; heartbeat(id: string, owner: string): Promise; append(id: string, owner: string, event: Record): Promise; finish(id: string, owner: string, state: "completed" | "cancelled"): Promise; cancel(id: string): Promise; } declare const evalExecutionError: (code: string, message: string, status?: number) => KortyxError; declare const evalExecutionUnknown: () => { type: string; message: string; failure: { version: number; code: string; category: string; message: string; retryable: boolean; }; }; declare const evalExecutionCancelled: () => { type: string; message: string; failure: { version: number; code: string; category: string; message: string; retryable: boolean; }; }; declare const evalExecutionExpired: () => { type: string; message: string; failure: { version: number; code: string; category: string; message: string; retryable: boolean; }; }; declare function validateEvalExecutionSubmission(input: EvalExecutionSubmission): void; declare const evalExecutionClone: (value: T) => T; declare function validateEvalExecutionLimits(limits: EvalExecutionLimits): void; /** Unknown jobs retain their capacity reservation until explicitly cancelled. */ declare function evalExecutionFits(jobs: EvalExecutionJob[], candidate: EvalExecutionSubmission | EvalExecutionJob, limits: EvalExecutionLimits): boolean; /** Single-process storage. Share one instance between handlers; use PostgreSQL across replicas. */ declare function createInMemoryEvalExecutionStore({ retentionMs, leaseMs, maxBytes, maxJobBytes, queueTimeoutMs, now, }?: { retentionMs?: number; leaseMs?: number; maxBytes?: number; maxJobBytes?: number; queueTimeoutMs?: number; now?: () => number; }): EvalExecutionStore; /** Durable admission, capacity and event replay, scoped independently from session checkpoints. */ declare function createPostgresEvalExecutionStore({ connectionString, namespace, retentionMs, leaseMs, maxBytes, maxJobBytes, queueTimeoutMs, }: { connectionString: string; namespace: string; retentionMs?: number; leaseMs?: number; maxBytes?: number; maxJobBytes?: number; queueTimeoutMs?: number; }): EvalExecutionStore & { setup(): Promise; close(): Promise; }; interface CompiledGraphBase { invoke(state: unknown, options?: Record): Promise; streamEvents(state: GraphState, options?: { version?: string; configurable?: Record; }): AsyncIterable | AsyncGenerator; } type ExecutionControl = { /** Internal: Response delivery belongs to the current invocation, not configuration. */ resumeDelivery?: ResumeDelivery | undefined; completeResponse?: ((options: _kortyx_hooks.CompleteResponseOptions, state: GraphState) => Promise) | undefined; abortSignal?: AbortSignal | undefined; budget?: _kortyx_core.ExecutionBudget | undefined; }; interface GraphExtensions { execution: ExecutionControl; name: string; config: ExecutionRuntimeConfig; resume(state: GraphState, input: unknown): Promise; timeTravelTo(state: GraphState, checkpointId: string): Promise; } interface ExecutionRuntimeConfig { prompts?: _kortyx_prompts.PromptExecution | undefined; executionRunId?: string | undefined; executionBranchId?: string | undefined; prepareChildTelemetry?: ((workflow: WorkflowDefinition, config: ExecutionRuntimeConfig) => ExecutionRuntimeConfig) | undefined; selectWorkflow?: ((id: string) => Promise) | undefined; workflowCallDepth?: number; invocationPath?: string; emit?: (event: string, payload: unknown) => void; onCheckpoint?: (args: { nodeId: string; state: GraphState; }) => void; checkpointer?: BaseCheckpointSaver; reasonTrace?: ReasonTraceAdapter | undefined; telemetry?: KortyxTelemetryConfig | undefined; getProvider?: GetProviderFn | undefined; [key: string]: unknown; } declare function createExecutionGraph(workflow: WorkflowDefinition, config: ExecutionRuntimeConfig, execution?: ExecutionControl): Promise; declare function makeResumeToken(): string; declare function makeRequestId(prefix?: string): string; declare function registerNode(id: string, fn: NodeFn): void; declare function getRegisteredNode(id: string): NodeFn | null; declare function listRegisteredNodes(): string[]; declare function clearRegisteredNodes(): void; declare function resolveNode(id: string): NodeFn; type AnyWorkflow = WorkflowDefinition; interface WorkflowRegistry { list: () => Promise; get: (id: string) => Promise; select: (id: string, options?: { fallbackId?: string; }) => Promise; refresh?: () => Promise; } interface FileWorkflowRegistryOptions { workflowsDir: string; fallbackId?: string; cache?: boolean; extensions?: string[]; } declare function createFileWorkflowRegistry(options: FileWorkflowRegistryOptions): WorkflowRegistry; declare function createInMemoryWorkflowRegistry(workflows: WorkflowDefinition[], options?: { fallbackId?: string; }): WorkflowRegistry; /** * Prepares the initial graph state from chat context, runtime state, and runtime config. * This stays deliberately generic in the config type so apps can shape it. */ interface InitialStateArgs { input: unknown; runtime: RuntimeEnvelope; config: Config; defaultWorkflowId?: string; } declare function buildInitialGraphState({ input, runtime, config, defaultWorkflowId, }: InitialStateArgs): Promise; export { type AppendSessionCheckpointArgs, type CheckpointId, type CheckpointSummary, type CreateCachingFrameworkAdapterOptions, type CreateInMemoryFrameworkAdapterOptions, type CreatePostgresFrameworkAdapterOptions, type CreateRedisFrameworkAdapterOptions, type EvalExecutionEvent, type EvalExecutionJob, type EvalExecutionLimits, type EvalExecutionState, type EvalExecutionStore, type EvalExecutionSubmission, type ExecutionControl, type ExecutionRuntimeConfig, type FileWorkflowRegistryOptions, type ForkSessionCheckpointResult, type FrameworkAdapter, type GraphSnapshotBundle, type HumanInputKind, type HumanInputOption, type InitialStateArgs, type ManagedFrameworkAdapter, type PendingRequestRecord, type PendingRequestStore, type PostgresFrameworkAdapter, type PruneRuntimeOptions, type PruneRuntimeResult, type ResumeDelivery, type RollbackSessionCheckpointResult, type RuntimeMaintenance, type RuntimeRetentionPolicy, type SessionCheckpointRecord, type SessionCheckpointStore, type SessionCheckpointStoreOptions, type WorkflowRegistry, acknowledgeResumeDelivery, buildInitialGraphState, captureGraphSnapshot, clearRegisteredNodes, createCachingFrameworkAdapter, createExecutionGraph, createFileWorkflowRegistry, createFrameworkAdapterFromEnv, createInMemoryEvalExecutionStore, createInMemoryFrameworkAdapter, createInMemoryPendingRequestStore, createInMemorySessionCheckpointStore, createInMemoryWorkflowRegistry, createPostgresEvalExecutionStore, createPostgresFrameworkAdapter, createRedisFrameworkAdapter, createResumeDelivery, evalExecutionCancelled, evalExecutionClone, evalExecutionError, evalExecutionExpired, evalExecutionFits, evalExecutionUnknown, getCheckpointer, getRegisteredNode, listRegisteredNodes, makeRequestId, makeResumeToken, prepareSuspensionSnapshot, registerNode, resolveNode, restoreGraphSnapshot, resumeDeliveryInput, sessionCheckpointPayloadFields, validateEvalExecutionLimits, validateEvalExecutionSubmission };