rivetkit 2.3.26 → 2.3.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/browser/client.js +2 -5
  2. package/dist/browser/client.js.map +1 -1
  3. package/dist/browser/inspector/client.js +2 -5
  4. package/dist/browser/inspector/client.js.map +1 -1
  5. package/dist/tsup/agent-os/index.cjs +3 -2652
  6. package/dist/tsup/agent-os/index.cjs.map +1 -1
  7. package/dist/tsup/agent-os/index.d.cts +1 -2717
  8. package/dist/tsup/agent-os/index.d.ts +1 -2717
  9. package/dist/tsup/agent-os/index.js +3 -2652
  10. package/dist/tsup/agent-os/index.js.map +1 -1
  11. package/dist/tsup/{chunk-LEXBAJ2Q.js → chunk-3EYXDC64.js} +3 -3
  12. package/dist/tsup/chunk-3EYXDC64.js.map +1 -0
  13. package/dist/tsup/{chunk-4SGTACEH.cjs → chunk-3X3QZVH6.cjs} +140 -140
  14. package/dist/tsup/chunk-3X3QZVH6.cjs.map +1 -0
  15. package/dist/tsup/{chunk-A27ATZJ4.cjs → chunk-4LMR7FES.cjs} +7 -7
  16. package/dist/tsup/{chunk-A27ATZJ4.cjs.map → chunk-4LMR7FES.cjs.map} +1 -1
  17. package/dist/tsup/{chunk-ZRCMI2TE.cjs → chunk-67PPGBOA.cjs} +3 -3
  18. package/dist/tsup/{chunk-ZRCMI2TE.cjs.map → chunk-67PPGBOA.cjs.map} +1 -1
  19. package/dist/tsup/{chunk-W5ADMRWL.cjs → chunk-DRG3YQ42.cjs} +3 -3
  20. package/dist/tsup/{chunk-W5ADMRWL.cjs.map → chunk-DRG3YQ42.cjs.map} +1 -1
  21. package/dist/tsup/{chunk-EQODJ4G7.cjs → chunk-FHZZ6PLK.cjs} +3 -6
  22. package/dist/tsup/chunk-FHZZ6PLK.cjs.map +1 -0
  23. package/dist/tsup/{chunk-NHXI4GVK.js → chunk-IKMLO5KS.js} +4 -4
  24. package/dist/tsup/{chunk-YXVLQDDK.js → chunk-KJBV7M2J.js} +3 -3
  25. package/dist/tsup/{chunk-7HU3OZCW.js → chunk-QLIVFNLT.js} +2 -2
  26. package/dist/tsup/{chunk-ORMO5OOW.cjs → chunk-S5EZP52Q.cjs} +3 -3
  27. package/dist/tsup/{chunk-ORMO5OOW.cjs.map → chunk-S5EZP52Q.cjs.map} +1 -1
  28. package/dist/tsup/{chunk-WI2Q7NT3.cjs → chunk-SRRUW63T.cjs} +4 -4
  29. package/dist/tsup/{chunk-WI2Q7NT3.cjs.map → chunk-SRRUW63T.cjs.map} +1 -1
  30. package/dist/tsup/{chunk-BKUZYZRZ.js → chunk-SWESH3VP.js} +2 -2
  31. package/dist/tsup/{chunk-XKVT36WN.js → chunk-UEQ5NN24.js} +2 -2
  32. package/dist/tsup/{chunk-3CZAZIO5.js → chunk-WB3BJJWJ.js} +3 -6
  33. package/dist/tsup/chunk-WB3BJJWJ.js.map +1 -0
  34. package/dist/tsup/{chunk-6AU5SM6I.cjs → chunk-XQIPFU3I.cjs} +10 -10
  35. package/dist/tsup/{chunk-6AU5SM6I.cjs.map → chunk-XQIPFU3I.cjs.map} +1 -1
  36. package/dist/tsup/{chunk-YQ7QHMPY.js → chunk-XQVCT3CM.js} +2 -2
  37. package/dist/tsup/client/mod.cjs +5 -5
  38. package/dist/tsup/client/mod.js +4 -4
  39. package/dist/tsup/common/log.cjs +2 -2
  40. package/dist/tsup/common/log.js +1 -1
  41. package/dist/tsup/common/websocket.cjs +3 -3
  42. package/dist/tsup/common/websocket.js +2 -2
  43. package/dist/tsup/db/drizzle.cjs +2 -2
  44. package/dist/tsup/db/drizzle.js +1 -1
  45. package/dist/tsup/db/mod.cjs +3 -3
  46. package/dist/tsup/db/mod.js +2 -2
  47. package/dist/tsup/inspector/mod.cjs +5 -5
  48. package/dist/tsup/inspector/mod.js +4 -4
  49. package/dist/tsup/inspector/workflow.cjs +4 -4
  50. package/dist/tsup/inspector/workflow.js +3 -3
  51. package/dist/tsup/mod.cjs +84 -84
  52. package/dist/tsup/mod.js +5 -5
  53. package/dist/tsup/test/mod.cjs +6 -6
  54. package/dist/tsup/test/mod.js +4 -4
  55. package/dist/tsup/utils.cjs +2 -2
  56. package/dist/tsup/utils.js +1 -1
  57. package/dist/tsup/workflow/mod.cjs +7 -7
  58. package/dist/tsup/workflow/mod.js +4 -4
  59. package/package.json +10 -13
  60. package/src/agent-os/index.ts +5 -65
  61. package/src/client/actor-handle.ts +3 -1
  62. package/src/client/client.ts +8 -4
  63. package/dist/tsup/chunk-3CZAZIO5.js.map +0 -1
  64. package/dist/tsup/chunk-4SGTACEH.cjs.map +0 -1
  65. package/dist/tsup/chunk-EQODJ4G7.cjs.map +0 -1
  66. package/dist/tsup/chunk-LEXBAJ2Q.js.map +0 -1
  67. package/src/agent-os/actor/cron.ts +0 -84
  68. package/src/agent-os/actor/db.ts +0 -54
  69. package/src/agent-os/actor/filesystem.ts +0 -131
  70. package/src/agent-os/actor/index.ts +0 -285
  71. package/src/agent-os/actor/network.ts +0 -58
  72. package/src/agent-os/actor/preview.ts +0 -190
  73. package/src/agent-os/actor/process.ts +0 -177
  74. package/src/agent-os/actor/session.ts +0 -518
  75. package/src/agent-os/actor/shell.ts +0 -60
  76. package/src/agent-os/config.ts +0 -79
  77. package/src/agent-os/fs/database-vfs.ts +0 -624
  78. package/src/agent-os/types.ts +0 -148
  79. /package/dist/tsup/{chunk-NHXI4GVK.js.map → chunk-IKMLO5KS.js.map} +0 -0
  80. /package/dist/tsup/{chunk-YXVLQDDK.js.map → chunk-KJBV7M2J.js.map} +0 -0
  81. /package/dist/tsup/{chunk-7HU3OZCW.js.map → chunk-QLIVFNLT.js.map} +0 -0
  82. /package/dist/tsup/{chunk-BKUZYZRZ.js.map → chunk-SWESH3VP.js.map} +0 -0
  83. /package/dist/tsup/{chunk-XKVT36WN.js.map → chunk-UEQ5NN24.js.map} +0 -0
  84. /package/dist/tsup/{chunk-YQ7QHMPY.js.map → chunk-XQVCT3CM.js.map} +0 -0
@@ -1,2718 +1,2 @@
1
- import * as _rivet_dev_agent_os_core from '@rivet-dev/agent-os-core';
2
- import { AgentOs, JsonRpcNotification, PermissionRequest, CronEvent, AgentCapabilities, AgentInfo, JsonRpcResponse, AgentOsOptions, BatchReadResult, BatchWriteEntry, BatchWriteResult, ReaddirRecursiveOptions, DirEntry, AgentRegistryEntry, SpawnedProcessInfo, ProcessInfo, ProcessTreeNode, SessionModeState, SessionConfigOption, GetEventsOptions, SequencedEvent, PermissionReply, AgentType, CreateSessionOptions, SessionInfo, OpenShellOptions } from '@rivet-dev/agent-os-core';
3
- import { z as z$1 } from 'zod/v4';
4
- import { StandardSchemaV1 } from '@standard-schema/spec';
5
- import { Rivet } from '@rivetkit/engine-api-full';
6
- import { Context, Handler, Hono } from 'hono';
7
- import { UniversalWebSocket } from '@rivetkit/virtual-websocket';
8
- import * as _rivetkit_rivetkit_wasm from '@rivetkit/rivetkit-wasm';
9
- import { z } from 'zod';
10
- import { Logger } from 'pino';
11
- import { ContentfulStatusCode } from 'hono/utils/http-status';
12
1
 
13
- type AnyDatabaseProvider = DatabaseProvider<any> | undefined;
14
- interface ActorMetricsLike {
15
- totalKvReads: number;
16
- totalKvWrites: number;
17
- trackSql(query: string, durationMs: number): void;
18
- }
19
- type InferDatabaseClient<DBProvider extends AnyDatabaseProvider> = DBProvider extends DatabaseProvider<any> ? Awaited<ReturnType<DBProvider["createClient"]>> : RawAccess;
20
- type SqliteBindings = unknown[] | Record<string, unknown>;
21
- interface SqliteQueryResult {
22
- columns: string[];
23
- rows: unknown[][];
24
- }
25
- interface SqliteExecuteResult extends SqliteQueryResult {
26
- changes: number;
27
- lastInsertRowId?: number | null;
28
- }
29
- interface SqliteBatchStatement {
30
- sql: string;
31
- params?: SqliteBindings;
32
- }
33
- interface SqliteTransactionOptions {
34
- /** Static operation name used to aggregate transaction performance. */
35
- name?: string;
36
- /** Deadlock-safety timeout in milliseconds. */
37
- timeout?: number;
38
- /** @experimental */
39
- experimental?: {
40
- /**
41
- * Atomically includes actor and hibernatable connection state.
42
- * Only single-statement `execute` calls are supported in the transaction.
43
- * Concurrent actions that try to mutate state while the transaction is
44
- * active fail with `actor.state_transaction_conflict`.
45
- */
46
- includeState?: boolean;
47
- };
48
- }
49
- /**
50
- * SQLite profiling configuration.
51
- *
52
- * @experimental This entire configuration surface is experimental and subject
53
- * to change without notice.
54
- */
55
- interface SqliteProfilingOptions {
56
- enabled?: boolean;
57
- maxTrackedStatementFingerprints?: number;
58
- maxTrackedTransactionFingerprints?: number;
59
- maxPrometheusSeries?: number;
60
- maxStatementsPerTransactionTrace?: number;
61
- maxGetPagesRequestsPerTrace?: number;
62
- maxTransactionNameBytes?: number;
63
- slowOperationThresholdMs?: number;
64
- baselineSampleRate?: number;
65
- maxDiagnosticEventsPerMinute?: number;
66
- diagnosticEventQueueCapacity?: number;
67
- }
68
- interface SqliteNativeMetrics {
69
- requestBuildNs: number;
70
- serializeNs: number;
71
- transportNs: number;
72
- stateUpdateNs: number;
73
- totalNs: number;
74
- commitCount: number;
75
- pageCacheEntries: number;
76
- pageCacheWeightedSize: number;
77
- pageCacheCapacityPages: number;
78
- writeBufferDirtyPages: number;
79
- dbSizePages: number;
80
- }
81
- interface SqliteDatabase {
82
- exec(sql: string, callback?: (row: unknown[], columns: string[]) => void): Promise<void>;
83
- execute(sql: string, params?: SqliteBindings): Promise<SqliteExecuteResult>;
84
- executeBatch(statements: SqliteBatchStatement[]): Promise<SqliteExecuteResult[]>;
85
- beginTransaction(timeoutMs?: number, name?: string): Promise<SqliteTransactionDatabase>;
86
- run(sql: string, params?: SqliteBindings): Promise<void>;
87
- query(sql: string, params?: SqliteBindings): Promise<SqliteQueryResult>;
88
- nativeMetrics?(): SqliteNativeMetrics | Promise<SqliteNativeMetrics | null> | null;
89
- close(): Promise<void>;
90
- }
91
- interface SqliteTransactionDatabase {
92
- exec(sql: string, callback?: (row: unknown[], columns: string[]) => void): Promise<void>;
93
- execute(sql: string, params?: SqliteBindings): Promise<SqliteExecuteResult>;
94
- commit(): Promise<void>;
95
- rollback(): Promise<void>;
96
- }
97
- /**
98
- * Provider for opening native databases from the active runtime.
99
- */
100
- interface NativeDatabaseProvider {
101
- open(actorId: string): Promise<SqliteDatabase>;
102
- }
103
- /**
104
- * Context provided to database providers for creating database clients
105
- */
106
- interface DatabaseProviderContext {
107
- /**
108
- * Actor ID
109
- */
110
- actorId: string;
111
- /**
112
- * Override the default Drizzle database client (optional).
113
- * If not provided, a KV-backed client will be constructed.
114
- */
115
- overrideDrizzleDatabaseClient?: () => Promise<DrizzleDatabaseClient | undefined>;
116
- /** KV operations exposed for custom database providers. */
117
- kv: {
118
- batchPut: (entries: [Uint8Array, Uint8Array][]) => Promise<void>;
119
- batchGet: (keys: Uint8Array[]) => Promise<(Uint8Array | null)[]>;
120
- batchDelete: (keys: Uint8Array[]) => Promise<void>;
121
- deleteRange: (start: Uint8Array, end: Uint8Array) => Promise<void>;
122
- };
123
- /**
124
- * Actor metrics instance. When provided, KV and SQL operations are tracked.
125
- */
126
- metrics?: ActorMetricsLike;
127
- /**
128
- * Logger for debug output. When provided, SQL queries are logged with
129
- * duration and KV call count.
130
- */
131
- log?: {
132
- debug(obj: Record<string, unknown>): void;
133
- };
134
- /**
135
- * Provider for opening native databases from the active runtime.
136
- */
137
- nativeDatabaseProvider?: NativeDatabaseProvider;
138
- }
139
- type DatabaseProvider<DB extends RawAccess> = {
140
- /**
141
- * Local SQLite profiling controls consumed by the actor runtime.
142
- *
143
- * @experimental This entire configuration surface is experimental and
144
- * subject to change without notice.
145
- */
146
- sqliteProfiling?: SqliteProfilingOptions;
147
- /**
148
- * Creates a new database client for the actor.
149
- * The result is passed to the actor context as `c.db`.
150
- * @experimental
151
- */
152
- createClient: (ctx: DatabaseProviderContext) => Promise<DB>;
153
- /**
154
- * Runs before the actor has started.
155
- * Use this to run migrations or other setup tasks.
156
- * @experimental
157
- */
158
- onMigrate: (client: DB) => void | Promise<void>;
159
- };
160
- /**
161
- * Drizzle database client interface (will be extended by drizzle-orm types)
162
- */
163
- type DrizzleDatabaseClient = {};
164
- type ExecuteFunction = <TRow extends Record<string, unknown> = Record<string, unknown>>(query: string, ...args: unknown[]) => Promise<TRow[]>;
165
- type RawAccess = {
166
- /**
167
- * Executes a raw SQL query.
168
- */
169
- execute: ExecuteFunction;
170
- /** Runs a callback in an isolated SQLite transaction. */
171
- transaction: <T>(callback: (tx: RawAccess) => Promise<T> | T, options?: SqliteTransactionOptions) => Promise<T>;
172
- /**
173
- * Returns native SQLite metrics when the active runtime supports them.
174
- */
175
- nativeMetrics?: () => SqliteNativeMetrics | Promise<SqliteNativeMetrics | null> | null;
176
- /**
177
- * Closes the database connection and releases resources.
178
- */
179
- close: () => Promise<void>;
180
- };
181
-
182
- declare const ActorsSchema: z.ZodRecord<z.ZodString, z.ZodCustom<AnyActorDefinition, AnyActorDefinition>>;
183
- type RegistryActors = z.infer<typeof ActorsSchema>;
184
- declare const RegistryConfigSchema: z.ZodPipe<z.ZodObject<{
185
- use: z.ZodRecord<z.ZodString, z.ZodCustom<AnyActorDefinition, AnyActorDefinition>>;
186
- test: z.ZodDefault<z.ZodOptional<z.ZodObject<{
187
- enabled: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
188
- sqliteBackend: z.ZodOptional<z.ZodEnum<{
189
- local: "local";
190
- remote: "remote";
191
- }>>;
192
- }, z.core.$strip>>>;
193
- maxIncomingMessageSize: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
194
- maxOutgoingMessageSize: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
195
- runtime: z.ZodPipe<z.ZodOptional<z.ZodEnum<{
196
- auto: "auto";
197
- native: "native";
198
- wasm: "wasm";
199
- }>>, z.ZodTransform<"auto" | "native" | "wasm", "auto" | "native" | "wasm" | undefined>>;
200
- wasm: z.ZodDefault<z.ZodOptional<z.ZodObject<{
201
- bindings: z.ZodOptional<z.ZodCustom<typeof _rivetkit_rivetkit_wasm, typeof _rivetkit_rivetkit_wasm>>;
202
- initInput: z.ZodOptional<z.ZodCustom<any, any>>;
203
- }, z.core.$strip>>>;
204
- sqlite: z.ZodPipe<z.ZodOptional<z.ZodUnion<readonly [z.ZodEnum<{
205
- local: "local";
206
- remote: "remote";
207
- }>, z.ZodObject<{
208
- backend: z.ZodEnum<{
209
- local: "local";
210
- remote: "remote";
211
- }>;
212
- }, z.core.$strip>]>>, z.ZodTransform<{
213
- backend: "local" | "remote";
214
- } | undefined, "local" | "remote" | {
215
- backend: "local" | "remote";
216
- } | undefined>>;
217
- noWelcome: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
218
- logging: z.ZodDefault<z.ZodOptional<z.ZodObject<{
219
- baseLogger: z.ZodOptional<z.ZodCustom<Logger, Logger>>;
220
- level: z.ZodOptional<z.ZodEnum<{
221
- fatal: "fatal";
222
- error: "error";
223
- warn: "warn";
224
- info: "info";
225
- debug: "debug";
226
- trace: "trace";
227
- silent: "silent";
228
- }>>;
229
- }, z.core.$strip>>>;
230
- endpoint: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
231
- token: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
232
- namespace: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
233
- headers: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
234
- staticDir: z.ZodOptional<z.ZodString>;
235
- httpBasePath: z.ZodDefault<z.ZodOptional<z.ZodString>>;
236
- httpPort: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
237
- httpHost: z.ZodOptional<z.ZodString>;
238
- startEngine: z.ZodDefault<z.ZodBoolean>;
239
- engineHost: z.ZodDefault<z.ZodOptional<z.ZodString>>;
240
- enginePort: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
241
- engineVersion: z.ZodDefault<z.ZodOptional<z.ZodString>>;
242
- startServices: z.ZodOptional<z.ZodBoolean>;
243
- configurePool: z.ZodOptional<z.ZodOptional<z.ZodObject<{
244
- name: z.ZodOptional<z.ZodString>;
245
- url: z.ZodString;
246
- headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
247
- requestLifespan: z.ZodOptional<z.ZodNumber>;
248
- drainGracePeriod: z.ZodOptional<z.ZodNumber>;
249
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
250
- metadataPollInterval: z.ZodOptional<z.ZodNumber>;
251
- drainOnVersionUpgrade: z.ZodOptional<z.ZodBoolean>;
252
- }, z.core.$strip>>>;
253
- serverless: z.ZodDefault<z.ZodOptional<z.ZodObject<{
254
- basePath: z.ZodDefault<z.ZodOptional<z.ZodString>>;
255
- maxStartPayloadBytes: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
256
- publicEndpoint: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
257
- publicToken: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>;
258
- }, z.core.$strip>>>;
259
- envoy: z.ZodDefault<z.ZodOptional<z.ZodObject<{
260
- poolName: z.ZodDefault<z.ZodString>;
261
- version: z.ZodDefault<z.ZodNumber>;
262
- totalSlots: z.ZodDefault<z.ZodNumber>;
263
- envoyKey: z.ZodOptional<z.ZodString>;
264
- }, z.core.$strip>>>;
265
- shutdown: z.ZodDefault<z.ZodOptional<z.ZodObject<{
266
- gracePeriodMs: z.ZodOptional<z.ZodNumber>;
267
- disableSignalHandlers: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
268
- }, z.core.$strip>>>;
269
- }, z.core.$strip>, z.ZodTransform<{
270
- sqlite: {
271
- backend: "local" | "remote";
272
- } | undefined;
273
- endpoint: string | undefined;
274
- startServices: boolean;
275
- namespace: string;
276
- token: string | undefined;
277
- publicEndpoint: string | undefined;
278
- publicNamespace: string | undefined;
279
- publicToken: string | undefined;
280
- validateServerlessEndpoint: boolean;
281
- serverless: {
282
- publicEndpoint: string | undefined;
283
- basePath: string;
284
- maxStartPayloadBytes: number;
285
- publicToken: string | undefined;
286
- };
287
- use: Record<string, AnyActorDefinition>;
288
- test: {
289
- enabled: boolean;
290
- sqliteBackend?: "local" | "remote" | undefined;
291
- };
292
- maxIncomingMessageSize: number;
293
- maxOutgoingMessageSize: number;
294
- runtime: "auto" | "native" | "wasm";
295
- wasm: {
296
- bindings?: typeof _rivetkit_rivetkit_wasm | undefined;
297
- initInput?: any;
298
- };
299
- noWelcome: boolean;
300
- logging: {
301
- baseLogger?: Logger | undefined;
302
- level?: "fatal" | "error" | "warn" | "info" | "debug" | "trace" | "silent" | undefined;
303
- };
304
- headers: Record<string, string>;
305
- httpBasePath: string;
306
- httpPort: number;
307
- startEngine: boolean;
308
- engineHost: string;
309
- enginePort: number;
310
- engineVersion: string;
311
- envoy: {
312
- poolName: string;
313
- version: number;
314
- totalSlots: number;
315
- envoyKey?: string | undefined;
316
- };
317
- shutdown: {
318
- disableSignalHandlers: boolean;
319
- gracePeriodMs?: number | undefined;
320
- };
321
- staticDir?: string | undefined;
322
- httpHost?: string | undefined;
323
- configurePool?: {
324
- url: string;
325
- name?: string | undefined;
326
- headers?: Record<string, string> | undefined;
327
- requestLifespan?: number | undefined;
328
- drainGracePeriod?: number | undefined;
329
- metadata?: Record<string, unknown> | undefined;
330
- metadataPollInterval?: number | undefined;
331
- drainOnVersionUpgrade?: boolean | undefined;
332
- } | undefined;
333
- }, {
334
- use: Record<string, AnyActorDefinition>;
335
- test: {
336
- enabled: boolean;
337
- sqliteBackend?: "local" | "remote" | undefined;
338
- };
339
- maxIncomingMessageSize: number;
340
- maxOutgoingMessageSize: number;
341
- runtime: "auto" | "native" | "wasm";
342
- wasm: {
343
- bindings?: typeof _rivetkit_rivetkit_wasm | undefined;
344
- initInput?: any;
345
- };
346
- sqlite: {
347
- backend: "local" | "remote";
348
- } | undefined;
349
- noWelcome: boolean;
350
- logging: {
351
- baseLogger?: Logger | undefined;
352
- level?: "fatal" | "error" | "warn" | "info" | "debug" | "trace" | "silent" | undefined;
353
- };
354
- endpoint: string | undefined;
355
- token: string | undefined;
356
- namespace: string | undefined;
357
- headers: Record<string, string>;
358
- httpBasePath: string;
359
- httpPort: number;
360
- startEngine: boolean;
361
- engineHost: string;
362
- enginePort: number;
363
- engineVersion: string;
364
- serverless: {
365
- basePath: string;
366
- maxStartPayloadBytes: number;
367
- publicEndpoint: string | undefined;
368
- publicToken: string | undefined;
369
- };
370
- envoy: {
371
- poolName: string;
372
- version: number;
373
- totalSlots: number;
374
- envoyKey?: string | undefined;
375
- };
376
- shutdown: {
377
- disableSignalHandlers: boolean;
378
- gracePeriodMs?: number | undefined;
379
- };
380
- staticDir?: string | undefined;
381
- httpHost?: string | undefined;
382
- startServices?: boolean | undefined;
383
- configurePool?: {
384
- url: string;
385
- name?: string | undefined;
386
- headers?: Record<string, string> | undefined;
387
- requestLifespan?: number | undefined;
388
- drainGracePeriod?: number | undefined;
389
- metadata?: Record<string, unknown> | undefined;
390
- metadataPollInterval?: number | undefined;
391
- drainOnVersionUpgrade?: boolean | undefined;
392
- } | undefined;
393
- }>>;
394
- type RegistryConfig = z.infer<typeof RegistryConfigSchema>;
395
- type RegistryConfigInput<A extends RegistryActors> = Omit<z.input<typeof RegistryConfigSchema>, "use"> & {
396
- use: A;
397
- };
398
-
399
- type SchemaHookResult = boolean | Promise<boolean>;
400
- type SchemaHook<TContext = any> = (ctx: TContext) => SchemaHookResult;
401
- interface EventTypeToken<T, TContext = any> {
402
- readonly _eventType?: T;
403
- readonly canSubscribe?: SchemaHook<TContext>;
404
- readonly schema?: PrimitiveSchema;
405
- }
406
- interface QueueTypeToken<TMessage, TComplete = never, TContext = any> {
407
- readonly _queueMessage?: TMessage;
408
- readonly _queueComplete?: TComplete;
409
- readonly canPublish?: SchemaHook<TContext>;
410
- readonly message?: PrimitiveSchema;
411
- readonly complete?: PrimitiveSchema;
412
- }
413
- type PrimitiveSchema = StandardSchemaV1 | EventTypeToken<unknown, any>;
414
- interface EventSchemaDefinition<TContext = any> {
415
- schema: PrimitiveSchema;
416
- canSubscribe?: SchemaHook<TContext>;
417
- }
418
- interface QueueSchemaDefinition<TContext = any> {
419
- message: PrimitiveSchema;
420
- complete?: PrimitiveSchema;
421
- canPublish?: SchemaHook<TContext>;
422
- }
423
- type EventSchema<TContext = any> = PrimitiveSchema | EventSchemaDefinition<TContext>;
424
- type QueueSchema = PrimitiveSchema | QueueSchemaDefinition<any> | QueueTypeToken<unknown, unknown, any>;
425
- type EventSchemaConfig<TContext = any> = Record<string, EventSchema<TContext>>;
426
- type QueueSchemaConfig<_TContext = any> = Record<string, QueueSchema>;
427
- type InferSchema<T> = T extends QueueSchemaDefinition<any> ? InferSchema<T["message"]> : T extends QueueTypeToken<infer M, unknown, any> ? M : T extends EventSchemaDefinition<any> ? InferSchema<T["schema"]> : T extends StandardSchemaV1<any, infer O> ? O : T extends EventTypeToken<infer R, any> ? R : never;
428
- type InferSchemaMap<T extends Record<string, unknown>> = {
429
- [K in keyof T]: InferSchema<T[K]>;
430
- };
431
- type InferQueueComplete<T> = T extends QueueTypeToken<unknown, infer C, any> ? [C] extends [never] ? never : C : T extends QueueSchemaDefinition<any> ? T["complete"] extends PrimitiveSchema ? InferSchema<T["complete"]> : never : never;
432
- type InferQueueCompleteMap<T extends QueueSchemaConfig> = {
433
- [K in keyof T]: InferQueueComplete<T[K]>;
434
- };
435
- type InferEventArgs<T> = T extends readonly unknown[] ? number extends T["length"] ? [T] : T : [T];
436
-
437
- interface BaseActorDefinition<S, CP, CS, V, I, DB extends AnyDatabaseProvider, E extends EventSchemaConfig = Record<never, never>, Q extends QueueSchemaConfig = Record<never, never>, _R extends Actions<S, CP, CS, V, I, DB, E, Q> = Actions<S, CP, CS, V, I, DB, E, Q>> {
438
- readonly config: ActorConfig<S, CP, CS, V, I, DB, E, Q, _R>;
439
- }
440
- interface AnyActorDefinition {
441
- readonly config: any;
442
- }
443
- declare class ActorDefinition<S, CP, CS, V, I, DB extends AnyDatabaseProvider, E extends EventSchemaConfig = Record<never, never>, Q extends QueueSchemaConfig = Record<never, never>, R extends Actions<S, CP, CS, V, I, DB, E, Q> = Actions<S, CP, CS, V, I, DB, E, Q>> implements BaseActorDefinition<S, CP, CS, V, I, DB, E, Q, R> {
444
- #private;
445
- constructor(config: ActorConfig<S, CP, CS, V, I, DB, E, Q, R>);
446
- get config(): ActorConfig<S, CP, CS, V, I, DB, E, Q, R>;
447
- }
448
-
449
- /** Options for `client.auth.issueToken()`. `expiresIn` is in seconds. */
450
- type IssueTokenOptions = Pick<Rivet.AuthTokenCreateRequest, "subject" | "grants"> & {
451
- expiresIn?: Rivet.AuthTokenCreateRequest["duration"];
452
- };
453
- /** Token timestamps are Unix milliseconds. */
454
- interface IssuedToken {
455
- token: Rivet.AuthTokenCreateResponse["token"];
456
- issuedAt: Rivet.AuthTokenCreateResponse["issuedTs"];
457
- expiresAt: Rivet.AuthTokenCreateResponse["expiresTs"];
458
- }
459
- /** Resources that can be scoped to a single actor ID. */
460
- type ActorTokenResource = Extract<Rivet.AuthTokenGrant["resource"], "actor_gateway" | "actor" | "actor_kv">;
461
- type ActorTokenPermissions = Partial<Record<ActorTokenResource, Rivet.AuthTokenGrant["operations"]>>;
462
- /** Options for `actor.issueToken()`. Omit permissions for gateway read access only. */
463
- type ActorIssueTokenOptions = Pick<IssueTokenOptions, "subject" | "expiresIn"> & {
464
- permissions?: ActorTokenPermissions;
465
- };
466
-
467
- declare const EncodingSchema: z$1.ZodEnum<{
468
- json: "json";
469
- cbor: "cbor";
470
- bare: "bare";
471
- }>;
472
- /**
473
- * Encoding used to communicate between the client & actor.
474
- */
475
- type Encoding = z$1.infer<typeof EncodingSchema>;
476
-
477
- declare const ActorKeySchema: z$1.ZodArray<z$1.ZodString>;
478
- type ActorKey = z$1.infer<typeof ActorKeySchema>;
479
- /**
480
- * Crash policy for actor lifecycle management.
481
- *
482
- * This schema is only used by the engine driver for actor creation. The manager
483
- * driver ignores crash policy and passes it through to the engine unchanged.
484
- */
485
- declare const CrashPolicySchema: z$1.ZodEnum<{
486
- restart: "restart";
487
- sleep: "sleep";
488
- destroy: "destroy";
489
- }>;
490
- type CrashPolicy = z$1.infer<typeof CrashPolicySchema>;
491
- declare const ActorQuerySchema: z$1.ZodUnion<readonly [z$1.ZodObject<{
492
- getForId: z$1.ZodObject<{
493
- name: z$1.ZodString;
494
- actorId: z$1.ZodString;
495
- }, z$1.core.$strip>;
496
- }, z$1.core.$strip>, z$1.ZodObject<{
497
- getForKey: z$1.ZodObject<{
498
- name: z$1.ZodString;
499
- key: z$1.ZodArray<z$1.ZodString>;
500
- }, z$1.core.$strip>;
501
- }, z$1.core.$strip>, z$1.ZodObject<{
502
- getOrCreateForKey: z$1.ZodObject<{
503
- name: z$1.ZodString;
504
- key: z$1.ZodArray<z$1.ZodString>;
505
- input: z$1.ZodOptional<z$1.ZodUnknown>;
506
- region: z$1.ZodOptional<z$1.ZodString>;
507
- poolName: z$1.ZodOptional<z$1.ZodString>;
508
- }, z$1.core.$strip>;
509
- }, z$1.core.$strip>, z$1.ZodObject<{
510
- create: z$1.ZodObject<{
511
- name: z$1.ZodString;
512
- key: z$1.ZodArray<z$1.ZodString>;
513
- input: z$1.ZodOptional<z$1.ZodUnknown>;
514
- region: z$1.ZodOptional<z$1.ZodString>;
515
- poolName: z$1.ZodOptional<z$1.ZodString>;
516
- }, z$1.core.$strip>;
517
- }, z$1.core.$strip>]>;
518
- type ActorQuery = z$1.infer<typeof ActorQuerySchema>;
519
-
520
- interface DeconstructedError {
521
- __type: "ActorError";
522
- statusCode: ContentfulStatusCode;
523
- public: boolean;
524
- group: string;
525
- code: string;
526
- message: string;
527
- metadata?: unknown;
528
- rayId?: string;
529
- actor?: ActorSpecifier;
530
- }
531
-
532
- interface RivetErrorOptions extends ErrorOptions {
533
- /** Error data can safely be serialized in a response to the client. */
534
- public?: boolean;
535
- /** Metadata associated with this error. */
536
- metadata?: unknown;
537
- /** Request identifier used to correlate this error with engine logs. */
538
- rayId?: string;
539
- /** Explicit HTTP status override for router responses. */
540
- statusCode?: number;
541
- /** Actor context associated with this error. */
542
- actor?: ActorSpecifier;
543
- }
544
- /** Identifies the actor that was handling work when an error was produced. */
545
- interface ActorSpecifier {
546
- actorId: string;
547
- generation: number;
548
- key?: string;
549
- }
550
- declare class RivetError extends Error {
551
- __type: "RivetError";
552
- public: boolean;
553
- metadata?: unknown;
554
- readonly rayId?: string;
555
- statusCode: number;
556
- actor?: ActorSpecifier;
557
- readonly group: string;
558
- readonly code: string;
559
- static isRivetError(error: unknown): error is RivetError | DeconstructedError;
560
- static isActorError(error: unknown): error is RivetError | DeconstructedError;
561
- constructor(group: string, code: string, message: string, options?: RivetErrorOptions | unknown);
562
- toString(): string;
563
- }
564
-
565
- /** Sample rates keyed by action name, nested like the actor's action groups. */
566
- interface ActionSampleRates {
567
- readonly [name: string]: number | ActionSampleRates;
568
- }
569
- /**
570
- * {@link ActionSampleRates} limited to the actions of one actor, so a rate for
571
- * an action that does not exist is a compile error.
572
- */
573
- type ActionTraceSamplers<TActions> = {
574
- readonly [K in keyof TActions]?: TActions[K] extends (...args: never[]) => unknown ? number : ActionTraceSamplers<TActions[K]>;
575
- };
576
- /** Trace sampling for one actor definition. */
577
- interface ActorTracingOptions<TActions> {
578
- /**
579
- * Share of this actor's invocations that are recorded, from 0 to 1. A rate
580
- * lowers what is recorded and never raises it, so an invocation inside a
581
- * trace the caller did not record is not recorded at any rate.
582
- */
583
- readonly sampler?: number;
584
- /** Rates that replace `sampler` for single actions. */
585
- readonly actions?: ActionTraceSamplers<TActions>;
586
- }
587
-
588
- type UpgradeWebSocket = (createEvents: (c: Context) => any) => Handler;
589
- type GetUpgradeWebSocket = () => UpgradeWebSocket;
590
-
591
- type GatewayTarget = {
592
- directId: string;
593
- } | ActorQuery;
594
- interface GatewayRequestOptions {
595
- skipReadyWait?: boolean;
596
- }
597
- interface EngineControlClient {
598
- issueToken(options: IssueTokenOptions): Promise<IssuedToken>;
599
- getForId(input: GetForIdInput): Promise<ActorOutput | undefined>;
600
- getWithKey(input: GetWithKeyInput): Promise<ActorOutput | undefined>;
601
- getOrCreateWithKey(input: GetOrCreateWithKeyInput): Promise<ActorOutput>;
602
- createActor(input: CreateInput): Promise<ActorOutput>;
603
- listActors(input: ListActorsInput): Promise<ActorOutput[]>;
604
- sendRequest(target: GatewayTarget, actorRequest: Request, options?: GatewayRequestOptions): Promise<Response>;
605
- openWebSocket(path: string, target: GatewayTarget, encoding: Encoding, params: unknown, options?: GatewayRequestOptions): Promise<UniversalWebSocket>;
606
- /** Refresh a credential rejected during this WebSocket handshake, if supported. */
607
- refreshAuthToken?(ws: UniversalWebSocket): Promise<boolean>;
608
- proxyRequest(c: Context, actorRequest: Request, actorId: string): Promise<Response>;
609
- proxyWebSocket(c: Context, path: string, actorId: string, encoding: Encoding, params: unknown): Promise<Response>;
610
- buildGatewayUrl(target: GatewayTarget, options?: GatewayRequestOptions): Promise<string>;
611
- displayInformation(): RuntimeDisplayInformation;
612
- extraStartupLog?: () => Record<string, unknown>;
613
- modifyRuntimeRouter?: (config: RegistryConfig, router: Hono) => void;
614
- setGetUpgradeWebSocket(getUpgradeWebSocket: GetUpgradeWebSocket): void;
615
- shutdown?(): void;
616
- /**
617
- * Test-only helper that simulates an abrupt actor crash.
618
- */
619
- hardCrashActor?(actorId: string): Promise<void>;
620
- }
621
- interface RuntimeDisplayInformation {
622
- properties: Record<string, string>;
623
- }
624
- interface GetForIdInput {
625
- c?: Context | undefined;
626
- name: string;
627
- actorId: string;
628
- }
629
- interface GetWithKeyInput {
630
- c?: Context | undefined;
631
- name: string;
632
- key: ActorKey;
633
- }
634
- interface GetOrCreateWithKeyInput {
635
- c?: Context | undefined;
636
- name: string;
637
- key: ActorKey;
638
- input?: unknown;
639
- region?: string;
640
- crashPolicy?: CrashPolicy;
641
- /** Overrides the client's configured pool name for this actor. */
642
- poolName?: string;
643
- }
644
- interface CreateInput {
645
- c?: Context | undefined;
646
- name: string;
647
- key: ActorKey;
648
- input?: unknown;
649
- region?: string;
650
- crashPolicy?: CrashPolicy;
651
- /** Overrides the client's configured pool name for this actor. */
652
- poolName?: string;
653
- }
654
- interface ListActorsInput {
655
- c?: Context | undefined;
656
- name: string;
657
- key?: string;
658
- includeDestroyed?: boolean;
659
- }
660
- interface ActorOutput {
661
- actorId: string;
662
- name: string;
663
- key: ActorKey;
664
- createTs?: number;
665
- startTs?: number | null;
666
- connectableTs?: number | null;
667
- sleepTs?: number | null;
668
- destroyTs?: number | null;
669
- error?: unknown;
670
- }
671
-
672
- /** Correlation owned by the currently executing Core actor invocation. */
673
- interface ActorInvocationTraceContext {
674
- /** Ray ID the invocation received, absent when nothing upstream supplied one. */
675
- readonly rayId?: string;
676
- /** Core-owned invocation span context, absent when tracing is disabled. */
677
- readonly span?: ActorInvocationSpanContext;
678
- }
679
- /** W3C span context of the Core invocation span. */
680
- interface ActorInvocationSpanContext {
681
- /** W3C trace identifier. */
682
- readonly traceId: string;
683
- /** W3C span identifier for the Core invocation. */
684
- readonly spanId: string;
685
- /** OpenTelemetry trace flags encoded as an integer. */
686
- readonly traceFlags: number;
687
- /** Optional vendor trace state inherited by the Core invocation. */
688
- readonly tracestate?: string;
689
- }
690
-
691
- declare const handleBrand: unique symbol;
692
- type OpaqueHandle<Name extends string> = {
693
- readonly [handleBrand]: Name;
694
- };
695
- type RegistryHandle = OpaqueHandle<"registry">;
696
- type ActorFactoryHandle = OpaqueHandle<"actorFactory">;
697
- type ActorContextHandle = OpaqueHandle<"actorContext">;
698
- type ConnHandle = OpaqueHandle<"conn">;
699
- type WebSocketHandle = OpaqueHandle<"webSocket">;
700
- type CancellationTokenHandle = OpaqueHandle<"cancellationToken">;
701
- type ActorStateTransactionHandle = OpaqueHandle<"actorStateTransaction">;
702
- type SqliteTransactionHandle = OpaqueHandle<"sqliteTransaction">;
703
- type RuntimeBytes = Uint8Array;
704
- interface RuntimeActorKeySegment {
705
- kind: string;
706
- stringValue?: string;
707
- numberValue?: number;
708
- }
709
- /** Resolves correlation at operation time so retained clients cannot freeze stale context. */
710
- type CurrentActorInvocation = () => ActorInvocationTraceContext | undefined;
711
- /** One open call from an actor out to another actor. */
712
- interface RuntimeOutboundCall {
713
- /**
714
- * W3C context of the call's own span, to send to the callee so it parents to
715
- * the call. Absent when tracing is disabled.
716
- */
717
- readonly span?: ActorInvocationSpanContext;
718
- /**
719
- * Records the call's outcome. `error` is the failure encoded the way the
720
- * bridge encodes errors, so a structured error keeps its group and code.
721
- */
722
- finish(error?: string): void;
723
- }
724
- /**
725
- * Opens the span covering one call out to another actor, or returns `undefined`
726
- * outside an invocation or on a runtime without invocation telemetry. Callers
727
- * send their own context when it returns nothing.
728
- */
729
- type StartCallSpan = (actorName: string, actionName: string) => RuntimeOutboundCall | undefined;
730
- interface RuntimeHttpRequest {
731
- method: string;
732
- uri: string;
733
- headers?: Record<string, string>;
734
- body?: RuntimeBytes;
735
- }
736
- interface RuntimeHttpResponseBodyStream {
737
- cancelled(): Promise<void>;
738
- write(chunk: Uint8Array): Promise<void>;
739
- end(): Promise<void>;
740
- error(message: string): Promise<void>;
741
- }
742
- interface RuntimeStateDeltaPayload {
743
- state?: RuntimeBytes;
744
- connHibernation: Array<{
745
- connId: string;
746
- bytes: RuntimeBytes;
747
- }>;
748
- connHibernationRemoved: string[];
749
- }
750
- interface RuntimeWorkflowKvWrite {
751
- key: RuntimeBytes;
752
- value: RuntimeBytes;
753
- }
754
- interface RuntimeRequestSaveOpts {
755
- immediate?: boolean;
756
- maxWaitMs?: number;
757
- }
758
- interface RuntimeInspectorSnapshot {
759
- stateRevision: number;
760
- connectionsRevision: number;
761
- queueRevision: number;
762
- activeConnections: number;
763
- queueSize: number;
764
- connectedClients: number;
765
- }
766
- interface RuntimeQueueMessage {
767
- id(): bigint;
768
- name(): string;
769
- body(): RuntimeBytes;
770
- createdAt(): number;
771
- isCompletable(): boolean;
772
- complete(response?: RuntimeBytes | undefined | null): Promise<void>;
773
- }
774
- interface RuntimeQueueInspectMessage {
775
- id: number;
776
- name: string;
777
- createdAtMs: number;
778
- }
779
- interface RuntimeScheduledEventInfo {
780
- id: string;
781
- action: string;
782
- args: RuntimeBytes;
783
- runAt: number;
784
- }
785
- interface RuntimeCronJobInfo {
786
- name: string;
787
- kind: "cron" | "every";
788
- action: string;
789
- args: RuntimeBytes;
790
- nextRunAt: number;
791
- lastRunAt?: number;
792
- expression?: string;
793
- timezone?: string;
794
- intervalMs?: number;
795
- maxHistory: number;
796
- }
797
- interface RuntimeScheduleErrorInfo {
798
- group: string;
799
- code: string;
800
- message: string;
801
- metadata?: unknown;
802
- }
803
- interface RuntimeCronFire {
804
- action: string;
805
- scheduledAt: number;
806
- firedAt: number;
807
- finishedAt?: number;
808
- result: "running" | "ok" | "error" | "skipped";
809
- error?: RuntimeScheduleErrorInfo;
810
- }
811
- interface RuntimeQueueNextBatchOptions {
812
- names?: string[];
813
- count?: number;
814
- timeoutMs?: number;
815
- completable?: boolean;
816
- }
817
- interface RuntimeQueueWaitOptions {
818
- timeoutMs?: number;
819
- completable?: boolean;
820
- }
821
- interface RuntimeQueueEnqueueAndWaitOptions {
822
- timeoutMs?: number;
823
- }
824
- interface RuntimeQueueTryNextBatchOptions {
825
- names?: string[];
826
- count?: number;
827
- completable?: boolean;
828
- }
829
- interface RuntimeKvListOptions {
830
- reverse?: boolean;
831
- limit?: number;
832
- }
833
- interface RuntimeKvEntry {
834
- key: RuntimeBytes;
835
- value: RuntimeBytes;
836
- }
837
- type RuntimeSqlBindNoValues = {
838
- intValue?: never;
839
- floatValue?: never;
840
- textValue?: never;
841
- blobValue?: never;
842
- };
843
- type RuntimeSqlBindParam = ({
844
- kind: "null";
845
- } & RuntimeSqlBindNoValues) | {
846
- kind: "int";
847
- intValue: number;
848
- floatValue?: never;
849
- textValue?: never;
850
- blobValue?: never;
851
- } | {
852
- kind: "float";
853
- intValue?: never;
854
- floatValue: number;
855
- textValue?: never;
856
- blobValue?: never;
857
- } | {
858
- kind: "text";
859
- intValue?: never;
860
- floatValue?: never;
861
- textValue: string;
862
- blobValue?: never;
863
- } | {
864
- kind: "blob";
865
- intValue?: never;
866
- floatValue?: never;
867
- textValue?: never;
868
- blobValue: RuntimeBytes;
869
- };
870
- type RuntimeSqlBindParams = RuntimeSqlBindParam[] | null;
871
- interface RuntimeActorRuntimeSocketEndpointInfo {
872
- path: string;
873
- }
874
- interface RuntimeSqlQueryResult {
875
- columns: string[];
876
- rows: unknown[][];
877
- }
878
- type RuntimeSqlExecResult = RuntimeSqlQueryResult;
879
- interface RuntimeSqlExecuteResult extends RuntimeSqlQueryResult {
880
- changes: number;
881
- lastInsertRowId?: number | null;
882
- }
883
- interface RuntimeSqlBatchStatement {
884
- sql: string;
885
- params?: RuntimeSqlBindParams;
886
- }
887
- interface RuntimeSqlRunResult {
888
- changes: number;
889
- }
890
- /** Sample rates for the traces an actor starts, in the shape core takes. */
891
- interface RuntimeActorTracingConfig {
892
- sampler?: number;
893
- /** Keyed by flattened, dot-separated action name. */
894
- actions?: Record<string, number>;
895
- }
896
- interface RuntimeActorConfig {
897
- name?: string;
898
- icon?: string;
899
- hasDatabase?: boolean;
900
- remoteSqlite?: boolean;
901
- sqliteProfiling?: SqliteProfilingOptions;
902
- tracing?: RuntimeActorTracingConfig;
903
- enableActorRuntimeSocket?: boolean;
904
- hasState?: boolean;
905
- canHibernateWebsocket?: boolean;
906
- stateSaveIntervalMs?: number;
907
- createStateTimeoutMs?: number;
908
- onCreateTimeoutMs?: number;
909
- createVarsTimeoutMs?: number;
910
- createConnStateTimeoutMs?: number;
911
- onBeforeConnectTimeoutMs?: number;
912
- onConnectTimeoutMs?: number;
913
- onMigrateTimeoutMs?: number;
914
- onWakeTimeoutMs?: number;
915
- onBeforeActorStartTimeoutMs?: number;
916
- actionTimeoutMs?: number;
917
- onRequestTimeoutMs?: number;
918
- sleepTimeoutMs?: number;
919
- noSleep?: boolean;
920
- sleepGracePeriodMs?: number;
921
- connectionLivenessTimeoutMs?: number;
922
- connectionLivenessIntervalMs?: number;
923
- maxQueueSize?: number;
924
- maxSchedules?: number;
925
- maxQueueMessageSize?: number;
926
- maxIncomingMessageSize?: number;
927
- maxOutgoingMessageSize?: number;
928
- preloadMaxWorkflowBytes?: number;
929
- preloadMaxConnectionsBytes?: number;
930
- actions?: Array<{
931
- name: string;
932
- }>;
933
- inspectorTabs?: Array<RuntimeInspectorTabEntry>;
934
- }
935
- interface RuntimeInspectorTabEntry {
936
- id: string;
937
- /** Required for custom entries; omitted for built-in hides. */
938
- label?: string;
939
- /**
940
- * Required for custom entries — absolute path to the source directory.
941
- * Resolved on the TS side before being handed to the runtime.
942
- */
943
- source?: string;
944
- /** Optional icon id for custom entries. */
945
- icon?: string;
946
- /** Set to true for built-in hide entries. */
947
- hidden?: boolean;
948
- }
949
- interface RuntimeServeConfig {
950
- version: number;
951
- endpoint: string;
952
- token?: string;
953
- namespace: string;
954
- poolName: string;
955
- engineBinaryPath?: string;
956
- startServices?: boolean;
957
- servicesBinaryPath?: string;
958
- engineHost?: string;
959
- enginePort?: number;
960
- handleInspectorHttpInRuntime?: boolean;
961
- inspectorTestToken?: string;
962
- serverlessBasePath?: string;
963
- serverlessPackageVersion: string;
964
- serverlessClientEndpoint?: string;
965
- serverlessClientNamespace?: string;
966
- serverlessClientToken?: string;
967
- serverlessValidateEndpoint: boolean;
968
- serverlessMaxStartPayloadBytes: number;
969
- }
970
- interface RuntimeListenerConfig {
971
- port: number;
972
- host?: string;
973
- publicDir?: string;
974
- application?: RuntimeApplicationFetch;
975
- }
976
- interface RuntimeServerlessRequest {
977
- method: string;
978
- url: string;
979
- headers: Record<string, string>;
980
- body: RuntimeBytes;
981
- }
982
- interface RuntimeApplicationRequest extends RuntimeServerlessRequest {
983
- cancelToken?: CancellationTokenHandle;
984
- }
985
- interface RuntimeApplicationResponse {
986
- status: number;
987
- headers: Record<string, string>;
988
- body?: RuntimeBytes;
989
- stream?: boolean;
990
- }
991
- type RuntimeApplicationFetch = (request: RuntimeApplicationRequest, responseBodyStream?: RuntimeHttpResponseBodyStream) => Promise<RuntimeApplicationResponse>;
992
- interface RuntimeApplicationListenerConfig extends RuntimeListenerConfig {
993
- application: RuntimeApplicationFetch;
994
- }
995
- interface RuntimeServerlessResponseHead {
996
- status: number;
997
- headers: Record<string, string>;
998
- }
999
- interface RuntimeRegistryRouteResponse {
1000
- status: number;
1001
- headers: Record<string, string>;
1002
- body: RuntimeBytes;
1003
- }
1004
- type RuntimeServerlessStreamEvent = {
1005
- kind: "chunk";
1006
- chunk?: RuntimeBytes;
1007
- } | {
1008
- kind: "end";
1009
- error?: {
1010
- group: string;
1011
- code: string;
1012
- message: string;
1013
- };
1014
- };
1015
- type RuntimeServerlessStreamCallback = (error: unknown, event?: RuntimeServerlessStreamEvent) => unknown;
1016
- type RuntimeWebSocketEvent = {
1017
- kind: "message";
1018
- data: string | RuntimeBytes;
1019
- binary: boolean;
1020
- messageIndex?: number;
1021
- } | {
1022
- kind: "close";
1023
- code: number;
1024
- reason: string;
1025
- wasClean: boolean;
1026
- };
1027
- interface CoreRuntime {
1028
- readonly kind: "napi" | "wasm";
1029
- createRegistry(): RegistryHandle;
1030
- registerActor(registry: RegistryHandle, name: string, factory: ActorFactoryHandle): void;
1031
- serveRegistry(registry: RegistryHandle, config: RuntimeServeConfig): Promise<void>;
1032
- waitRegistryReady(registry: RegistryHandle): Promise<void>;
1033
- shutdownRegistry(registry: RegistryHandle): Promise<void>;
1034
- shutdownTelemetry?(): Promise<void>;
1035
- registryActorStopThresholdMs?(registry: RegistryHandle): Promise<number | undefined>;
1036
- handleServerlessRequest(registry: RegistryHandle, req: RuntimeServerlessRequest, onStreamEvent: RuntimeServerlessStreamCallback, cancelToken: CancellationTokenHandle, config: RuntimeServeConfig): Promise<RuntimeServerlessResponseHead>;
1037
- serveListener(registry: RegistryHandle, listener: RuntimeListenerConfig, config: RuntimeServeConfig): Promise<void>;
1038
- serveApplicationListener(registry: RegistryHandle, listener: RuntimeApplicationListenerConfig, config: RuntimeServeConfig): Promise<void>;
1039
- registryHealth?(registry: RegistryHandle): Promise<RuntimeRegistryRouteResponse>;
1040
- registryMetadata?(registry: RegistryHandle): Promise<RuntimeRegistryRouteResponse>;
1041
- registryMetrics?(registry: RegistryHandle): Promise<RuntimeRegistryRouteResponse>;
1042
- createActorFactory(callbacks: object, config?: RuntimeActorConfig | undefined | null): ActorFactoryHandle;
1043
- createCancellationToken(): CancellationTokenHandle;
1044
- cancellationTokenAborted(token: CancellationTokenHandle): boolean;
1045
- cancelCancellationToken(token: CancellationTokenHandle): void;
1046
- onCancellationTokenCancelled(token: CancellationTokenHandle, callback: (...args: unknown[]) => unknown): void;
1047
- actorState(ctx: ActorContextHandle): RuntimeBytes;
1048
- actorBeginOnStateChange(ctx: ActorContextHandle): void;
1049
- actorEndOnStateChange(ctx: ActorContextHandle): void;
1050
- actorSetAlarm(ctx: ActorContextHandle, timestampMs?: number | undefined | null): void;
1051
- actorSetRunWakeAt(ctx: ActorContextHandle, timestampMs?: number | undefined | null): Promise<void>;
1052
- actorRequestSave(ctx: ActorContextHandle, opts?: RuntimeRequestSaveOpts | undefined | null): void;
1053
- actorRequestSaveAndWait(ctx: ActorContextHandle, opts?: RuntimeRequestSaveOpts | undefined | null): Promise<void>;
1054
- actorInspectorSnapshot(ctx: ActorContextHandle): RuntimeInspectorSnapshot;
1055
- actorDecodeInspectorRequest(ctx: ActorContextHandle, bytes: RuntimeBytes, advertisedVersion: number): RuntimeBytes;
1056
- actorEncodeInspectorResponse(ctx: ActorContextHandle, bytes: RuntimeBytes, targetVersion: number): RuntimeBytes;
1057
- actorVerifyInspectorAuth(ctx: ActorContextHandle, bearerToken?: string | undefined | null): Promise<void>;
1058
- actorQueueHibernationRemoval(ctx: ActorContextHandle, connId: string): void;
1059
- actorTakePendingHibernationChanges(ctx: ActorContextHandle): string[];
1060
- actorDirtyHibernatableConns(ctx: ActorContextHandle): ConnHandle[];
1061
- actorSaveState(ctx: ActorContextHandle, payload: RuntimeStateDeltaPayload): Promise<void>;
1062
- actorSaveStateAndWorkflowBatch(ctx: ActorContextHandle, writes: RuntimeWorkflowKvWrite[]): Promise<void>;
1063
- actorId(ctx: ActorContextHandle): string;
1064
- /**
1065
- * Runs one actor callback with `ctx` as the current invocation: operations
1066
- * on retained handles for the same actor resolve to it, and its Core span
1067
- * is the active OpenTelemetry span for the duration of `run`. Only actions,
1068
- * raw requests, and queue dispatch run this way; other callbacks have no
1069
- * invocation span.
1070
- */
1071
- runWithActorInvocationContext<T>(ctx: ActorContextHandle, run: () => T): T;
1072
- /**
1073
- * Correlation of the invocation currently executing for this actor, or
1074
- * `undefined` outside an invocation or after it finished. A sampled-out
1075
- * invocation can still expose valid span context for propagation.
1076
- */
1077
- actorInvocationTraceContext(ctx: ActorContextHandle): ActorInvocationTraceContext | undefined;
1078
- /**
1079
- * Opens the span covering one call this actor makes to another actor. See
1080
- * `StartCallSpan` for when this returns nothing.
1081
- */
1082
- startCallSpan(ctx: ActorContextHandle, actorName: string, actionName: string): RuntimeOutboundCall | undefined;
1083
- /** Backs `ActorRun.startWorkflowSpan`. */
1084
- startWorkflowSpan(ctx: ActorContextHandle): Promise<WorkflowSpan>;
1085
- /** Backs `ActorRun.runOutsideWorkflowSpan`. */
1086
- runOutsideActorInvocationContext<T>(run: () => T): T;
1087
- /** Identity of the invocation the caller runs in, usable as a cache key. */
1088
- currentInvocationScope(): object | undefined;
1089
- actorName(ctx: ActorContextHandle): string;
1090
- actorKey(ctx: ActorContextHandle): RuntimeActorKeySegment[];
1091
- actorRegion(ctx: ActorContextHandle): string;
1092
- actorSleep(ctx: ActorContextHandle): void;
1093
- actorDestroy(ctx: ActorContextHandle): void;
1094
- actorAbortSignal(ctx: ActorContextHandle): AbortSignal;
1095
- actorConns(ctx: ActorContextHandle): ConnHandle[];
1096
- actorConnectConn(ctx: ActorContextHandle, params: RuntimeBytes, request?: RuntimeHttpRequest | undefined | null): Promise<ConnHandle>;
1097
- actorBroadcast(ctx: ActorContextHandle, name: string, args: RuntimeBytes): void;
1098
- actorWaitUntil(ctx: ActorContextHandle, promise: Promise<unknown>): void;
1099
- actorWaitForTrackedShutdownWork(ctx: ActorContextHandle): Promise<boolean>;
1100
- actorWaitForTrackedShutdownWorkUnbounded(ctx: ActorContextHandle): Promise<void>;
1101
- actorKeepAwake(ctx: ActorContextHandle, promise: Promise<unknown>): void;
1102
- actorBeginKeepAwake(ctx: ActorContextHandle): number;
1103
- actorEndKeepAwake(ctx: ActorContextHandle, regionId: number): void;
1104
- actorRegisterTask(ctx: ActorContextHandle, promise: Promise<unknown>): void;
1105
- actorRuntimeState(ctx: ActorContextHandle): object;
1106
- actorClearRuntimeState(ctx: ActorContextHandle): void;
1107
- actorRestartRunHandler(ctx: ActorContextHandle): void;
1108
- actorBeginWebsocketCallback(ctx: ActorContextHandle): number;
1109
- actorEndWebsocketCallback(ctx: ActorContextHandle, regionId: number): void;
1110
- actorKvGet(ctx: ActorContextHandle, key: RuntimeBytes): Promise<RuntimeBytes | null>;
1111
- actorKvPut(ctx: ActorContextHandle, key: RuntimeBytes, value: RuntimeBytes): Promise<void>;
1112
- actorKvDelete(ctx: ActorContextHandle, key: RuntimeBytes): Promise<void>;
1113
- actorKvDeleteRange(ctx: ActorContextHandle, start: RuntimeBytes, end: RuntimeBytes): Promise<void>;
1114
- actorKvListPrefix(ctx: ActorContextHandle, prefix: RuntimeBytes, options?: RuntimeKvListOptions | undefined | null): Promise<RuntimeKvEntry[]>;
1115
- actorKvListRange(ctx: ActorContextHandle, start: RuntimeBytes, end: RuntimeBytes, options?: RuntimeKvListOptions | undefined | null): Promise<RuntimeKvEntry[]>;
1116
- actorKvBatchGet(ctx: ActorContextHandle, keys: RuntimeBytes[]): Promise<Array<RuntimeBytes | undefined | null>>;
1117
- actorKvBatchPut(ctx: ActorContextHandle, entries: RuntimeKvEntry[]): Promise<void>;
1118
- actorKvBatchDelete(ctx: ActorContextHandle, keys: RuntimeBytes[]): Promise<void>;
1119
- actorSqlExec(ctx: ActorContextHandle, sql: string): Promise<RuntimeSqlExecResult>;
1120
- actorSqlExecute(ctx: ActorContextHandle, sql: string, params?: RuntimeSqlBindParams): Promise<RuntimeSqlExecuteResult>;
1121
- actorSqlExecuteBatch(ctx: ActorContextHandle, statements: RuntimeSqlBatchStatement[]): Promise<RuntimeSqlExecuteResult[]>;
1122
- actorSqlBeginTransaction(ctx: ActorContextHandle, timeoutMs?: number, name?: string): Promise<SqliteTransactionHandle>;
1123
- actorSqlTransactionExec(transaction: SqliteTransactionHandle, sql: string): Promise<RuntimeSqlExecResult>;
1124
- actorSqlTransactionExecute(transaction: SqliteTransactionHandle, sql: string, params?: RuntimeSqlBindParams): Promise<RuntimeSqlExecuteResult>;
1125
- actorSqlTransactionCommit(transaction: SqliteTransactionHandle): Promise<void>;
1126
- actorSqlTransactionRollback(transaction: SqliteTransactionHandle): Promise<void>;
1127
- actorBeginStateTransaction(ctx: ActorContextHandle, timeoutMs?: number): Promise<ActorStateTransactionHandle>;
1128
- actorStateTransactionExecute(transaction: ActorStateTransactionHandle, sql: string, params?: RuntimeSqlBindParams): Promise<RuntimeSqlExecuteResult>;
1129
- actorStateTransactionCommit(transaction: ActorStateTransactionHandle, payload: RuntimeStateDeltaPayload): Promise<void>;
1130
- actorStateTransactionRollback(transaction: ActorStateTransactionHandle): Promise<void>;
1131
- actorSqlQuery(ctx: ActorContextHandle, sql: string, params?: RuntimeSqlBindParams): Promise<RuntimeSqlQueryResult>;
1132
- actorSqlRun(ctx: ActorContextHandle, sql: string, params?: RuntimeSqlBindParams): Promise<RuntimeSqlRunResult>;
1133
- actorSqlMetrics(ctx: ActorContextHandle): SqliteNativeMetrics | null;
1134
- actorSqlTakeLastKvError(ctx: ActorContextHandle): string | null;
1135
- actorSqlClose(ctx: ActorContextHandle): Promise<void>;
1136
- actorRuntimeSocketProvision(ctx: ActorContextHandle): Promise<RuntimeActorRuntimeSocketEndpointInfo>;
1137
- actorQueueSend(ctx: ActorContextHandle, name: string, body: RuntimeBytes): Promise<RuntimeQueueMessage>;
1138
- actorQueueNextBatch(ctx: ActorContextHandle, options?: RuntimeQueueNextBatchOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null): Promise<RuntimeQueueMessage[]>;
1139
- actorQueueWaitForNames(ctx: ActorContextHandle, names: string[], options?: RuntimeQueueWaitOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null): Promise<RuntimeQueueMessage>;
1140
- actorQueueWaitForNamesAvailable(ctx: ActorContextHandle, names: string[], options?: RuntimeQueueWaitOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null): Promise<void>;
1141
- actorQueueCompletePersisted(ctx: ActorContextHandle, messageId: bigint, expectedName: string, response?: RuntimeBytes | undefined | null): Promise<boolean>;
1142
- actorQueueEnqueueAndWait(ctx: ActorContextHandle, name: string, body: RuntimeBytes, options?: RuntimeQueueEnqueueAndWaitOptions | undefined | null, signal?: CancellationTokenHandle | undefined | null): Promise<RuntimeBytes | null>;
1143
- actorQueueTryNextBatch(ctx: ActorContextHandle, options?: RuntimeQueueTryNextBatchOptions | undefined | null): RuntimeQueueMessage[];
1144
- actorQueueMaxSize(ctx: ActorContextHandle): number;
1145
- actorQueueInspectMessages(ctx: ActorContextHandle): Promise<RuntimeQueueInspectMessage[]>;
1146
- actorQueueReset(ctx: ActorContextHandle): Promise<void>;
1147
- actorScheduleAfter(ctx: ActorContextHandle, durationMs: number, actionName: string, args: RuntimeBytes): Promise<string>;
1148
- actorScheduleAt(ctx: ActorContextHandle, timestampMs: number, actionName: string, args: RuntimeBytes): Promise<string>;
1149
- actorScheduleCancel(ctx: ActorContextHandle, id: string): Promise<boolean>;
1150
- actorScheduleGet(ctx: ActorContextHandle, id: string): Promise<RuntimeScheduledEventInfo | undefined>;
1151
- actorScheduleList(ctx: ActorContextHandle): Promise<RuntimeScheduledEventInfo[]>;
1152
- actorCronSet(ctx: ActorContextHandle, name: string, expression: string, timezone: string | undefined, actionName: string, args: RuntimeBytes, maxHistory: number | undefined): Promise<void>;
1153
- actorCronEvery(ctx: ActorContextHandle, name: string, intervalMs: number, actionName: string, args: RuntimeBytes, maxHistory: number | undefined): Promise<void>;
1154
- actorCronGet(ctx: ActorContextHandle, name: string): Promise<RuntimeCronJobInfo | undefined>;
1155
- actorCronList(ctx: ActorContextHandle): Promise<RuntimeCronJobInfo[]>;
1156
- actorCronDelete(ctx: ActorContextHandle, name: string): Promise<boolean>;
1157
- actorCronHistory(ctx: ActorContextHandle, name: string, limit: number | undefined): Promise<RuntimeCronFire[]>;
1158
- connId(conn: ConnHandle): string;
1159
- connParams(conn: ConnHandle): RuntimeBytes;
1160
- connState(conn: ConnHandle): RuntimeBytes;
1161
- connSetState(conn: ConnHandle, state: RuntimeBytes): void;
1162
- connIsHibernatable(conn: ConnHandle): boolean;
1163
- connSend(conn: ConnHandle, name: string, args: RuntimeBytes): void;
1164
- connDisconnect(conn: ConnHandle, reason?: string | undefined | null): Promise<void>;
1165
- webSocketSend(ws: WebSocketHandle, data: RuntimeBytes, binary: boolean): void;
1166
- webSocketClose(ws: WebSocketHandle, code?: number | undefined | null, reason?: string | undefined | null): Promise<void>;
1167
- webSocketSetEventCallback(ws: WebSocketHandle, callback: (event: RuntimeWebSocketEvent) => void): void;
1168
- }
1169
-
1170
- declare function buildConfiguredRegistry(config: RegistryConfig): Promise<{
1171
- runtime: CoreRuntime;
1172
- registry: RegistryHandle;
1173
- serveConfig: RuntimeServeConfig;
1174
- }>;
1175
-
1176
- type FetchHandler = (request: Request, ...args: any) => Response | Promise<Response>;
1177
- interface ServerlessHandler {
1178
- fetch: FetchHandler;
1179
- }
1180
- interface RegistryApplication {
1181
- fetch: FetchHandler;
1182
- }
1183
- interface RegistryListenOptions {
1184
- port?: number;
1185
- host?: string;
1186
- publicDir?: string;
1187
- application?: RegistryApplication;
1188
- }
1189
- interface RegistryRoutes {
1190
- health(): Promise<Response>;
1191
- metadata(): Promise<Response>;
1192
- prometheusMetrics(request?: Request): Promise<Response>;
1193
- }
1194
- /**
1195
- * Injectable dependencies for {@link Registry}. Production code uses the
1196
- * defaults. Tests override `buildConfiguredRegistry` to drive lifecycle
1197
- * orchestration against a fake `CoreRuntime` without an engine.
1198
- */
1199
- interface RegistryDeps {
1200
- buildConfiguredRegistry: typeof buildConfiguredRegistry;
1201
- }
1202
- declare class Registry<A extends RegistryActors> {
1203
- #private;
1204
- readonly routes: RegistryRoutes;
1205
- get config(): RegistryConfigInput<A>;
1206
- parseConfig(): RegistryConfig;
1207
- constructor(config: RegistryConfigInput<A>, deps?: Partial<RegistryDeps>);
1208
- /**
1209
- * Handle an incoming HTTP request for serverless deployments.
1210
- *
1211
- * @example
1212
- * ```ts
1213
- * const app = new Hono();
1214
- * app.all("/api/rivet/*", (c) => registry.handler(c.req.raw));
1215
- * export default app;
1216
- * ```
1217
- */
1218
- handler(request: Request): Promise<Response>;
1219
- /**
1220
- * Returns a fetch handler for serverless deployments.
1221
- *
1222
- * @example
1223
- * ```ts
1224
- * export default registry.serve();
1225
- * ```
1226
- */
1227
- serve(): ServerlessHandler;
1228
- /**
1229
- * Bind an HTTP listener provided by the native (Rust) runtime and serve
1230
- * the registry's serverless endpoints over it. Resolves only after the
1231
- * registry is shut down (SIGINT/SIGTERM or `nativeRegistry.shutdown()`).
1232
- *
1233
- * @param opts.port Port to listen on. Defaults to `process.env.RIVET_PORT`
1234
- * if set, otherwise 3000.
1235
- * @param opts.host Address to bind. Defaults to `0.0.0.0`.
1236
- * @param opts.publicDir If set, serves static files from this directory
1237
- * as a fallback below the framework routes.
1238
- * @param opts.application If set, handles requests that do not match a
1239
- * framework route.
1240
- *
1241
- * @example
1242
- * ```ts
1243
- * await registry.listen();
1244
- * await registry.listen({ application: app });
1245
- * ```
1246
- */
1247
- listen(opts?: RegistryListenOptions): Promise<void>;
1248
- /**
1249
- * Gracefully drains all live registries.
1250
- *
1251
- * Programmatic counterpart to the SIGINT/SIGTERM handlers: tears down
1252
- * every live `CoreRegistry` (both `start()` and `handler()` modes) and
1253
- * waits for the serve promise to resolve, all bounded by the shutdown
1254
- * grace period. Unlike a signal-driven shutdown, this does not re-raise a
1255
- * signal or exit the process. The caller owns process lifetime.
1256
- *
1257
- * Idempotent: concurrent or repeated calls share a single drain. Safe to
1258
- * call even if nothing has been started.
1259
- *
1260
- * @example
1261
- * ```ts
1262
- * const registry = setup({ use: { counter } });
1263
- * registry.start();
1264
- * // ...later, on your own shutdown trigger:
1265
- * await registry.shutdown();
1266
- * ```
1267
- */
1268
- shutdown(): Promise<void>;
1269
- startEnvoy(): void;
1270
- /**
1271
- * Starts the serverful registry if needed and waits until its envoy has
1272
- * registered with the Engine. Repeated and concurrent calls share one
1273
- * startup lifecycle and readiness promise.
1274
- *
1275
- * Unlike {@link start}, this reports startup failures and does not resolve
1276
- * merely because an HTTP health endpoint is listening.
1277
- */
1278
- startAndWait(): Promise<void>;
1279
- /**
1280
- * Starts the actor envoy for standalone server deployments.
1281
- *
1282
- * Set `RIVETKIT_RUNTIME_MODE=serverless` to instead bind an HTTP listener
1283
- * via `listen()` (Mode B). Mode A (envoy) and Mode B (listener) are
1284
- * mutually exclusive per registry instance.
1285
- *
1286
- * @example
1287
- * ```ts
1288
- * const registry = setup({ use: { counter } });
1289
- * registry.start();
1290
- * ```
1291
- */
1292
- start(): void;
1293
- }
1294
-
1295
- interface QueueSendWaitOptions {
1296
- wait: true;
1297
- timeout?: number;
1298
- signal?: AbortSignal;
1299
- }
1300
- interface QueueSendNoWaitOptions {
1301
- wait?: false;
1302
- timeout?: never;
1303
- signal?: AbortSignal;
1304
- }
1305
- interface QueueSendResult<TResponse = unknown> {
1306
- status: "completed" | "timedOut";
1307
- response?: TResponse;
1308
- }
1309
-
1310
- /**
1311
- * Action function returned by Actor connections and handles.
1312
- *
1313
- * @typedef {Function} ActorActionFunction
1314
- * @template Args
1315
- * @template Response
1316
- * @param {...Args} args - Arguments for the action function.
1317
- * @returns {Promise<Response>}
1318
- */
1319
- type ActorActionFunction<Args extends Array<unknown> = unknown[], Response = unknown> = (...args: Args extends [unknown, ...infer Rest] ? Rest : Args) => Promise<Response>;
1320
- type IsAny<T> = 0 extends 1 & T ? true : false;
1321
- type LooseEventSubscribe = (eventName: string, callback: (...args: any[]) => void) => () => void;
1322
- type ActorActionMap<R> = {
1323
- [K in keyof NonNullable<R>]: NonNullable<R>[K] extends (...args: infer Args) => infer Return ? ActorActionFunction<Args, Awaited<Return>> : NonNullable<R>[K] extends Record<string, unknown> ? ActorActionMap<NonNullable<R>[K]> : never;
1324
- };
1325
- type ActionsOf<AD extends AnyActorDefinition> = AD["config"] extends {
1326
- actions?: infer R;
1327
- } ? R : never;
1328
- interface ActorGatewayOptions {
1329
- skipReadyWait?: boolean;
1330
- }
1331
- interface ActorActionOptions extends ActorGatewayOptions {
1332
- signal?: AbortSignal;
1333
- }
1334
- type ActorConnectOptions = ActorGatewayOptions;
1335
- type ActorFetchInit = RequestInit & ActorGatewayOptions;
1336
- type ActorWebSocketOptions = ActorGatewayOptions;
1337
- /**
1338
- * Maps action methods from actor definition to typed function signatures.
1339
- */
1340
- type ActorDefinitionActions<AD extends AnyActorDefinition> = IsAny<AD> extends true ? Record<string, ActorActionFunction<any[], any>> : ActorActionMap<ActionsOf<AD>>;
1341
- type ActorQueueSend<TQueues extends QueueSchemaConfig> = {
1342
- <K extends keyof TQueues & string>(name: K, body: InferSchemaMap<TQueues>[K], options: QueueSendWaitOptions): Promise<QueueSendResult<InferQueueCompleteMap<TQueues>[K]>>;
1343
- <K extends keyof TQueues & string>(name: K, body: InferSchemaMap<TQueues>[K], options?: QueueSendNoWaitOptions): Promise<void>;
1344
- (name: keyof TQueues extends never ? string : never, body: unknown, options: QueueSendWaitOptions): Promise<QueueSendResult>;
1345
- (name: keyof TQueues extends never ? string : never, body: unknown, options?: QueueSendNoWaitOptions): Promise<void>;
1346
- };
1347
- type ActorEventSubscribe<TEvents extends EventSchemaConfig> = {
1348
- <K extends keyof TEvents & string>(eventName: K, callback: (...args: InferEventArgs<InferSchemaMap<TEvents>[K]>) => void): () => void;
1349
- (eventName: keyof TEvents extends never ? string : never, callback: (...args: any[]) => void): () => void;
1350
- };
1351
- type ActorDefinitionQueueSend<AD extends AnyActorDefinition> = IsAny<AD> extends true ? {
1352
- send: ActorQueueSend<Record<string, any>>;
1353
- } : AD extends {
1354
- config: {
1355
- queues?: infer Q;
1356
- };
1357
- } ? Q extends QueueSchemaConfig ? {
1358
- send: ActorQueueSend<Q>;
1359
- } : {} : AD extends BaseActorDefinition<any, any, any, any, any, any, any, infer Q, any> ? Q extends QueueSchemaConfig ? {
1360
- send: ActorQueueSend<Q>;
1361
- } : {} : {};
1362
- type ActorDefinitionEventSubscriptions<AD extends AnyActorDefinition> = IsAny<AD> extends true ? {
1363
- on: LooseEventSubscribe;
1364
- once: LooseEventSubscribe;
1365
- } : AD extends {
1366
- config: {
1367
- events?: infer E;
1368
- };
1369
- } ? E extends EventSchemaConfig ? {
1370
- on: ActorEventSubscribe<E>;
1371
- once: ActorEventSubscribe<E>;
1372
- } : {} : AD extends BaseActorDefinition<any, any, any, any, any, any, infer E, any, any> ? E extends EventSchemaConfig ? {
1373
- on: ActorEventSubscribe<E>;
1374
- once: ActorEventSubscribe<E>;
1375
- } : {} : {};
1376
-
1377
- type ActorResolutionState = ActorQuery;
1378
-
1379
- /**
1380
- * Connection status for an actor connection.
1381
- *
1382
- * - `"idle"`: Not connected, no auto-reconnect (initial state, after dispose, or disabled)
1383
- * - `"connecting"`: Attempting to establish connection
1384
- * - `"connected"`: Connection is active
1385
- * - `"disconnected"`: Connection was lost, will auto-reconnect
1386
- */
1387
- type ActorConnStatus = "idle" | "connecting" | "connected" | "disconnected";
1388
- /**
1389
- * A function that unsubscribes from an event.
1390
- *
1391
- * @typedef {Function} EventUnsubscribe
1392
- */
1393
- type EventUnsubscribe = () => void;
1394
- /**
1395
- * A function that handles connection errors.
1396
- *
1397
- * @typedef {Function} ActorErrorCallback
1398
- */
1399
- type ActorErrorCallback = (error: RivetError) => void;
1400
- /**
1401
- * A callback for connection state changes.
1402
- *
1403
- * @typedef {Function} ConnectionStateCallback
1404
- */
1405
- type ConnectionStateCallback = () => void;
1406
- /**
1407
- * A callback for connection status changes.
1408
- *
1409
- * @typedef {Function} StatusChangeCallback
1410
- */
1411
- type StatusChangeCallback = (status: ActorConnStatus) => void;
1412
- declare const CONNECT_SYMBOL: unique symbol;
1413
- /**
1414
- * Provides underlying functions for {@link ActorConn}. See {@link ActorConn} for using type-safe remote procedure calls.
1415
- *
1416
- * @see {@link ActorConn}
1417
- */
1418
- declare class ActorConnRaw {
1419
- #private;
1420
- /**
1421
- * Do not call this directly.
1422
- *
1423
- * Creates an instance of ActorConnRaw.
1424
- *
1425
- * @protected
1426
- */
1427
- constructor(client: ClientRaw, driver: EngineControlClient, params: unknown, getParams: (() => Promise<unknown>) | undefined, encoding: Encoding, actorResolutionState: ActorResolutionState, gatewayOptions?: ActorGatewayOptions, currentActorInvocation?: CurrentActorInvocation);
1428
- send(name: string, body: unknown, options: QueueSendWaitOptions): Promise<QueueSendResult>;
1429
- send(name: string, body: unknown, options?: QueueSendNoWaitOptions): Promise<void>;
1430
- /**
1431
- * Call a raw action connection. See {@link ActorConn} for type-safe action calls.
1432
- *
1433
- * @see {@link ActorConn}
1434
- * @template Args - The type of arguments to pass to the action function.
1435
- * @template Response - The type of the response returned by the action function.
1436
- * @param {string} name - The name of the action function to call.
1437
- * @param {...Args} args - The arguments to pass to the action function.
1438
- * @returns {Promise<Response>} - A promise that resolves to the response of the action function.
1439
- */
1440
- action<Args extends Array<unknown> = unknown[], Response = unknown>(opts: {
1441
- name: string;
1442
- args: Args;
1443
- signal?: AbortSignal;
1444
- }): Promise<Response>;
1445
- /**
1446
- * Do not call this directly.
1447
- * Establishes a connection to the server using the specified endpoint & encoding & driver.
1448
- *
1449
- * @protected
1450
- */
1451
- [CONNECT_SYMBOL](): void;
1452
- /**
1453
- * Subscribes to an event that will happen repeatedly.
1454
- *
1455
- * @template Args - The type of arguments the event callback will receive.
1456
- * @param {string} eventName - The name of the event to subscribe to.
1457
- * @param {(...args: Args) => void} callback - The callback function to execute when the event is triggered.
1458
- * @returns {EventUnsubscribe} - A function to unsubscribe from the event.
1459
- * @see {@link https://rivet.dev/docs/events|Events Documentation}
1460
- */
1461
- on<Args extends Array<unknown> = unknown[]>(eventName: string, callback: (...args: Args) => void): EventUnsubscribe;
1462
- /**
1463
- * Subscribes to an event that will be triggered only once.
1464
- *
1465
- * @template Args - The type of arguments the event callback will receive.
1466
- * @param {string} eventName - The name of the event to subscribe to.
1467
- * @param {(...args: Args) => void} callback - The callback function to execute when the event is triggered.
1468
- * @returns {EventUnsubscribe} - A function to unsubscribe from the event.
1469
- * @see {@link https://rivet.dev/docs/events|Events Documentation}
1470
- */
1471
- once<Args extends Array<unknown> = unknown[]>(eventName: string, callback: (...args: Args) => void): EventUnsubscribe;
1472
- /**
1473
- * Subscribes to connection errors.
1474
- *
1475
- * @param {ActorErrorCallback} callback - The callback function to execute when a connection error occurs.
1476
- * @returns {() => void} - A function to unsubscribe from the error handler.
1477
- */
1478
- onError(callback: ActorErrorCallback): () => void;
1479
- /**
1480
- * Returns the current connection status.
1481
- *
1482
- * @returns {ActorConnStatus} - The current connection status.
1483
- */
1484
- get connStatus(): ActorConnStatus;
1485
- /**
1486
- * Returns whether the connection is currently open.
1487
- *
1488
- * @deprecated Use `connStatus` instead.
1489
- * @returns {boolean} - True if the connection is open, false otherwise.
1490
- */
1491
- get isConnected(): boolean;
1492
- /**
1493
- * Resolves when this connection first reaches the connected state.
1494
- */
1495
- get ready(): Promise<void>;
1496
- /**
1497
- * Subscribes to connection open events.
1498
- *
1499
- * This is called when the WebSocket connection is established and the Init message is received.
1500
- *
1501
- * @param {ConnectionStateCallback} callback - The callback function to execute when the connection opens.
1502
- * @returns {() => void} - A function to unsubscribe from the open handler.
1503
- */
1504
- onOpen(callback: ConnectionStateCallback): () => void;
1505
- /**
1506
- * Subscribes to connection close events.
1507
- *
1508
- * This is called when the WebSocket connection is closed. The connection will automatically
1509
- * attempt to reconnect unless disposed.
1510
- *
1511
- * @param {ConnectionStateCallback} callback - The callback function to execute when the connection closes.
1512
- * @returns {() => void} - A function to unsubscribe from the close handler.
1513
- */
1514
- onClose(callback: ConnectionStateCallback): () => void;
1515
- /**
1516
- * Subscribes to connection status changes.
1517
- *
1518
- * This is called whenever the connection status changes between Disconnected, Connecting, and Connected.
1519
- *
1520
- * @param {StatusChangeCallback} callback - The callback function to execute when the status changes.
1521
- * @returns {() => void} - A function to unsubscribe from the status change handler.
1522
- */
1523
- onStatusChange(callback: StatusChangeCallback): () => void;
1524
- /**
1525
- * Disconnects from the actor.
1526
- *
1527
- * @returns {Promise<void>} A promise that resolves when the socket is gracefully closed.
1528
- */
1529
- dispose(): Promise<void>;
1530
- }
1531
- /**
1532
- * Connection to a actor. Allows calling actor's remote procedure calls with inferred types. See {@link ActorConnRaw} for underlying methods.
1533
- *
1534
- * @example
1535
- * ```
1536
- * const room = client.connect<ChatRoom>(...etc...);
1537
- * // This calls the action named `sendMessage` on the `ChatRoom` actor.
1538
- * await room.sendMessage('Hello, world!');
1539
- * ```
1540
- *
1541
- * Private methods (e.g. those starting with `_`) are automatically excluded.
1542
- *
1543
- * @template AD The actor class that this connection is for.
1544
- * @see {@link ActorConnRaw}
1545
- */
1546
- type ActorConn<AD extends AnyActorDefinition> = Omit<ActorConnRaw, "send" | "on" | "once"> & ActorDefinitionQueueSend<AD> & ActorDefinitionEventSubscriptions<AD> & ActorDefinitionActions<AD>;
1547
-
1548
- /**
1549
- * Provides underlying functions for stateless {@link ActorHandle} for action calls.
1550
- * Similar to ActorConnRaw but doesn't maintain a connection.
1551
- *
1552
- * @see {@link ActorHandle}
1553
- */
1554
- declare class ActorHandleRaw {
1555
- #private;
1556
- /**
1557
- * Do not call this directly.
1558
- *
1559
- * Creates an instance of ActorHandleRaw.
1560
- *
1561
- * @protected
1562
- */
1563
- constructor(client: any, driver: EngineControlClient, params: unknown, getParams: (() => Promise<unknown>) | undefined, encoding: Encoding, actorResolutionState: ActorResolutionState, gatewayOptions?: ActorGatewayOptions, signal?: AbortSignal, currentActorInvocation?: CurrentActorInvocation, startCallSpan?: StartCallSpan);
1564
- send(name: string, body: unknown, options: QueueSendWaitOptions): Promise<QueueSendResult>;
1565
- send(name: string, body: unknown, options?: QueueSendNoWaitOptions): Promise<void>;
1566
- /**
1567
- * Call a raw action. This method sends an HTTP request to invoke the named action.
1568
- *
1569
- * @see {@link ActorHandle}
1570
- * @template Args - The type of arguments to pass to the action function.
1571
- * @template Response - The type of the response returned by the action function.
1572
- */
1573
- action<Args extends Array<unknown> = unknown[], Response = unknown>(opts: {
1574
- name: string;
1575
- args: Args;
1576
- } & ActorActionOptions): Promise<Response>;
1577
- /**
1578
- * Establishes a persistent connection to the actor.
1579
- *
1580
- * @template AD The actor class that this connection is for.
1581
- * @returns {ActorConn<AD>} A connection to the actor.
1582
- */
1583
- connect(params?: unknown, options?: ActorConnectOptions): ActorConn<AnyActorDefinition>;
1584
- /**
1585
- * Fetches a resource from this actor via the /request endpoint. This is a
1586
- * convenience wrapper around the raw HTTP API.
1587
- */
1588
- fetch(input: string | URL | Request, init?: ActorFetchInit): Promise<Response>;
1589
- /**
1590
- * Opens a raw WebSocket connection to this actor.
1591
- */
1592
- webSocket(path?: string, protocols?: string | string[], options?: ActorWebSocketOptions): Promise<any>;
1593
- /**
1594
- * Resolves the actor to get its unique actor ID.
1595
- */
1596
- resolve(): Promise<string>;
1597
- /** Issue a token scoped to this actor. Defaults to actor gateway read access. */
1598
- issueToken(options?: ActorIssueTokenOptions): Promise<IssuedToken>;
1599
- /**
1600
- * Returns the raw URL for routing traffic to the actor.
1601
- */
1602
- getGatewayUrl(): Promise<string>;
1603
- reload(): Promise<void>;
1604
- }
1605
- /**
1606
- * Stateless handle to a actor. Allows calling actor's remote procedure calls with inferred types
1607
- * without establishing a persistent connection.
1608
- *
1609
- * @example
1610
- * ```
1611
- * const room = client.get<ChatRoom>(...etc...);
1612
- * // This calls the action named `sendMessage` on the `ChatRoom` actor without a connection.
1613
- * await room.sendMessage('Hello, world!');
1614
- * ```
1615
- *
1616
- * Private methods (e.g. those starting with `_`) are automatically excluded.
1617
- *
1618
- * @template AD The actor class that this handle is for.
1619
- * @see {@link ActorHandleRaw}
1620
- */
1621
- type ActorHandle<AD extends AnyActorDefinition> = Omit<ActorHandleRaw, "connect" | "send"> & {
1622
- connect(params?: unknown, options?: ActorConnectOptions): ActorConn<AD>;
1623
- resolve(): Promise<string>;
1624
- } & ActorDefinitionQueueSend<AD> & Omit<ActorDefinitionActions<AD>, keyof ActorHandleRaw>;
1625
-
1626
- /** Extract the actor registry from the registry definition. */
1627
- type ExtractActorsFromRegistry<A extends Registry<any>> = A extends Registry<infer Actors> ? Actors : never;
1628
- /**
1629
- * Represents a actor accessor that provides methods to interact with a specific actor.
1630
- */
1631
- interface ActorAccessor<AD extends AnyActorDefinition> {
1632
- /**
1633
- * Gets a stateless handle to a actor by its key, but does not create the actor if it doesn't exist.
1634
- * The actor name is automatically injected from the property accessor.
1635
- *
1636
- * Each operation resolves the current actor for the key before sending the
1637
- * request.
1638
- *
1639
- * @template AD The actor class that this handle is for.
1640
- * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
1641
- * @param {GetWithIdOptions} [opts] - Options for getting the actor.
1642
- * @returns {ActorHandle<AD>} - A handle to the actor.
1643
- */
1644
- get(key?: string | string[], opts?: GetWithIdOptions): ActorHandle<AD>;
1645
- /**
1646
- * Gets a stateless handle to a actor by its key, creating it if necessary.
1647
- * The actor name is automatically injected from the property accessor.
1648
- *
1649
- * Each operation resolves the current actor for the key before sending the
1650
- * request.
1651
- *
1652
- * @template AD The actor class that this handle is for.
1653
- * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
1654
- * @param {GetOptions} [opts] - Options for getting the actor.
1655
- * @returns {ActorHandle<AD>} - A handle to the actor.
1656
- */
1657
- getOrCreate(key?: string | string[], opts?: GetOrCreateOptions): ActorHandle<AD>;
1658
- /**
1659
- * Gets a stateless handle to a actor by its ID.
1660
- *
1661
- * If the actor is destroyed, operations will throw without retrying since
1662
- * there is no key to re-resolve.
1663
- *
1664
- * @template AD The actor class that this handle is for.
1665
- * @param {string} actorId - The ID of the actor.
1666
- * @param {GetWithIdOptions} [opts] - Options for getting the actor.
1667
- * @returns {ActorHandle<AD>} - A handle to the actor.
1668
- */
1669
- getForId(actorId: string, opts?: GetWithIdOptions): ActorHandle<AD>;
1670
- /**
1671
- * Creates a new actor with the name automatically injected from the property accessor,
1672
- * and returns a stateless handle to it with the actor ID resolved.
1673
- *
1674
- * If the actor is destroyed, operations will throw without retrying since
1675
- * creation is a one-shot operation.
1676
- *
1677
- * @template AD The actor class that this handle is for.
1678
- * @param {string | string[]} key - The key to identify the actor. Can be a single string or an array of strings.
1679
- * @param {CreateOptions} [opts] - Options for creating the actor (excluding name and key).
1680
- * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the actor.
1681
- */
1682
- create(key?: string | string[], opts?: CreateOptions): Promise<ActorHandle<AD>>;
1683
- }
1684
- /**
1685
- * Options for querying actors.
1686
- * @typedef {Object} QueryOptions
1687
- * @property {unknown} [parameters] - Parameters to pass to the connection.
1688
- */
1689
- interface QueryOptions {
1690
- /** Parameters to pass to the connection. */
1691
- params?: unknown;
1692
- /**
1693
- * Lazily resolves connection parameters for `.connect()` and `.webSocket()`.
1694
- * This is called each time a new connection is opened.
1695
- */
1696
- getParams?: () => Promise<unknown>;
1697
- /** Signal to abort the request. */
1698
- signal?: AbortSignal;
1699
- }
1700
- /**
1701
- * Options for getting a actor by ID.
1702
- * @typedef {QueryOptions} GetWithIdOptions
1703
- */
1704
- interface GetWithIdOptions extends QueryOptions {
1705
- }
1706
- /**
1707
- * Options for getting or creating a actor.
1708
- * @typedef {QueryOptions} GetOrCreateOptions
1709
- * @property {string} [createInRegion] - Region to create the actor in if it doesn't exist.
1710
- */
1711
- interface GetOrCreateOptions extends QueryOptions {
1712
- /** Region to create the actor in if it doesn't exist. */
1713
- createInRegion?: string;
1714
- /** Input data to pass to the actor. */
1715
- createWithInput?: unknown;
1716
- /**
1717
- * Name of the envoy pool to select for this actor if it is created.
1718
- * Overrides the client's configured `poolName` for this call.
1719
- */
1720
- poolName?: string;
1721
- }
1722
- /**
1723
- * Options for creating a actor.
1724
- * @typedef {QueryOptions} CreateOptions
1725
- * @property {string} [region] - The region to create the actor in.
1726
- */
1727
- interface CreateOptions extends QueryOptions {
1728
- /** The region to create the actor in. */
1729
- region?: string;
1730
- /** Input data to pass to the actor. */
1731
- input?: unknown;
1732
- /**
1733
- * Name of the envoy pool to select for this actor.
1734
- * Overrides the client's configured `poolName` for this call.
1735
- */
1736
- poolName?: string;
1737
- }
1738
- declare const ACTOR_CONNS_SYMBOL: unique symbol;
1739
- declare const CREATE_ACTOR_CONN_PROXY: unique symbol;
1740
- /** Options for constructing a raw actor client. */
1741
- interface ClientRawOptions {
1742
- encoding?: Encoding;
1743
- gateway?: ActorGatewayOptions;
1744
- }
1745
- /** Runtime-supplied wiring for clients created inside an actor. Set only by the native runtime. */
1746
- interface ActorClientRuntimeOptions {
1747
- /** Supplies the calling actor's invocation so actor-to-actor clients propagate its trace and ray ID. */
1748
- currentActorInvocation?: CurrentActorInvocation;
1749
- /** Opens and finishes the Core span covering an actor-to-actor call. */
1750
- startCallSpan?: StartCallSpan;
1751
- }
1752
- /**
1753
- * Client for managing & connecting to actors.
1754
- *
1755
- * @template A The actors map type that defines the available actors.
1756
- * @see {@link https://rivet.dev/docs/manage|Create & Manage Actors}
1757
- */
1758
- declare class ClientRaw {
1759
- #private;
1760
- /** Issue namespace-scoped tokens with an explicit grant list. */
1761
- readonly auth: {
1762
- issueToken(options: IssueTokenOptions): Promise<IssuedToken>;
1763
- };
1764
- [ACTOR_CONNS_SYMBOL]: Set<ActorConnRaw>;
1765
- /**
1766
- * Creates an instance of Client.
1767
- */
1768
- constructor(driver: EngineControlClient, options?: ClientRawOptions & ActorClientRuntimeOptions);
1769
- /**
1770
- * Gets a stateless handle to a actor by its ID.
1771
- *
1772
- * @template AD The actor class that this handle is for.
1773
- * @param {string} name - The name of the actor.
1774
- * @param {string} actorId - The ID of the actor.
1775
- * @param {GetWithIdOptions} [opts] - Options for getting the actor.
1776
- * @returns {ActorHandle<AD>} - A handle to the actor.
1777
- */
1778
- getForId<AD extends AnyActorDefinition>(name: string, actorId: string, opts?: GetWithIdOptions): ActorHandle<AD>;
1779
- /**
1780
- * Gets a stateless handle to a actor by its key, but does not create the actor if it doesn't exist.
1781
- *
1782
- * @template AD The actor class that this handle is for.
1783
- * @param {string} name - The name of the actor.
1784
- * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
1785
- * @param {GetWithIdOptions} [opts] - Options for getting the actor.
1786
- * @returns {ActorHandle<AD>} - A handle to the actor.
1787
- */
1788
- get<AD extends AnyActorDefinition>(name: string, key?: string | string[], opts?: GetWithIdOptions): ActorHandle<AD>;
1789
- /**
1790
- * Gets a stateless handle to a actor by its key, creating it if necessary.
1791
- *
1792
- * @template AD The actor class that this handle is for.
1793
- * @param {string} name - The name of the actor.
1794
- * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
1795
- * @param {GetOptions} [opts] - Options for getting the actor.
1796
- * @returns {ActorHandle<AD>} - A handle to the actor.
1797
- */
1798
- getOrCreate<AD extends AnyActorDefinition>(name: string, key?: string | string[], opts?: GetOrCreateOptions): ActorHandle<AD>;
1799
- /**
1800
- * Creates a new actor with the provided key and returns a stateless handle to it.
1801
- * Resolves the actor ID and returns a handle with getForId query.
1802
- *
1803
- * @template AD The actor class that this handle is for.
1804
- * @param {string} name - The name of the actor.
1805
- * @param {string | string[]} key - The key to identify the actor. Can be a single string or an array of strings.
1806
- * @param {CreateOptions} [opts] - Options for creating the actor (excluding name and key).
1807
- * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the actor.
1808
- */
1809
- create<AD extends AnyActorDefinition>(name: string, key?: string | string[], opts?: CreateOptions): Promise<ActorHandle<AD>>;
1810
- [CREATE_ACTOR_CONN_PROXY]<AD extends AnyActorDefinition>(conn: ActorConnRaw): ActorConn<AD>;
1811
- /**
1812
- * Disconnects from all actors.
1813
- *
1814
- * @returns {Promise<void>} A promise that resolves when all connections are closed.
1815
- */
1816
- dispose(): Promise<void>;
1817
- }
1818
- /**
1819
- * Client type with actor accessors.
1820
- * This adds property accessors for actor names to the ClientRaw base class.
1821
- *
1822
- * @template A The actor registry type.
1823
- */
1824
- type Client<A extends Registry<any>> = ClientRaw & Omit<{
1825
- [K in keyof ExtractActorsFromRegistry<A>]: ActorAccessor<ExtractActorsFromRegistry<A>[K]>;
1826
- }, keyof ClientRaw>;
1827
-
1828
- /** @experimental State exposed by a durable workflow run handler to the Inspector. */
1829
- type WorkflowState = "pending" | "running" | "sleeping" | "failed" | "completed" | "cancelled" | "rolling_back";
1830
-
1831
- declare const ACTOR_CONTEXT_INTERNAL_SYMBOL: unique symbol;
1832
- declare const RAW_STATE_SYMBOL: unique symbol;
1833
- interface ActorLogger {
1834
- level: any;
1835
- fatal: any;
1836
- trace: any;
1837
- silent: any;
1838
- msgPrefix: any;
1839
- debug: any;
1840
- info: any;
1841
- warn: any;
1842
- error: any;
1843
- [key: string]: any;
1844
- }
1845
- type ActorKvValueType = "text" | "arrayBuffer" | "binary";
1846
- type ActorKvKeyType = "text" | "binary";
1847
- type ActorKvValueTypeMap = {
1848
- text: string;
1849
- arrayBuffer: ArrayBuffer;
1850
- binary: Uint8Array;
1851
- };
1852
- type ActorKvKeyTypeMap = {
1853
- text: string;
1854
- binary: Uint8Array;
1855
- };
1856
- type ActorKvValueOptions<T extends ActorKvValueType = "text"> = {
1857
- type?: T;
1858
- };
1859
- type ActorKvListOptions<T extends ActorKvValueType = "text", K extends ActorKvKeyType = "text"> = ActorKvValueOptions<T> & {
1860
- keyType?: K;
1861
- reverse?: boolean;
1862
- limit?: number;
1863
- };
1864
- type ActorClientFor<T> = T extends Registry<any> ? Client<T> : T;
1865
- /**
1866
- * @deprecated Actor KV is deprecated. Use embedded SQLite (`c.db`)
1867
- * or actor state instead.
1868
- */
1869
- interface ActorKv {
1870
- get<T extends ActorKvValueType = "text">(key: Uint8Array | string, options?: ActorKvValueOptions<T>): Promise<ActorKvValueTypeMap[T] | null>;
1871
- put<T extends ActorKvValueType = "text">(key: Uint8Array | string, value: Uint8Array | string | ArrayBuffer, options?: ActorKvValueOptions<T>): Promise<void>;
1872
- delete(key: Uint8Array | string): Promise<void>;
1873
- batchPut(entries: [Uint8Array, Uint8Array][]): Promise<void>;
1874
- batchGet(keys: Uint8Array[]): Promise<(Uint8Array | null)[]>;
1875
- batchDelete(keys: Uint8Array[]): Promise<void>;
1876
- deleteRange(start: Uint8Array, end: Uint8Array): Promise<void>;
1877
- listPrefix<T extends ActorKvValueType = "text", K extends ActorKvKeyType = "text">(prefix: Uint8Array | string, options?: ActorKvListOptions<T, K>): Promise<Array<[ActorKvKeyTypeMap[K], ActorKvValueTypeMap[T]]>>;
1878
- listRange<T extends ActorKvValueType = "text", K extends ActorKvKeyType = "text">(start: Uint8Array | string, end: Uint8Array | string, options?: ActorKvListOptions<T, K>): Promise<Array<[ActorKvKeyTypeMap[K], ActorKvValueTypeMap[T]]>>;
1879
- list<T extends ActorKvValueType = "text", K extends ActorKvKeyType = "text">(prefix: Uint8Array | string, options?: ActorKvListOptions<T, K>): Promise<Array<[ActorKvKeyTypeMap[K], ActorKvValueTypeMap[T]]>>;
1880
- [key: string]: any;
1881
- }
1882
- interface ActorSchedule {
1883
- after(duration: number, action: string, ...args: unknown[]): Promise<string>;
1884
- at(timestamp: number, action: string, ...args: unknown[]): Promise<string>;
1885
- cancel(id: string): Promise<boolean>;
1886
- get(id: string): Promise<ScheduledEventInfo | undefined>;
1887
- list(): Promise<ScheduledEventInfo[]>;
1888
- [key: string]: any;
1889
- }
1890
- interface ActorCronSetOptions {
1891
- name: string;
1892
- expression: string;
1893
- action: string;
1894
- args?: unknown[];
1895
- timezone?: string;
1896
- /** Defaults to 100. Set to 0 to disable and clear history. Maximum 1,000. */
1897
- maxHistory?: number;
1898
- }
1899
- interface ActorCronEveryOptions {
1900
- name: string;
1901
- /** Fixed interval in milliseconds. Minimum 5,000. */
1902
- interval: number;
1903
- action: string;
1904
- args?: unknown[];
1905
- /** Defaults to 100. Set to 0 to disable and clear history. Maximum 1,000. */
1906
- maxHistory?: number;
1907
- }
1908
- interface ActorCron {
1909
- set(options: ActorCronSetOptions): Promise<void>;
1910
- every(options: ActorCronEveryOptions): Promise<void>;
1911
- get(name: string): Promise<CronJobInfo | undefined>;
1912
- list(): Promise<CronJobInfo[]>;
1913
- delete(name: string): Promise<boolean>;
1914
- history(name: string, options?: {
1915
- limit?: number;
1916
- }): Promise<CronFire[]>;
1917
- [key: string]: any;
1918
- }
1919
- interface ScheduledEventInfo {
1920
- id: string;
1921
- action: string;
1922
- args: unknown[];
1923
- runAt: number;
1924
- }
1925
- type CronJobInfo = {
1926
- name: string;
1927
- action: string;
1928
- args: unknown[];
1929
- nextRunAt: number;
1930
- lastRunAt?: number;
1931
- maxHistory: number;
1932
- } & ({
1933
- kind: "cron";
1934
- expression: string;
1935
- timezone: string;
1936
- } | {
1937
- kind: "every";
1938
- interval: number;
1939
- });
1940
- interface CronFire {
1941
- action: string;
1942
- scheduledAt: number;
1943
- firedAt: number;
1944
- finishedAt?: number;
1945
- result: "running" | "ok" | "error" | "skipped";
1946
- error?: {
1947
- group: string;
1948
- code: string;
1949
- message: string;
1950
- metadata?: unknown;
1951
- };
1952
- }
1953
- type QueueMessageOf<Name extends string, Body> = {
1954
- id: number | bigint;
1955
- name: Name;
1956
- body: Body;
1957
- createdAt: number;
1958
- [key: string]: unknown;
1959
- };
1960
- type QueueName<TQueues extends QueueSchemaConfig> = keyof TQueues & string;
1961
- type QueueFilterName<TQueues extends QueueSchemaConfig> = keyof TQueues extends never ? string : QueueName<TQueues>;
1962
- type QueueMessageForName<TQueues extends QueueSchemaConfig, TName extends QueueFilterName<TQueues>> = keyof TQueues extends never ? QueueMessageOf<string, unknown> : TName extends QueueName<TQueues> ? QueueMessageOf<TName, InferSchemaMap<TQueues>[TName]> : never;
1963
- type QueueCompleteArgs<T> = undefined extends T ? [response?: T] : [response: T];
1964
- type QueueCompleteArgsForName<TQueues extends QueueSchemaConfig, TName extends QueueFilterName<TQueues>> = keyof TQueues extends never ? [response?: unknown] : TName extends QueueName<TQueues> ? [InferQueueCompleteMap<TQueues>[TName]] extends [never] ? [response?: unknown] : QueueCompleteArgs<InferQueueCompleteMap<TQueues>[TName]> : [response?: unknown];
1965
- type QueueCompletionResultForName<TQueues extends QueueSchemaConfig, TName extends QueueFilterName<TQueues>> = keyof TQueues extends never ? unknown | undefined : TName extends QueueName<TQueues> ? InferQueueCompleteMap<TQueues>[TName] | undefined : unknown | undefined;
1966
- interface QueueNextOptions<TName extends string = string, TCompletable extends boolean = boolean> {
1967
- names?: readonly TName[];
1968
- timeout?: number;
1969
- signal?: AbortSignal;
1970
- completable?: TCompletable;
1971
- }
1972
- interface QueueNextBatchOptions<TName extends string = string, TCompletable extends boolean = boolean> {
1973
- names?: readonly TName[];
1974
- count?: number;
1975
- timeout?: number;
1976
- signal?: AbortSignal;
1977
- completable?: TCompletable;
1978
- }
1979
- interface QueueWaitOptions<TCompletable extends boolean = boolean> {
1980
- timeout?: number;
1981
- signal?: AbortSignal;
1982
- completable?: TCompletable;
1983
- }
1984
- interface QueueEnqueueAndWaitOptions {
1985
- timeout?: number;
1986
- signal?: AbortSignal;
1987
- }
1988
- interface QueueTryNextOptions<TName extends string = string, TCompletable extends boolean = boolean> {
1989
- names?: readonly TName[];
1990
- completable?: TCompletable;
1991
- }
1992
- interface QueueTryNextBatchOptions<TName extends string = string, TCompletable extends boolean = boolean> {
1993
- names?: readonly TName[];
1994
- count?: number;
1995
- completable?: TCompletable;
1996
- }
1997
- interface QueueIterOptions<TName extends string = string, TCompletable extends boolean = boolean> {
1998
- names?: readonly TName[];
1999
- signal?: AbortSignal;
2000
- completable?: TCompletable;
2001
- }
2002
- interface ActorQueue<TQueues extends QueueSchemaConfig = Record<never, never>> {
2003
- send<TName extends QueueFilterName<TQueues>>(name: TName, body: QueueMessageForName<TQueues, TName>["body"]): Promise<any>;
2004
- next<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueNextOptions<TName, TCompletable>): Promise<any>;
2005
- nextBatch<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueNextBatchOptions<TName, TCompletable>): Promise<any[]>;
2006
- waitForNames<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(names: readonly TName[], opts?: QueueWaitOptions<TCompletable>): Promise<any>;
2007
- /** @experimental */
2008
- waitForAvailable<const TName extends QueueFilterName<TQueues>>(names?: readonly TName[], opts?: Omit<QueueWaitOptions<false>, "completable">): Promise<void>;
2009
- /** @experimental */
2010
- complete<const TName extends QueueFilterName<TQueues>>(message: {
2011
- id: number | bigint;
2012
- name: TName;
2013
- }, ...args: QueueCompleteArgsForName<TQueues, TName>): Promise<void>;
2014
- enqueueAndWait<const TName extends QueueFilterName<TQueues>>(name: TName, body: QueueMessageForName<TQueues, TName>["body"], opts?: QueueEnqueueAndWaitOptions): Promise<QueueCompletionResultForName<TQueues, TName>>;
2015
- tryNext<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueTryNextOptions<TName, TCompletable>): Promise<any>;
2016
- tryNextBatch<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueTryNextBatchOptions<TName, TCompletable>): Promise<any[]>;
2017
- iter<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueIterOptions<TName, TCompletable>): AsyncIterable<any>;
2018
- [key: string]: any;
2019
- }
2020
- interface Conn<_TState = unknown, TConnParams = unknown, TConnState = unknown, _TVars = unknown, _TInput = unknown, _TDatabase extends AnyDatabaseProvider = AnyDatabaseProvider, _TEvents extends EventSchemaConfig = Record<never, never>, _TQueues extends QueueSchemaConfig = Record<never, never>> {
2021
- id: string;
2022
- params: TConnParams;
2023
- state: TConnState;
2024
- isHibernatable: boolean;
2025
- send(name: string, ...args: any[]): void;
2026
- disconnect(reason?: string): Promise<void>;
2027
- [key: string]: any;
2028
- }
2029
- interface ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> {
2030
- [ACTOR_CONTEXT_INTERNAL_SYMBOL]?: unknown;
2031
- /** Returns the raw unwrapped state without the write-through proxy. */
2032
- [RAW_STATE_SYMBOL](): TState;
2033
- state: TState;
2034
- vars: TVars;
2035
- /**
2036
- * @deprecated Actor KV is deprecated. Use embedded SQLite (`c.db`)
2037
- * or actor state instead.
2038
- */
2039
- readonly kv: ActorKv;
2040
- readonly db: InferDatabaseClient<TDatabase>;
2041
- readonly schedule: ActorSchedule;
2042
- readonly cron: ActorCron;
2043
- readonly queue: ActorQueue<TQueues>;
2044
- /** @experimental */
2045
- readonly run: ActorRun;
2046
- readonly actorId: string;
2047
- readonly name: string;
2048
- readonly key: string[];
2049
- readonly region: string;
2050
- /** Provisions the experimental Actor Runtime Socket for this actor generation. */
2051
- actorRuntimeSocket(): Promise<{
2052
- path: string;
2053
- }>;
2054
- readonly conns: Map<string, Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>>;
2055
- readonly log: ActorLogger;
2056
- readonly abortSignal: AbortSignal;
2057
- readonly aborted: boolean;
2058
- readonly request?: Request;
2059
- /** @deprecated No-op. Always returns `false`. Use `keepAwake(promise)` or `waitUntil(promise)` instead. Will be removed in 2.2.0. */
2060
- readonly preventSleep: boolean;
2061
- broadcast(name: string, ...args: any[]): void;
2062
- saveState(opts?: {
2063
- immediate?: boolean;
2064
- maxWait?: number;
2065
- }): Promise<void>;
2066
- keepAwake<T>(promise: Promise<T>): Promise<T>;
2067
- waitUntil(promise: Promise<unknown>): void;
2068
- /** @deprecated No-op. Use `keepAwake(promise)` to hold the actor awake for a specific promise. Will be removed in 2.2.0. */
2069
- setPreventSleep(preventSleep: boolean): void;
2070
- sleep(): void;
2071
- destroy(): void;
2072
- client<T = any>(): ActorClientFor<T>;
2073
- [key: string]: any;
2074
- }
2075
- /** @experimental How one run of a workflow function ended. */
2076
- type WorkflowOutcome = "completed" | "sleeping" | "evicted" | "failed" | "cancelled";
2077
- /** @experimental How one workflow step attempt ended. `retry` will be tried again, `failed` will not. */
2078
- type WorkflowStepOutcome = "ok" | "retry" | "failed";
2079
- /** @experimental One open run of a workflow function, traced as its own invocation. */
2080
- interface WorkflowSpan {
2081
- /** Runs `body` attributed to this run. */
2082
- run<T>(body: () => Promise<T>): Promise<T>;
2083
- /**
2084
- * Called by a workflow engine before each attempt at a step. Returns
2085
- * nothing when tracing is off.
2086
- */
2087
- startStep(name: string, attempt: number): WorkflowStepSpan | undefined;
2088
- finish(outcome: WorkflowOutcome): Promise<void>;
2089
- }
2090
- /** @experimental One open attempt at one workflow step. */
2091
- interface WorkflowStepSpan {
2092
- /** Runs `body` attributed to this attempt. */
2093
- run<T>(body: () => Promise<T>): Promise<T>;
2094
- /** `error` is what the step callback threw. */
2095
- finish(outcome: WorkflowStepOutcome, error?: unknown): void;
2096
- }
2097
- /** @experimental */
2098
- interface ActorRun {
2099
- /**
2100
- * @experimental Sets or clears the durable Unix-millisecond deadline that
2101
- * ensures this actor's run handler is active, starting it if inactive.
2102
- */
2103
- setWakeAt(timestamp: number | null): Promise<void>;
2104
- /** @experimental Called by a workflow engine each time it runs the workflow function. */
2105
- startWorkflowSpan(): Promise<WorkflowSpan>;
2106
- /**
2107
- * @experimental Runs `body` outside the current workflow run, so a workflow
2108
- * engine's own history storage stays out of the trace.
2109
- */
2110
- runOutsideWorkflowSpan<T>(body: () => T): T;
2111
- }
2112
- type ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & {
2113
- conn: Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2114
- };
2115
- type BeforeActionResponseContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2116
- type BeforeConnectContext<TState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, unknown, unknown, TVars, TInput, TDatabase, TEvents, TQueues>;
2117
- type ConnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2118
- type CreateConnStateContext<TState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, unknown, unknown, TVars, TInput, TDatabase, TEvents, TQueues>;
2119
- type CreateContext<TState, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, unknown, unknown, unknown, TInput, TDatabase, TEvents, TQueues>;
2120
- type CreateVarsContext<TState, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = CreateContext<TState, TInput, TDatabase, TEvents, TQueues>;
2121
- type DestroyContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2122
- type DisconnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2123
- type RequestContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2124
- type RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2125
- type SleepContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2126
- type StateChangeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2127
- type WakeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2128
- type MigrateContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = WakeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2129
- type WebSocketContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2130
- type InspectorUnsubscribe = () => void;
2131
- declare const RunConfigSchema: z$1.ZodObject<{
2132
- name: z$1.ZodOptional<z$1.ZodString>;
2133
- icon: z$1.ZodOptional<z$1.ZodString>;
2134
- run: z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>;
2135
- inspector: z$1.ZodOptional<z$1.ZodOptional<z$1.ZodObject<{
2136
- workflow: z$1.ZodOptional<z$1.ZodObject<{
2137
- getHistory: z$1.ZodCustom<() => unknown, () => unknown>;
2138
- getState: z$1.ZodOptional<z$1.ZodCustom<() => Promise<WorkflowState | null>, () => Promise<WorkflowState | null>>>;
2139
- onHistoryUpdated: z$1.ZodOptional<z$1.ZodCustom<(listener: (history: unknown) => void) => InspectorUnsubscribe, (listener: (history: unknown) => void) => InspectorUnsubscribe>>;
2140
- replayFromStep: z$1.ZodOptional<z$1.ZodCustom<(entryId?: string) => Promise<unknown>, (entryId?: string) => Promise<unknown>>>;
2141
- }, z$1.core.$strip>>;
2142
- }, z$1.core.$strip>>>;
2143
- }, z$1.core.$strip>;
2144
- type RunConfigRuntime = z$1.infer<typeof RunConfigSchema>;
2145
- type RunConfig<TState = unknown, TConnParams = unknown, TConnState = unknown, TVars = unknown, TInput = unknown, TDatabase extends AnyDatabaseProvider = AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = Omit<RunConfigRuntime, "run"> & {
2146
- run: (c: RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
2147
- };
2148
- declare const ActorConfigSchema: z$1.ZodObject<{
2149
- onCreate: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2150
- onDestroy: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2151
- onMigrate: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2152
- onWake: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2153
- onSleep: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2154
- run: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>, z$1.ZodObject<{
2155
- name: z$1.ZodOptional<z$1.ZodString>;
2156
- icon: z$1.ZodOptional<z$1.ZodString>;
2157
- run: z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>;
2158
- inspector: z$1.ZodOptional<z$1.ZodOptional<z$1.ZodObject<{
2159
- workflow: z$1.ZodOptional<z$1.ZodObject<{
2160
- getHistory: z$1.ZodCustom<() => unknown, () => unknown>;
2161
- getState: z$1.ZodOptional<z$1.ZodCustom<() => Promise<WorkflowState | null>, () => Promise<WorkflowState | null>>>;
2162
- onHistoryUpdated: z$1.ZodOptional<z$1.ZodCustom<(listener: (history: unknown) => void) => InspectorUnsubscribe, (listener: (history: unknown) => void) => InspectorUnsubscribe>>;
2163
- replayFromStep: z$1.ZodOptional<z$1.ZodCustom<(entryId?: string) => Promise<unknown>, (entryId?: string) => Promise<unknown>>>;
2164
- }, z$1.core.$strip>>;
2165
- }, z$1.core.$strip>>>;
2166
- }, z$1.core.$strip>]>>;
2167
- onStateChange: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2168
- onBeforeConnect: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2169
- onConnect: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2170
- onDisconnect: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2171
- onBeforeActionResponse: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2172
- onRequest: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2173
- onWebSocket: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2174
- actions: z$1.ZodDefault<z$1.ZodCustom<Record<string, unknown>, Record<string, unknown>>>;
2175
- actionInputSchemas: z$1.ZodOptional<z$1.ZodRecord<z$1.ZodString, z$1.ZodAny>>;
2176
- tracing: z$1.ZodOptional<z$1.ZodObject<{
2177
- sampler: z$1.ZodOptional<z$1.ZodNumber>;
2178
- actions: z$1.ZodOptional<z$1.ZodType<ActionSampleRates, unknown, z$1.core.$ZodTypeInternals<ActionSampleRates, unknown>>>;
2179
- }, z$1.core.$strict>>;
2180
- connParamsSchema: z$1.ZodOptional<z$1.ZodAny>;
2181
- events: z$1.ZodOptional<z$1.ZodRecord<z$1.ZodString, z$1.ZodAny>>;
2182
- queues: z$1.ZodOptional<z$1.ZodRecord<z$1.ZodString, z$1.ZodAny>>;
2183
- state: z$1.ZodOptional<z$1.ZodAny>;
2184
- createState: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2185
- connState: z$1.ZodOptional<z$1.ZodAny>;
2186
- createConnState: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2187
- vars: z$1.ZodOptional<z$1.ZodAny>;
2188
- db: z$1.ZodOptional<z$1.ZodAny>;
2189
- createVars: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2190
- options: z$1.ZodPrefault<z$1.ZodObject<{
2191
- name: z$1.ZodOptional<z$1.ZodString>;
2192
- icon: z$1.ZodOptional<z$1.ZodString>;
2193
- enableActorRuntimeSocket: z$1.ZodDefault<z$1.ZodBoolean>;
2194
- canHibernateWebSocket: z$1.ZodDefault<z$1.ZodUnion<readonly [z$1.ZodBoolean, z$1.ZodCustom<(request: Request) => boolean, (request: Request) => boolean>]>>;
2195
- createVarsTimeout: z$1.ZodDefault<z$1.ZodNumber>;
2196
- createConnStateTimeout: z$1.ZodDefault<z$1.ZodNumber>;
2197
- onBeforeConnectTimeout: z$1.ZodDefault<z$1.ZodNumber>;
2198
- onConnectTimeout: z$1.ZodDefault<z$1.ZodNumber>;
2199
- onMigrateTimeout: z$1.ZodDefault<z$1.ZodNumber>;
2200
- sleepGracePeriod: z$1.ZodDefault<z$1.ZodNumber>;
2201
- onDestroyTimeout: z$1.ZodOptional<z$1.ZodNumber>;
2202
- waitUntilTimeout: z$1.ZodOptional<z$1.ZodNumber>;
2203
- stateSaveInterval: z$1.ZodDefault<z$1.ZodNumber>;
2204
- actionTimeout: z$1.ZodDefault<z$1.ZodNumber>;
2205
- connectionLivenessTimeout: z$1.ZodDefault<z$1.ZodNumber>;
2206
- connectionLivenessInterval: z$1.ZodDefault<z$1.ZodNumber>;
2207
- noSleep: z$1.ZodDefault<z$1.ZodBoolean>;
2208
- sleepTimeout: z$1.ZodDefault<z$1.ZodNumber>;
2209
- maxQueueSize: z$1.ZodDefault<z$1.ZodNumber>;
2210
- maxSchedules: z$1.ZodDefault<z$1.ZodNumber>;
2211
- maxQueueMessageSize: z$1.ZodDefault<z$1.ZodNumber>;
2212
- preloadMaxWorkflowBytes: z$1.ZodOptional<z$1.ZodNumber>;
2213
- preloadMaxConnectionsBytes: z$1.ZodOptional<z$1.ZodNumber>;
2214
- }, z$1.core.$strict>>;
2215
- inspector: z$1.ZodOptional<z$1.ZodObject<{
2216
- tabs: z$1.ZodDefault<z$1.ZodArray<z$1.ZodUnion<readonly [z$1.ZodObject<{
2217
- id: z$1.ZodString;
2218
- label: z$1.ZodString;
2219
- source: z$1.ZodString;
2220
- icon: z$1.ZodOptional<z$1.ZodString>;
2221
- hidden: z$1.ZodOptional<z$1.ZodLiteral<false>>;
2222
- }, z$1.core.$strict>, z$1.ZodObject<{
2223
- id: z$1.ZodEnum<{
2224
- workflow: "workflow";
2225
- state: "state";
2226
- database: "database";
2227
- queue: "queue";
2228
- schedules: "schedules";
2229
- connections: "connections";
2230
- console: "console";
2231
- }>;
2232
- hidden: z$1.ZodLiteral<true>;
2233
- }, z$1.core.$strict>]>>>;
2234
- }, z$1.core.$strict>>;
2235
- }, z$1.core.$strict>;
2236
- type CreateState<TState, _TConnParams, _TConnState, _TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig> = {
2237
- state: TState;
2238
- } | {
2239
- createState: (c: CreateContext<TState, TInput, TDatabase, TEvents, TQueues>, input: TInput) => TState | Promise<TState>;
2240
- } | Record<never, never>;
2241
- type CreateConnState<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig> = {
2242
- connState: TConnState;
2243
- } | {
2244
- createConnState: (c: CreateConnStateContext<TState, TVars, TInput, TDatabase, TEvents, TQueues>, params: TConnParams) => TConnState | Promise<TConnState>;
2245
- } | Record<never, never>;
2246
- /**
2247
- * @experimental
2248
- */
2249
- type CreateVars<TState, _TConnParams, _TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig> = {
2250
- /**
2251
- * @experimental
2252
- */
2253
- vars: TVars;
2254
- } | {
2255
- /**
2256
- * @experimental
2257
- */
2258
- createVars: (c: CreateVarsContext<TState, TInput, TDatabase, TEvents, TQueues>, driverCtx: any) => TVars | Promise<TVars>;
2259
- } | Record<never, never>;
2260
- interface Actions<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> {
2261
- [Action: string]: ((c: ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, ...args: any[]) => any) | Actions<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2262
- }
2263
- interface ActionInputSchemas {
2264
- [Action: string]: PrimitiveSchema | ActionInputSchemas;
2265
- }
2266
- interface BaseActorConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig, TActions extends Actions<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>> {
2267
- /**
2268
- * Called when the actor is first initialized.
2269
- *
2270
- * Use this hook to initialize your actor's state.
2271
- * This is called before any other lifecycle hooks.
2272
- */
2273
- onCreate?: (c: CreateContext<TState, TInput, TDatabase, TEvents, TQueues>, input: TInput) => void | Promise<void>;
2274
- /**
2275
- * Called when the actor is destroyed.
2276
- */
2277
- onDestroy?: (c: DestroyContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
2278
- /**
2279
- * Called on every actor start after persisted state loads and before onWake.
2280
- *
2281
- * Use this hook for repeatable schema migrations or other startup work that
2282
- * must run on both first boot and wake.
2283
- */
2284
- onMigrate?: (c: MigrateContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, isNew: boolean) => void | Promise<void>;
2285
- /**
2286
- * Called when the actor is started and ready to receive connections and action.
2287
- *
2288
- * Use this hook to initialize resources needed for the actor's operation
2289
- * (timers, external connections, etc.)
2290
- *
2291
- * @returns Void or a Promise that resolves when startup is complete
2292
- */
2293
- onWake?: (c: WakeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
2294
- /**
2295
- * Called when the actor is stopping or sleeping.
2296
- *
2297
- * Use this hook to clean up resources, save state, or perform
2298
- * any shutdown operations before the actor sleeps or stops.
2299
- *
2300
- * Not supported on all platforms.
2301
- *
2302
- * @returns Void or a Promise that resolves when shutdown is complete
2303
- */
2304
- onSleep?: (c: SleepContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
2305
- /**
2306
- * Called after the actor starts up. Does not block actor startup.
2307
- *
2308
- * Use this for background tasks like:
2309
- * - Reading from queues in a loop
2310
- * - Tick loops for periodic work
2311
- * - Custom workflow logic
2312
- *
2313
- * **Important:** The actor may go to sleep at any time during the `run`
2314
- * handler. Wrap work that must keep the actor awake with
2315
- * `c.keepAwake(promise)` to block idle sleep and shutdown finalize until
2316
- * the promise settles, or use `c.waitUntil(promise)` to let the graceful
2317
- * shutdown window (`sleepGracePeriod`) cover deferred work.
2318
- *
2319
- * The handler receives an abort signal via `c.abortSignal` and a
2320
- * `c.aborted` alias. Use these to gracefully exit when shutdown starts.
2321
- *
2322
- * If this handler exits, the actor will follow the normal idle sleep timeout
2323
- * once it becomes idle.
2324
- * If this handler throws, the actor logs the error and then sleeps once it
2325
- * becomes idle.
2326
- * Call `c.destroy()` explicitly if a run handler should destroy the actor.
2327
- *
2328
- * Can be either a function or a RunConfig object with optional name/icon metadata.
2329
- *
2330
- * @returns Void or a Promise.
2331
- */
2332
- run?: ((c: RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>) | RunConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
2333
- /**
2334
- * Called when the actor's state changes.
2335
- *
2336
- * Use this hook to react to state changes, such as updating
2337
- * external systems or triggering events.
2338
- *
2339
- * State changes made within this hook will NOT trigger
2340
- * another onStateChange call, preventing infinite recursion.
2341
- *
2342
- * @param newState The updated state
2343
- */
2344
- onStateChange?: (c: StateChangeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, newState: TState) => void;
2345
- /**
2346
- * Called before a client connects to the actor.
2347
- *
2348
- * Use this hook to determine if a connection should be accepted
2349
- * and to validate client-provided parameters. The pending connection
2350
- * is not visible in `c.conns` while this hook runs.
2351
- *
2352
- * @param opts Connection parameters including client-provided data
2353
- * @returns Void or a Promise.
2354
- * @throws Throw an error to reject the connection
2355
- */
2356
- onBeforeConnect?: (c: BeforeConnectContext<TState, TVars, TInput, TDatabase, TEvents, TQueues>, params: TConnParams) => void | Promise<void>;
2357
- /**
2358
- * Called when a client successfully connects to the actor.
2359
- *
2360
- * Use this hook to perform actions when a connection is established,
2361
- * such as sending initial data or updating the actor's state. The
2362
- * connection is visible in `c.conns` before this hook runs.
2363
- *
2364
- * @param conn The connection object
2365
- * @returns Void or a Promise that resolves when connection handling is complete
2366
- */
2367
- onConnect?: (c: ConnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, conn: Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
2368
- /**
2369
- * Called when a client disconnects from the actor.
2370
- *
2371
- * Use this hook to clean up resources associated with the connection
2372
- * or update the actor's state.
2373
- *
2374
- * @param conn The connection that is being closed
2375
- * @returns Void or a Promise that resolves when disconnect handling is complete
2376
- */
2377
- onDisconnect?: (c: DisconnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, conn: Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
2378
- /**
2379
- * Called before sending an action response to the client.
2380
- *
2381
- * Use this hook to modify or transform the output of an action before it's sent
2382
- * to the client. This is useful for formatting responses, adding metadata,
2383
- * or applying transformations to the output.
2384
- *
2385
- * @param name The name of the action that was called
2386
- * @param args The arguments that were passed to the action
2387
- * @param output The output that will be sent to the client
2388
- * @returns The modified output to send to the client
2389
- */
2390
- onBeforeActionResponse?: <Out>(c: BeforeActionResponseContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, name: string, args: unknown[], output: Out) => Out | Promise<Out>;
2391
- /**
2392
- * Called when a raw HTTP request is made to the actor.
2393
- *
2394
- * This handler receives raw HTTP requests made to `/actors/{actorName}/http/*` endpoints.
2395
- * Use this hook to handle custom HTTP patterns, REST APIs, or other HTTP-based protocols.
2396
- *
2397
- * @param c The request context with access to the connection
2398
- * @param request The raw HTTP request object
2399
- * @param opts Additional options
2400
- * @returns A Response object to send back, or void to continue with default routing
2401
- */
2402
- onRequest?: (c: RequestContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, request: Request) => Response | Promise<Response>;
2403
- /**
2404
- * Called when a raw WebSocket connection is established to the actor.
2405
- *
2406
- * This handler receives WebSocket connections made to `/actors/{actorName}/websocket/*` endpoints.
2407
- * Use this hook to handle custom WebSocket protocols, binary streams, or other WebSocket-based communication.
2408
- *
2409
- * @param c The WebSocket context with access to the connection
2410
- * @param websocket The actor-facing raw WebSocket connection
2411
- * @param opts Additional options including the original HTTP upgrade request
2412
- */
2413
- onWebSocket?: (c: WebSocketContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, websocket: UniversalWebSocket) => void | Promise<void>;
2414
- actions?: TActions;
2415
- /**
2416
- * Optional schemas for validating action argument tuples in native runtimes.
2417
- * May mirror nested action groups or use dot-separated low-level action names.
2418
- */
2419
- actionInputSchemas?: ActionInputSchemas;
2420
- /**
2421
- * How much of this actor's work is recorded in traces. Defaults to the
2422
- * process sampler from `OTEL_TRACES_SAMPLER`.
2423
- */
2424
- tracing?: ActorTracingOptions<TActions>;
2425
- /**
2426
- * Optional schema for validating connection params in native runtimes.
2427
- */
2428
- connParamsSchema?: PrimitiveSchema;
2429
- /**
2430
- * Schema map for events broadcasted by this actor.
2431
- */
2432
- events?: TEvents;
2433
- /**
2434
- * Schema map for queue payloads sent by this actor.
2435
- */
2436
- queues?: TQueues;
2437
- }
2438
- type ActorDatabaseConfig<TDatabase extends AnyDatabaseProvider> = {
2439
- /**
2440
- * @experimental
2441
- */
2442
- db: TDatabase;
2443
- } | Record<never, never>;
2444
- type ActorConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>, TActions extends Actions<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> = Actions<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>> = Omit<z$1.infer<typeof ActorConfigSchema>, "actions" | "events" | "queues" | "onCreate" | "onDestroy" | "onMigrate" | "onWake" | "onSleep" | "run" | "onStateChange" | "onBeforeConnect" | "onConnect" | "onDisconnect" | "onBeforeActionResponse" | "onRequest" | "onWebSocket" | "state" | "createState" | "connState" | "createConnState" | "vars" | "createVars" | "db"> & BaseActorConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues, TActions> & CreateState<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & CreateConnState<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & CreateVars<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & ActorDatabaseConfig<TDatabase>;
2445
-
2446
- type AgentOsActorState = {};
2447
- interface AgentOsActorVars {
2448
- agentOs: AgentOs | null;
2449
- activeSessionIds: Set<string>;
2450
- activeProcesses: Set<number>;
2451
- activeHooks: Set<Promise<void>>;
2452
- activeShells: Set<string>;
2453
- sessions: Set<string>;
2454
- }
2455
- interface SessionEventPayload {
2456
- sessionId: string;
2457
- event: JsonRpcNotification;
2458
- }
2459
- interface PermissionRequestPayload {
2460
- sessionId: string;
2461
- request: PermissionRequest;
2462
- }
2463
- type VmBootedPayload = Record<string, never>;
2464
- interface VmShutdownPayload {
2465
- reason: "sleep" | "destroy" | "error";
2466
- }
2467
- interface ProcessOutputPayload {
2468
- pid: number;
2469
- stream: "stdout" | "stderr";
2470
- data: Uint8Array;
2471
- }
2472
- interface ProcessExitPayload {
2473
- pid: number;
2474
- exitCode: number;
2475
- }
2476
- interface ShellDataPayload {
2477
- shellId: string;
2478
- data: Uint8Array;
2479
- }
2480
- interface CronEventPayload {
2481
- event: CronEvent;
2482
- }
2483
- interface AgentOsEvents {
2484
- sessionEvent: SessionEventPayload;
2485
- permissionRequest: PermissionRequestPayload;
2486
- vmBooted: VmBootedPayload;
2487
- vmShutdown: VmShutdownPayload;
2488
- processOutput: ProcessOutputPayload;
2489
- processExit: ProcessExitPayload;
2490
- shellData: ShellDataPayload;
2491
- cronEvent: CronEventPayload;
2492
- }
2493
- /** Result from sendPrompt. */
2494
- interface PromptResult {
2495
- /** Raw JSON-RPC response from the ACP adapter. */
2496
- response: JsonRpcResponse;
2497
- /** Accumulated agent text output from streamed message chunks. */
2498
- text: string;
2499
- }
2500
- interface SessionRecord {
2501
- sessionId: string;
2502
- agentType: string;
2503
- capabilities: AgentCapabilities;
2504
- agentInfo: AgentInfo | null;
2505
- }
2506
- interface PersistedSessionRecord {
2507
- sessionId: string;
2508
- agentType: string;
2509
- capabilities: AgentCapabilities;
2510
- agentInfo: AgentInfo | null;
2511
- createdAt: number;
2512
- }
2513
- interface PersistedSessionEvent {
2514
- sessionId: string;
2515
- seq: number;
2516
- event: JsonRpcNotification;
2517
- createdAt: number;
2518
- }
2519
- type SerializableCronAction = {
2520
- type: "session";
2521
- agentType: string;
2522
- prompt: string;
2523
- cwd?: string;
2524
- } | {
2525
- type: "exec";
2526
- command: string;
2527
- args?: string[];
2528
- };
2529
- interface SerializableCronJobOptions {
2530
- id?: string;
2531
- schedule: string;
2532
- action: SerializableCronAction;
2533
- overlap?: "allow" | "skip" | "queue";
2534
- }
2535
- interface SerializableCronJobInfo {
2536
- id: string;
2537
- schedule: string;
2538
- action: SerializableCronAction;
2539
- overlap: "allow" | "skip" | "queue";
2540
- lastRun?: string;
2541
- nextRun?: string;
2542
- runCount: number;
2543
- running: boolean;
2544
- }
2545
- type AgentOsActionContext<TConnParams = undefined> = ActionContext<AgentOsActorState, TConnParams, undefined, AgentOsActorVars, undefined, any>;
2546
-
2547
- declare const agentOsActorConfigSchema: z$1.ZodObject<{
2548
- options: z$1.ZodOptional<z$1.ZodCustom<AgentOsOptions, AgentOsOptions>>;
2549
- preview: z$1.ZodPrefault<z$1.ZodObject<{
2550
- defaultExpiresInSeconds: z$1.ZodDefault<z$1.ZodNumber>;
2551
- maxExpiresInSeconds: z$1.ZodDefault<z$1.ZodNumber>;
2552
- }, z$1.core.$strict>>;
2553
- onBeforeConnect: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2554
- onSessionEvent: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2555
- onPermissionRequest: z$1.ZodOptional<z$1.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2556
- }, z$1.core.$strict>;
2557
- type AgentOsActorContext<TConnParams> = ActorContext<AgentOsActorState, TConnParams, undefined, AgentOsActorVars, undefined, any>;
2558
- interface AgentOsActorConfigCallbacks<TConnParams> {
2559
- onBeforeConnect?: (c: BeforeConnectContext<AgentOsActorState, AgentOsActorVars, undefined, any>, params: TConnParams) => void | Promise<void>;
2560
- onSessionEvent?: (c: AgentOsActorContext<TConnParams>, sessionId: string, event: JsonRpcNotification) => void | Promise<void>;
2561
- onPermissionRequest?: (c: AgentOsActorContext<TConnParams>, sessionId: string, request: PermissionRequest) => void | Promise<void>;
2562
- }
2563
- type AgentOsActorConfig<TConnParams = undefined> = Omit<z$1.infer<typeof agentOsActorConfigSchema>, "onBeforeConnect" | "onSessionEvent" | "onPermissionRequest"> & AgentOsActorConfigCallbacks<TConnParams>;
2564
- type AgentOsActorConfigInput<TConnParams = undefined> = Omit<z$1.input<typeof agentOsActorConfigSchema>, "onBeforeConnect" | "onSessionEvent" | "onPermissionRequest"> & AgentOsActorConfigCallbacks<TConnParams>;
2565
-
2566
- declare function buildCronActions<TConnParams>(config: AgentOsActorConfig<TConnParams>): {
2567
- scheduleCron: (c: AgentOsActionContext<TConnParams>, options: SerializableCronJobOptions) => Promise<{
2568
- id: string;
2569
- }>;
2570
- listCronJobs: (c: AgentOsActionContext<TConnParams>) => Promise<SerializableCronJobInfo[]>;
2571
- cancelCronJob: (c: AgentOsActionContext<TConnParams>, id: string) => Promise<void>;
2572
- };
2573
-
2574
- declare function migrateAgentOsTables(db: RawAccess): Promise<void>;
2575
-
2576
- type VirtualStat = Awaited<ReturnType<_rivet_dev_agent_os_core.AgentOs["stat"]>>;
2577
- type DeleteOptions = Parameters<_rivet_dev_agent_os_core.AgentOs["delete"]>[1];
2578
- declare function buildFilesystemActions<TConnParams>(config: AgentOsActorConfig<TConnParams>): {
2579
- readFile: (c: AgentOsActionContext<TConnParams>, path: string) => Promise<Uint8Array>;
2580
- writeFile: (c: AgentOsActionContext<TConnParams>, path: string, content: string | Uint8Array) => Promise<void>;
2581
- readFiles: (c: AgentOsActionContext<TConnParams>, paths: string[]) => Promise<BatchReadResult[]>;
2582
- writeFiles: (c: AgentOsActionContext<TConnParams>, entries: BatchWriteEntry[]) => Promise<BatchWriteResult[]>;
2583
- mkdir: (c: AgentOsActionContext<TConnParams>, path: string, options?: {
2584
- recursive?: boolean;
2585
- }) => Promise<void>;
2586
- readdir: (c: AgentOsActionContext<TConnParams>, path: string) => Promise<string[]>;
2587
- readdirRecursive: (c: AgentOsActionContext<TConnParams>, path: string, options?: ReaddirRecursiveOptions) => Promise<DirEntry[]>;
2588
- stat: (c: AgentOsActionContext<TConnParams>, path: string) => Promise<VirtualStat>;
2589
- exists: (c: AgentOsActionContext<TConnParams>, path: string) => Promise<boolean>;
2590
- move: (c: AgentOsActionContext<TConnParams>, from: string, to: string) => Promise<void>;
2591
- deleteFile: (c: AgentOsActionContext<TConnParams>, path: string, options?: DeleteOptions) => Promise<void>;
2592
- listAgents: (c: AgentOsActionContext<TConnParams>) => Promise<AgentRegistryEntry[]>;
2593
- };
2594
-
2595
- declare function ensureVm<TConnParams>(c: AgentOsActionContext<TConnParams>, config: AgentOsActorConfig<TConnParams>): Promise<AgentOs>;
2596
- declare function syncPreventSleep<TConnParams>(c: AgentOsActionContext<TConnParams>): void;
2597
- declare function runHook<TConnParams>(c: AgentOsActionContext<TConnParams>, name: string, callback: () => void | Promise<void>): void;
2598
- declare function agentOs<TConnParams = undefined>(config: AgentOsActorConfigInput<TConnParams>): ActorDefinition<AgentOsActorState, TConnParams, undefined, AgentOsActorVars, undefined, DatabaseProvider<RawAccess>, {
2599
- sessionEvent: typeof sessionEventToken;
2600
- permissionRequest: typeof permissionRequestToken;
2601
- vmBooted: typeof vmBootedToken;
2602
- vmShutdown: typeof vmShutdownToken;
2603
- processOutput: typeof processOutputToken;
2604
- processExit: typeof processExitToken;
2605
- shellData: typeof shellDataToken;
2606
- cronEvent: typeof cronEventToken;
2607
- }, Record<never, never>, any>;
2608
- declare const sessionEventToken: EventTypeToken<SessionEventPayload, any>;
2609
- declare const permissionRequestToken: EventTypeToken<PermissionRequestPayload, any>;
2610
- declare const vmBootedToken: EventTypeToken<VmBootedPayload, any>;
2611
- declare const vmShutdownToken: EventTypeToken<VmShutdownPayload, any>;
2612
- declare const processOutputToken: EventTypeToken<ProcessOutputPayload, any>;
2613
- declare const processExitToken: EventTypeToken<ProcessExitPayload, any>;
2614
- declare const shellDataToken: EventTypeToken<ShellDataPayload, any>;
2615
- declare const cronEventToken: EventTypeToken<CronEventPayload, any>;
2616
-
2617
- interface VmFetchOptions {
2618
- method?: string;
2619
- headers?: Record<string, string>;
2620
- body?: string | Uint8Array;
2621
- }
2622
- interface VmFetchResult {
2623
- status: number;
2624
- statusText: string;
2625
- headers: Record<string, string>;
2626
- body: Uint8Array;
2627
- }
2628
- declare function buildNetworkActions<TConnParams>(config: AgentOsActorConfig<TConnParams>): {
2629
- vmFetch: (c: AgentOsActionContext<TConnParams>, port: number, url: string, options?: VmFetchOptions) => Promise<VmFetchResult>;
2630
- };
2631
-
2632
- declare function generateToken(): string;
2633
- type AgentOsRequestContext<TConnParams> = RequestContext<AgentOsActorState, TConnParams, undefined, AgentOsActorVars, undefined, DatabaseProvider<RawAccess>>;
2634
- declare function buildOnRequestHandler<TConnParams>(config: AgentOsActorConfig<TConnParams>): (c: AgentOsRequestContext<TConnParams>, request: Request) => Promise<Response>;
2635
- declare function buildPreviewActions<TConnParams>(config: AgentOsActorConfig<TConnParams>): {
2636
- createSignedPreviewUrl: (c: AgentOsActionContext<TConnParams>, port: number, expiresInSeconds?: number) => Promise<{
2637
- path: string;
2638
- token: string;
2639
- port: number;
2640
- expiresAt: number;
2641
- }>;
2642
- expireSignedPreviewUrl: (c: AgentOsActionContext<TConnParams>, token: string) => Promise<void>;
2643
- };
2644
-
2645
- type ExecResult = Awaited<ReturnType<_rivet_dev_agent_os_core.AgentOs["exec"]>>;
2646
- type ExecOptions = Parameters<_rivet_dev_agent_os_core.AgentOs["exec"]>[1];
2647
- type SpawnOptions = Parameters<_rivet_dev_agent_os_core.AgentOs["spawn"]>[2];
2648
- declare function buildProcessActions<TConnParams>(config: AgentOsActorConfig<TConnParams>): {
2649
- exec: (c: AgentOsActionContext<TConnParams>, command: string, options?: ExecOptions) => Promise<ExecResult>;
2650
- spawn: (c: AgentOsActionContext<TConnParams>, command: string, args: string[], options?: SpawnOptions) => Promise<{
2651
- pid: number;
2652
- }>;
2653
- writeProcessStdin: (c: AgentOsActionContext<TConnParams>, pid: number, data: string | Uint8Array) => Promise<void>;
2654
- closeProcessStdin: (c: AgentOsActionContext<TConnParams>, pid: number) => Promise<void>;
2655
- waitProcess: (c: AgentOsActionContext<TConnParams>, pid: number) => Promise<number>;
2656
- listProcesses: (c: AgentOsActionContext<TConnParams>) => Promise<SpawnedProcessInfo[]>;
2657
- allProcesses: (c: AgentOsActionContext<TConnParams>) => Promise<ProcessInfo[]>;
2658
- processTree: (c: AgentOsActionContext<TConnParams>) => Promise<ProcessTreeNode[]>;
2659
- getProcess: (c: AgentOsActionContext<TConnParams>, pid: number) => Promise<SpawnedProcessInfo>;
2660
- stopProcess: (c: AgentOsActionContext<TConnParams>, pid: number) => Promise<void>;
2661
- killProcess: (c: AgentOsActionContext<TConnParams>, pid: number) => Promise<void>;
2662
- };
2663
-
2664
- declare function subscribeToSession<TConnParams>(c: AgentOsActionContext<TConnParams>, agentOs: AgentOs, sessionId: string, parsedConfig: AgentOsActorConfig<TConnParams>): void;
2665
- declare function buildSessionActions<TConnParams>(config: AgentOsActorConfig<TConnParams>): {
2666
- createSession: (c: AgentOsActionContext<TConnParams>, agentType: AgentType, options?: CreateSessionOptions) => Promise<SessionRecord>;
2667
- listSessions: (c: AgentOsActionContext<TConnParams>) => Promise<SessionInfo[]>;
2668
- getSession: (c: AgentOsActionContext<TConnParams>, sessionId: string) => Promise<SessionRecord>;
2669
- destroySession: (c: AgentOsActionContext<TConnParams>, sessionId: string) => Promise<void>;
2670
- resumeSession: (c: AgentOsActionContext<TConnParams>, sessionId: string) => Promise<{
2671
- sessionId: string;
2672
- }>;
2673
- closeSession: (c: AgentOsActionContext<TConnParams>, sessionId: string) => Promise<void>;
2674
- };
2675
- declare function buildPromptActions<TConnParams>(_config: AgentOsActorConfig<TConnParams>): {
2676
- sendPrompt: (c: AgentOsActionContext<TConnParams>, sessionId: string, text: string) => Promise<PromptResult>;
2677
- cancelPrompt: (c: AgentOsActionContext<TConnParams>, sessionId: string) => Promise<JsonRpcResponse>;
2678
- respondPermission: (c: AgentOsActionContext<TConnParams>, sessionId: string, permissionId: string, reply: PermissionReply) => Promise<JsonRpcResponse>;
2679
- };
2680
- declare function buildConfigActions<TConnParams>(_config: AgentOsActorConfig<TConnParams>): {
2681
- setMode: (c: AgentOsActionContext<TConnParams>, sessionId: string, modeId: string) => Promise<JsonRpcResponse>;
2682
- getModes: (c: AgentOsActionContext<TConnParams>, sessionId: string) => Promise<SessionModeState | null>;
2683
- setModel: (c: AgentOsActionContext<TConnParams>, sessionId: string, model: string) => Promise<JsonRpcResponse>;
2684
- setThoughtLevel: (c: AgentOsActionContext<TConnParams>, sessionId: string, level: string) => Promise<JsonRpcResponse>;
2685
- getConfigOptions: (c: AgentOsActionContext<TConnParams>, sessionId: string) => Promise<SessionConfigOption[]>;
2686
- getEvents: (c: AgentOsActionContext<TConnParams>, sessionId: string, options?: GetEventsOptions) => Promise<JsonRpcNotification[]>;
2687
- getSequencedEvents: (c: AgentOsActionContext<TConnParams>, sessionId: string, options?: GetEventsOptions) => Promise<SequencedEvent[]>;
2688
- rawSend: (c: AgentOsActionContext<TConnParams>, sessionId: string, method: string, params?: Record<string, unknown>) => Promise<JsonRpcResponse>;
2689
- };
2690
- declare function buildSessionPersistenceActions<TConnParams>(_config: AgentOsActorConfig<TConnParams>): {
2691
- listPersistedSessions: (c: AgentOsActionContext<TConnParams>) => Promise<PersistedSessionRecord[]>;
2692
- getSessionEvents: (c: AgentOsActionContext<TConnParams>, sessionId: string) => Promise<PersistedSessionEvent[]>;
2693
- };
2694
-
2695
- declare function buildShellActions<TConnParams>(config: AgentOsActorConfig<TConnParams>): {
2696
- openShell: (c: AgentOsActionContext<TConnParams>, options?: OpenShellOptions) => Promise<{
2697
- shellId: string;
2698
- }>;
2699
- writeShell: (c: AgentOsActionContext<TConnParams>, shellId: string, data: string | Uint8Array) => Promise<void>;
2700
- resizeShell: (c: AgentOsActionContext<TConnParams>, shellId: string, cols: number, rows: number) => Promise<void>;
2701
- closeShell: (c: AgentOsActionContext<TConnParams>, shellId: string) => Promise<void>;
2702
- };
2703
-
2704
- type VirtualFileSystem = _rivet_dev_agent_os_core.PlainMountConfig["driver"];
2705
- interface DatabaseVfsOptions {
2706
- /** The RawAccess database handle from the actor's db provider. */
2707
- db: RawAccess;
2708
- }
2709
- /**
2710
- * Create a VirtualFileSystem backed by SQLite.
2711
- *
2712
- * The returned filesystem stores all content and metadata in the
2713
- * `agent_os_fs_entries` table. The table must be created beforehand
2714
- * via `migrateAgentOsTables()`.
2715
- */
2716
- declare function createDatabaseVfs(options: DatabaseVfsOptions): VirtualFileSystem;
2717
-
2718
- export { type AgentOsActionContext, type AgentOsActorConfig, type AgentOsActorConfigInput, type AgentOsActorState, type AgentOsActorVars, type AgentOsEvents, type CronEventPayload, type DatabaseVfsOptions, type PermissionRequestPayload, type PersistedSessionEvent, type PersistedSessionRecord, type ProcessExitPayload, type ProcessOutputPayload, type PromptResult, type SerializableCronAction, type SerializableCronJobOptions, type SessionEventPayload, type SessionRecord, type ShellDataPayload, type VmBootedPayload, type VmFetchOptions, type VmFetchResult, type VmShutdownPayload, agentOs, agentOsActorConfigSchema, buildConfigActions, buildCronActions, buildFilesystemActions, buildNetworkActions, buildOnRequestHandler, buildPreviewActions, buildProcessActions, buildPromptActions, buildSessionActions, buildSessionPersistenceActions, buildShellActions, createDatabaseVfs, ensureVm, generateToken, migrateAgentOsTables, runHook, subscribeToSession, syncPreventSleep };
2
+ export { }