rivetkit 3.0.7 → 3.1.0-rc.1

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 (113) hide show
  1. package/dist/browser/client.d.ts +112 -2
  2. package/dist/browser/client.js +145 -7
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +1 -1
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/{chunk-AY25XAXA.js → chunk-5NNDJCH7.js} +3 -3
  7. package/dist/tsup/{chunk-AY25XAXA.js.map → chunk-5NNDJCH7.js.map} +1 -1
  8. package/dist/tsup/{chunk-U3CMQVMS.cjs → chunk-6LQ23TJA.cjs} +3 -3
  9. package/dist/tsup/{chunk-U3CMQVMS.cjs.map → chunk-6LQ23TJA.cjs.map} +1 -1
  10. package/dist/tsup/{chunk-YMCG4FCB.js → chunk-76FFOINJ.js} +149 -12
  11. package/dist/tsup/chunk-76FFOINJ.js.map +1 -0
  12. package/dist/tsup/{chunk-YO4TJ56P.js → chunk-CRC7NMU3.js} +2 -2
  13. package/dist/tsup/{chunk-NMLZDHH2.js → chunk-ECLJJGV6.js} +2 -2
  14. package/dist/tsup/{chunk-YTELGNB3.cjs → chunk-I3YW5B3I.cjs} +7 -7
  15. package/dist/tsup/{chunk-YTELGNB3.cjs.map → chunk-I3YW5B3I.cjs.map} +1 -1
  16. package/dist/tsup/{chunk-OEOODXVI.cjs → chunk-K6O7IE7P.cjs} +4 -4
  17. package/dist/tsup/{chunk-OEOODXVI.cjs.map → chunk-K6O7IE7P.cjs.map} +1 -1
  18. package/dist/tsup/{chunk-WBUHPDDM.cjs → chunk-MT3ZLU7U.cjs} +2 -2
  19. package/dist/tsup/chunk-MT3ZLU7U.cjs.map +1 -0
  20. package/dist/tsup/{chunk-HKD7AH4Z.cjs → chunk-MUCEIMJW.cjs} +287 -150
  21. package/dist/tsup/chunk-MUCEIMJW.cjs.map +1 -0
  22. package/dist/tsup/{chunk-YWWDUC6D.cjs → chunk-OKLZYDQB.cjs} +5 -1
  23. package/dist/tsup/chunk-OKLZYDQB.cjs.map +1 -0
  24. package/dist/tsup/{chunk-RFJ4NNO3.js → chunk-R4VUGJNR.js} +4 -4
  25. package/dist/tsup/{chunk-QTCX5KN3.js → chunk-SVWVXVV7.js} +2 -2
  26. package/dist/tsup/{chunk-K6WETGBW.cjs → chunk-SXEIT5DF.cjs} +3 -3
  27. package/dist/tsup/{chunk-K6WETGBW.cjs.map → chunk-SXEIT5DF.cjs.map} +1 -1
  28. package/dist/tsup/{chunk-S6ZMUE7Q.js → chunk-TDHEMJHH.js} +2 -2
  29. package/dist/tsup/{chunk-PBIQPYE5.js → chunk-UFHGMXXV.js} +5 -1
  30. package/dist/tsup/chunk-UFHGMXXV.js.map +1 -0
  31. package/dist/tsup/{chunk-7OXC5BQF.js → chunk-UYCRHJY2.js} +2 -2
  32. package/dist/tsup/chunk-UYCRHJY2.js.map +1 -0
  33. package/dist/tsup/{chunk-5A2KUC5L.cjs → chunk-VOGVBK5O.cjs} +10 -10
  34. package/dist/tsup/{chunk-5A2KUC5L.cjs.map → chunk-VOGVBK5O.cjs.map} +1 -1
  35. package/dist/tsup/{chunk-VM4SXQOC.cjs → chunk-YTSSP6NX.cjs} +3 -3
  36. package/dist/tsup/{chunk-VM4SXQOC.cjs.map → chunk-YTSSP6NX.cjs.map} +1 -1
  37. package/dist/tsup/client/mod.cjs +5 -5
  38. package/dist/tsup/client/mod.d.cts +2 -2
  39. package/dist/tsup/client/mod.d.ts +2 -2
  40. package/dist/tsup/client/mod.js +4 -4
  41. package/dist/tsup/common/log.cjs +2 -2
  42. package/dist/tsup/common/log.js +1 -1
  43. package/dist/tsup/common/websocket.cjs +3 -3
  44. package/dist/tsup/common/websocket.js +2 -2
  45. package/dist/tsup/{config-BDJltifk.d.cts → config-DFAysGOK.d.cts} +114 -3
  46. package/dist/tsup/{config-DXC7qzme.d.ts → config-Dn8SZJF8.d.ts} +114 -3
  47. package/dist/tsup/{context-DgPsVbw6.d.ts → context-D_c2ERjO.d.ts} +5 -1
  48. package/dist/tsup/{context-osC4Q1ax.d.cts → context-fSkMTO5w.d.cts} +5 -1
  49. package/dist/tsup/db/drizzle.cjs +2 -2
  50. package/dist/tsup/db/drizzle.js +1 -1
  51. package/dist/tsup/db/mod.cjs +3 -3
  52. package/dist/tsup/db/mod.js +2 -2
  53. package/dist/tsup/dynamic/mod.cjs +2 -2
  54. package/dist/tsup/dynamic/mod.d.cts +1 -1
  55. package/dist/tsup/dynamic/mod.d.ts +1 -1
  56. package/dist/tsup/dynamic/mod.js +1 -1
  57. package/dist/tsup/inspector/mod.cjs +5 -5
  58. package/dist/tsup/inspector/mod.js +4 -4
  59. package/dist/tsup/inspector/workflow.cjs +4 -4
  60. package/dist/tsup/inspector/workflow.js +3 -3
  61. package/dist/tsup/inspector-tab/mod.cjs +2 -2
  62. package/dist/tsup/inspector-tab/mod.d.cts +2 -2
  63. package/dist/tsup/inspector-tab/mod.d.ts +2 -2
  64. package/dist/tsup/inspector-tab/mod.js +1 -1
  65. package/dist/tsup/mod.cjs +153 -110
  66. package/dist/tsup/mod.cjs.map +1 -1
  67. package/dist/tsup/mod.d.cts +3 -3
  68. package/dist/tsup/mod.d.ts +3 -3
  69. package/dist/tsup/mod.js +49 -6
  70. package/dist/tsup/mod.js.map +1 -1
  71. package/dist/tsup/test/mod.cjs +6 -6
  72. package/dist/tsup/test/mod.d.cts +1 -1
  73. package/dist/tsup/test/mod.d.ts +1 -1
  74. package/dist/tsup/test/mod.js +4 -4
  75. package/dist/tsup/utils.cjs +2 -2
  76. package/dist/tsup/utils.js +1 -1
  77. package/dist/tsup/workflow/mod.cjs +22 -10
  78. package/dist/tsup/workflow/mod.cjs.map +1 -1
  79. package/dist/tsup/workflow/mod.d.cts +3 -3
  80. package/dist/tsup/workflow/mod.d.ts +3 -3
  81. package/dist/tsup/workflow/mod.js +17 -5
  82. package/dist/tsup/workflow/mod.js.map +1 -1
  83. package/package.json +9 -9
  84. package/src/actor/config.ts +79 -0
  85. package/src/client/actor-conn.ts +43 -7
  86. package/src/client/client.ts +93 -0
  87. package/src/client/errors.ts +12 -0
  88. package/src/client/lifecycle-errors.ts +28 -1
  89. package/src/client/mod.ts +1 -0
  90. package/src/client/retry-budget.ts +4 -1
  91. package/src/common/actor-router-consts.ts +1 -0
  92. package/src/engine-api/actors.ts +12 -0
  93. package/src/engine-client/actor-http-client.ts +6 -0
  94. package/src/engine-client/actor-websocket-client.ts +25 -1
  95. package/src/engine-client/api-endpoints.ts +16 -0
  96. package/src/engine-client/driver.ts +12 -0
  97. package/src/engine-client/mod.ts +30 -0
  98. package/src/registry/napi-runtime.ts +8 -0
  99. package/src/registry/native.ts +49 -0
  100. package/src/registry/runtime.ts +11 -0
  101. package/src/registry/wasm-runtime.ts +9 -0
  102. package/src/workflow/context.ts +17 -0
  103. package/dist/tsup/chunk-7OXC5BQF.js.map +0 -1
  104. package/dist/tsup/chunk-HKD7AH4Z.cjs.map +0 -1
  105. package/dist/tsup/chunk-PBIQPYE5.js.map +0 -1
  106. package/dist/tsup/chunk-WBUHPDDM.cjs.map +0 -1
  107. package/dist/tsup/chunk-YMCG4FCB.js.map +0 -1
  108. package/dist/tsup/chunk-YWWDUC6D.cjs.map +0 -1
  109. /package/dist/tsup/{chunk-YO4TJ56P.js.map → chunk-CRC7NMU3.js.map} +0 -0
  110. /package/dist/tsup/{chunk-NMLZDHH2.js.map → chunk-ECLJJGV6.js.map} +0 -0
  111. /package/dist/tsup/{chunk-RFJ4NNO3.js.map → chunk-R4VUGJNR.js.map} +0 -0
  112. /package/dist/tsup/{chunk-QTCX5KN3.js.map → chunk-SVWVXVV7.js.map} +0 -0
  113. /package/dist/tsup/{chunk-S6ZMUE7Q.js.map → chunk-TDHEMJHH.js.map} +0 -0
@@ -448,6 +448,8 @@ interface EngineControlClient {
448
448
  getWithKey(input: GetWithKeyInput): Promise<ActorOutput | undefined>;
449
449
  getOrCreateWithKey(input: GetOrCreateWithKeyInput): Promise<ActorOutput>;
450
450
  createActor(input: CreateInput): Promise<ActorOutput>;
451
+ /** Forks the actor `actorId` into a new actor of the same name, started on a copy of its database. */
452
+ forkActor(input: ForkInput): Promise<ActorOutput>;
451
453
  listActors(input: ListActorsInput): Promise<ActorOutput[]>;
452
454
  sendRequest(target: GatewayTarget, actorRequest: Request, options?: GatewayRequestOptions): Promise<Response>;
453
455
  openWebSocket(path: string, target: GatewayTarget, encoding: Encoding, params: unknown, options?: GatewayRequestOptions): Promise<UniversalWebSocket>;
@@ -499,6 +501,15 @@ interface CreateInput {
499
501
  /** Overrides the client's configured pool name for this actor. */
500
502
  poolName?: string;
501
503
  }
504
+ interface ForkInput {
505
+ c?: Context | undefined;
506
+ /** The source actor. */
507
+ actorId: string;
508
+ /** The new actor's key; omitted for a keyless actor. */
509
+ key?: ActorKey;
510
+ /** The fork input, given to the new actor's `onFork` hook. */
511
+ input?: unknown;
512
+ }
502
513
  interface ListActorsInput {
503
514
  c?: Context | undefined;
504
515
  name: string;
@@ -554,6 +565,12 @@ interface RuntimeActorKeySegment {
554
565
  stringValue?: string;
555
566
  numberValue?: number;
556
567
  }
568
+ /** One individual actor fork behind an actor, as the runtime reports it. */
569
+ interface RuntimeForkLink {
570
+ actorId: string;
571
+ key: RuntimeActorKeySegment[];
572
+ forkedAt: number;
573
+ }
557
574
  /** Resolves correlation at operation time so retained clients cannot freeze stale context. */
558
575
  type CurrentActorInvocation = () => ActorInvocationTraceContext | undefined;
559
576
  /** One open call from an actor out to another actor. */
@@ -941,7 +958,11 @@ interface CoreRuntime {
941
958
  currentInvocationScope(): object | undefined;
942
959
  actorName(ctx: ActorContextHandle): string;
943
960
  actorKey(ctx: ActorContextHandle): RuntimeActorKeySegment[];
961
+ /** The individual actor forks behind the actor, oldest first. */
962
+ actorForkChain(ctx: ActorContextHandle): RuntimeForkLink[];
944
963
  actorRegion(ctx: ActorContextHandle): string;
964
+ /** The name of the namespace the actor runs in. */
965
+ actorNamespace(ctx: ActorContextHandle): string;
945
966
  actorSleep(ctx: ActorContextHandle): void;
946
967
  actorDestroy(ctx: ActorContextHandle): void;
947
968
  actorAbortSignal(ctx: ActorContextHandle): AbortSignal;
@@ -1523,6 +1544,20 @@ interface ActorAccessor<AD extends AnyActorDefinition> {
1523
1544
  * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the actor.
1524
1545
  */
1525
1546
  create(key?: string | string[], opts?: CreateOptions): Promise<ActorHandle<AD>>;
1547
+ /**
1548
+ * Forks the actor `actorId` into a new actor of this name, and returns a
1549
+ * stateless handle to the new actor with its ID resolved.
1550
+ *
1551
+ * The new actor starts at once on a copy of the source's database as of
1552
+ * its last committed write, runs `onFork` once with `opts.input`, and
1553
+ * keeps running independently of the source. A fork is not idempotent:
1554
+ * a `key` already held answers `actor.duplicate_key`.
1555
+ *
1556
+ * @param {string} actorId - The ID of the source actor.
1557
+ * @param {ForkOptions} [opts] - The new actor's key and the fork input.
1558
+ * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the new actor.
1559
+ */
1560
+ fork(actorId: string, opts?: ForkOptions): Promise<ActorHandle<AD>>;
1526
1561
  }
1527
1562
  /**
1528
1563
  * Options for querying actors.
@@ -1584,6 +1619,15 @@ interface CreateOptions extends QueryOptions {
1584
1619
  */
1585
1620
  poolName?: string;
1586
1621
  }
1622
+ /**
1623
+ * Options for forking an actor.
1624
+ */
1625
+ interface ForkOptions extends QueryOptions {
1626
+ /** The new actor's key. Omit for a keyless actor. */
1627
+ key?: string | string[];
1628
+ /** The fork input, passed to the new actor's `onFork` hook. */
1629
+ input?: unknown;
1630
+ }
1587
1631
  /**
1588
1632
  * Represents a region to connect to.
1589
1633
  * @typedef {Object} Region
@@ -1676,6 +1720,16 @@ declare class ClientRaw {
1676
1720
  * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the actor.
1677
1721
  */
1678
1722
  create<AD extends AnyActorDefinition>(name: string, key?: string | string[], opts?: CreateOptions): Promise<ActorHandle<AD>>;
1723
+ /**
1724
+ * Forks the actor `actorId` into a new actor and returns a handle to it.
1725
+ *
1726
+ * @template AD The actor class that this handle is for.
1727
+ * @param {string} name - The name of the actor; the source has the same name.
1728
+ * @param {string} actorId - The ID of the source actor.
1729
+ * @param {ForkOptions} [opts] - The new actor's key and the fork input.
1730
+ * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the new actor.
1731
+ */
1732
+ fork<AD extends AnyActorDefinition>(name: string, actorId: string, opts?: ForkOptions): Promise<ActorHandle<AD>>;
1679
1733
  [CREATE_ACTOR_CONN_PROXY]<AD extends AnyActorDefinition>(conn: ActorConnRaw): ActorConn<AD>;
1680
1734
  /**
1681
1735
  * Disconnects from all actors.
@@ -1745,6 +1799,20 @@ interface ActorKv {
1745
1799
  list<T extends ActorKvValueType = "text", K extends ActorKvKeyType = "text">(prefix: Uint8Array | string, options?: ActorKvListOptions<T, K>): Promise<Array<[ActorKvKeyTypeMap[K], ActorKvValueTypeMap[T]]>>;
1746
1800
  [key: string]: any;
1747
1801
  }
1802
+ /** One individual actor fork behind an actor, as `c.forkChain` lists it. */
1803
+ interface ActorForkLink {
1804
+ /** The source actor's ID. */
1805
+ actorId: string;
1806
+ /** The source actor's key. */
1807
+ key: string[];
1808
+ /** When the fork was made, in milliseconds since the epoch. */
1809
+ forkedAt: number;
1810
+ }
1811
+ /** The fork an `onFork` hook runs for: the newest entry of `c.forkChain` and the fork input. */
1812
+ interface ActorFork extends ActorForkLink {
1813
+ /** The `input` passed to `client.<actor>.fork`, or `undefined`. */
1814
+ input: unknown;
1815
+ }
1748
1816
  interface ActorSchedule {
1749
1817
  after(duration: number, action: string, ...args: unknown[]): Promise<string>;
1750
1818
  at(timestamp: number, action: string, ...args: unknown[]): Promise<string>;
@@ -1920,7 +1988,18 @@ interface ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase
1920
1988
  readonly actorId: string;
1921
1989
  readonly name: string;
1922
1990
  readonly key: string[];
1991
+ /**
1992
+ * The individual actor forks behind this actor, oldest first; empty when it was never
1993
+ * forked. Namespace forks are not listed.
1994
+ */
1995
+ readonly forkChain: ActorForkLink[];
1923
1996
  readonly region: string;
1997
+ /**
1998
+ * The name of the namespace the actor runs in. After a namespace fork it differs from the
1999
+ * source actor's namespace while the actor id stays the same, so an actor that owns an
2000
+ * external resource can store this to detect that it was copied.
2001
+ */
2002
+ readonly namespace: string;
1924
2003
  readonly conns: Map<string, Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>>;
1925
2004
  readonly log: ActorLogger;
1926
2005
  readonly abortSignal: AbortSignal;
@@ -2025,6 +2104,7 @@ declare const ActorConfigSchema: z.ZodObject<{
2025
2104
  onDestroy: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2026
2105
  onMigrate: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2027
2106
  onWake: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2107
+ onFork: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2028
2108
  onSleep: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
2029
2109
  run: z.ZodOptional<z.ZodUnion<readonly [z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>, z.ZodObject<{
2030
2110
  name: z.ZodOptional<z.ZodString>;
@@ -2160,6 +2240,36 @@ interface BaseActorConfig<TState, TConnParams, TConnState, TVars, TInput, TDatab
2160
2240
  * must run on both first boot and wake.
2161
2241
  */
2162
2242
  onMigrate?: (c: MigrateContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, isNew: boolean) => void | Promise<void>;
2243
+ /**
2244
+ * Called once at the first start of an actor made by forking another actor
2245
+ * (`client.<actor>.fork`), after its state loads and before `onWake` and any
2246
+ * overdue schedule events run. `createState` and `onCreate` do not run for a fork.
2247
+ *
2248
+ * Use this hook to cancel schedules the fork inherited, drop resources copied
2249
+ * from the source, or record the fork input. `c.forkChain` already ends with
2250
+ * this fork. A throw fails the start, and the hook runs again on the next start.
2251
+ * Forks of a whole namespace do not call it.
2252
+ *
2253
+ * State edits made in this hook are saved in one commit with the record that the
2254
+ * fork ran, so a start that finds the fork recorded also finds the hook's final
2255
+ * state. On native SQLite the hook's `c.db` writes and any save it starts itself
2256
+ * join that commit too, and a failed start drops them. Two limits apply:
2257
+ *
2258
+ * - On remote SQLite (wasm runtimes), `c.db` writes, and state the hook writes
2259
+ * itself in a transaction (for example `c.db.transaction` with
2260
+ * `experimental.includeState`), are committed at once, without the fork record.
2261
+ * A `c.saveState` call is not such a write: the startup save carries its
2262
+ * state. Only state the hook leaves to the startup save is atomic with it. A
2263
+ * crash or a failed start before the record lands runs the hook again on top
2264
+ * of those writes, so the hook must be idempotent there.
2265
+ * - On native SQLite the hook's writes must fit one commit (32,768 pages, 128 MiB
2266
+ * at the default page size). A transaction that would take them past it fails as
2267
+ * too large instead of committing part of them early; a hook that lets the error
2268
+ * throw fails the start, and nothing it wrote lands. Move a backfill that large
2269
+ * into later actions.
2270
+ * `onCreate` differs: its writes held so far are committed early instead.
2271
+ */
2272
+ onFork?: (c: WakeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, fork: ActorFork) => void | Promise<void>;
2163
2273
  /**
2164
2274
  * Called when the actor is started and ready to receive connections and action.
2165
2275
  *
@@ -2328,7 +2438,7 @@ type ActorDatabaseConfig<TDatabase extends AnyDatabaseProvider> = {
2328
2438
  */
2329
2439
  db: TDatabase;
2330
2440
  } | Record<never, never>;
2331
- 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.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>;
2441
+ 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.infer<typeof ActorConfigSchema>, "actions" | "events" | "queues" | "onCreate" | "onDestroy" | "onMigrate" | "onWake" | "onFork" | "onSleep" | "run" | "onStateChange" | "onBeforeConnect" | "onConnect" | "onDisconnect" | "onBeforeActionResponse" | "onRequest" | "onWebSocket" | "state" | "createState" | "connState" | "createConnState" | "vars" | "createVars" | "db"> & BaseActorConfig<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>;
2332
2442
 
2333
2443
  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>> {
2334
2444
  readonly config: ActorConfig<S, CP, CS, V, I, DB, E, Q, _R>;
@@ -2716,4 +2826,4 @@ declare class Registry<A extends RegistryActors> {
2716
2826
  */
2717
2827
  declare function createClient<A extends Registry<any>>(endpointOrConfig?: string | ClientConfigInput): Client<A>;
2718
2828
 
2719
- export { type ActorAccessor, type ActorActionFunction, type ActorActionOptions, ActorClientError, type ActorConn, ActorConnDisposed, ActorConnRaw, type ActorConnStatus, type ActorConnectOptions, ActorDefinition, RivetError as ActorError, type ActorGatewayOptions, type ActorHandle, ActorHandleRaw, type ActorIssueTokenOptions, type ActorTokenPermissions, type ActorTokenResource, type AnyActorDefinition, type Client, type ClientConfigInput, ClientRaw, type ConnectionStateCallback, type CreateOptions, type CreateRequest, type Encoding, type EventUnsubscribe, type ExtractActorsFromRegistry, type ExtractRegistryFromClient, type GetOptions, type GetToken, type GetWithIdOptions, type IssueTokenOptions, type IssuedToken, MalformedResponseMessage, ManagerError, type QueryOptions, type Region, RivetError, type StatusChangeCallback, type TokenGrant, UserError, createClient };
2829
+ export { type ActorAccessor, type ActorActionFunction, type ActorActionOptions, ActorClientError, type ActorConn, ActorConnDisposed, ActorConnRaw, type ActorConnStatus, type ActorConnectOptions, ActorDefinition, RivetError as ActorError, type ActorGatewayOptions, type ActorHandle, ActorHandleRaw, type ActorIssueTokenOptions, type ActorTokenPermissions, type ActorTokenResource, type AnyActorDefinition, type Client, type ClientConfigInput, ClientRaw, type ConnectionStateCallback, type CreateOptions, type CreateRequest, type Encoding, type EventUnsubscribe, type ExtractActorsFromRegistry, type ExtractRegistryFromClient, type ForkOptions, type GetOptions, type GetToken, type GetWithIdOptions, type IssueTokenOptions, type IssuedToken, MalformedResponseMessage, ManagerError, type QueryOptions, type Region, RivetError, type StatusChangeCallback, type TokenGrant, UserError, createClient };
@@ -230,7 +230,7 @@ function noopNext() {
230
230
  // package.json
231
231
  var package_default = {
232
232
  name: "rivetkit",
233
- version: "3.0.7",
233
+ version: "3.1.0-rc.1",
234
234
  description: "Lightweight libraries for building stateful actors on edge platforms",
235
235
  license: "Apache-2.0",
236
236
  keywords: [
@@ -1251,10 +1251,12 @@ var HEADER_TRACEPARENT = "traceparent";
1251
1251
  var HEADER_TRACESTATE = "tracestate";
1252
1252
  var HEADER_RIVET_TARGET = "x-rivet-target";
1253
1253
  var HEADER_RIVET_ACTOR = "x-rivet-actor";
1254
+ var HEADER_RIVET_NAMESPACE = "x-rivet-namespace";
1254
1255
  var HEADER_RIVET_SKIP_READY_WAIT = "x-rivet-skip-ready-wait";
1255
1256
  var WS_PROTOCOL_STANDARD = "rivet";
1256
1257
  var WS_PROTOCOL_TARGET = "rivet_target.";
1257
1258
  var WS_PROTOCOL_ACTOR = "rivet_actor.";
1259
+ var WS_PROTOCOL_NAMESPACE = "rivet_namespace.";
1258
1260
  var WS_PROTOCOL_ENCODING = "rivet_encoding.";
1259
1261
  var WS_PROTOCOL_CONN_PARAMS = "rivet_conn_params.";
1260
1262
  var WS_PROTOCOL_TOKEN = "rivet_token.";
@@ -1340,6 +1342,9 @@ function buildGuardHeaders(runConfig, actorRequest, options) {
1340
1342
  if (options.directActorId !== void 0) {
1341
1343
  headers.set(HEADER_RIVET_TARGET, "actor");
1342
1344
  headers.set(HEADER_RIVET_ACTOR, options.directActorId);
1345
+ if (runConfig.namespace) {
1346
+ headers.set(HEADER_RIVET_NAMESPACE, runConfig.namespace);
1347
+ }
1343
1348
  }
1344
1349
  if (shouldSkipReadyWait(options)) {
1345
1350
  headers.set(HEADER_RIVET_SKIP_READY_WAIT, "1");
@@ -1734,9 +1739,22 @@ var BufferedRemoteWebSocket = class {
1734
1739
  return true;
1735
1740
  }
1736
1741
  };
1737
- function buildActorGatewayUrl(endpoint, actorId, token, path = "") {
1742
+ function buildActorGatewayUrl(endpoint, namespace, actorId, token, path = "") {
1743
+ if (namespace.length === 0) {
1744
+ throw new Error("actor gateway namespace must not be empty");
1745
+ }
1738
1746
  const tokenSegment = token !== void 0 ? `@${encodeURIComponent(token)}` : "";
1739
- const gatewayPath = `/gateway/${encodeURIComponent(actorId)}${tokenSegment}${path}`;
1747
+ const params = new URLSearchParams();
1748
+ params.append("rvt-namespace", namespace);
1749
+ let separator;
1750
+ if (path.endsWith("?") || path.endsWith("&")) {
1751
+ separator = "";
1752
+ } else if (path.includes("?")) {
1753
+ separator = "&";
1754
+ } else {
1755
+ separator = "?";
1756
+ }
1757
+ const gatewayPath = `/gateway/${encodeURIComponent(actorId)}${tokenSegment}${path}${separator}${params.toString()}`;
1740
1758
  return combineUrlPath(endpoint, gatewayPath);
1741
1759
  }
1742
1760
  function buildActorQueryGatewayUrl(endpoint, namespace, query, token, path = "", maxInputSize = DEFAULT_MAX_QUERY_INPUT_SIZE, crashPolicy = void 0, runnerName, options = {}) {
@@ -1868,6 +1886,9 @@ function buildWebSocketProtocols(runConfig, encoding, params, ackHookToken, targ
1868
1886
  if (target) {
1869
1887
  protocols.push(`${WS_PROTOCOL_TARGET}${target.target}`);
1870
1888
  protocols.push(`${WS_PROTOCOL_ACTOR}${target.actorId}`);
1889
+ if (runConfig.namespace) {
1890
+ protocols.push(`${WS_PROTOCOL_NAMESPACE}${runConfig.namespace}`);
1891
+ }
1871
1892
  if (runConfig.token) {
1872
1893
  protocols.push(`${WS_PROTOCOL_TOKEN}${runConfig.token}`);
1873
1894
  }
@@ -3882,6 +3903,12 @@ var ActorConnDisposed = class extends ActorClientError {
3882
3903
  function isSchedulingError(group, code) {
3883
3904
  return group === "guard" && (code === "actor_ready_timeout" || code === "actor_runner_failed");
3884
3905
  }
3906
+ function isActorDestroyed(group, code) {
3907
+ return group === "actor" && code === "destroyed";
3908
+ }
3909
+ function isActorNotFound(group, code) {
3910
+ return group === "actor" && code === "not_found";
3911
+ }
3885
3912
  function actorSchedulingError(group, code, actorId, details, rayId) {
3886
3913
  return new RivetError(
3887
3914
  group,
@@ -4154,6 +4181,14 @@ async function createActor(config, request) {
4154
4181
  request
4155
4182
  );
4156
4183
  }
4184
+ async function forkActor(config, actorId, request) {
4185
+ return apiCall(
4186
+ config,
4187
+ "POST",
4188
+ `/actors/${encodeURIComponent(actorId)}/fork`,
4189
+ request
4190
+ );
4191
+ }
4157
4192
  async function destroyActor(config, actorId) {
4158
4193
  return apiCall(
4159
4194
  config,
@@ -4563,6 +4598,24 @@ var RemoteEngineControlClient = class {
4563
4598
  });
4564
4599
  return apiActorToOutput(result.actor);
4565
4600
  }
4601
+ async forkActor({ actorId, key, input }) {
4602
+ await this.#metadataPromise;
4603
+ logger3().info({ msg: "forking actor via engine api", actorId, key });
4604
+ const result = await this.#withCredential(
4605
+ (config) => forkActor(config, actorId, {
4606
+ key: key ? serializeActorKey(key) : void 0,
4607
+ input: input !== void 0 ? uint8ArrayToBase64(
4608
+ encodeCborCompat(input)
4609
+ ) : void 0
4610
+ })
4611
+ );
4612
+ logger3().info({
4613
+ msg: "actor forked",
4614
+ actorId: result.actor.actor_id,
4615
+ sourceActorId: actorId
4616
+ });
4617
+ return apiActorToOutput(result.actor);
4618
+ }
4566
4619
  async listActors({ name }) {
4567
4620
  await this.#metadataPromise;
4568
4621
  logger3().debug({ msg: "listing actors via engine api", name });
@@ -4715,6 +4768,7 @@ var RemoteEngineControlClient = class {
4715
4768
  if ("directId" in target) {
4716
4769
  return buildActorGatewayUrl(
4717
4770
  endpoint,
4771
+ config.namespace,
4718
4772
  target.directId,
4719
4773
  config.token,
4720
4774
  path
@@ -4723,6 +4777,7 @@ var RemoteEngineControlClient = class {
4723
4777
  if ("getForId" in target) {
4724
4778
  return buildActorGatewayUrl(
4725
4779
  endpoint,
4780
+ config.namespace,
4726
4781
  target.getForId.actorId,
4727
4782
  config.token,
4728
4783
  path
@@ -4896,7 +4951,10 @@ function retryAfterMs(error) {
4896
4951
  return typeof hint === "number" && hint >= 0 ? hint : void 0;
4897
4952
  }
4898
4953
  function retryDelayMs(attempt, opts) {
4899
- const backoff = Math.min(opts.initialDelayMs * 2 ** attempt, opts.maxDelayMs);
4954
+ const backoff = Math.min(
4955
+ opts.initialDelayMs * 2 ** attempt,
4956
+ opts.maxDelayMs
4957
+ );
4900
4958
  const jittered = backoff / 2 + Math.random() * (backoff / 2);
4901
4959
  return Math.max(jittered, opts.hintMs ?? 0);
4902
4960
  }
@@ -5082,10 +5140,24 @@ async function waitWithSignal(ms, signal) {
5082
5140
  signal?.addEventListener("abort", onAbort, { once: true });
5083
5141
  });
5084
5142
  }
5143
+ function isRetryableForkRefusal(error) {
5144
+ if (!(error instanceof RivetError)) {
5145
+ return false;
5146
+ }
5147
+ if (error.group === "actor" && error.code === "fork_unavailable") {
5148
+ return true;
5149
+ }
5150
+ if (error.group === "guard" && error.code === "service_unavailable") {
5151
+ const metadata = error.metadata;
5152
+ return metadata?.reason === "actor_moving";
5153
+ }
5154
+ return false;
5155
+ }
5085
5156
  async function retryOnLifecycleBoundary(run, opts) {
5086
5157
  const maxAttempts = opts?.maxAttempts ?? 5;
5087
5158
  const initialDelayMs = opts?.initialDelayMs ?? 25;
5088
5159
  const maxDelayMs = opts?.maxDelayMs ?? 200;
5160
+ const isRetryable = opts?.isRetryable ?? isRetryableLifecycleRequestError;
5089
5161
  opts?.budget?.deposit();
5090
5162
  let lastError;
5091
5163
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
@@ -5093,7 +5165,7 @@ async function retryOnLifecycleBoundary(run, opts) {
5093
5165
  try {
5094
5166
  return await run();
5095
5167
  } catch (error) {
5096
- if (!isRetryableLifecycleRequestError(error)) {
5168
+ if (!isRetryable(error)) {
5097
5169
  throw error;
5098
5170
  }
5099
5171
  lastError = error;
@@ -5270,6 +5342,7 @@ var ActorConnRaw = class {
5270
5342
  #connStatus = "idle";
5271
5343
  /** The opening failure that stopped retries. Later actions must fail instead of queueing. */
5272
5344
  #connectionOpenError;
5345
+ #dispatchedErrors = /* @__PURE__ */ new WeakSet();
5273
5346
  #actorId;
5274
5347
  #connId;
5275
5348
  #messageQueue = [];
@@ -5364,7 +5437,13 @@ var ActorConnRaw = class {
5364
5437
  return true;
5365
5438
  }
5366
5439
  #shouldReconnectForStaleActor(group, code) {
5367
- return isDynamicActorQuery(this.#actorResolutionState) && isStaleResolvedActorError(group, code) && this.#onOpenPromise !== void 0 && this.#connStatus !== "connected";
5440
+ if (!isDynamicActorQuery(this.#actorResolutionState) || !isStaleResolvedActorError(group, code) || this.#onOpenPromise === void 0 || this.#connStatus === "connected") {
5441
+ return false;
5442
+ }
5443
+ if (isActorNotFound(group, code) && "getForKey" in this.#actorResolutionState) {
5444
+ return false;
5445
+ }
5446
+ return true;
5368
5447
  }
5369
5448
  send(name, body, options) {
5370
5449
  return this.#sendQueueMessage(name, body, options);
@@ -5534,7 +5613,9 @@ var ActorConnRaw = class {
5534
5613
  );
5535
5614
  this.#connectionOpenError = actorError;
5536
5615
  this.#rejectPendingPromises(actorError, false);
5537
- this.#dispatchActorError(actorError);
5616
+ if (!this.#dispatchedErrors.has(actorError)) {
5617
+ this.#dispatchActorError(actorError);
5618
+ }
5538
5619
  this.#setConnStatus("idle");
5539
5620
  throw new AbortError(
5540
5621
  error instanceof Error ? error : new Error(stringifyError(error))
@@ -5964,6 +6045,16 @@ var ActorConnRaw = class {
5964
6045
  if (error instanceof RivetError) {
5965
6046
  this.#dispatchActorError(error);
5966
6047
  }
6048
+ if (error instanceof RivetError && isActorDestroyed(error.group, error.code)) {
6049
+ this.#connectionOpenError = error;
6050
+ this.#setConnStatus("idle");
6051
+ return;
6052
+ }
6053
+ if (error instanceof RivetError && isInvalidToken(error.group, error.code) && !this.#authRetryAvailable) {
6054
+ this.#connectionOpenError = error;
6055
+ this.#setConnStatus("idle");
6056
+ return;
6057
+ }
5967
6058
  if (wasConnected && this.#authRetryAvailable) {
5968
6059
  logger2().debug({
5969
6060
  msg: "triggering reconnect",
@@ -6033,6 +6124,7 @@ var ActorConnRaw = class {
6033
6124
  }
6034
6125
  }
6035
6126
  #dispatchActorError(error) {
6127
+ this.#dispatchedErrors.add(error);
6036
6128
  for (const handler of [...this.#errorHandlers]) {
6037
6129
  try {
6038
6130
  handler(error);
@@ -7548,6 +7640,49 @@ var ClientRaw = class {
7548
7640
  const proxy = createActorProxy(handle);
7549
7641
  return proxy;
7550
7642
  }
7643
+ /**
7644
+ * Forks the actor `actorId` into a new actor and returns a handle to it.
7645
+ *
7646
+ * @template AD The actor class that this handle is for.
7647
+ * @param {string} name - The name of the actor; the source has the same name.
7648
+ * @param {string} actorId - The ID of the source actor.
7649
+ * @param {ForkOptions} [opts] - The new actor's key and the fork input.
7650
+ * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the new actor.
7651
+ */
7652
+ async fork(name, actorId, opts) {
7653
+ const key = typeof opts?.key === "string" ? [opts.key] : opts?.key;
7654
+ logger2().debug({
7655
+ msg: "fork actor",
7656
+ name,
7657
+ sourceActorId: actorId,
7658
+ key
7659
+ });
7660
+ const forked = await retryOnLifecycleBoundary(
7661
+ () => this.#driver.forkActor({
7662
+ actorId,
7663
+ key,
7664
+ input: opts?.input
7665
+ }),
7666
+ {
7667
+ signal: opts?.signal,
7668
+ budget: this.#retryBudget,
7669
+ isRetryable: isRetryableForkRefusal
7670
+ }
7671
+ );
7672
+ const getForIdQuery = {
7673
+ getForId: {
7674
+ name,
7675
+ actorId: forked.actorId
7676
+ }
7677
+ };
7678
+ const handle = this.#createHandle(
7679
+ opts?.params,
7680
+ opts?.getParams,
7681
+ getForIdQuery,
7682
+ opts?.signal
7683
+ );
7684
+ return createActorProxy(handle);
7685
+ }
7551
7686
  #createHandle(params, getParams, actorQuery, signal) {
7552
7687
  return new ActorHandleRaw(
7553
7688
  this,
@@ -7612,6 +7747,9 @@ function createClientWithDriver(driver, options = {}) {
7612
7747
  },
7613
7748
  create: async (key, opts = {}) => {
7614
7749
  return await target.create(prop, key, opts);
7750
+ },
7751
+ fork: async (actorId, opts = {}) => {
7752
+ return await target.fork(prop, actorId, opts);
7615
7753
  }
7616
7754
  };
7617
7755
  }