import * as _rivetkit_rivetkit_wasm from '@rivetkit/rivetkit-wasm'; import { z as z$2 } from 'zod'; import z$1, { z } from 'zod/v4'; import { Rivet } from '@rivetkit/engine-api-full'; import { Context, Handler, Hono } from 'hono'; import { UniversalWebSocket } from '@rivetkit/virtual-websocket'; import { StandardSchemaV1 } from '@standard-schema/spec'; import { ContentfulStatusCode } from 'hono/utils/http-status'; import { Logger } from 'pino'; type AnyDatabaseProvider = DatabaseProvider | undefined; interface ActorMetricsLike { totalKvReads: number; totalKvWrites: number; trackSql(query: string, durationMs: number): void; } type InferDatabaseClient = DBProvider extends DatabaseProvider ? Awaited> : RawAccess; type SqliteBindings = unknown[] | Record; interface SqliteQueryResult { columns: string[]; rows: unknown[][]; } interface SqliteExecuteResult extends SqliteQueryResult { changes: number; lastInsertRowId?: number | null; } interface SqliteBatchStatement { sql: string; params?: SqliteBindings; } interface SqliteTransactionOptions { /** Static operation name used to aggregate transaction performance. */ name?: string; /** Deadlock-safety timeout in milliseconds. */ timeout?: number; /** @experimental */ experimental?: { /** * Atomically includes actor and hibernatable connection state. * Only single-statement `execute` calls are supported in the transaction. * Concurrent actions that try to mutate state while the transaction is * active fail with `actor.state_transaction_conflict`. */ includeState?: boolean; }; } /** * SQLite profiling configuration. * * @experimental This entire configuration surface is experimental and subject * to change without notice. */ interface SqliteProfilingOptions { /** Exact SQL filter. Union with filterQueryFingerprints; both empty means all queries. */ filterQueries?: string[]; /** Fingerprint filter, including transaction fingerprints. Filters metrics, not diagnostic logs. */ filterQueryFingerprints?: string[]; /** Metric defaults apply even when omitted. Disabled metrics allocate no series. */ metrics?: SqliteProfilingMetricsOptions; /** Duration buckets in seconds. Default [0.01, 0.1, 1]. Positive, finite, strictly increasing. * All actors in a process enabling the duration histogram must use identical buckets. */ durationHistogramBucketsSeconds?: number[]; /** Maximum distinct statement fingerprints per process. Default: 512. */ maxTrackedStatementFingerprints?: number; maxTrackedTransactionFingerprints?: number; maxPrometheusSeries?: number; maxStatementsPerTransactionTrace?: number; maxGetPagesRequestsPerTrace?: number; maxTransactionNameBytes?: number; slowOperationThresholdMs?: number; baselineSampleRate?: number; maxDiagnosticEventsPerMinute?: number; diagnosticEventQueueCapacity?: number; } /** SQLite profiling metrics. Physical-request metrics and gauges have no query labels. */ interface SqliteProfilingMetricsOptions { /** Execution count and cumulative seconds. Uses histogram count/sum when enabled, otherwise counters. Default: true. */ duration?: boolean; /** Execution duration histogram. Only applies when duration is enabled. Default: true. */ durationHistogram?: boolean; /** Outcome counters, including success and errors. Default: true. */ outcomes?: boolean; /** Per-query timing phase histograms. Default: false. */ phaseDurationHistogram?: boolean; /** Storage round trips per operation histogram. Default: false. */ getPagesRoundTripsHistogram?: boolean; /** Statements per transaction histogram. Default: false. */ transactionStatementCountHistogram?: boolean; /** Per-query pages returned from storage, including returned prefetch pages. Default: true. */ pagesFetched?: boolean; /** Actor-level page counters by page kind (no query labels). Default: false. */ localPages?: boolean; /** Actor-level byte counters by byte kind (no query labels). Default: false. */ localBytes?: boolean; /** Actor-level physical storage request duration histogram. Default: false. */ getPagesDurationHistogram?: boolean; /** Actor-level pages per storage request histograms, by page kind. Default: false. */ getPagesPagesHistogram?: boolean; /** Actor-level storage response byte histogram. Default: false. */ getPagesResponseBytesHistogram?: boolean; /** Actor-level missing response page counter. Default: false. */ getPagesMissingPages?: boolean; /** Queued SQLite work, aggregated by actor name. Default: true. */ workerQueueDepth?: boolean; /** Executing SQLite work, aggregated by actor name. Default: true. */ workerInflight?: boolean; /** Transaction waiters, aggregated by actor name. Default: true. */ coordinatorQueueDepth?: boolean; /** Counts observations exceeding fingerprint or series limits. Default: true. */ fingerprintOverflow?: boolean; /** Counts diagnostic events dropped by rate limits or backpressure. Default: true. */ eventDropped?: boolean; } interface SqliteNativeMetrics { requestBuildNs: number; serializeNs: number; transportNs: number; stateUpdateNs: number; totalNs: number; commitCount: number; pageCacheEntries: number; pageCacheWeightedSize: number; pageCacheCapacityPages: number; writeBufferDirtyPages: number; dbSizePages: number; } interface SqliteDatabase { exec(sql: string, callback?: (row: unknown[], columns: string[]) => void): Promise; execute(sql: string, params?: SqliteBindings): Promise; executeBatch(statements: SqliteBatchStatement[]): Promise; beginTransaction(timeoutMs?: number, name?: string): Promise; run(sql: string, params?: SqliteBindings): Promise; query(sql: string, params?: SqliteBindings): Promise; nativeMetrics?(): SqliteNativeMetrics | Promise | null; close(): Promise; } interface SqliteTransactionDatabase { exec(sql: string, callback?: (row: unknown[], columns: string[]) => void): Promise; execute(sql: string, params?: SqliteBindings): Promise; commit(): Promise; rollback(): Promise; } /** * Provider for opening native databases from the active runtime. */ interface NativeDatabaseProvider { open(actorId: string): Promise; } /** * Context provided to database providers for creating database clients */ interface DatabaseProviderContext { /** * Actor ID */ actorId: string; /** * Override the default Drizzle database client (optional). * If not provided, a KV-backed client will be constructed. */ overrideDrizzleDatabaseClient?: () => Promise; /** KV operations exposed for custom database providers. */ kv: { batchPut: (entries: [Uint8Array, Uint8Array][]) => Promise; batchGet: (keys: Uint8Array[]) => Promise<(Uint8Array | null)[]>; batchDelete: (keys: Uint8Array[]) => Promise; deleteRange: (start: Uint8Array, end: Uint8Array) => Promise; }; /** * Actor metrics instance. When provided, KV and SQL operations are tracked. */ metrics?: ActorMetricsLike; /** * Logger for debug output. When provided, SQL queries are logged with * duration and KV call count. */ log?: { debug(obj: Record): void; }; /** * Provider for opening native databases from the active runtime. */ nativeDatabaseProvider?: NativeDatabaseProvider; } type DatabaseProvider = { /** * Local SQLite profiling controls consumed by the actor runtime. * * @experimental This entire configuration surface is experimental and * subject to change without notice. */ sqliteProfiling?: SqliteProfilingOptions; /** * Creates a new database client for the actor. * The result is passed to the actor context as `c.db`. * @experimental */ createClient: (ctx: DatabaseProviderContext) => Promise; /** * Runs before the actor has started. * Use this to run migrations or other setup tasks. * @experimental */ onMigrate: (client: DB) => void | Promise; }; /** * Drizzle database client interface (will be extended by drizzle-orm types) */ type DrizzleDatabaseClient = {}; type ExecuteFunction = = Record>(query: string, ...args: unknown[]) => Promise; type RawAccess = { /** * Executes a raw SQL query. */ execute: ExecuteFunction; /** Runs a callback in an isolated SQLite transaction. */ transaction: (callback: (tx: RawAccess) => Promise | T, options?: SqliteTransactionOptions) => Promise; /** * Returns native SQLite metrics when the active runtime supports them. */ nativeMetrics?: () => SqliteNativeMetrics | Promise | null; /** * Closes the database connection and releases resources. */ close: () => Promise; }; /** A namespace-scoped Engine grant. The caller must provide every grant explicitly. */ type TokenGrant = Rivet.AuthTokenGrant; /** Options for `client.auth.issueToken()`. `expiresIn` is in seconds. */ type IssueTokenOptions = Pick & { expiresIn?: Rivet.AuthTokenCreateRequest["duration"]; }; /** Token timestamps are Unix milliseconds. */ interface IssuedToken { token: Rivet.AuthTokenCreateResponse["token"]; issuedAt: Rivet.AuthTokenCreateResponse["issuedTs"]; expiresAt: Rivet.AuthTokenCreateResponse["expiresTs"]; } /** Resources that can be scoped to a single actor ID. */ type ActorTokenResource = Extract; type ActorTokenPermissions = Partial>; /** Options for `actor.issueToken()`. Omit permissions for gateway read access only. */ type ActorIssueTokenOptions = Pick & { permissions?: ActorTokenPermissions; }; declare const EncodingSchema: z.ZodEnum<{ json: "json"; cbor: "cbor"; bare: "bare"; }>; /** * Encoding used to communicate between the client & actor. */ type Encoding = z.infer; declare const ActorKeySchema: z.ZodArray; type ActorKey = z.infer; /** * Crash policy for actor lifecycle management. * * This schema is only used by the engine driver for actor creation. The manager * driver ignores crash policy and passes it through to the engine unchanged. */ declare const CrashPolicySchema: z.ZodEnum<{ restart: "restart"; sleep: "sleep"; destroy: "destroy"; }>; type CrashPolicy = z.infer; declare const CreateRequestSchema: z.ZodObject<{ name: z.ZodString; key: z.ZodArray; input: z.ZodOptional; region: z.ZodOptional; poolName: z.ZodOptional; }, z.core.$strip>; declare const ActorQuerySchema: z.ZodUnion; }, z.core.$strip>, z.ZodObject<{ getForKey: z.ZodObject<{ name: z.ZodString; key: z.ZodArray; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ getOrCreateForKey: z.ZodObject<{ name: z.ZodString; key: z.ZodArray; input: z.ZodOptional; region: z.ZodOptional; poolName: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ create: z.ZodObject<{ name: z.ZodString; key: z.ZodArray; input: z.ZodOptional; region: z.ZodOptional; poolName: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>]>; type ActorQuery = z.infer; /** * Interface representing a request to create a actor. */ type CreateRequest = z.infer; type SchemaHookResult = boolean | Promise; type SchemaHook = (ctx: TContext) => SchemaHookResult; interface EventTypeToken { readonly _eventType?: T; readonly canSubscribe?: SchemaHook; readonly schema?: PrimitiveSchema; } interface QueueTypeToken { readonly _queueMessage?: TMessage; readonly _queueComplete?: TComplete; /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ readonly canPublish?: SchemaHook; readonly message?: PrimitiveSchema; readonly complete?: PrimitiveSchema; } type PrimitiveSchema = StandardSchemaV1 | EventTypeToken; interface EventSchemaDefinition { schema: PrimitiveSchema; canSubscribe?: SchemaHook; } interface QueueSchemaDefinition { message: PrimitiveSchema; complete?: PrimitiveSchema; /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ canPublish?: SchemaHook; } type EventSchema = PrimitiveSchema | EventSchemaDefinition; type QueueSchema = PrimitiveSchema | QueueSchemaDefinition | QueueTypeToken; type EventSchemaConfig = Record>; type QueueSchemaConfig<_TContext = any> = Record; type InferSchema = T extends QueueSchemaDefinition ? InferSchema : T extends QueueTypeToken ? M : T extends EventSchemaDefinition ? InferSchema : T extends StandardSchemaV1 ? O : T extends EventTypeToken ? R : never; type InferSchemaMap> = { [K in keyof T]: InferSchema; }; type InferQueueComplete = T extends QueueTypeToken ? [C] extends [never] ? never : C : T extends QueueSchemaDefinition ? T["complete"] extends PrimitiveSchema ? InferSchema : never : never; type InferQueueCompleteMap = { [K in keyof T]: InferQueueComplete; }; type InferEventArgs = T extends readonly unknown[] ? number extends T["length"] ? [T] : T : [T]; interface DeconstructedError { __type: "ActorError"; statusCode: ContentfulStatusCode; public: boolean; group: string; code: string; message: string; metadata?: unknown; rayId?: string; actor?: ActorSpecifier; } interface RivetErrorOptions extends ErrorOptions { /** Error data can safely be serialized in a response to the client. */ public?: boolean; /** Metadata associated with this error. */ metadata?: unknown; /** Request identifier used to correlate this error with engine logs. */ rayId?: string; /** Explicit HTTP status override for router responses. */ statusCode?: number; /** Actor context associated with this error. */ actor?: ActorSpecifier; } /** Identifies the actor that was handling work when an error was produced. */ interface ActorSpecifier { actorId: string; generation: number; key?: string; } interface UserErrorOptions extends ErrorOptions { /** * Machine readable code for this error. Useful for catching different types of * errors in try-catch. */ code?: string; /** * Additional metadata related to the error. Useful for understanding context * about the error. */ metadata?: unknown; } declare class RivetError extends Error { __type: "RivetError"; public: boolean; metadata?: unknown; readonly rayId?: string; statusCode: number; actor?: ActorSpecifier; readonly group: string; readonly code: string; static isRivetError(error: unknown): error is RivetError | DeconstructedError; static isActorError(error: unknown): error is RivetError | DeconstructedError; constructor(group: string, code: string, message: string, options?: RivetErrorOptions | unknown); toString(): string; } declare class UserError extends RivetError { constructor(message: string, options?: UserErrorOptions); } /** Sample rates keyed by action name, nested like the actor's action groups. */ interface ActionSampleRates { readonly [name: string]: number | ActionSampleRates; } /** * {@link ActionSampleRates} limited to the actions of one actor, so a rate for * an action that does not exist is a compile error. */ type ActionTraceSamplers = { readonly [K in keyof TActions]?: TActions[K] extends (...args: never[]) => unknown ? number : ActionTraceSamplers; }; /** Trace sampling for one actor definition. */ interface ActorTracingOptions { /** * Share of this actor's invocations that are recorded, from 0 to 1. A rate * lowers what is recorded and never raises it, so an invocation inside a * trace the caller did not record is not recorded at any rate. */ readonly sampler?: number; /** Rates that replace `sampler` for single actions. */ readonly actions?: ActionTraceSamplers; } type UpgradeWebSocket = (createEvents: (c: Context) => any) => Handler; type GetUpgradeWebSocket = () => UpgradeWebSocket; type GatewayTarget = { directId: string; } | ActorQuery; interface GatewayRequestOptions { skipReadyWait?: boolean; } interface EngineControlClient { issueToken(options: IssueTokenOptions): Promise; getForId(input: GetForIdInput): Promise; getWithKey(input: GetWithKeyInput): Promise; getOrCreateWithKey(input: GetOrCreateWithKeyInput): Promise; createActor(input: CreateInput): Promise; /** Forks the actor `actorId` into a new actor of the same name, started on a copy of its database. */ forkActor(input: ForkInput): Promise; listActors(input: ListActorsInput): Promise; sendRequest(target: GatewayTarget, actorRequest: Request, options?: GatewayRequestOptions): Promise; openWebSocket(path: string, target: GatewayTarget, encoding: Encoding, params: unknown, options?: GatewayRequestOptions): Promise; /** Refresh a credential rejected during this WebSocket handshake, if supported. */ refreshAuthToken?(ws: UniversalWebSocket): Promise; proxyRequest(c: Context, actorRequest: Request, actorId: string): Promise; proxyWebSocket(c: Context, path: string, actorId: string, encoding: Encoding, params: unknown): Promise; buildGatewayUrl(target: GatewayTarget, options?: GatewayRequestOptions): Promise; displayInformation(): RuntimeDisplayInformation; extraStartupLog?: () => Record; modifyRuntimeRouter?: (config: RegistryConfig, router: Hono) => void; setGetUpgradeWebSocket(getUpgradeWebSocket: GetUpgradeWebSocket): void; shutdown?(): void; /** * Test-only helper that simulates an abrupt actor crash. */ hardCrashActor?(actorId: string): Promise; } interface RuntimeDisplayInformation { properties: Record; } interface GetForIdInput { c?: Context | undefined; name: string; actorId: string; } interface GetWithKeyInput { c?: Context | undefined; name: string; key: ActorKey; } interface GetOrCreateWithKeyInput { c?: Context | undefined; name: string; key: ActorKey; input?: unknown; region?: string; crashPolicy?: CrashPolicy; /** Overrides the client's configured pool name for this actor. */ poolName?: string; } interface CreateInput { c?: Context | undefined; name: string; key: ActorKey; input?: unknown; region?: string; crashPolicy?: CrashPolicy; /** Overrides the client's configured pool name for this actor. */ poolName?: string; } interface ForkInput { c?: Context | undefined; /** The source actor. */ actorId: string; /** The new actor's key; omitted for a keyless actor. */ key?: ActorKey; /** The fork input, given to the new actor's `onFork` hook. */ input?: unknown; } interface ListActorsInput { c?: Context | undefined; name: string; key?: string; includeDestroyed?: boolean; } interface ActorOutput { actorId: string; name: string; key: ActorKey; createTs?: number; startTs?: number | null; connectableTs?: number | null; sleepTs?: number | null; destroyTs?: number | null; error?: unknown; } /** Correlation owned by the currently executing Core actor invocation. */ interface ActorInvocationTraceContext { /** Ray ID the invocation received, absent when nothing upstream supplied one. */ readonly rayId?: string; /** Core-owned invocation span context, absent when tracing is disabled. */ readonly span?: ActorInvocationSpanContext; } /** W3C span context of the Core invocation span. */ interface ActorInvocationSpanContext { /** W3C trace identifier. */ readonly traceId: string; /** W3C span identifier for the Core invocation. */ readonly spanId: string; /** OpenTelemetry trace flags encoded as an integer. */ readonly traceFlags: number; /** Optional vendor trace state inherited by the Core invocation. */ readonly tracestate?: string; } declare const handleBrand: unique symbol; type OpaqueHandle = { readonly [handleBrand]: Name; }; type RegistryHandle = OpaqueHandle<"registry">; type ActorFactoryHandle = OpaqueHandle<"actorFactory">; type ActorContextHandle = OpaqueHandle<"actorContext">; type ConnHandle = OpaqueHandle<"conn">; type WebSocketHandle = OpaqueHandle<"webSocket">; type CancellationTokenHandle = OpaqueHandle<"cancellationToken">; type ActorStateTransactionHandle = OpaqueHandle<"actorStateTransaction">; type SqliteTransactionHandle = OpaqueHandle<"sqliteTransaction">; type RuntimeBytes = Uint8Array; interface RuntimeActorKeySegment { kind: string; stringValue?: string; numberValue?: number; } /** One individual actor fork behind an actor, as the runtime reports it. */ interface RuntimeForkLink { actorId: string; key: RuntimeActorKeySegment[]; forkedAt: number; } /** Resolves correlation at operation time so retained clients cannot freeze stale context. */ type CurrentActorInvocation = () => ActorInvocationTraceContext | undefined; /** One open call from an actor out to another actor. */ interface RuntimeOutboundCall { /** * W3C context of the call's own span, to send to the callee so it parents to * the call. Absent when tracing is disabled. */ readonly span?: ActorInvocationSpanContext; /** * Records the call's outcome. `error` is the failure encoded the way the * bridge encodes errors, so a structured error keeps its group and code. */ finish(error?: string): void; } /** * Opens the span covering one call out to another actor, or returns `undefined` * outside an invocation or on a runtime without invocation telemetry. Callers * send their own context when it returns nothing. */ type StartCallSpan = (actorName: string, actionName: string) => RuntimeOutboundCall | undefined; interface RuntimeHttpRequest { method: string; uri: string; headers?: Record; body?: RuntimeBytes; } interface RuntimeHttpResponseBodyStream { cancelled(): Promise; write(chunk: Uint8Array): Promise; end(): Promise; error(message: string): Promise; } interface RuntimeStateDeltaPayload { state?: RuntimeBytes; connHibernation: Array<{ connId: string; bytes: RuntimeBytes; }>; connHibernationRemoved: string[]; } interface RuntimeWorkflowKvWrite { key: RuntimeBytes; value: RuntimeBytes; } interface RuntimeRequestSaveOpts { immediate?: boolean; maxWaitMs?: number; } interface RuntimeInspectorSnapshot { stateRevision: number; connectionsRevision: number; queueRevision: number; activeConnections: number; queueSize: number; connectedClients: number; } interface RuntimeQueueMessage { id(): bigint; name(): string; body(): RuntimeBytes; createdAt(): number; isCompletable(): boolean; complete(response?: RuntimeBytes | undefined | null): Promise; } interface RuntimeQueueInspectMessage { id: number; name: string; createdAtMs: number; } interface RuntimeScheduledEventInfo { id: string; action: string; args: RuntimeBytes; runAt: number; } interface RuntimeCronJobInfo { name: string; kind: "cron" | "every"; action: string; args: RuntimeBytes; nextRunAt: number; lastRunAt?: number; expression?: string; timezone?: string; intervalMs?: number; maxHistory: number; } interface RuntimeScheduleErrorInfo { group: string; code: string; message: string; metadata?: unknown; } interface RuntimeCronFire { action: string; scheduledAt: number; firedAt: number; finishedAt?: number; result: "running" | "ok" | "error" | "skipped"; error?: RuntimeScheduleErrorInfo; } interface RuntimeQueueNextBatchOptions { names?: string[]; count?: number; timeoutMs?: number; completable?: boolean; } interface RuntimeQueueWaitOptions { timeoutMs?: number; completable?: boolean; } interface RuntimeQueueEnqueueAndWaitOptions { timeoutMs?: number; } interface RuntimeQueueTryNextBatchOptions { names?: string[]; count?: number; completable?: boolean; } interface RuntimeKvListOptions { reverse?: boolean; limit?: number; } interface RuntimeKvEntry { key: RuntimeBytes; value: RuntimeBytes; } type RuntimeSqlBindNoValues = { intValue?: never; floatValue?: never; textValue?: never; blobValue?: never; }; type RuntimeSqlBindParam = ({ kind: "null"; } & RuntimeSqlBindNoValues) | { kind: "int"; intValue: number; floatValue?: never; textValue?: never; blobValue?: never; } | { kind: "float"; intValue?: never; floatValue: number; textValue?: never; blobValue?: never; } | { kind: "text"; intValue?: never; floatValue?: never; textValue: string; blobValue?: never; } | { kind: "blob"; intValue?: never; floatValue?: never; textValue?: never; blobValue: RuntimeBytes; }; type RuntimeSqlBindParams = RuntimeSqlBindParam[] | null; interface RuntimeSqlQueryResult { columns: string[]; rows: unknown[][]; } type RuntimeSqlExecResult = RuntimeSqlQueryResult; interface RuntimeSqlExecuteResult extends RuntimeSqlQueryResult { changes: number; lastInsertRowId?: number | null; } interface RuntimeSqlBatchStatement { sql: string; params?: RuntimeSqlBindParams; } interface RuntimeSqlRunResult { changes: number; } /** Sample rates for the traces an actor starts, in the shape core takes. */ interface RuntimeActorTracingConfig { sampler?: number; /** Keyed by flattened, dot-separated action name. */ actions?: Record; } interface RuntimeActorConfig { name?: string; icon?: string; hasDatabase?: boolean; remoteSqlite?: boolean; sqliteProfiling?: SqliteProfilingOptions; tracing?: RuntimeActorTracingConfig; hasState?: boolean; canHibernateWebsocket?: boolean; stateSaveIntervalMs?: number; createStateTimeoutMs?: number; onCreateTimeoutMs?: number; createVarsTimeoutMs?: number; createConnStateTimeoutMs?: number; onBeforeConnectTimeoutMs?: number; onConnectTimeoutMs?: number; onMigrateTimeoutMs?: number; onWakeTimeoutMs?: number; onBeforeActorStartTimeoutMs?: number; actionTimeoutMs?: number; onRequestTimeoutMs?: number; sleepTimeoutMs?: number; noSleep?: boolean; sleepGracePeriodMs?: number; connectionLivenessTimeoutMs?: number; connectionLivenessIntervalMs?: number; maxQueueSize?: number; maxSchedules?: number; maxQueueMessageSize?: number; maxIncomingMessageSize?: number; maxOutgoingMessageSize?: number; preloadMaxWorkflowBytes?: number; preloadMaxConnectionsBytes?: number; actions?: Array<{ name: string; }>; inspectorTabs?: Array; } interface RuntimeInspectorTabEntry { id: string; /** Required for custom entries; omitted for built-in hides. */ label?: string; /** * Required for custom entries — absolute path to the source directory. * Resolved on the TS side before being handed to the runtime. */ source?: string; /** Optional icon id for custom entries. */ icon?: string; /** Set to true for built-in hide entries. */ hidden?: boolean; } interface RuntimeServeConfig { version: number; endpoint: string; token?: string; namespace: string; poolName: string; engineBinaryPath?: string; startServices?: boolean; servicesBinaryPath?: string; /** Whether config resolution selected a managed local development engine. */ engineSpawn?: boolean; engineHost?: string; enginePort?: number; handleInspectorHttpInRuntime?: boolean; inspectorTestToken?: string; serverlessBasePath?: string; serverlessPackageVersion: string; serverlessClientEndpoint?: string; serverlessClientNamespace?: string; serverlessClientToken?: string; serverlessValidateEndpoint: boolean; serverlessMaxStartPayloadBytes: number; } interface RuntimeListenerConfig { port: number; host?: string; publicDir?: string; application?: RuntimeApplicationFetch; } interface RuntimeServerlessRequest { method: string; url: string; headers: Record; body: RuntimeBytes; } interface RuntimeApplicationRequest extends RuntimeServerlessRequest { cancelToken?: CancellationTokenHandle; } interface RuntimeApplicationResponse { status: number; headers: Record; body?: RuntimeBytes; stream?: boolean; } type RuntimeApplicationFetch = (request: RuntimeApplicationRequest, responseBodyStream?: RuntimeHttpResponseBodyStream) => Promise; interface RuntimeApplicationListenerConfig extends RuntimeListenerConfig { application: RuntimeApplicationFetch; } interface RuntimeServerlessResponseHead { status: number; headers: Record; } interface RuntimeRegistryRouteResponse { status: number; headers: Record; body: RuntimeBytes; } type RuntimeServerlessStreamEvent = { kind: "chunk"; chunk?: RuntimeBytes; } | { kind: "end"; error?: { group: string; code: string; message: string; }; }; type RuntimeServerlessStreamCallback = (error: unknown, event?: RuntimeServerlessStreamEvent) => unknown; type RuntimeWebSocketEvent = { kind: "message"; data: string | RuntimeBytes; binary: boolean; messageIndex?: number; } | { kind: "close"; code: number; reason: string; wasClean: boolean; }; interface CoreRuntime { readonly kind: "napi" | "wasm"; createRegistry(): RegistryHandle; registerActor(registry: RegistryHandle, name: string, factory: ActorFactoryHandle): void; serveRegistry(registry: RegistryHandle, config: RuntimeServeConfig): Promise; waitRegistryReady(registry: RegistryHandle): Promise; shutdownRegistry(registry: RegistryHandle): Promise; shutdownTelemetry?(): Promise; registryActorStopThresholdMs?(registry: RegistryHandle): Promise; registryActiveActorCount?(registry: RegistryHandle): number; onRegistryActiveActorCountChange?(registry: RegistryHandle, callback: (count: number) => void, cancelToken: CancellationTokenHandle): void; handleServerlessRequest(registry: RegistryHandle, req: RuntimeServerlessRequest, onStreamEvent: RuntimeServerlessStreamCallback, cancelToken: CancellationTokenHandle, config: RuntimeServeConfig): Promise; serveListener(registry: RegistryHandle, listener: RuntimeListenerConfig, config: RuntimeServeConfig): Promise; serveApplicationListener(registry: RegistryHandle, listener: RuntimeApplicationListenerConfig, config: RuntimeServeConfig): Promise; registryHealth?(registry: RegistryHandle): Promise; registryMetadata?(registry: RegistryHandle): Promise; registryMetrics?(registry: RegistryHandle): Promise; createActorFactory(callbacks: object, config?: RuntimeActorConfig | undefined | null): ActorFactoryHandle; createCancellationToken(): CancellationTokenHandle; cancellationTokenAborted(token: CancellationTokenHandle): boolean; cancelCancellationToken(token: CancellationTokenHandle): void; /** * Calls `callback` once when `token` is cancelled. Returns a release * function that drops the registration without calling `callback`; call it * once cancellation no longer matters so the native listener is freed. */ onCancellationTokenCancelled(token: CancellationTokenHandle, callback: (...args: unknown[]) => unknown): () => void; actorState(ctx: ActorContextHandle): RuntimeBytes; actorBeginOnStateChange(ctx: ActorContextHandle): void; actorEndOnStateChange(ctx: ActorContextHandle): void; actorSetAlarm(ctx: ActorContextHandle, timestampMs?: number | undefined | null): void; actorSetRunWakeAt(ctx: ActorContextHandle, timestampMs?: number | undefined | null): Promise; actorRequestSave(ctx: ActorContextHandle, opts?: RuntimeRequestSaveOpts | undefined | null): void; actorRequestSaveAndWait(ctx: ActorContextHandle, opts?: RuntimeRequestSaveOpts | undefined | null): Promise; actorInspectorSnapshot(ctx: ActorContextHandle): RuntimeInspectorSnapshot; actorDecodeInspectorRequest(ctx: ActorContextHandle, bytes: RuntimeBytes, advertisedVersion: number): RuntimeBytes; actorEncodeInspectorResponse(ctx: ActorContextHandle, bytes: RuntimeBytes, targetVersion: number): RuntimeBytes; actorVerifyInspectorAuth(ctx: ActorContextHandle, bearerToken?: string | undefined | null): Promise; actorQueueHibernationRemoval(ctx: ActorContextHandle, connId: string): void; actorTakePendingHibernationChanges(ctx: ActorContextHandle): string[]; actorDirtyHibernatableConns(ctx: ActorContextHandle): ConnHandle[]; actorSaveState(ctx: ActorContextHandle, payload: RuntimeStateDeltaPayload): Promise; actorSaveStateAndWorkflowBatch(ctx: ActorContextHandle, writes: RuntimeWorkflowKvWrite[]): Promise; actorId(ctx: ActorContextHandle): string; /** * Runs one actor callback with `ctx` as the current invocation: operations * on retained handles for the same actor resolve to it, and its Core span * is the active OpenTelemetry span for the duration of `run`. Only actions, * raw requests, and queue dispatch run this way; other callbacks have no * invocation span. */ runWithActorInvocationContext(ctx: ActorContextHandle, run: () => T): T; /** * Correlation of the invocation currently executing for this actor, or * `undefined` outside an invocation or after it finished. A sampled-out * invocation can still expose valid span context for propagation. */ actorInvocationTraceContext(ctx: ActorContextHandle): ActorInvocationTraceContext | undefined; /** * Opens the span covering one call this actor makes to another actor. See * `StartCallSpan` for when this returns nothing. */ startCallSpan(ctx: ActorContextHandle, actorName: string, actionName: string): RuntimeOutboundCall | undefined; /** Backs `ActorRun.startWorkflowSpan`. */ startWorkflowSpan(ctx: ActorContextHandle): Promise; /** Backs `ActorRun.runOutsideWorkflowSpan`. */ runOutsideActorInvocationContext(run: () => T): T; /** Identity of the invocation the caller runs in, usable as a cache key. */ currentInvocationScope(): object | undefined; actorName(ctx: ActorContextHandle): string; actorKey(ctx: ActorContextHandle): RuntimeActorKeySegment[]; /** The individual actor forks behind the actor, oldest first. */ actorForkChain(ctx: ActorContextHandle): RuntimeForkLink[]; actorRegion(ctx: ActorContextHandle): string; /** The name of the namespace the actor runs in. */ actorNamespace(ctx: ActorContextHandle): string; actorSleep(ctx: ActorContextHandle): void; actorDestroy(ctx: ActorContextHandle): void; actorAbortSignal(ctx: ActorContextHandle): AbortSignal; actorConns(ctx: ActorContextHandle): ConnHandle[]; actorConnectConn(ctx: ActorContextHandle, params: RuntimeBytes, request?: RuntimeHttpRequest | undefined | null): Promise; actorBroadcast(ctx: ActorContextHandle, name: string, args: RuntimeBytes): void; actorWaitUntil(ctx: ActorContextHandle, promise: Promise): void; actorWaitForTrackedShutdownWork(ctx: ActorContextHandle): Promise; actorWaitForTrackedShutdownWorkUnbounded(ctx: ActorContextHandle): Promise; actorKeepAwake(ctx: ActorContextHandle, promise: Promise): void; actorBeginKeepAwake(ctx: ActorContextHandle): number; actorEndKeepAwake(ctx: ActorContextHandle, regionId: number): void; actorRegisterTask(ctx: ActorContextHandle, promise: Promise): void; actorRuntimeState(ctx: ActorContextHandle): object; actorClearRuntimeState(ctx: ActorContextHandle): void; actorRestartRunHandler(ctx: ActorContextHandle): void; actorBeginWebsocketCallback(ctx: ActorContextHandle): number; actorEndWebsocketCallback(ctx: ActorContextHandle, regionId: number): void; actorKvGet(ctx: ActorContextHandle, key: RuntimeBytes): Promise; actorKvPut(ctx: ActorContextHandle, key: RuntimeBytes, value: RuntimeBytes): Promise; actorKvDelete(ctx: ActorContextHandle, key: RuntimeBytes): Promise; actorKvDeleteRange(ctx: ActorContextHandle, start: RuntimeBytes, end: RuntimeBytes): Promise; actorKvListPrefix(ctx: ActorContextHandle, prefix: RuntimeBytes, options?: RuntimeKvListOptions | undefined | null): Promise; actorKvListRange(ctx: ActorContextHandle, start: RuntimeBytes, end: RuntimeBytes, options?: RuntimeKvListOptions | undefined | null): Promise; actorKvBatchGet(ctx: ActorContextHandle, keys: RuntimeBytes[]): Promise>; actorKvBatchPut(ctx: ActorContextHandle, entries: RuntimeKvEntry[]): Promise; actorKvBatchDelete(ctx: ActorContextHandle, keys: RuntimeBytes[]): Promise; actorSqlExec(ctx: ActorContextHandle, sql: string): Promise; actorSqlExecute(ctx: ActorContextHandle, sql: string, params?: RuntimeSqlBindParams): Promise; actorSqlExecuteBatch(ctx: ActorContextHandle, statements: RuntimeSqlBatchStatement[]): Promise; actorSqlBeginTransaction(ctx: ActorContextHandle, timeoutMs?: number, name?: string): Promise; actorSqlTransactionExec(transaction: SqliteTransactionHandle, sql: string): Promise; actorSqlTransactionExecute(transaction: SqliteTransactionHandle, sql: string, params?: RuntimeSqlBindParams): Promise; actorSqlTransactionCommit(transaction: SqliteTransactionHandle): Promise; actorSqlTransactionRollback(transaction: SqliteTransactionHandle): Promise; actorBeginStateTransaction(ctx: ActorContextHandle, timeoutMs?: number): Promise; actorStateTransactionExecute(transaction: ActorStateTransactionHandle, sql: string, params?: RuntimeSqlBindParams): Promise; actorStateTransactionCommit(transaction: ActorStateTransactionHandle, payload: RuntimeStateDeltaPayload): Promise; actorStateTransactionRollback(transaction: ActorStateTransactionHandle): Promise; actorSqlQuery(ctx: ActorContextHandle, sql: string, params?: RuntimeSqlBindParams): Promise; actorSqlRun(ctx: ActorContextHandle, sql: string, params?: RuntimeSqlBindParams): Promise; actorSqlMetrics(ctx: ActorContextHandle): SqliteNativeMetrics | null; actorSqlTakeLastKvError(ctx: ActorContextHandle): string | null; actorSqlClose(ctx: ActorContextHandle): Promise; actorQueueSend(ctx: ActorContextHandle, name: string, body: RuntimeBytes): Promise; actorQueueNextBatch(ctx: ActorContextHandle, options?: RuntimeQueueNextBatchOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null): Promise; actorQueueWaitForNames(ctx: ActorContextHandle, names: string[], options?: RuntimeQueueWaitOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null): Promise; actorQueueWaitForNamesAvailable(ctx: ActorContextHandle, names: string[], options?: RuntimeQueueWaitOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null): Promise; actorQueueCompletePersisted(ctx: ActorContextHandle, messageId: bigint, expectedName: string, response?: RuntimeBytes | undefined | null): Promise; actorQueueEnqueueAndWait(ctx: ActorContextHandle, name: string, body: RuntimeBytes, options?: RuntimeQueueEnqueueAndWaitOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null): Promise; actorQueueTryNextBatch(ctx: ActorContextHandle, options?: RuntimeQueueTryNextBatchOptions | undefined | null): RuntimeQueueMessage[]; actorQueueMaxSize(ctx: ActorContextHandle): number; actorQueueInspectMessages(ctx: ActorContextHandle): Promise; actorQueueReset(ctx: ActorContextHandle): Promise; actorScheduleAfter(ctx: ActorContextHandle, durationMs: number, actionName: string, args: RuntimeBytes): Promise; actorScheduleAt(ctx: ActorContextHandle, timestampMs: number, actionName: string, args: RuntimeBytes): Promise; actorScheduleCancel(ctx: ActorContextHandle, id: string): Promise; actorScheduleGet(ctx: ActorContextHandle, id: string): Promise; actorScheduleList(ctx: ActorContextHandle): Promise; actorCronSet(ctx: ActorContextHandle, name: string, expression: string, timezone: string | undefined, actionName: string, args: RuntimeBytes, maxHistory: number | undefined): Promise; actorCronEvery(ctx: ActorContextHandle, name: string, intervalMs: number, actionName: string, args: RuntimeBytes, maxHistory: number | undefined): Promise; actorCronGet(ctx: ActorContextHandle, name: string): Promise; actorCronList(ctx: ActorContextHandle): Promise; actorCronDelete(ctx: ActorContextHandle, name: string): Promise; actorCronHistory(ctx: ActorContextHandle, name: string, limit: number | undefined): Promise; connId(conn: ConnHandle): string; connParams(conn: ConnHandle): RuntimeBytes; connState(conn: ConnHandle): RuntimeBytes; connSetState(conn: ConnHandle, state: RuntimeBytes): void; connIsHibernatable(conn: ConnHandle): boolean; connSend(conn: ConnHandle, name: string, args: RuntimeBytes): void; connDisconnect(conn: ConnHandle, reason?: string | undefined | null): Promise; webSocketSend(ws: WebSocketHandle, data: RuntimeBytes, binary: boolean): void; webSocketClose(ws: WebSocketHandle, code?: number | undefined | null, reason?: string | undefined | null): Promise; webSocketSetEventCallback(ws: WebSocketHandle, callback: (event: RuntimeWebSocketEvent) => void): void; } interface QueueSendWaitOptions { wait: true; timeout?: number; signal?: AbortSignal; } interface QueueSendNoWaitOptions { wait?: false; timeout?: never; signal?: AbortSignal; } interface QueueSendResult { status: "completed" | "timedOut"; response?: TResponse; } /** * Action function returned by Actor connections and handles. * * @typedef {Function} ActorActionFunction * @template Args * @template Response * @param {...Args} args - Arguments for the action function. * @returns {Promise} */ type ActorActionFunction = unknown[], Response = unknown> = (...args: Args extends [unknown, ...infer Rest] ? Rest : Args) => Promise; type IsAny = 0 extends 1 & T ? true : false; type LooseEventSubscribe = (eventName: string, callback: (...args: any[]) => void) => () => void; type ActorActionMap = { [K in keyof NonNullable]: NonNullable[K] extends (...args: infer Args) => infer Return ? ActorActionFunction> : NonNullable[K] extends Record ? ActorActionMap[K]> : never; }; type ActionsOf = AD["config"] extends { actions?: infer R; } ? R : never; interface ActorGatewayOptions { skipReadyWait?: boolean; } interface ActorActionOptions extends ActorGatewayOptions { signal?: AbortSignal; } type ActorConnectOptions = ActorGatewayOptions; type ActorFetchInit = RequestInit & ActorGatewayOptions; type ActorWebSocketOptions = ActorGatewayOptions; /** * Maps action methods from actor definition to typed function signatures. */ type ActorDefinitionActions = IsAny extends true ? Record> : ActorActionMap>; type ActorQueueSend = { /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ (name: K, body: InferSchemaMap[K], options: QueueSendWaitOptions): Promise[K]>>; /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ (name: K, body: InferSchemaMap[K], options?: QueueSendNoWaitOptions): Promise; /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ (name: keyof TQueues extends never ? string : never, body: unknown, options: QueueSendWaitOptions): Promise; /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ (name: keyof TQueues extends never ? string : never, body: unknown, options?: QueueSendNoWaitOptions): Promise; }; type ActorEventSubscribe = { (eventName: K, callback: (...args: InferEventArgs[K]>) => void): () => void; (eventName: keyof TEvents extends never ? string : never, callback: (...args: any[]) => void): () => void; }; type ActorDefinitionQueueSend = IsAny extends true ? { send: ActorQueueSend>; } : AD extends { config: { queues?: infer Q; }; } ? Q extends QueueSchemaConfig ? { send: ActorQueueSend; } : {} : AD extends BaseActorDefinition ? Q extends QueueSchemaConfig ? { send: ActorQueueSend; } : {} : {}; type ActorDefinitionEventSubscriptions = IsAny extends true ? { on: LooseEventSubscribe; once: LooseEventSubscribe; } : AD extends { config: { events?: infer E; }; } ? E extends EventSchemaConfig ? { on: ActorEventSubscribe; once: ActorEventSubscribe; } : {} : AD extends BaseActorDefinition ? E extends EventSchemaConfig ? { on: ActorEventSubscribe; once: ActorEventSubscribe; } : {} : {}; declare class ActorClientError extends Error { } declare class ManagerError extends ActorClientError { constructor(error: string, opts?: ErrorOptions); } declare class MalformedResponseMessage extends ActorClientError { constructor(cause?: unknown); } declare class ActorConnDisposed extends ActorClientError { constructor(); } type ActorResolutionState = ActorQuery; /** * Connection status for an actor connection. * * - `"idle"`: Not connected, no auto-reconnect (initial state, after dispose, or disabled) * - `"connecting"`: Attempting to establish connection * - `"connected"`: Connection is active * - `"disconnected"`: Connection was lost, will auto-reconnect */ type ActorConnStatus = "idle" | "connecting" | "connected" | "disconnected"; /** * A function that unsubscribes from an event. * * @typedef {Function} EventUnsubscribe */ type EventUnsubscribe = () => void; /** * A function that handles connection errors. * * @typedef {Function} ActorErrorCallback */ type ActorErrorCallback = (error: RivetError) => void; /** * A callback for connection state changes. * * @typedef {Function} ConnectionStateCallback */ type ConnectionStateCallback = () => void; /** * A callback for connection status changes. * * @typedef {Function} StatusChangeCallback */ type StatusChangeCallback = (status: ActorConnStatus) => void; declare const CONNECT_SYMBOL: unique symbol; /** * Provides underlying functions for {@link ActorConn}. See {@link ActorConn} for using type-safe remote procedure calls. * * @see {@link ActorConn} */ declare class ActorConnRaw { #private; /** * Do not call this directly. * * Creates an instance of ActorConnRaw. * * @protected */ constructor(client: ClientRaw, driver: EngineControlClient, params: unknown, getParams: (() => Promise) | undefined, encoding: Encoding, actorResolutionState: ActorResolutionState, gatewayOptions?: ActorGatewayOptions, currentActorInvocation?: CurrentActorInvocation); /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ send(name: string, body: unknown, options: QueueSendWaitOptions): Promise; /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ send(name: string, body: unknown, options?: QueueSendNoWaitOptions): Promise; /** * Call a raw action connection. See {@link ActorConn} for type-safe action calls. * * @see {@link ActorConn} * @template Args - The type of arguments to pass to the action function. * @template Response - The type of the response returned by the action function. * @param {string} name - The name of the action function to call. * @param {...Args} args - The arguments to pass to the action function. * @returns {Promise} - A promise that resolves to the response of the action function. */ action = unknown[], Response = unknown>(opts: { name: string; args: Args; signal?: AbortSignal; }): Promise; /** * Do not call this directly. * Establishes a connection to the server using the specified endpoint & encoding & driver. * * @protected */ [CONNECT_SYMBOL](): void; /** * Subscribes to an event that will happen repeatedly. * * @template Args - The type of arguments the event callback will receive. * @param {string} eventName - The name of the event to subscribe to. * @param {(...args: Args) => void} callback - The callback function to execute when the event is triggered. * @returns {EventUnsubscribe} - A function to unsubscribe from the event. * @see {@link https://rivet.dev/docs/events|Events Documentation} */ on = unknown[]>(eventName: string, callback: (...args: Args) => void): EventUnsubscribe; /** * Subscribes to an event that will be triggered only once. * * @template Args - The type of arguments the event callback will receive. * @param {string} eventName - The name of the event to subscribe to. * @param {(...args: Args) => void} callback - The callback function to execute when the event is triggered. * @returns {EventUnsubscribe} - A function to unsubscribe from the event. * @see {@link https://rivet.dev/docs/events|Events Documentation} */ once = unknown[]>(eventName: string, callback: (...args: Args) => void): EventUnsubscribe; /** * Subscribes to connection errors. * * @param {ActorErrorCallback} callback - The callback function to execute when a connection error occurs. * @returns {() => void} - A function to unsubscribe from the error handler. */ onError(callback: ActorErrorCallback): () => void; /** * Returns the current connection status. * * @returns {ActorConnStatus} - The current connection status. */ get connStatus(): ActorConnStatus; /** * Returns whether the connection is currently open. * * @deprecated Use `connStatus` instead. * @returns {boolean} - True if the connection is open, false otherwise. */ get isConnected(): boolean; /** * Resolves when this connection first reaches the connected state. */ get ready(): Promise; /** * Subscribes to connection open events. * * This is called when the WebSocket connection is established and the Init message is received. * * @param {ConnectionStateCallback} callback - The callback function to execute when the connection opens. * @returns {() => void} - A function to unsubscribe from the open handler. */ onOpen(callback: ConnectionStateCallback): () => void; /** * Subscribes to connection close events. * * This is called when the WebSocket connection is closed. The connection will automatically * attempt to reconnect unless disposed. * * @param {ConnectionStateCallback} callback - The callback function to execute when the connection closes. * @returns {() => void} - A function to unsubscribe from the close handler. */ onClose(callback: ConnectionStateCallback): () => void; /** * Subscribes to connection status changes. * * This is called whenever the connection status changes between Disconnected, Connecting, and Connected. * * @param {StatusChangeCallback} callback - The callback function to execute when the status changes. * @returns {() => void} - A function to unsubscribe from the status change handler. */ onStatusChange(callback: StatusChangeCallback): () => void; /** * Disconnects from the actor. * * @returns {Promise} A promise that resolves when the socket is gracefully closed. */ dispose(): Promise; } /** * Connection to a actor. Allows calling actor's remote procedure calls with inferred types. See {@link ActorConnRaw} for underlying methods. * * @example * ``` * const room = client.connect(...etc...); * // This calls the action named `sendMessage` on the `ChatRoom` actor. * await room.sendMessage('Hello, world!'); * ``` * * Private methods (e.g. those starting with `_`) are automatically excluded. * * @template AD The actor class that this connection is for. * @see {@link ActorConnRaw} */ type ActorConn = Omit & ActorDefinitionQueueSend & ActorDefinitionEventSubscriptions & ActorDefinitionActions; /** How many retries a client may spend, as a share of the requests it sends. */ interface RetryBudgetOptions { /** Retries allowed per 100 requests (default 10). */ percent?: number; /** Retries the client can bank for a burst of refusals; the budget starts full (default 100). */ maxTokens?: number; } /** * Bounds the client's retries of refused requests. Each request adds a fraction of a token and * each retry spends one, so retries stay a fixed share of traffic while the service sheds load * instead of multiplying it. */ declare class RetryBudget { #private; constructor(options?: RetryBudgetOptions); /** Credits one request sent. */ deposit(): void; /** Spends one token. Returns `false` when the budget is spent. */ tryWithdraw(): boolean; } /** * Provides underlying functions for stateless {@link ActorHandle} for action calls. * Similar to ActorConnRaw but doesn't maintain a connection. * * @see {@link ActorHandle} */ declare class ActorHandleRaw { #private; /** * Do not call this directly. * * Creates an instance of ActorHandleRaw. * * @protected */ constructor(client: any, driver: EngineControlClient, params: unknown, getParams: (() => Promise) | undefined, encoding: Encoding, actorResolutionState: ActorResolutionState, gatewayOptions?: ActorGatewayOptions, signal?: AbortSignal, currentActorInvocation?: CurrentActorInvocation, startCallSpan?: StartCallSpan, retryBudget?: RetryBudget); /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ send(name: string, body: unknown, options: QueueSendWaitOptions): Promise; /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ send(name: string, body: unknown, options?: QueueSendNoWaitOptions): Promise; /** * Call a raw action. This method sends an HTTP request to invoke the named action. * * @see {@link ActorHandle} * @template Args - The type of arguments to pass to the action function. * @template Response - The type of the response returned by the action function. */ action = unknown[], Response = unknown>(opts: { name: string; args: Args; } & ActorActionOptions): Promise; /** * Establishes a persistent connection to the actor. * * @template AD The actor class that this connection is for. * @returns {ActorConn} A connection to the actor. */ connect(params?: unknown, options?: ActorConnectOptions): ActorConn; /** * Fetches a resource from this actor via the /request endpoint. This is a * convenience wrapper around the raw HTTP API. */ fetch(input: string | URL | Request, init?: ActorFetchInit): Promise; /** * Opens a raw WebSocket connection to this actor. */ webSocket(path?: string, protocols?: string | string[], options?: ActorWebSocketOptions): Promise; /** * Resolves the actor to get its unique actor ID. */ resolve(): Promise; /** Issue a token scoped to this actor. Defaults to actor gateway read access. */ issueToken(options?: ActorIssueTokenOptions): Promise; /** * Returns the raw URL for routing traffic to the actor. */ getGatewayUrl(): Promise; reload(): Promise; } /** * Stateless handle to a actor. Allows calling actor's remote procedure calls with inferred types * without establishing a persistent connection. * * @example * ``` * const room = client.get(...etc...); * // This calls the action named `sendMessage` on the `ChatRoom` actor without a connection. * await room.sendMessage('Hello, world!'); * ``` * * Private methods (e.g. those starting with `_`) are automatically excluded. * * @template AD The actor class that this handle is for. * @see {@link ActorHandleRaw} */ type ActorHandle = Omit & { connect(params?: unknown, options?: ActorConnectOptions): ActorConn; resolve(): Promise; } & ActorDefinitionQueueSend & Omit, keyof ActorHandleRaw>; /** Called when RivetKit needs a credential. Keep issuer secrets on your backend. */ type GetToken = (options: { forceRefresh: boolean; }) => Promise; declare const ClientConfigSchema: z$1.ZodPipe, z$1.ZodTransform>; token: z$1.ZodPipe, z$1.ZodTransform>; getToken: z$1.ZodOptional>; namespace: z$1.ZodPipe, z$1.ZodTransform>; poolName: z$1.ZodDefault; encoding: z$1.ZodDefault>; headers: z$1.ZodDefault>>; gateway: z$1.ZodDefault>; }, z$1.core.$strip>>>; getUpgradeWebSocket: z$1.ZodOptional>; retryBudget: z$1.ZodOptional; maxTokens: z$1.ZodOptional; }, z$1.core.$strip>>; fetch: z$1.ZodOptional>; disableMetadataLookup: z$1.ZodDefault>; maxInputSize: z$1.ZodDefault; devtools: z$1.ZodDefault; }, z$1.core.$strip>, z$1.ZodTransform<{ endpoint: string | undefined; namespace: string; token: string | undefined; poolName: string; encoding: "json" | "cbor" | "bare"; headers: Record; gateway: { skipReadyWait: boolean; }; disableMetadataLookup: boolean; maxInputSize: number; devtools: boolean; getToken?: GetToken | undefined; getUpgradeWebSocket?: GetUpgradeWebSocket | undefined; retryBudget?: { percent?: number | undefined; maxTokens?: number | undefined; } | undefined; fetch?: typeof fetch | undefined; }, { endpoint: string; token: string | undefined; namespace: string | undefined; poolName: string; encoding: "json" | "cbor" | "bare"; headers: Record; gateway: { skipReadyWait: boolean; }; disableMetadataLookup: boolean; maxInputSize: number; devtools: boolean; getToken?: GetToken | undefined; getUpgradeWebSocket?: GetUpgradeWebSocket | undefined; retryBudget?: { percent?: number | undefined; maxTokens?: number | undefined; } | undefined; fetch?: typeof fetch | undefined; }>>; type ClientConfigInput = z$1.input; /** Extract the actor registry from the registry definition. */ type ExtractActorsFromRegistry> = A extends Registry ? Actors : never; /** Extract the registry definition from the client. */ type ExtractRegistryFromClient>> = C extends Client ? A : never; /** * Represents a actor accessor that provides methods to interact with a specific actor. */ interface ActorAccessor { /** * Gets a stateless handle to a actor by its key, but does not create the actor if it doesn't exist. * The actor name is automatically injected from the property accessor. * * Each operation resolves the current actor for the key before sending the * request. * * @template AD The actor class that this handle is for. * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings. * @param {GetWithIdOptions} [opts] - Options for getting the actor. * @returns {ActorHandle} - A handle to the actor. */ get(key?: string | string[], opts?: GetWithIdOptions): ActorHandle; /** * Gets a stateless handle to a actor by its key, creating it if necessary. * The actor name is automatically injected from the property accessor. * * Each operation resolves the current actor for the key before sending the * request. * * @template AD The actor class that this handle is for. * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings. * @param {GetOptions} [opts] - Options for getting the actor. * @returns {ActorHandle} - A handle to the actor. */ getOrCreate(key?: string | string[], opts?: GetOrCreateOptions): ActorHandle; /** * Gets a stateless handle to a actor by its ID. * * If the actor is destroyed, operations will throw without retrying since * there is no key to re-resolve. * * @template AD The actor class that this handle is for. * @param {string} actorId - The ID of the actor. * @param {GetWithIdOptions} [opts] - Options for getting the actor. * @returns {ActorHandle} - A handle to the actor. */ getForId(actorId: string, opts?: GetWithIdOptions): ActorHandle; /** * Creates a new actor with the name automatically injected from the property accessor, * and returns a stateless handle to it with the actor ID resolved. * * If the actor is destroyed, operations will throw without retrying since * creation is a one-shot operation. * * @template AD The actor class that this handle is for. * @param {string | string[]} key - The key to identify the actor. Can be a single string or an array of strings. * @param {CreateOptions} [opts] - Options for creating the actor (excluding name and key). * @returns {Promise>} - A promise that resolves to a handle to the actor. */ create(key?: string | string[], opts?: CreateOptions): Promise>; /** * Forks the actor `actorId` into a new actor of this name, and returns a * stateless handle to the new actor with its ID resolved. * * The new actor starts at once on a copy of the source's database as of * its last committed write, runs `onFork` once with `opts.input`, and * keeps running independently of the source. A fork is not idempotent: * a `key` already held answers `actor.duplicate_key`. * * @param {string} actorId - The ID of the source actor. * @param {ForkOptions} [opts] - The new actor's key and the fork input. * @returns {Promise>} - A promise that resolves to a handle to the new actor. */ fork(actorId: string, opts?: ForkOptions): Promise>; } /** * Options for querying actors. * @typedef {Object} QueryOptions * @property {unknown} [parameters] - Parameters to pass to the connection. */ interface QueryOptions { /** Parameters to pass to the connection. */ params?: unknown; /** * Lazily resolves connection parameters for `.connect()` and `.webSocket()`. * This is called each time a new connection is opened. */ getParams?: () => Promise; /** Signal to abort the request. */ signal?: AbortSignal; } /** * Options for getting a actor by ID. * @typedef {QueryOptions} GetWithIdOptions */ interface GetWithIdOptions extends QueryOptions { } /** * Options for getting a actor. * @typedef {QueryOptions} GetOptions */ interface GetOptions extends QueryOptions { } /** * Options for getting or creating a actor. * @typedef {QueryOptions} GetOrCreateOptions * @property {string} [createInRegion] - Region to create the actor in if it doesn't exist. */ interface GetOrCreateOptions extends QueryOptions { /** Region to create the actor in if it doesn't exist. */ createInRegion?: string; /** Input data to pass to the actor. */ createWithInput?: unknown; /** * Name of the envoy pool to select for this actor if it is created. * Overrides the client's configured `poolName` for this call. */ poolName?: string; } /** * Options for creating a actor. * @typedef {QueryOptions} CreateOptions * @property {string} [region] - The region to create the actor in. */ interface CreateOptions extends QueryOptions { /** The region to create the actor in. */ region?: string; /** Input data to pass to the actor. */ input?: unknown; /** * Name of the envoy pool to select for this actor. * Overrides the client's configured `poolName` for this call. */ poolName?: string; } /** * Options for forking an actor. */ interface ForkOptions extends QueryOptions { /** The new actor's key. Omit for a keyless actor. */ key?: string | string[]; /** The fork input, passed to the new actor's `onFork` hook. */ input?: unknown; } /** * Represents a region to connect to. * @typedef {Object} Region * @property {string} id - The region ID. * @property {string} name - The region name. * @see {@link https://rivet.dev/docs/edge|Edge Networking} * @see {@link https://rivet.dev/docs/regions|Available Regions} */ interface Region { /** * The region slug. */ id: string; /** * The human-friendly region name. */ name: string; } declare const ACTOR_CONNS_SYMBOL: unique symbol; declare const CREATE_ACTOR_CONN_PROXY: unique symbol; /** Options for constructing a raw actor client. */ interface ClientRawOptions { encoding?: Encoding; gateway?: ActorGatewayOptions; /** Bounds retries of refused requests across every handle of this client. */ retryBudget?: RetryBudgetOptions; } /** Runtime-supplied wiring for clients created inside an actor. Set only by the native runtime. */ interface ActorClientRuntimeOptions { /** Supplies the calling actor's invocation so actor-to-actor clients propagate its trace and ray ID. */ currentActorInvocation?: CurrentActorInvocation; /** Opens and finishes the Core span covering an actor-to-actor call. */ startCallSpan?: StartCallSpan; } /** * Client for managing & connecting to actors. * * @template A The actors map type that defines the available actors. * @see {@link https://rivet.dev/docs/manage|Create & Manage Actors} */ declare class ClientRaw { #private; /** Issue namespace-scoped tokens with an explicit grant list. */ readonly auth: { issueToken(options: IssueTokenOptions): Promise; }; [ACTOR_CONNS_SYMBOL]: Set; /** * Creates an instance of Client. */ constructor(driver: EngineControlClient, options?: ClientRawOptions & ActorClientRuntimeOptions); /** * Gets a stateless handle to a actor by its ID. * * @template AD The actor class that this handle is for. * @param {string} name - The name of the actor. * @param {string} actorId - The ID of the actor. * @param {GetWithIdOptions} [opts] - Options for getting the actor. * @returns {ActorHandle} - A handle to the actor. */ getForId(name: string, actorId: string, opts?: GetWithIdOptions): ActorHandle; /** * Gets a stateless handle to a actor by its key, but does not create the actor if it doesn't exist. * * @template AD The actor class that this handle is for. * @param {string} name - The name of the actor. * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings. * @param {GetWithIdOptions} [opts] - Options for getting the actor. * @returns {ActorHandle} - A handle to the actor. */ get(name: string, key?: string | string[], opts?: GetWithIdOptions): ActorHandle; /** * Gets a stateless handle to a actor by its key, creating it if necessary. * * @template AD The actor class that this handle is for. * @param {string} name - The name of the actor. * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings. * @param {GetOptions} [opts] - Options for getting the actor. * @returns {ActorHandle} - A handle to the actor. */ getOrCreate(name: string, key?: string | string[], opts?: GetOrCreateOptions): ActorHandle; /** * Creates a new actor with the provided key and returns a stateless handle to it. * Resolves the actor ID and returns a handle with getForId query. * * @template AD The actor class that this handle is for. * @param {string} name - The name of the actor. * @param {string | string[]} key - The key to identify the actor. Can be a single string or an array of strings. * @param {CreateOptions} [opts] - Options for creating the actor (excluding name and key). * @returns {Promise>} - A promise that resolves to a handle to the actor. */ create(name: string, key?: string | string[], opts?: CreateOptions): Promise>; /** * Forks the actor `actorId` into a new actor and returns a handle to it. * * @template AD The actor class that this handle is for. * @param {string} name - The name of the actor; the source has the same name. * @param {string} actorId - The ID of the source actor. * @param {ForkOptions} [opts] - The new actor's key and the fork input. * @returns {Promise>} - A promise that resolves to a handle to the new actor. */ fork(name: string, actorId: string, opts?: ForkOptions): Promise>; [CREATE_ACTOR_CONN_PROXY](conn: ActorConnRaw): ActorConn; /** * Disconnects from all actors. * * @returns {Promise} A promise that resolves when all connections are closed. */ dispose(): Promise; } /** * Client type with actor accessors. * This adds property accessors for actor names to the ClientRaw base class. * * @template A The actor registry type. */ type Client> = ClientRaw & Omit<{ [K in keyof ExtractActorsFromRegistry]: ActorAccessor[K]>; }, keyof ClientRaw>; /** @experimental State exposed by a durable workflow run handler to the Inspector. */ type WorkflowState = "pending" | "running" | "sleeping" | "failed" | "completed" | "cancelled" | "rolling_back"; declare const ACTOR_CONTEXT_INTERNAL_SYMBOL: unique symbol; declare const RAW_STATE_SYMBOL: unique symbol; interface ActorLogger { level: any; fatal: any; trace: any; silent: any; msgPrefix: any; debug: any; info: any; warn: any; error: any; [key: string]: any; } type ActorKvValueType = "text" | "arrayBuffer" | "binary"; type ActorKvKeyType = "text" | "binary"; type ActorKvValueTypeMap = { text: string; arrayBuffer: ArrayBuffer; binary: Uint8Array; }; type ActorKvKeyTypeMap = { text: string; binary: Uint8Array; }; type ActorKvValueOptions = { type?: T; }; type ActorKvListOptions = ActorKvValueOptions & { keyType?: K; reverse?: boolean; limit?: number; }; type ActorClientFor = T extends Registry ? Client : T; /** @deprecated Actor KV was deprecated in 3.0 and will be removed in a future version. Store data in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/kv */ interface ActorKv { get(key: Uint8Array | string, options?: ActorKvValueOptions): Promise; put(key: Uint8Array | string, value: Uint8Array | string | ArrayBuffer, options?: ActorKvValueOptions): Promise; delete(key: Uint8Array | string): Promise; batchPut(entries: [Uint8Array, Uint8Array][]): Promise; batchGet(keys: Uint8Array[]): Promise<(Uint8Array | null)[]>; batchDelete(keys: Uint8Array[]): Promise; deleteRange(start: Uint8Array, end: Uint8Array): Promise; listPrefix(prefix: Uint8Array | string, options?: ActorKvListOptions): Promise>; listRange(start: Uint8Array | string, end: Uint8Array | string, options?: ActorKvListOptions): Promise>; list(prefix: Uint8Array | string, options?: ActorKvListOptions): Promise>; [key: string]: any; } /** One individual actor fork behind an actor, as `c.forkChain` lists it. */ interface ActorForkLink { /** The source actor's ID. */ actorId: string; /** The source actor's key. */ key: string[]; /** When the fork was made, in milliseconds since the epoch. */ forkedAt: number; } /** The fork an `onFork` hook runs for: the newest entry of `c.forkChain` and the fork input. */ interface ActorFork extends ActorForkLink { /** * The `input` passed to `client..fork`, or `undefined`. It comes from the caller that * forked the actor, so validate it like any client input. */ input: unknown; } interface ActorSchedule { after(duration: number, action: string, ...args: unknown[]): Promise; at(timestamp: number, action: string, ...args: unknown[]): Promise; cancel(id: string): Promise; get(id: string): Promise; list(): Promise; [key: string]: any; } interface ActorCronSetOptions { name: string; expression: string; action: string; args?: unknown[]; timezone?: string; /** Defaults to 100. Set to 0 to disable and clear history. Maximum 1,000. */ maxHistory?: number; } interface ActorCronEveryOptions { name: string; /** Fixed interval in milliseconds. Minimum 5,000. */ interval: number; action: string; args?: unknown[]; /** Defaults to 100. Set to 0 to disable and clear history. Maximum 1,000. */ maxHistory?: number; } interface ActorCron { set(options: ActorCronSetOptions): Promise; every(options: ActorCronEveryOptions): Promise; get(name: string): Promise; list(): Promise; delete(name: string): Promise; history(name: string, options?: { limit?: number; }): Promise; [key: string]: any; } interface ScheduledEventInfo { id: string; action: string; args: unknown[]; runAt: number; } type CronJobInfo = { name: string; action: string; args: unknown[]; nextRunAt: number; lastRunAt?: number; maxHistory: number; } & ({ kind: "cron"; expression: string; timezone: string; } | { kind: "every"; interval: number; }); interface ScheduledFireInfo { kind: "at" | "cron" | "every"; id: string; name?: string; scheduledAt: number; firedAt: number; } interface CronFire { action: string; scheduledAt: number; firedAt: number; finishedAt?: number; result: "running" | "ok" | "error" | "skipped"; error?: { group: string; code: string; message: string; metadata?: unknown; }; } type QueueMessageOf = { id: number | bigint; name: Name; body: Body; createdAt: number; [key: string]: unknown; }; type QueueName = keyof TQueues & string; type QueueFilterName = keyof TQueues extends never ? string : QueueName; type QueueMessageForName> = keyof TQueues extends never ? QueueMessageOf : TName extends QueueName ? QueueMessageOf[TName]> : never; type QueueCompleteArgs = undefined extends T ? [response?: T] : [response: T]; type QueueCompleteArgsForName> = keyof TQueues extends never ? [response?: unknown] : TName extends QueueName ? [InferQueueCompleteMap[TName]] extends [never] ? [response?: unknown] : QueueCompleteArgs[TName]> : [response?: unknown]; type QueueCompletionResultForName> = keyof TQueues extends never ? unknown | undefined : TName extends QueueName ? InferQueueCompleteMap[TName] | undefined : unknown | undefined; interface QueueNextOptions { names?: readonly TName[]; timeout?: number; signal?: AbortSignal; completable?: TCompletable; } interface QueueNextBatchOptions { names?: readonly TName[]; count?: number; timeout?: number; signal?: AbortSignal; completable?: TCompletable; } interface QueueWaitOptions { timeout?: number; signal?: AbortSignal; completable?: TCompletable; } interface QueueEnqueueAndWaitOptions { timeout?: number; signal?: AbortSignal; } interface QueueTryNextOptions { names?: readonly TName[]; completable?: TCompletable; } interface QueueTryNextBatchOptions { names?: readonly TName[]; count?: number; completable?: TCompletable; } interface QueueIterOptions { names?: readonly TName[]; signal?: AbortSignal; completable?: TCompletable; } /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ interface ActorQueue> { send>(name: TName, body: QueueMessageForName["body"]): Promise; next, const TCompletable extends boolean = false>(opts?: QueueNextOptions): Promise; nextBatch, const TCompletable extends boolean = false>(opts?: QueueNextBatchOptions): Promise; waitForNames, const TCompletable extends boolean = false>(names: readonly TName[], opts?: QueueWaitOptions): Promise; /** @experimental */ waitForAvailable>(names?: readonly TName[], opts?: Omit, "completable">): Promise; /** @experimental */ complete>(message: { id: number | bigint; name: TName; }, ...args: QueueCompleteArgsForName): Promise; enqueueAndWait>(name: TName, body: QueueMessageForName["body"], opts?: QueueEnqueueAndWaitOptions): Promise>; tryNext, const TCompletable extends boolean = false>(opts?: QueueTryNextOptions): Promise; tryNextBatch, const TCompletable extends boolean = false>(opts?: QueueTryNextBatchOptions): Promise; iter, const TCompletable extends boolean = false>(opts?: QueueIterOptions): AsyncIterable; [key: string]: any; } interface Conn<_TState = unknown, TConnParams = unknown, TConnState = unknown, _TVars = unknown, _TInput = unknown, _TDatabase extends AnyDatabaseProvider = AnyDatabaseProvider, _TEvents extends EventSchemaConfig = Record, _TQueues extends QueueSchemaConfig = Record> { id: string; params: TConnParams; /** @deprecated Connection state was deprecated in 3.0 and will be removed in a future version. Track live connections in `c.vars` from `onConnect` and `onDisconnect`, and store durable per-connection data in SQLite. See https://rivet.dev/actors/docs/deprecated/state#connection-state */ state: TConnState; isHibernatable: boolean; send(name: string, ...args: any[]): void; disconnect(reason?: string): Promise; [key: string]: any; } interface ActorContext, TQueues extends QueueSchemaConfig = Record> { [ACTOR_CONTEXT_INTERNAL_SYMBOL]?: unknown; /** Returns the raw unwrapped state without the write-through proxy. */ [RAW_STATE_SYMBOL](): TState; /** @deprecated Actor state was deprecated in 3.0 and will be removed in a future version. Store durable data in SQLite (`c.db`) and in-memory data in `c.vars`. See https://rivet.dev/actors/docs/deprecated/state */ state: TState; vars: TVars; /** @deprecated Actor KV was deprecated in 3.0 and will be removed in a future version. Store data in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/kv */ readonly kv: ActorKv; readonly db: InferDatabaseClient; readonly schedule: ActorSchedule; readonly cron: ActorCron; /** @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ readonly queue: ActorQueue; /** @experimental */ readonly run: ActorRun; readonly actorId: string; readonly name: string; readonly key: string[]; /** * The individual actor forks behind this actor, oldest first; empty when it was never * forked. Namespace forks are not listed. */ readonly forkChain: ActorForkLink[]; readonly region: string; /** * The name of the namespace the actor runs in. After a namespace fork it differs from the * source actor's namespace while the actor id stays the same, so an actor that owns an * external resource can store this to detect that it was copied. */ readonly namespace: string; readonly conns: Map>; readonly log: ActorLogger; readonly abortSignal: AbortSignal; readonly aborted: boolean; readonly request?: Request; /** @deprecated `preventSleep` was deprecated in 3.0 and will be removed in a future version. It is a no-op that always returns `false`. Use `c.keepAwake(promise)` or `c.waitUntil(promise)`. See https://rivet.dev/actors/docs/deprecated/prevent-sleep */ readonly preventSleep: boolean; broadcast(name: string, ...args: any[]): void; /** @deprecated Actor state was deprecated in 3.0 and will be removed in a future version. Store durable data in SQLite (`c.db`) and in-memory data in `c.vars`. See https://rivet.dev/actors/docs/deprecated/state */ saveState(opts?: { immediate?: boolean; maxWait?: number; }): Promise; keepAwake(promise: Promise): Promise; waitUntil(promise: Promise): void; /** @deprecated `setPreventSleep` was deprecated in 3.0 and will be removed in a future version. It is a no-op. Use `c.keepAwake(promise)` or `c.waitUntil(promise)`. See https://rivet.dev/actors/docs/deprecated/prevent-sleep */ setPreventSleep(preventSleep: boolean): void; sleep(): void; destroy(): void; client(): ActorClientFor; [key: string]: any; } /** @experimental How one run of a workflow function ended. */ type WorkflowOutcome = "completed" | "sleeping" | "evicted" | "failed" | "cancelled"; /** @experimental How one workflow step attempt ended. `retry` will be tried again, `failed` will not. */ type WorkflowStepOutcome = "ok" | "retry" | "failed"; /** @experimental One open run of a workflow function, traced as its own invocation. */ interface WorkflowSpan { /** Runs `body` attributed to this run. */ run(body: () => Promise): Promise; /** * Called by a workflow engine before each attempt at a step. Returns * nothing when tracing is off. */ startStep(name: string, attempt: number): WorkflowStepSpan | undefined; finish(outcome: WorkflowOutcome): Promise; } /** @experimental One open attempt at one workflow step. */ interface WorkflowStepSpan { /** Runs `body` attributed to this attempt. */ run(body: () => Promise): Promise; /** `error` is what the step callback threw. */ finish(outcome: WorkflowStepOutcome, error?: unknown): void; } /** @experimental */ interface ActorRun { /** * @experimental Sets or clears the durable Unix-millisecond deadline that * ensures this actor's run handler is active, starting it if inactive. */ setWakeAt(timestamp: number | null): Promise; /** @experimental Called by a workflow engine each time it runs the workflow function. */ startWorkflowSpan(): Promise; /** * @experimental Runs `body` outside the current workflow run, so a workflow * engine's own history storage stays out of the trace. */ runOutsideWorkflowSpan(body: () => T): T; } type ActionContext, TQueues extends QueueSchemaConfig = Record> = ActorContext & { /** Present only when a durable schedule or cron invokes this action. */ readonly scheduledFire?: ScheduledFireInfo; conn: Conn; }; type BeforeActionResponseContext, TQueues extends QueueSchemaConfig = Record> = ActionContext; type BeforeConnectContext, TQueues extends QueueSchemaConfig = Record> = ActorContext; type ConnectContext, TQueues extends QueueSchemaConfig = Record> = ActionContext; /** @deprecated Connection state was deprecated in 3.0 and will be removed in a future version. Track live connections in `c.vars` from `onConnect` and `onDisconnect`, and store durable per-connection data in SQLite. See https://rivet.dev/actors/docs/deprecated/state#connection-state */ type CreateConnStateContext, TQueues extends QueueSchemaConfig = Record> = ActorContext; type CreateContext, TQueues extends QueueSchemaConfig = Record> = ActorContext; type CreateVarsContext, TQueues extends QueueSchemaConfig = Record> = CreateContext; type DestroyContext, TQueues extends QueueSchemaConfig = Record> = ActorContext; type DisconnectContext, TQueues extends QueueSchemaConfig = Record> = ActionContext; type RequestContext, TQueues extends QueueSchemaConfig = Record> = ActionContext; type RunContext, TQueues extends QueueSchemaConfig = Record> = ActorContext; type SleepContext, TQueues extends QueueSchemaConfig = Record> = RunContext; /** @deprecated Actor state was deprecated in 3.0 and will be removed in a future version. See https://rivet.dev/actors/docs/deprecated/state */ type StateChangeContext, TQueues extends QueueSchemaConfig = Record> = RunContext; type WakeContext, TQueues extends QueueSchemaConfig = Record> = RunContext; type MigrateContext, TQueues extends QueueSchemaConfig = Record> = WakeContext; type WebSocketContext, TQueues extends QueueSchemaConfig = Record> = ActionContext; type InspectorUnsubscribe = () => void; declare const RunConfigSchema: z.ZodObject<{ name: z.ZodOptional; icon: z.ZodOptional; run: z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>; inspector: z.ZodOptional unknown, () => unknown>; getState: z.ZodOptional Promise, () => Promise>>; onHistoryUpdated: z.ZodOptional void) => InspectorUnsubscribe, (listener: (history: unknown) => void) => InspectorUnsubscribe>>; replayFromStep: z.ZodOptional Promise, (entryId?: string) => Promise>>; }, z.core.$strip>>; }, z.core.$strip>>>; }, z.core.$strip>; type RunConfigRuntime = z.infer; type RunConfig, TQueues extends QueueSchemaConfig = Record> = Omit & { run: (c: RunContext) => void | Promise; }; declare const ActorConfigSchema: z.ZodObject<{ onCreate: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; onDestroy: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; onMigrate: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; onWake: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; onFork: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; onSleep: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; run: z.ZodOptional unknown, (...args: unknown[]) => unknown>, z.ZodObject<{ name: z.ZodOptional; icon: z.ZodOptional; run: z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>; inspector: z.ZodOptional unknown, () => unknown>; getState: z.ZodOptional Promise, () => Promise>>; onHistoryUpdated: z.ZodOptional void) => InspectorUnsubscribe, (listener: (history: unknown) => void) => InspectorUnsubscribe>>; replayFromStep: z.ZodOptional Promise, (entryId?: string) => Promise>>; }, z.core.$strip>>; }, z.core.$strip>>>; }, z.core.$strip>]>>; onStateChange: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; onBeforeConnect: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; onConnect: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; onDisconnect: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; onBeforeActionResponse: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; onRequest: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; onWebSocket: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; actions: z.ZodDefault, Record>>; actionInputSchemas: z.ZodOptional>; tracing: z.ZodOptional; actions: z.ZodOptional>>; }, z.core.$strict>>; connParamsSchema: z.ZodOptional; events: z.ZodOptional>; queues: z.ZodOptional>; state: z.ZodOptional; createState: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; connState: z.ZodOptional; createConnState: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; vars: z.ZodOptional; db: z.ZodOptional; createVars: z.ZodOptional unknown, (...args: unknown[]) => unknown>>; options: z.ZodPrefault; icon: z.ZodOptional; canHibernateWebSocket: z.ZodDefault boolean, (request: Request) => boolean>]>>; createVarsTimeout: z.ZodDefault; createConnStateTimeout: z.ZodDefault; onBeforeConnectTimeout: z.ZodDefault; onConnectTimeout: z.ZodDefault; onMigrateTimeout: z.ZodDefault; sleepGracePeriod: z.ZodDefault; onDestroyTimeout: z.ZodOptional; waitUntilTimeout: z.ZodOptional; stateSaveInterval: z.ZodDefault; actionTimeout: z.ZodDefault; connectionLivenessTimeout: z.ZodDefault; connectionLivenessInterval: z.ZodDefault; noSleep: z.ZodDefault; sleepTimeout: z.ZodDefault; maxQueueSize: z.ZodDefault; maxSchedules: z.ZodDefault; maxQueueMessageSize: z.ZodDefault; preloadMaxWorkflowBytes: z.ZodOptional; preloadMaxConnectionsBytes: z.ZodOptional; }, z.core.$strict>>; inspector: z.ZodOptional; hidden: z.ZodOptional>; }, z.core.$strict>, z.ZodObject<{ id: z.ZodEnum<{ state: "state"; database: "database"; console: "console"; queue: "queue"; workflow: "workflow"; schedules: "schedules"; connections: "connections"; }>; hidden: z.ZodLiteral; }, z.core.$strict>]>>>; }, z.core.$strict>>; }, z.core.$strict>; type CreateState = { /** @deprecated Actor state was deprecated in 3.0 and will be removed in a future version. Store durable data in SQLite (`c.db`) and in-memory data in `c.vars`. See https://rivet.dev/actors/docs/deprecated/state */ state: TState; } | { /** @deprecated Actor state was deprecated in 3.0 and will be removed in a future version. Store durable data in SQLite (`c.db`) and in-memory data in `c.vars`. See https://rivet.dev/actors/docs/deprecated/state */ createState: (c: CreateContext, input: TInput) => TState | Promise; } | Record; type CreateConnState = { /** @deprecated Connection state was deprecated in 3.0 and will be removed in a future version. Track live connections in `c.vars` from `onConnect` and `onDisconnect`, and store durable per-connection data in SQLite. See https://rivet.dev/actors/docs/deprecated/state#connection-state */ connState: TConnState; } | { /** @deprecated Connection state was deprecated in 3.0 and will be removed in a future version. Track live connections in `c.vars` from `onConnect` and `onDisconnect`, and store durable per-connection data in SQLite. See https://rivet.dev/actors/docs/deprecated/state#connection-state */ createConnState: (c: CreateConnStateContext, params: TConnParams) => TConnState | Promise; } | Record; /** * @experimental */ type CreateVars = { /** * @experimental */ vars: TVars; } | { /** * @experimental */ createVars: (c: CreateVarsContext, driverCtx: any) => TVars | Promise; } | Record; interface Actions, TQueues extends QueueSchemaConfig = Record> { [Action: string]: ((c: ActionContext, ...args: any[]) => any) | Actions; } interface ActionInputSchemas { [Action: string]: PrimitiveSchema | ActionInputSchemas; } interface BaseActorConfig> { /** * Called when the actor is first initialized. * * Use this hook to initialize your actor's state. * This is called before any other lifecycle hooks. */ onCreate?: (c: CreateContext, input: TInput) => void | Promise; /** * Called when the actor is destroyed. */ onDestroy?: (c: DestroyContext) => void | Promise; /** * Called on every actor start after persisted state loads and before onWake. * * Use this hook for repeatable schema migrations or other startup work that * must run on both first boot and wake. */ onMigrate?: (c: MigrateContext, isNew: boolean) => void | Promise; /** * Called once at the first start of an actor made by forking another actor * (`client..fork`), after its state loads and before `onWake` and any * overdue schedule events run. `createState` and `onCreate` do not run for a fork. * * Use this hook to cancel schedules the fork inherited, drop resources copied * from the source, or record the fork input. `c.forkChain` already ends with * this fork. A throw fails the start, and the hook runs again on the next start. * Forks of a whole namespace do not call it. * * State edits made in this hook are saved in one commit with the record that the * fork ran, so a start that finds the fork recorded also finds the hook's final * state. On native SQLite the hook's `c.db` writes and any save it starts itself * join that commit too, and a failed start drops them. Two limits apply: * * - On remote SQLite (wasm runtimes), `c.db` writes, and state the hook writes * itself in a transaction (for example `c.db.transaction` with * `experimental.includeState`), are committed at once, without the fork record. * A `c.saveState` call is not such a write: the startup save carries its * state. Only state the hook leaves to the startup save is atomic with it. A * crash or a failed start before the record lands runs the hook again on top * of those writes, so the hook must be idempotent there. * - On native SQLite the hook's writes must fit one commit (32,768 pages, 128 MiB * at the default page size). A transaction that would take them past it fails as * too large instead of committing part of them early; a hook that lets the error * throw fails the start, and nothing it wrote lands. Move a backfill that large * into later actions. * `onCreate` differs: its writes held so far are committed early instead. */ onFork?: (c: WakeContext, fork: ActorFork) => void | Promise; /** * Called when the actor is started and ready to receive connections and action. * * Use this hook to initialize resources needed for the actor's operation * (timers, external connections, etc.) * * @returns Void or a Promise that resolves when startup is complete */ onWake?: (c: WakeContext) => void | Promise; /** * Called when the actor is stopping or sleeping. * * Use this hook to clean up resources, save state, or perform * any shutdown operations before the actor sleeps or stops. * * Not supported on all platforms. * * @returns Void or a Promise that resolves when shutdown is complete */ onSleep?: (c: SleepContext) => void | Promise; /** * Called after the actor starts up. Does not block actor startup. * * Use this for background tasks like: * - Reading from queues in a loop * - Tick loops for periodic work * - Custom workflow logic * * **Important:** The actor may go to sleep at any time during the `run` * handler. Wrap work that must keep the actor awake with * `c.keepAwake(promise)` to block idle sleep and shutdown finalize until * the promise settles, or use `c.waitUntil(promise)` to let the graceful * shutdown window (`sleepGracePeriod`) cover deferred work. * * The handler receives an abort signal via `c.abortSignal` and a * `c.aborted` alias. Use these to gracefully exit when shutdown starts. * * If this handler exits, the actor will follow the normal idle sleep timeout * once it becomes idle. * If this handler throws, the actor logs the error and then sleeps once it * becomes idle. * Call `c.destroy()` explicitly if a run handler should destroy the actor. * * Can be either a function or a RunConfig object with optional name/icon metadata. * * Passing a plain function was deprecated in 3.0 and will be removed in a * future version; it logs a warning at startup. Start background work from * `onWake` with `c.keepAwake` and track it in `c.vars` instead. * `run: workflow(...)` is not deprecated. See * https://rivet.dev/actors/docs/deprecated/run * * @returns Void or a Promise. */ run?: ((c: RunContext) => void | Promise) | RunConfig; /** * Called when the actor's state changes. * * Use this hook to react to state changes, such as updating * external systems or triggering events. * * State changes made within this hook will NOT trigger * another onStateChange call, preventing infinite recursion. * * @param newState The updated state * @deprecated Actor state was deprecated in 3.0 and will be removed in a future version. Store durable data in SQLite (`c.db`) and in-memory data in `c.vars`. See https://rivet.dev/actors/docs/deprecated/state */ onStateChange?: (c: StateChangeContext, newState: TState) => void; /** * Called before a client connects to the actor. * * Use this hook to determine if a connection should be accepted * and to validate client-provided parameters. The pending connection * is not visible in `c.conns` while this hook runs. * * @param opts Connection parameters including client-provided data * @returns Void or a Promise. * @throws Throw an error to reject the connection */ onBeforeConnect?: (c: BeforeConnectContext, params: TConnParams) => void | Promise; /** * Called when a client successfully connects to the actor. * * Use this hook to perform actions when a connection is established, * such as sending initial data or updating the actor's state. The * connection is visible in `c.conns` before this hook runs. * * @param conn The connection object * @returns Void or a Promise that resolves when connection handling is complete */ onConnect?: (c: ConnectContext, conn: Conn) => void | Promise; /** * Called when a client disconnects from the actor. * * Use this hook to clean up resources associated with the connection * or update the actor's state. * * @param conn The connection that is being closed * @returns Void or a Promise that resolves when disconnect handling is complete */ onDisconnect?: (c: DisconnectContext, conn: Conn) => void | Promise; /** * Called before sending an action response to the client. * * Use this hook to modify or transform the output of an action before it's sent * to the client. This is useful for formatting responses, adding metadata, * or applying transformations to the output. * * @param name The name of the action that was called * @param args The arguments that were passed to the action * @param output The output that will be sent to the client * @returns The modified output to send to the client */ onBeforeActionResponse?: (c: BeforeActionResponseContext, name: string, args: unknown[], output: Out) => Out | Promise; /** * Called when a raw HTTP request is made to the actor. * * This handler receives raw HTTP requests made to `/actors/{actorName}/http/*` endpoints. * Use this hook to handle custom HTTP patterns, REST APIs, or other HTTP-based protocols. * * @param c The request context with access to the connection * @param request The raw HTTP request object * @param opts Additional options * @returns A Response object to send back, or void to continue with default routing */ onRequest?: (c: RequestContext, request: Request) => Response | Promise; /** * Called when a raw WebSocket connection is established to the actor. * * This handler receives WebSocket connections made to `/actors/{actorName}/websocket/*` endpoints. * Use this hook to handle custom WebSocket protocols, binary streams, or other WebSocket-based communication. * * @param c The WebSocket context with access to the connection * @param websocket The actor-facing raw WebSocket connection * @param opts Additional options including the original HTTP upgrade request */ onWebSocket?: (c: WebSocketContext, websocket: UniversalWebSocket) => void | Promise; actions?: TActions; /** * Optional schemas for validating action argument tuples in native runtimes. * May mirror nested action groups or use dot-separated low-level action names. */ actionInputSchemas?: ActionInputSchemas; /** * How much of this actor's work is recorded in traces. Defaults to the * process sampler from `OTEL_TRACES_SAMPLER`. */ tracing?: ActorTracingOptions; /** * Optional schema for validating connection params in native runtimes. */ connParamsSchema?: PrimitiveSchema; /** * Schema map for events broadcasted by this actor. */ events?: TEvents; /** * Schema map for queue payloads sent by this actor. * * @deprecated Queues were deprecated in 3.0 and will be removed in a future version. Use actions and store pending work in SQLite (`c.db`). See https://rivet.dev/actors/docs/deprecated/queues */ queues?: TQueues; } type ActorDatabaseConfig = { /** * @experimental */ db: TDatabase; } | Record; type ActorConfig, TQueues extends QueueSchemaConfig = Record, TActions extends Actions = Actions> = Omit, "actions" | "events" | "queues" | "onCreate" | "onDestroy" | "onMigrate" | "onWake" | "onFork" | "onSleep" | "run" | "onStateChange" | "onBeforeConnect" | "onConnect" | "onDisconnect" | "onBeforeActionResponse" | "onRequest" | "onWebSocket" | "state" | "createState" | "connState" | "createConnState" | "vars" | "createVars" | "db"> & BaseActorConfig & CreateState & CreateConnState & CreateVars & ActorDatabaseConfig; interface BaseActorDefinition, Q extends QueueSchemaConfig = Record, _R extends Actions = Actions> { readonly config: ActorConfig; } interface AnyActorDefinition { readonly config: any; } declare class ActorDefinition, Q extends QueueSchemaConfig = Record, R extends Actions = Actions> implements BaseActorDefinition { #private; constructor(config: ActorConfig); get config(): ActorConfig; } declare const ActorsSchema: z$2.ZodRecord>; type RegistryActors = z$2.infer; declare const RegistryConfigSchema: z$2.ZodPipe>; test: z$2.ZodDefault>; sqliteBackend: z$2.ZodOptional>; }, z$2.core.$strip>>>; maxIncomingMessageSize: z$2.ZodDefault>; maxOutgoingMessageSize: z$2.ZodDefault>; runtime: z$2.ZodPipe>, z$2.ZodTransform<"auto" | "native" | "wasm", "auto" | "native" | "wasm" | undefined>>; wasm: z$2.ZodDefault>; initInput: z$2.ZodOptional; } | _rivetkit_rivetkit_wasm.InitInput | Promise<_rivetkit_rivetkit_wasm.InitInput> | undefined, { module_or_path: _rivetkit_rivetkit_wasm.InitInput | Promise<_rivetkit_rivetkit_wasm.InitInput>; } | _rivetkit_rivetkit_wasm.InitInput | Promise<_rivetkit_rivetkit_wasm.InitInput> | undefined>>; }, z$2.core.$strip>>>; sqlite: z$2.ZodPipe, z$2.ZodObject<{ backend: z$2.ZodEnum<{ local: "local"; remote: "remote"; }>; }, z$2.core.$strip>]>>, z$2.ZodTransform<{ backend: "local" | "remote"; } | undefined, "local" | "remote" | { backend: "local" | "remote"; } | undefined>>; noWelcome: z$2.ZodDefault>; logging: z$2.ZodDefault>; level: z$2.ZodOptional>; }, z$2.core.$strip>>>; endpoint: z$2.ZodPipe, z$2.ZodTransform>; token: z$2.ZodPipe, z$2.ZodTransform>; namespace: z$2.ZodPipe, z$2.ZodTransform>; headers: z$2.ZodDefault>>; staticDir: z$2.ZodOptional; httpBasePath: z$2.ZodDefault>; httpPort: z$2.ZodDefault>; httpHost: z$2.ZodOptional; startEngine: z$2.ZodDefault; engineHost: z$2.ZodDefault>; enginePort: z$2.ZodDefault>; engineVersion: z$2.ZodDefault>; startServices: z$2.ZodOptional; configurePool: z$2.ZodOptional; url: z$2.ZodString; headers: z$2.ZodOptional>; requestLifespan: z$2.ZodOptional; drainGracePeriod: z$2.ZodOptional; metadata: z$2.ZodOptional>; metadataPollInterval: z$2.ZodOptional; drainOnVersionUpgrade: z$2.ZodOptional; }, z$2.core.$strip>>>; serverless: z$2.ZodDefault>; maxStartPayloadBytes: z$2.ZodDefault>; publicEndpoint: z$2.ZodPipe, z$2.ZodTransform>; publicToken: z$2.ZodPipe, z$2.ZodTransform>; }, z$2.core.$strip>>>; node: z$2.ZodDefault; version: z$2.ZodDefault; totalSlots: z$2.ZodDefault; nodeKey: z$2.ZodOptional; }, z$2.core.$strip>>>; shutdown: z$2.ZodDefault; disableSignalHandlers: z$2.ZodDefault>; }, z$2.core.$strip>>>; }, z$2.core.$strip>, z$2.ZodTransform<{ sqlite: { backend: "local" | "remote"; } | undefined; endpoint: string | undefined; engineSpawn: boolean; startServices: boolean; namespace: string; token: string | undefined; publicEndpoint: string | undefined; publicNamespace: string | undefined; publicToken: string | undefined; validateServerlessEndpoint: boolean; serverless: { publicEndpoint: string | undefined; basePath: string; maxStartPayloadBytes: number; publicToken: string | undefined; }; use: Record; test: { enabled: boolean; sqliteBackend?: "local" | "remote" | undefined; }; maxIncomingMessageSize: number; maxOutgoingMessageSize: number; runtime: "auto" | "native" | "wasm"; wasm: { bindings?: typeof _rivetkit_rivetkit_wasm | undefined; initInput?: { module_or_path: _rivetkit_rivetkit_wasm.InitInput | Promise<_rivetkit_rivetkit_wasm.InitInput>; } | _rivetkit_rivetkit_wasm.InitInput | Promise<_rivetkit_rivetkit_wasm.InitInput> | undefined; }; noWelcome: boolean; logging: { baseLogger?: Logger | undefined; level?: "fatal" | "error" | "warn" | "info" | "debug" | "trace" | "silent" | undefined; }; headers: Record; httpBasePath: string; httpPort: number; startEngine: boolean; engineHost: string; enginePort: number; engineVersion: string; node: { poolName: string; version: number; totalSlots: number; nodeKey?: string | undefined; }; shutdown: { disableSignalHandlers: boolean; gracePeriodMs?: number | undefined; }; staticDir?: string | undefined; httpHost?: string | undefined; configurePool?: { url: string; name?: string | undefined; headers?: Record | undefined; requestLifespan?: number | undefined; drainGracePeriod?: number | undefined; metadata?: Record | undefined; metadataPollInterval?: number | undefined; drainOnVersionUpgrade?: boolean | undefined; } | undefined; }, { use: Record; test: { enabled: boolean; sqliteBackend?: "local" | "remote" | undefined; }; maxIncomingMessageSize: number; maxOutgoingMessageSize: number; runtime: "auto" | "native" | "wasm"; wasm: { bindings?: typeof _rivetkit_rivetkit_wasm | undefined; initInput?: { module_or_path: _rivetkit_rivetkit_wasm.InitInput | Promise<_rivetkit_rivetkit_wasm.InitInput>; } | _rivetkit_rivetkit_wasm.InitInput | Promise<_rivetkit_rivetkit_wasm.InitInput> | undefined; }; sqlite: { backend: "local" | "remote"; } | undefined; noWelcome: boolean; logging: { baseLogger?: Logger | undefined; level?: "fatal" | "error" | "warn" | "info" | "debug" | "trace" | "silent" | undefined; }; endpoint: string | undefined; token: string | undefined; namespace: string | undefined; headers: Record; httpBasePath: string; httpPort: number; startEngine: boolean; engineHost: string; enginePort: number; engineVersion: string; serverless: { basePath: string; maxStartPayloadBytes: number; publicEndpoint: string | undefined; publicToken: string | undefined; }; node: { poolName: string; version: number; totalSlots: number; nodeKey?: string | undefined; }; shutdown: { disableSignalHandlers: boolean; gracePeriodMs?: number | undefined; }; staticDir?: string | undefined; httpHost?: string | undefined; startServices?: boolean | undefined; configurePool?: { url: string; name?: string | undefined; headers?: Record | undefined; requestLifespan?: number | undefined; drainGracePeriod?: number | undefined; metadata?: Record | undefined; metadataPollInterval?: number | undefined; drainOnVersionUpgrade?: boolean | undefined; } | undefined; }>>; type RegistryConfig = z$2.infer; type RegistryConfigInput = Omit, "use"> & { use: A; }; declare function buildConfiguredRegistry(config: RegistryConfig): Promise<{ runtime: CoreRuntime; registry: RegistryHandle; serveConfig: RuntimeServeConfig; }>; type FetchHandler = (request: Request, ...args: any) => Response | Promise; interface ServerlessHandler { fetch: FetchHandler; } interface RegistryApplication { fetch: FetchHandler; } interface RegistryListenOptions { port?: number; host?: string; publicDir?: string; application?: RegistryApplication; } interface RegistryRoutes { health(): Promise; metadata(): Promise; prometheusMetrics(request?: Request): Promise; } /** * Injectable dependencies for {@link Registry}. Production code uses the * defaults. Tests override `buildConfiguredRegistry` to drive lifecycle * orchestration against a fake `CoreRuntime` without an engine. */ interface RegistryDeps { buildConfiguredRegistry: typeof buildConfiguredRegistry; } declare class Registry { #private; readonly routes: RegistryRoutes; get config(): RegistryConfigInput; parseConfig(): RegistryConfig; constructor(config: RegistryConfigInput, deps?: Partial); /** * Handle an incoming HTTP request for serverless deployments. * * @example * ```ts * const app = new Hono(); * app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); * export default app; * ``` */ handler(request: Request): Promise; /** * Returns a fetch handler for serverless deployments. * * @example * ```ts * export default registry.serve(); * ``` */ serve(): ServerlessHandler; /** * Bind an HTTP listener provided by the native (Rust) runtime and serve * the registry's serverless endpoints over it. Resolves only after the * registry is shut down (SIGINT/SIGTERM or `nativeRegistry.shutdown()`). * * @param opts.port Port to listen on. Defaults to `process.env.RIVET_PORT` * if set, otherwise 3000. * @param opts.host Address to bind. Defaults to `0.0.0.0`. * @param opts.publicDir If set, serves static files from this directory * as a fallback below the framework routes. * @param opts.application If set, handles requests that do not match a * framework route. * * @example * ```ts * await registry.listen(); * await registry.listen({ application: app }); * ``` */ listen(opts?: RegistryListenOptions): Promise; /** * Gracefully drains all live registries. * * Programmatic counterpart to the SIGINT/SIGTERM handlers: tears down * every live `CoreRegistry` (both `start()` and `handler()` modes) and * waits for the serve promise to resolve, all bounded by the shutdown * grace period. Unlike a signal-driven shutdown, this does not re-raise a * signal or exit the process. The caller owns process lifetime. * * Idempotent: concurrent or repeated calls share a single drain. Safe to * call even if nothing has been started. * * @example * ```ts * const registry = setup({ use: { counter } }); * registry.start(); * // ...later, on your own shutdown trigger: * await registry.shutdown(); * ``` */ shutdown(): Promise; startEnvoy(): void; /** * Starts the serverful registry if needed and waits until its envoy has * registered with the Engine. Repeated and concurrent calls share one * startup lifecycle and readiness promise. * * Unlike {@link start}, this reports startup failures and does not resolve * merely because an HTTP health endpoint is listening. */ startAndWait(): Promise; /** * Starts the actor envoy for standalone server deployments. * * Set `RIVETKIT_RUNTIME_MODE=serverless` to instead bind an HTTP listener * via `listen()` (Mode B). Mode A (envoy) and Mode B (listener) are * mutually exclusive per registry instance. * * @example * ```ts * const registry = setup({ use: { counter } }); * registry.start(); * ``` */ start(): void; /** * Returns the number of actors hosted by this process's envoy, which is zero * while it is not serving. Requires the native runtime. */ activeActorCount(): number; /** * Calls `callback` with the number of actors hosted by this process's envoy * and again whenever it changes. Rapid changes may coalesce. * Returns a function that unsubscribes. Requires the native runtime. * * @example * ```ts * const unsubscribe = registry.onActiveActorCountChange((count) => { * setTaskProtection(count > 0); * }); * ``` */ onActiveActorCountChange(callback: (count: number) => void): () => void; } /** * Creates a client with the actor accessor proxy. */ declare function createClient>(endpointOrConfig?: string | ClientConfigInput): Client; export { type ActorAccessor, type ActorActionFunction, type ActorActionOptions, ActorClientError, type ActorConn, ActorConnDisposed, ActorConnRaw, type ActorConnStatus, type ActorConnectOptions, ActorDefinition, RivetError as ActorError, type ActorGatewayOptions, type ActorHandle, ActorHandleRaw, type ActorIssueTokenOptions, type ActorTokenPermissions, type ActorTokenResource, type AnyActorDefinition, type Client, type ClientConfigInput, ClientRaw, type ConnectionStateCallback, type CreateOptions, type CreateRequest, type Encoding, type EventUnsubscribe, type ExtractActorsFromRegistry, type ExtractRegistryFromClient, type ForkOptions, type GetOptions, type GetToken, type GetWithIdOptions, type IssueTokenOptions, type IssuedToken, MalformedResponseMessage, ManagerError, type QueryOptions, type Region, RivetError, type StatusChangeCallback, type TokenGrant, UserError, createClient };