rivetkit 0.0.0-runner-config-drain-grace-threshold.e1be3d6 → 0.0.0-sqlite-uds.4e59a38

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 (250) hide show
  1. package/dist/browser/client.d.ts +557 -83
  2. package/dist/browser/client.js +1034 -410
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +22 -2
  5. package/dist/browser/inspector/client.js +1036 -232
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/actor/errors.cjs +6 -2
  8. package/dist/tsup/actor/errors.cjs.map +1 -1
  9. package/dist/tsup/actor/errors.d.cts +1 -74
  10. package/dist/tsup/actor/errors.d.ts +1 -74
  11. package/dist/tsup/actor/errors.js +5 -1
  12. package/dist/tsup/agent-os/index.cjs +2218 -2082
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +555 -82
  15. package/dist/tsup/agent-os/index.d.ts +555 -82
  16. package/dist/tsup/agent-os/index.js +2220 -2084
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-ZULMYDHF.cjs → chunk-3GC3EP6D.cjs} +18 -10
  19. package/dist/tsup/chunk-3GC3EP6D.cjs.map +1 -0
  20. package/dist/tsup/{chunk-5DM7UBJ6.js → chunk-3GLNEWGY.js} +77 -5
  21. package/dist/tsup/chunk-3GLNEWGY.js.map +1 -0
  22. package/dist/tsup/{chunk-V3QNBJ7N.cjs → chunk-4FC7TVS6.cjs} +35 -10
  23. package/dist/tsup/chunk-4FC7TVS6.cjs.map +1 -0
  24. package/dist/tsup/{chunk-5I23FPCU.cjs → chunk-62LSMTP2.cjs} +3 -3
  25. package/dist/tsup/{chunk-5I23FPCU.cjs.map → chunk-62LSMTP2.cjs.map} +1 -1
  26. package/dist/tsup/{chunk-TCQKPKZN.js → chunk-7IVUT2JT.js} +12 -4
  27. package/dist/tsup/chunk-7IVUT2JT.js.map +1 -0
  28. package/dist/tsup/{chunk-67RKOMDW.cjs → chunk-GEYQLGXC.cjs} +892 -303
  29. package/dist/tsup/chunk-GEYQLGXC.cjs.map +1 -0
  30. package/dist/tsup/{chunk-SRMJW54U.cjs → chunk-GMN45CQ6.cjs} +10 -10
  31. package/dist/tsup/chunk-GMN45CQ6.cjs.map +1 -0
  32. package/dist/tsup/{chunk-3YY5S6TV.js → chunk-HXUEHHJF.js} +2 -2
  33. package/dist/tsup/chunk-HXUEHHJF.js.map +1 -0
  34. package/dist/tsup/{chunk-ZLQ4AEF5.cjs → chunk-I336PMWT.cjs} +44 -9
  35. package/dist/tsup/chunk-I336PMWT.cjs.map +1 -0
  36. package/dist/tsup/{chunk-IWKPKMUZ.js → chunk-IB73AMGJ.js} +42 -7
  37. package/dist/tsup/chunk-IB73AMGJ.js.map +1 -0
  38. package/dist/tsup/{chunk-DPXHJ73A.js → chunk-ITWJ6Y7G.js} +2 -2
  39. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-JZ7TWV65.js} +1 -1
  40. package/dist/tsup/chunk-JZ7TWV65.js.map +1 -0
  41. package/dist/tsup/{chunk-YCTA3LBC.js → chunk-KTNBYGRU.js} +134 -20
  42. package/dist/tsup/chunk-KTNBYGRU.js.map +1 -0
  43. package/dist/tsup/{chunk-BNGG6IEA.cjs → chunk-OAPVVVTX.cjs} +78 -6
  44. package/dist/tsup/chunk-OAPVVVTX.cjs.map +1 -0
  45. package/dist/tsup/{chunk-M56BAR36.cjs → chunk-OUDV3ITX.cjs} +138 -24
  46. package/dist/tsup/chunk-OUDV3ITX.cjs.map +1 -0
  47. package/dist/tsup/{chunk-GL3HIPV4.cjs → chunk-PRXTIERO.cjs} +90 -65
  48. package/dist/tsup/chunk-PRXTIERO.cjs.map +1 -0
  49. package/dist/tsup/{chunk-LD5YASJU.cjs → chunk-VE2X4KMG.cjs} +2 -2
  50. package/dist/tsup/{chunk-LD5YASJU.cjs.map → chunk-VE2X4KMG.cjs.map} +1 -1
  51. package/dist/tsup/{chunk-27VQ5J4Q.js → chunk-WRZEVVLL.js} +6 -6
  52. package/dist/tsup/chunk-WRZEVVLL.js.map +1 -0
  53. package/dist/tsup/{chunk-FYDM3DOZ.js → chunk-XAIMHUPG.js} +745 -156
  54. package/dist/tsup/chunk-XAIMHUPG.js.map +1 -0
  55. package/dist/tsup/{chunk-5Q26DE3S.js → chunk-XZ62SWSC.js} +83 -58
  56. package/dist/tsup/chunk-XZ62SWSC.js.map +1 -0
  57. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-ZA7FLHKH.cjs} +1 -1
  58. package/dist/tsup/chunk-ZA7FLHKH.cjs.map +1 -0
  59. package/dist/tsup/{chunk-K34B3OVG.js → chunk-ZZ3WBRPD.js} +34 -9
  60. package/dist/tsup/chunk-ZZ3WBRPD.js.map +1 -0
  61. package/dist/tsup/client/mod.cjs +9 -9
  62. package/dist/tsup/client/mod.d.cts +5 -6
  63. package/dist/tsup/client/mod.d.ts +5 -6
  64. package/dist/tsup/client/mod.js +8 -8
  65. package/dist/tsup/common/log.cjs +5 -3
  66. package/dist/tsup/common/log.cjs.map +1 -1
  67. package/dist/tsup/common/log.d.cts +5 -1
  68. package/dist/tsup/common/log.d.ts +5 -1
  69. package/dist/tsup/common/log.js +6 -4
  70. package/dist/tsup/common/websocket.cjs +4 -4
  71. package/dist/tsup/common/websocket.js +3 -3
  72. package/dist/tsup/{config-BA5q_2Kt.d.cts → config-CxG53eQo.d.cts} +576 -33
  73. package/dist/tsup/{config-kxXbtrJU.d.ts → config-DLOxy81E.d.cts} +5 -5
  74. package/dist/tsup/{config-kxXbtrJU.d.cts → config-DLOxy81E.d.ts} +5 -5
  75. package/dist/tsup/{config-B2reim3z.d.ts → config-Ds6DCRhV.d.ts} +576 -33
  76. package/dist/tsup/context-8KlcOYIs.d.cts +129 -0
  77. package/dist/tsup/context-Cfbm4QLr.d.ts +129 -0
  78. package/dist/tsup/db/drizzle.cjs +151 -79
  79. package/dist/tsup/db/drizzle.cjs.map +1 -1
  80. package/dist/tsup/db/drizzle.d.cts +2 -2
  81. package/dist/tsup/db/drizzle.d.ts +2 -2
  82. package/dist/tsup/db/drizzle.js +151 -79
  83. package/dist/tsup/db/drizzle.js.map +1 -1
  84. package/dist/tsup/db/mod.cjs +79 -24
  85. package/dist/tsup/db/mod.cjs.map +1 -1
  86. package/dist/tsup/db/mod.d.cts +2 -2
  87. package/dist/tsup/db/mod.d.ts +2 -2
  88. package/dist/tsup/db/mod.js +78 -23
  89. package/dist/tsup/db/mod.js.map +1 -1
  90. package/dist/tsup/dynamic/mod.cjs +24 -0
  91. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  92. package/dist/tsup/dynamic/mod.d.cts +37 -0
  93. package/dist/tsup/dynamic/mod.d.ts +37 -0
  94. package/dist/tsup/dynamic/mod.js +24 -0
  95. package/dist/tsup/dynamic/mod.js.map +1 -0
  96. package/dist/tsup/inspector/mod.cjs +47 -12
  97. package/dist/tsup/inspector/mod.cjs.map +1 -1
  98. package/dist/tsup/inspector/mod.d.cts +37 -15
  99. package/dist/tsup/inspector/mod.d.ts +37 -15
  100. package/dist/tsup/inspector/mod.js +46 -11
  101. package/dist/tsup/inspector/mod.js.map +1 -1
  102. package/dist/tsup/inspector-tab/mod.cjs +162 -0
  103. package/dist/tsup/inspector-tab/mod.cjs.map +1 -0
  104. package/dist/tsup/inspector-tab/mod.d.cts +240 -0
  105. package/dist/tsup/inspector-tab/mod.d.ts +240 -0
  106. package/dist/tsup/inspector-tab/mod.js +162 -0
  107. package/dist/tsup/inspector-tab/mod.js.map +1 -0
  108. package/dist/tsup/mod.cjs +1076 -494
  109. package/dist/tsup/mod.cjs.map +1 -1
  110. package/dist/tsup/mod.d.cts +5 -6
  111. package/dist/tsup/mod.d.ts +5 -6
  112. package/dist/tsup/mod.js +992 -410
  113. package/dist/tsup/mod.js.map +1 -1
  114. package/dist/tsup/test/mod.cjs +21 -18
  115. package/dist/tsup/test/mod.cjs.map +1 -1
  116. package/dist/tsup/test/mod.d.cts +4 -5
  117. package/dist/tsup/test/mod.d.ts +4 -5
  118. package/dist/tsup/test/mod.js +18 -15
  119. package/dist/tsup/test/mod.js.map +1 -1
  120. package/dist/tsup/utils-CqDnC_PS.d.cts +104 -0
  121. package/dist/tsup/utils-CqDnC_PS.d.ts +104 -0
  122. package/dist/tsup/utils.cjs +3 -3
  123. package/dist/tsup/utils.d.cts +1 -1
  124. package/dist/tsup/utils.d.ts +1 -1
  125. package/dist/tsup/utils.js +2 -2
  126. package/dist/tsup/workflow/mod.cjs +386 -322
  127. package/dist/tsup/workflow/mod.cjs.map +1 -1
  128. package/dist/tsup/workflow/mod.d.cts +8 -9
  129. package/dist/tsup/workflow/mod.d.ts +8 -9
  130. package/dist/tsup/workflow/mod.js +363 -299
  131. package/dist/tsup/workflow/mod.js.map +1 -1
  132. package/package.json +35 -14
  133. package/src/actor/config.ts +186 -57
  134. package/src/actor/contexts/index.ts +7 -2
  135. package/src/actor/definition.ts +17 -19
  136. package/src/actor/driver.ts +3 -3
  137. package/src/actor/errors.ts +70 -7
  138. package/src/actor/instance/mod.ts +26 -35
  139. package/src/actor/keys.ts +1 -1
  140. package/src/actor/mod.ts +22 -20
  141. package/src/actor/schema.ts +2 -2
  142. package/src/agent-os/actor/index.ts +38 -18
  143. package/src/agent-os/actor/preview.ts +1 -2
  144. package/src/agent-os/actor/session.ts +2 -2
  145. package/src/agent-os/config.ts +1 -1
  146. package/src/agent-os/fs/database-vfs.ts +1 -1
  147. package/src/agent-os/index.ts +16 -15
  148. package/src/client/actor-common.ts +87 -54
  149. package/src/client/actor-conn.ts +58 -63
  150. package/src/client/actor-handle.ts +121 -69
  151. package/src/client/actor-query.ts +5 -5
  152. package/src/client/errors.ts +2 -1
  153. package/src/client/lifecycle-errors.ts +2 -4
  154. package/src/client/query.ts +1 -1
  155. package/src/client/queue.ts +8 -3
  156. package/src/client/raw-utils.ts +10 -10
  157. package/src/client/resolve-gateway-target.ts +1 -1
  158. package/src/client/utils.ts +34 -10
  159. package/src/common/actor-router-consts.ts +4 -0
  160. package/src/common/actor-websocket.ts +3 -1
  161. package/src/common/bare/actor-persist/v1.ts +205 -163
  162. package/src/common/bare/actor-persist/v2.ts +265 -213
  163. package/src/common/bare/actor-persist/v3.ts +176 -172
  164. package/src/common/bare/actor-persist/v4.ts +254 -253
  165. package/src/common/bare/generated/client-protocol/v4.ts +599 -0
  166. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  167. package/src/common/bare/transport/v1.ts +694 -542
  168. package/src/common/client-protocol-versioned.ts +176 -67
  169. package/src/common/client-protocol-zod.ts +7 -0
  170. package/src/common/client-protocol.ts +1 -1
  171. package/src/common/database/config.ts +16 -5
  172. package/src/common/database/mod.test.ts +83 -16
  173. package/src/common/database/mod.ts +86 -30
  174. package/src/common/database/native-database.test.ts +35 -22
  175. package/src/common/database/native-database.ts +26 -10
  176. package/src/common/database/shared.ts +1 -0
  177. package/src/common/encoding.ts +250 -16
  178. package/src/common/engine.ts +28 -1
  179. package/src/common/eventsource.ts +1 -1
  180. package/src/common/inline-websocket-adapter.ts +14 -13
  181. package/src/common/log.ts +15 -8
  182. package/src/common/router.ts +49 -23
  183. package/src/common/utils.ts +10 -202
  184. package/src/common/websocket-interface.ts +1 -1
  185. package/src/db/drizzle.ts +173 -96
  186. package/src/db/mod.ts +1 -1
  187. package/src/devtools-loader/index.ts +4 -7
  188. package/src/devtools-loader/serve-devtools.ts +26 -0
  189. package/src/drivers/engine/actor-driver.ts +76 -73
  190. package/src/dynamic/instance.ts +32 -0
  191. package/src/dynamic/internal.ts +50 -0
  192. package/src/dynamic/isolate-runtime.ts +66 -0
  193. package/src/dynamic/mod.ts +32 -0
  194. package/src/engine-client/actor-http-client.ts +3 -3
  195. package/src/engine-client/actor-websocket-client.ts +6 -5
  196. package/src/engine-client/api-endpoints.ts +51 -2
  197. package/src/engine-client/api-utils.ts +2 -2
  198. package/src/engine-client/driver.ts +1 -1
  199. package/src/engine-client/mod.ts +6 -3
  200. package/src/engine-client/ws-proxy.ts +9 -4
  201. package/src/inspector/client.browser.ts +66 -15
  202. package/src/inspector/mod.ts +2 -4
  203. package/src/inspector-tab/mod.ts +300 -0
  204. package/src/registry/config/envoy.ts +1 -2
  205. package/src/registry/config/index.ts +45 -20
  206. package/src/registry/index.ts +364 -87
  207. package/src/registry/napi-runtime.ts +97 -8
  208. package/src/registry/native-validation.ts +10 -12
  209. package/src/registry/native.ts +587 -363
  210. package/src/registry/process-metrics.ts +250 -0
  211. package/src/registry/runtime.ts +85 -6
  212. package/src/registry/wasm-runtime.ts +72 -3
  213. package/src/registry/write-through-proxy.ts +40 -0
  214. package/src/serde.ts +2 -2
  215. package/src/serverless/configure.ts +18 -7
  216. package/src/test/mod.ts +11 -8
  217. package/src/utils/crypto.ts +14 -0
  218. package/src/utils/endpoint-parser.ts +1 -1
  219. package/src/utils/env-vars.ts +37 -0
  220. package/src/utils/router.ts +1 -1
  221. package/src/utils.ts +1 -2
  222. package/src/workflow/context.ts +703 -240
  223. package/src/workflow/driver.ts +23 -12
  224. package/src/workflow/inspector.ts +12 -3
  225. package/src/workflow/mod.ts +37 -23
  226. package/dist/tsup/chunk-27VQ5J4Q.js.map +0 -1
  227. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  228. package/dist/tsup/chunk-3YY5S6TV.js.map +0 -1
  229. package/dist/tsup/chunk-5DM7UBJ6.js.map +0 -1
  230. package/dist/tsup/chunk-5Q26DE3S.js.map +0 -1
  231. package/dist/tsup/chunk-67RKOMDW.cjs.map +0 -1
  232. package/dist/tsup/chunk-BNGG6IEA.cjs.map +0 -1
  233. package/dist/tsup/chunk-FYDM3DOZ.js.map +0 -1
  234. package/dist/tsup/chunk-GL3HIPV4.cjs.map +0 -1
  235. package/dist/tsup/chunk-IWKPKMUZ.js.map +0 -1
  236. package/dist/tsup/chunk-K34B3OVG.js.map +0 -1
  237. package/dist/tsup/chunk-M56BAR36.cjs.map +0 -1
  238. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  239. package/dist/tsup/chunk-SRMJW54U.cjs.map +0 -1
  240. package/dist/tsup/chunk-TCQKPKZN.js.map +0 -1
  241. package/dist/tsup/chunk-V3QNBJ7N.cjs.map +0 -1
  242. package/dist/tsup/chunk-YCTA3LBC.js.map +0 -1
  243. package/dist/tsup/chunk-ZLQ4AEF5.cjs.map +0 -1
  244. package/dist/tsup/chunk-ZULMYDHF.cjs.map +0 -1
  245. package/dist/tsup/context-7374C2do.d.ts +0 -92
  246. package/dist/tsup/context-Vv4C_cT-.d.cts +0 -92
  247. package/dist/tsup/utils-fwx3o3K9.d.cts +0 -18
  248. package/dist/tsup/utils-fwx3o3K9.d.ts +0 -18
  249. package/src/utils/serve.ts +0 -217
  250. /package/dist/tsup/{chunk-DPXHJ73A.js.map → chunk-ITWJ6Y7G.js.map} +0 -0
package/dist/tsup/mod.js CHANGED
@@ -1,28 +1,26 @@
1
+ import {
2
+ decodeWorkflowHistoryTransport
3
+ } from "./chunk-IB73AMGJ.js";
1
4
  import {
2
5
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
3
6
  ActorConfigSchema,
4
7
  CONN_STATE_MANAGER_SYMBOL,
8
+ RAW_STATE_SYMBOL,
9
+ disposeRunInspector,
5
10
  getRunFunction,
6
11
  getRunInspectorConfig,
7
12
  getRunMetadata
8
- } from "./chunk-5DM7UBJ6.js";
9
- import {
10
- decodeWorkflowHistoryTransport
11
- } from "./chunk-IWKPKMUZ.js";
13
+ } from "./chunk-3GLNEWGY.js";
12
14
  import {
13
15
  ALLOWED_PUBLIC_HEADERS,
14
- CURRENT_VERSION,
15
16
  HEADER_CONN_PARAMS,
16
- HEADER_ENCODING,
17
- HTTP_RESPONSE_ERROR_VERSIONED,
18
- HttpResponseErrorSchema,
19
17
  RemoteEngineControlClient,
20
18
  convertRegistryConfigToClientConfig,
21
19
  createClientWithDriver,
22
20
  getDatacenters,
23
21
  tryParseEndpoint,
24
22
  updateRunnerConfig
25
- } from "./chunk-FYDM3DOZ.js";
23
+ } from "./chunk-XAIMHUPG.js";
26
24
  import {
27
25
  KEYS,
28
26
  makePrefixedKey,
@@ -30,19 +28,18 @@ import {
30
28
  queueMetadataKey,
31
29
  removePrefixFromKey,
32
30
  workflowStoragePrefix
33
- } from "./chunk-3YY5S6TV.js";
31
+ } from "./chunk-HXUEHHJF.js";
34
32
  import {
35
- contentTypeForEncoding,
33
+ assertJsonCompatValue,
36
34
  decodeCborCompat,
37
- decodeCborJsonCompat,
38
- encodeCborCompat,
39
- serializeWithEncoding
40
- } from "./chunk-YCTA3LBC.js";
41
- import "./chunk-PCBNKI2J.js";
42
- import "./chunk-DPXHJ73A.js";
35
+ encodeCborCompat
36
+ } from "./chunk-KTNBYGRU.js";
37
+ import "./chunk-JZ7TWV65.js";
38
+ import "./chunk-ITWJ6Y7G.js";
43
39
  import {
44
40
  LogLevelSchema,
45
41
  VERSION,
42
+ configureBaseLogger,
46
43
  deconstructError,
47
44
  getEnvUniversal,
48
45
  getLogger,
@@ -55,15 +52,20 @@ import {
55
52
  getRivetPublicEndpoint,
56
53
  getRivetPublicToken,
57
54
  getRivetRunEngine,
55
+ getRivetRunEngineHost,
56
+ getRivetRunEnginePort,
58
57
  getRivetRunEngineVersion,
59
58
  getRivetToken,
60
59
  getRivetTotalSlots,
60
+ getRivetkitPublicDir,
61
61
  getRivetkitRuntime,
62
+ getRivetkitRuntimeMode,
62
63
  isDev,
63
64
  noopNext,
65
+ parsePortEnv,
64
66
  stringifyError,
65
67
  toUint8Array
66
- } from "./chunk-5Q26DE3S.js";
68
+ } from "./chunk-XZ62SWSC.js";
67
69
  import {
68
70
  INTERNAL_ERROR_CODE,
69
71
  RivetError,
@@ -71,10 +73,11 @@ import {
71
73
  decodeBridgeRivetError,
72
74
  encodeBridgeRivetError,
73
75
  forbiddenError,
76
+ isActorAbortedError,
74
77
  isRivetErrorLike,
75
78
  toRivetError,
76
79
  unsupportedFeature
77
- } from "./chunk-K34B3OVG.js";
80
+ } from "./chunk-ZZ3WBRPD.js";
78
81
 
79
82
  // src/actor/log.ts
80
83
  function loggerWithoutContext() {
@@ -146,7 +149,7 @@ function hasSchemaConfigKey(schemas, key) {
146
149
  if (!schemas) {
147
150
  return false;
148
151
  }
149
- return Object.prototype.hasOwnProperty.call(schemas, key);
152
+ return Object.hasOwn(schemas, key);
150
153
  }
151
154
  function getEventCanSubscribe(schemas, key) {
152
155
  const schema = schemas == null ? void 0 : schemas[key];
@@ -207,8 +210,8 @@ function validateSchemaSync(schemas, key, data) {
207
210
  }
208
211
 
209
212
  // src/common/inline-websocket-adapter.ts
210
- import { WSContext } from "hono/ws";
211
213
  import { VirtualWebSocket } from "@rivetkit/virtual-websocket";
214
+ import { WSContext } from "hono/ws";
212
215
  function logger() {
213
216
  return getLogger("inline-websocket-adapter");
214
217
  }
@@ -320,24 +323,24 @@ var InlineWebSocketAdapter = class {
320
323
  this.#close(1011, "Internal error during initialization");
321
324
  }
322
325
  }
323
- #handleError(err) {
324
- console.error("INLINE_WEBSOCKET_ADAPTER_ERROR", err);
326
+ #handleError(error) {
327
+ console.error("INLINE_WEBSOCKET_ADAPTER_ERROR", error);
325
328
  logger().error({
326
329
  msg: "error in websocket",
327
- error: err,
328
- errorMessage: err instanceof Error ? err.message : String(err),
329
- stack: err instanceof Error ? err.stack : void 0
330
+ error,
331
+ errorMessage: error instanceof Error ? error.message : String(error),
332
+ stack: error instanceof Error ? error.stack : void 0
330
333
  });
331
334
  try {
332
- this.#handler.onError(err, this.#wsContext);
333
- } catch (handlerErr) {
335
+ this.#handler.onError(error, this.#wsContext);
336
+ } catch (error2) {
334
337
  logger().error({
335
338
  msg: "error in onError handler",
336
- error: handlerErr
339
+ error: error2
337
340
  });
338
341
  }
339
- this.#clientWs.triggerError(err);
340
- this.#actorWs.triggerError(err);
342
+ this.#clientWs.triggerError(error);
343
+ this.#actorWs.triggerError(error);
341
344
  }
342
345
  #close(code, reason) {
343
346
  if (this.#readyState === 3 || this.#readyState === 2) {
@@ -350,8 +353,8 @@ var InlineWebSocketAdapter = class {
350
353
  { code, reason, wasClean: true },
351
354
  this.#wsContext
352
355
  );
353
- } catch (err) {
354
- logger().error({ msg: "error closing websocket", error: err });
356
+ } catch (error) {
357
+ logger().error({ msg: "error closing websocket", error });
355
358
  } finally {
356
359
  this.#readyState = 3;
357
360
  this.#clientWs.triggerClose(code, reason);
@@ -361,8 +364,23 @@ var InlineWebSocketAdapter = class {
361
364
  };
362
365
 
363
366
  // src/common/engine.ts
367
+ var ENGINE_HOST = "127.0.0.1";
364
368
  var ENGINE_PORT = 6420;
365
- var ENGINE_ENDPOINT = `http://127.0.0.1:${ENGINE_PORT}`;
369
+ var ENGINE_ENDPOINT = buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT);
370
+ function buildEngineEndpoint(host, port) {
371
+ const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
372
+ return `http://${urlHost}:${port}`;
373
+ }
374
+ function isLocalEngineEndpoint(endpoint) {
375
+ let url;
376
+ try {
377
+ url = new URL(endpoint);
378
+ } catch {
379
+ return false;
380
+ }
381
+ const hostname = url.hostname.toLowerCase();
382
+ return hostname === "localhost" || hostname === "0.0.0.0" || hostname === "::" || hostname === "[::]" || hostname === "::1" || hostname === "[::1]" || /^127(?:\.\d{1,3}){0,3}$/.test(hostname);
383
+ }
366
384
 
367
385
  // src/registry/log.ts
368
386
  function logger2() {
@@ -377,10 +395,13 @@ function sleep(ms) {
377
395
  }
378
396
  function configureTimeoutMs() {
379
397
  const value = process.env.RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS;
380
- if (value === void 0 || value === "") return DEFAULT_CONFIGURE_TIMEOUT_MS;
398
+ if (value === void 0 || value === "")
399
+ return DEFAULT_CONFIGURE_TIMEOUT_MS;
381
400
  const parsed = Number(value);
382
401
  if (!Number.isFinite(parsed) || parsed < 0) {
383
- throw new Error("RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS must be a finite non-negative number");
402
+ throw new Error(
403
+ "RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS must be a finite non-negative number"
404
+ );
384
405
  }
385
406
  return parsed;
386
407
  }
@@ -394,13 +415,19 @@ async function configureServerlessPool(config) {
394
415
  attempts += 1;
395
416
  try {
396
417
  if (!config.namespace) {
397
- throw new Error("namespace is required for serverless configuration");
418
+ throw new Error(
419
+ "namespace is required for serverless configuration"
420
+ );
398
421
  }
399
422
  if (!config.endpoint) {
400
- throw new Error("endpoint is required for serverless configuration");
423
+ throw new Error(
424
+ "endpoint is required for serverless configuration"
425
+ );
401
426
  }
402
427
  if (!config.configurePool) {
403
- throw new Error("configurePool is required for serverless configuration");
428
+ throw new Error(
429
+ "configurePool is required for serverless configuration"
430
+ );
404
431
  }
405
432
  const customConfig = config.configurePool;
406
433
  const clientConfig = convertRegistryConfigToClientConfig(config);
@@ -569,6 +596,8 @@ var RegistryConfigSchema = z3.object({
569
596
  maxIncomingMessageSize: z3.number().optional().default(65536),
570
597
  /** @experimental */
571
598
  maxOutgoingMessageSize: z3.number().optional().default(1048576),
599
+ /** Enables the experimental per-actor Unix socket API. */
600
+ experimentalActorUds: z3.boolean().optional().default(false),
572
601
  // MARK: Runtime
573
602
  /**
574
603
  * @experimental
@@ -674,6 +703,18 @@ var RegistryConfigSchema = z3.object({
674
703
  * Starts the full Rust engine process locally.
675
704
  */
676
705
  startEngine: z3.boolean().default(() => getRivetRunEngine()),
706
+ /**
707
+ * @experimental
708
+ *
709
+ * Host to bind the spawned local engine process to.
710
+ */
711
+ engineHost: z3.string().optional().default(() => getRivetRunEngineHost() ?? ENGINE_HOST),
712
+ /**
713
+ * @experimental
714
+ *
715
+ * Port to bind the spawned local engine process to.
716
+ */
717
+ enginePort: z3.number().int().min(1).max(65535).optional().default(() => getRivetRunEnginePort() ?? ENGINE_PORT),
677
718
  /** @experimental */
678
719
  engineVersion: z3.string().optional().default(() => getRivetRunEngineVersion() ?? VERSION),
679
720
  /**
@@ -706,12 +747,12 @@ var RegistryConfigSchema = z3.object({
706
747
  shutdown: z3.object({
707
748
  /**
708
749
  * Wait this many milliseconds for the serve promise to resolve
709
- * after calling `CoreRegistry::shutdown()`. Defaults to 30s,
710
- * matching Kubernetes `terminationGracePeriodSeconds`.
750
+ * after calling `CoreRegistry::shutdown()`. Defaults to the
751
+ * engine-provided actor stop threshold once the envoy connects.
711
752
  *
712
- * Must be >= rivetkit-core's drain timeout (20s) + margin.
753
+ * Must be long enough for rivetkit-core to drain the envoy.
713
754
  */
714
- gracePeriodMs: z3.number().int().min(1e3).optional().default(3e4),
755
+ gracePeriodMs: z3.number().int().min(1e3).optional(),
715
756
  /**
716
757
  * If true, rivetkit will not install SIGINT/SIGTERM handlers.
717
758
  * Use when the host application owns signal policy and will
@@ -719,7 +760,6 @@ var RegistryConfigSchema = z3.object({
719
760
  */
720
761
  disableSignalHandlers: z3.boolean().optional().default(false)
721
762
  }).optional().default(() => ({
722
- gracePeriodMs: 3e4,
723
763
  disableSignalHandlers: false
724
764
  }))
725
765
  }).transform((config, ctx) => {
@@ -752,7 +792,11 @@ var RegistryConfigSchema = z3.object({
752
792
  message: "configurePool requires either endpoint or startEngine"
753
793
  });
754
794
  }
755
- const endpoint = config.startEngine ? ENGINE_ENDPOINT : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? ENGINE_ENDPOINT : void 0);
795
+ const localEngineEndpoint = buildEngineEndpoint(
796
+ config.engineHost,
797
+ config.enginePort
798
+ );
799
+ const endpoint = config.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT) : void 0);
756
800
  const validateServerlessEndpoint = Boolean(
757
801
  config.startEngine || parsedEndpoint
758
802
  );
@@ -769,7 +813,7 @@ var RegistryConfigSchema = z3.object({
769
813
  path: ["serverless", "publicEndpoint"]
770
814
  });
771
815
  }
772
- const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && config.startEngine ? ENGINE_ENDPOINT : void 0);
816
+ const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && config.startEngine ? endpoint : void 0);
773
817
  const publicNamespace = parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.namespace;
774
818
  const publicToken = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.token) ?? config.serverless.publicToken;
775
819
  return {
@@ -930,7 +974,8 @@ function shouldAttachNativeKvError(message) {
930
974
  }
931
975
  function enrichNativeDatabaseError(database, error) {
932
976
  var _a;
933
- const bridged = typeof error === "string" ? decodeBridgeRivetError(error) : error instanceof Error ? decodeBridgeRivetError(error.message) : void 0;
977
+ const bridgeReason = typeof error === "string" ? error : error instanceof Error ? error.message : void 0;
978
+ const bridged = bridgeReason === void 0 ? void 0 : decodeBridgeRivetError(bridgeReason);
934
979
  if (bridged) {
935
980
  throw bridged;
936
981
  }
@@ -1081,7 +1126,7 @@ function wrapJsNativeDatabase(database) {
1081
1126
  const gate = new NativeCloseGate();
1082
1127
  let closePromise;
1083
1128
  let lastInsertRowId = null;
1084
- const executeNative = async (sql, params) => {
1129
+ const executeNative = async (sql, params, lease) => {
1085
1130
  const lastInsertRowIdColumn = lastInsertRowIdColumnName(sql);
1086
1131
  if (lastInsertRowIdColumn) {
1087
1132
  return {
@@ -1094,7 +1139,12 @@ function wrapJsNativeDatabase(database) {
1094
1139
  const release = gate.enter();
1095
1140
  try {
1096
1141
  const nativeParams = toNativeBindings(sql, params);
1097
- const result = await database.execute(sql, nativeParams);
1142
+ const result = await database.execute(
1143
+ sql,
1144
+ nativeParams,
1145
+ lease == null ? void 0 : lease.key,
1146
+ lease == null ? void 0 : lease.timeoutMs
1147
+ );
1098
1148
  if (result.lastInsertRowId !== void 0) {
1099
1149
  lastInsertRowId = result.lastInsertRowId;
1100
1150
  }
@@ -1106,11 +1156,11 @@ function wrapJsNativeDatabase(database) {
1106
1156
  }
1107
1157
  };
1108
1158
  return {
1109
- async exec(sql, callback) {
1159
+ async exec(sql, callback, lease) {
1110
1160
  const release = gate.enter();
1111
1161
  let result;
1112
1162
  try {
1113
- result = await database.exec(sql);
1163
+ result = await database.exec(sql, lease == null ? void 0 : lease.key, lease == null ? void 0 : lease.timeoutMs);
1114
1164
  } catch (error) {
1115
1165
  enrichNativeDatabaseError(database, error);
1116
1166
  } finally {
@@ -1123,8 +1173,8 @@ function wrapJsNativeDatabase(database) {
1123
1173
  callback(row, result.columns);
1124
1174
  }
1125
1175
  },
1126
- async execute(sql, params) {
1127
- return await executeNative(sql, params);
1176
+ async execute(sql, params, lease) {
1177
+ return await executeNative(sql, params, lease);
1128
1178
  },
1129
1179
  async run(sql, params) {
1130
1180
  await executeNative(sql, params);
@@ -1133,9 +1183,6 @@ function wrapJsNativeDatabase(database) {
1133
1183
  const { columns, rows } = await executeNative(sql, params);
1134
1184
  return { columns, rows };
1135
1185
  },
1136
- async writeMode(callback) {
1137
- return await callback();
1138
- },
1139
1186
  nativeMetrics() {
1140
1187
  var _a;
1141
1188
  return normalizeNativeMetrics((_a = database.metrics) == null ? void 0 : _a.call(database));
@@ -1163,6 +1210,82 @@ function lastInsertRowIdColumnName(sql) {
1163
1210
  return alias;
1164
1211
  }
1165
1212
 
1213
+ // src/utils/node.ts
1214
+ import { createRequire } from "module";
1215
+ var nodeCrypto;
1216
+ var nodeFsSync;
1217
+ var nodeFs;
1218
+ var nodePath;
1219
+ var nodeOs;
1220
+ var nodeChildProcess;
1221
+ var nodeStream;
1222
+ var nodeUrl;
1223
+ var hasImportedDependencies = false;
1224
+ function getRequireFn() {
1225
+ return createRequire(import.meta.url);
1226
+ }
1227
+ function importNodeDependencies() {
1228
+ if (hasImportedDependencies) return;
1229
+ try {
1230
+ const requireFn = getRequireFn();
1231
+ nodeCrypto = requireFn(
1232
+ /* webpackIgnore: true */
1233
+ "node:crypto"
1234
+ );
1235
+ nodeFsSync = requireFn(
1236
+ /* webpackIgnore: true */
1237
+ "node:fs"
1238
+ );
1239
+ nodeFs = requireFn(
1240
+ /* webpackIgnore: true */
1241
+ "node:fs/promises"
1242
+ );
1243
+ nodePath = requireFn(
1244
+ /* webpackIgnore: true */
1245
+ "node:path"
1246
+ );
1247
+ nodeOs = requireFn(
1248
+ /* webpackIgnore: true */
1249
+ "node:os"
1250
+ );
1251
+ nodeChildProcess = requireFn(
1252
+ /* webpackIgnore: true */
1253
+ "node:child_process"
1254
+ );
1255
+ nodeStream = requireFn(
1256
+ /* webpackIgnore: true */
1257
+ "node:stream/promises"
1258
+ );
1259
+ nodeUrl = requireFn(
1260
+ /* webpackIgnore: true */
1261
+ "node:url"
1262
+ );
1263
+ hasImportedDependencies = true;
1264
+ } catch (err) {
1265
+ console.warn(
1266
+ "Node.js modules not available, file system driver will not work",
1267
+ err
1268
+ );
1269
+ throw err;
1270
+ }
1271
+ }
1272
+ function getNodeFsSync() {
1273
+ if (!nodeFsSync) {
1274
+ throw new Error(
1275
+ "Node fs module not loaded. Ensure importNodeDependencies() has been called."
1276
+ );
1277
+ }
1278
+ return nodeFsSync;
1279
+ }
1280
+ function getNodePath() {
1281
+ if (!nodePath) {
1282
+ throw new Error(
1283
+ "Node path module not loaded. Ensure importNodeDependencies() has been called."
1284
+ );
1285
+ }
1286
+ return nodePath;
1287
+ }
1288
+
1166
1289
  // src/registry/runtime.ts
1167
1290
  function normalizeRuntimeSqlExecuteResult(result) {
1168
1291
  return result;
@@ -1283,11 +1406,31 @@ var NapiCoreRuntime = class {
1283
1406
  async shutdownRegistry(registry) {
1284
1407
  await asNativeRegistry(registry).shutdown();
1285
1408
  }
1286
- async registryDiagnostics(registry) {
1287
- const diagnostics = await asNativeRegistry(registry).diagnostics();
1409
+ async registryActorStopThresholdMs(registry) {
1410
+ return await asNativeRegistry(registry).actorStopThresholdMs() ?? void 0;
1411
+ }
1412
+ async registryHealth(registry) {
1413
+ const response = await asNativeRegistry(registry).health();
1414
+ return {
1415
+ status: response.status,
1416
+ headers: response.headers,
1417
+ body: response.body
1418
+ };
1419
+ }
1420
+ async registryMetadata(registry) {
1421
+ const response = asNativeRegistry(registry).metadata();
1288
1422
  return {
1289
- mode: diagnostics.mode,
1290
- envoyActiveActorCount: diagnostics.envoyActiveActorCount
1423
+ status: response.status,
1424
+ headers: response.headers,
1425
+ body: response.body
1426
+ };
1427
+ }
1428
+ async registryMetrics(registry) {
1429
+ const response = asNativeRegistry(registry).metrics();
1430
+ return {
1431
+ status: response.status,
1432
+ headers: response.headers,
1433
+ body: response.body
1291
1434
  };
1292
1435
  }
1293
1436
  async handleServerlessRequest(registry, req, onStreamEvent, cancelToken, config) {
@@ -1298,6 +1441,16 @@ var NapiCoreRuntime = class {
1298
1441
  config
1299
1442
  );
1300
1443
  }
1444
+ async serveListener(registry, listener, config) {
1445
+ await asNativeRegistry(registry).serveListener(
1446
+ {
1447
+ port: listener.port,
1448
+ host: listener.host,
1449
+ publicDir: listener.publicDir
1450
+ },
1451
+ config
1452
+ );
1453
+ }
1301
1454
  createActorFactory(callbacks, config) {
1302
1455
  return asActorFactoryHandle(
1303
1456
  new this.#bindings.NapiActorFactory(callbacks, config)
@@ -1410,6 +1563,12 @@ var NapiCoreRuntime = class {
1410
1563
  actorWaitUntil(ctx, promise) {
1411
1564
  asNativeActorContext(ctx).waitUntil(promise);
1412
1565
  }
1566
+ async actorWaitForTrackedShutdownWork(ctx) {
1567
+ return await asNativeActorContext(ctx).waitForTrackedShutdownWork();
1568
+ }
1569
+ async actorWaitForTrackedShutdownWorkUnbounded(ctx) {
1570
+ await asNativeActorContext(ctx).waitForTrackedShutdownWorkUnbounded();
1571
+ }
1413
1572
  actorKeepAwake(ctx, promise) {
1414
1573
  asNativeActorContext(ctx).keepAwake(promise);
1415
1574
  }
@@ -1464,13 +1623,19 @@ var NapiCoreRuntime = class {
1464
1623
  async actorKvBatchDelete(ctx, keys) {
1465
1624
  await asNativeActorContext(ctx).kv().batchDelete(keys.map(toNapiBuffer));
1466
1625
  }
1467
- async actorSqlExec(ctx, sql) {
1468
- return await this.#actorSql(ctx).exec(sql);
1626
+ async actorSqlExec(ctx, sql, lease) {
1627
+ return await this.#actorSql(ctx).exec(
1628
+ sql,
1629
+ lease == null ? void 0 : lease.key,
1630
+ lease == null ? void 0 : lease.timeoutMs
1631
+ );
1469
1632
  }
1470
- async actorSqlExecute(ctx, sql, params) {
1633
+ async actorSqlExecute(ctx, sql, params, lease) {
1471
1634
  const result = await this.#actorSql(ctx).execute(
1472
1635
  sql,
1473
- toNapiSqlBindParams(params)
1636
+ toNapiSqlBindParams(params),
1637
+ lease == null ? void 0 : lease.key,
1638
+ lease == null ? void 0 : lease.timeoutMs
1474
1639
  );
1475
1640
  return normalizeRuntimeSqlExecuteResult(result);
1476
1641
  }
@@ -1500,6 +1665,9 @@ var NapiCoreRuntime = class {
1500
1665
  this.#sql.delete(nativeCtx);
1501
1666
  await database.close();
1502
1667
  }
1668
+ async actorUdsProvision(ctx) {
1669
+ return await asNativeActorContext(ctx).provisionActorUds();
1670
+ }
1503
1671
  async actorQueueSend(ctx, name, body) {
1504
1672
  return toNapiQueueMessage(
1505
1673
  await asNativeActorContext(ctx).queue().send(name, toNapiBuffer(body))
@@ -1521,8 +1689,12 @@ var NapiCoreRuntime = class {
1521
1689
  )
1522
1690
  );
1523
1691
  }
1524
- async actorQueueWaitForNamesAvailable(ctx, names, options) {
1525
- await asNativeActorContext(ctx).queue().waitForNamesAvailable(names, options);
1692
+ async actorQueueWaitForNamesAvailable(ctx, names, options, signal) {
1693
+ await asNativeActorContext(ctx).queue().waitForNamesAvailable(
1694
+ names,
1695
+ options,
1696
+ signal ? asNativeCancellationToken(signal) : signal
1697
+ );
1526
1698
  }
1527
1699
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
1528
1700
  return await asNativeActorContext(ctx).queue().enqueueAndWait(
@@ -1541,6 +1713,9 @@ var NapiCoreRuntime = class {
1541
1713
  async actorQueueInspectMessages(ctx) {
1542
1714
  return await asNativeActorContext(ctx).queue().inspectMessages();
1543
1715
  }
1716
+ async actorQueueReset(ctx) {
1717
+ await asNativeActorContext(ctx).queue().reset();
1718
+ }
1544
1719
  actorScheduleAfter(ctx, durationMs, actionName, args) {
1545
1720
  asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
1546
1721
  }
@@ -1656,20 +1831,18 @@ function validateQueueComplete(schemas, name, response) {
1656
1831
  response
1657
1832
  );
1658
1833
  if (!result.success) {
1659
- throw validationError(`queue \`${name}\` completion response`, result.issues);
1834
+ throw validationError(
1835
+ `queue \`${name}\` completion response`,
1836
+ result.issues
1837
+ );
1660
1838
  }
1661
1839
  return result.data;
1662
1840
  }
1663
1841
  function validationError(target, issues) {
1664
- return new RivetError(
1665
- "actor",
1666
- "validation_error",
1667
- `Invalid ${target}`,
1668
- {
1669
- public: true,
1670
- metadata: { issues }
1671
- }
1672
- );
1842
+ return new RivetError("actor", "validation_error", `Invalid ${target}`, {
1843
+ public: true,
1844
+ metadata: { issues }
1845
+ });
1673
1846
  }
1674
1847
 
1675
1848
  // src/registry/wasm-runtime.ts
@@ -1827,8 +2000,18 @@ var WasmCoreRuntime = class {
1827
2000
  async shutdownRegistry(registry) {
1828
2001
  await callWasm(() => asWasmRegistry(registry).shutdown());
1829
2002
  }
1830
- async registryDiagnostics() {
1831
- return { mode: "wasm", envoyActiveActorCount: null };
2003
+ async registryHealth() {
2004
+ return {
2005
+ status: 200,
2006
+ headers: { "content-type": "application/json" },
2007
+ body: new TextEncoder().encode(
2008
+ JSON.stringify({
2009
+ status: "ok",
2010
+ runtime: "rivetkit",
2011
+ version: "wasm"
2012
+ })
2013
+ )
2014
+ };
1832
2015
  }
1833
2016
  async handleServerlessRequest(registry, req, onStreamEvent, cancelToken, config) {
1834
2017
  return await callHandleAsync(
@@ -1840,6 +2023,11 @@ var WasmCoreRuntime = class {
1840
2023
  config
1841
2024
  );
1842
2025
  }
2026
+ async serveListener(_registry, _listener, _config) {
2027
+ throw new Error(
2028
+ "registry.listen() is not supported on the wasm runtime; use registry.serve() and mount the handler in your platform's HTTP server instead"
2029
+ );
2030
+ }
1843
2031
  createActorFactory(callbacks, config) {
1844
2032
  return callWasmSync(
1845
2033
  () => asActorFactoryHandle2(
@@ -1977,6 +2165,18 @@ var WasmCoreRuntime = class {
1977
2165
  actorWaitUntil(ctx, promise) {
1978
2166
  callHandle(asWasmActorContext(ctx), "waitUntil", promise);
1979
2167
  }
2168
+ async actorWaitForTrackedShutdownWork(ctx) {
2169
+ return await callHandle(
2170
+ asWasmActorContext(ctx),
2171
+ "waitForTrackedShutdownWork"
2172
+ );
2173
+ }
2174
+ async actorWaitForTrackedShutdownWorkUnbounded(ctx) {
2175
+ await callHandle(
2176
+ asWasmActorContext(ctx),
2177
+ "waitForTrackedShutdownWorkUnbounded"
2178
+ );
2179
+ }
1980
2180
  actorKeepAwake(ctx, promise) {
1981
2181
  const wasmCtx = asWasmActorContext(ctx);
1982
2182
  const regionId = callHandle(wasmCtx, "beginKeepAwake");
@@ -2064,10 +2264,20 @@ var WasmCoreRuntime = class {
2064
2264
  const kv = childHandle(asWasmActorContext(ctx), "kv");
2065
2265
  await callHandleAsync(kv, "batchDelete", keys);
2066
2266
  }
2067
- async actorSqlExec(ctx, sql) {
2267
+ async actorSqlExec(ctx, sql, lease) {
2268
+ if (lease) {
2269
+ throw new Error(
2270
+ "sqlite transaction leases are unavailable in the wasm runtime"
2271
+ );
2272
+ }
2068
2273
  return await callWasm(() => this.#actorSql(ctx).exec(sql));
2069
2274
  }
2070
- async actorSqlExecute(ctx, sql, params) {
2275
+ async actorSqlExecute(ctx, sql, params, lease) {
2276
+ if (lease) {
2277
+ throw new Error(
2278
+ "sqlite transaction leases are unavailable in the wasm runtime"
2279
+ );
2280
+ }
2071
2281
  const result = await callWasm(
2072
2282
  () => this.#actorSql(ctx).execute(sql, params)
2073
2283
  );
@@ -2096,6 +2306,9 @@ var WasmCoreRuntime = class {
2096
2306
  this.#sql.delete(wasmCtx);
2097
2307
  await callWasm(() => database.close());
2098
2308
  }
2309
+ async actorUdsProvision(_ctx) {
2310
+ throw new Error("actor UDS endpoints require the native runtime");
2311
+ }
2099
2312
  async actorQueueSend(ctx, name, body) {
2100
2313
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2101
2314
  return normalizeQueueMessage(
@@ -2124,9 +2337,15 @@ var WasmCoreRuntime = class {
2124
2337
  )
2125
2338
  );
2126
2339
  }
2127
- async actorQueueWaitForNamesAvailable(ctx, names, options) {
2340
+ async actorQueueWaitForNamesAvailable(ctx, names, options, signal) {
2128
2341
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2129
- await callHandleAsync(queue2, "waitForNamesAvailable", names, options);
2342
+ await callHandleAsync(
2343
+ queue2,
2344
+ "waitForNamesAvailable",
2345
+ names,
2346
+ options,
2347
+ signal
2348
+ );
2130
2349
  }
2131
2350
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
2132
2351
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
@@ -2157,6 +2376,10 @@ var WasmCoreRuntime = class {
2157
2376
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2158
2377
  return await callHandleAsync(queue2, "inspectMessages");
2159
2378
  }
2379
+ async actorQueueReset(ctx) {
2380
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2381
+ await callHandleAsync(queue2, "reset");
2382
+ }
2160
2383
  actorScheduleAfter(ctx, durationMs, actionName, args) {
2161
2384
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2162
2385
  callHandle(schedule, "after", wasmNumber(durationMs), actionName, args);
@@ -2218,6 +2441,29 @@ async function loadWasmRuntime(config) {
2218
2441
  };
2219
2442
  }
2220
2443
 
2444
+ // src/registry/write-through-proxy.ts
2445
+ import onChange from "@rivetkit/on-change";
2446
+ function createWriteThroughProxy(value, commit, beforeChange) {
2447
+ if (!value || typeof value !== "object") {
2448
+ return value;
2449
+ }
2450
+ return onChange(
2451
+ value,
2452
+ () => {
2453
+ commit(value);
2454
+ },
2455
+ {
2456
+ // Rejection is throw-based: beforeChange throws to prevent the
2457
+ // mutation. We always return true so on-change applies the change
2458
+ // if beforeChange did not throw.
2459
+ onValidate(_path, newValue) {
2460
+ beforeChange == null ? void 0 : beforeChange(newValue);
2461
+ return true;
2462
+ }
2463
+ }
2464
+ );
2465
+ }
2466
+
2221
2467
  // src/registry/native.ts
2222
2468
  var textEncoder = new TextEncoder();
2223
2469
  var textDecoder = new TextDecoder();
@@ -2371,6 +2617,14 @@ function databaseNotConfiguredError() {
2371
2617
  { public: true }
2372
2618
  );
2373
2619
  }
2620
+ function databaseClientNotReadyError() {
2621
+ return new RivetError(
2622
+ "actor",
2623
+ "database_client_not_ready",
2624
+ "actor database client was not initialized before user code ran. this is an internal lifecycle error; the migration callback should have pre-warmed the client. file an issue if you can reproduce.",
2625
+ { public: true }
2626
+ );
2627
+ }
2374
2628
  function stateNotEnabledError() {
2375
2629
  return new RivetError(
2376
2630
  "actor",
@@ -2422,21 +2676,27 @@ function resolveNativeDestroy(runtime, ctx) {
2422
2676
  function clearNativeRuntimeState(runtime, ctx) {
2423
2677
  callNativeSync(() => runtime.actorClearRuntimeState(ctx));
2424
2678
  }
2425
- async function cleanupNativeSleepRuntimeState(runtime, ctx) {
2679
+ async function cleanupNativeSleepRuntimeState(runtime, ctx, afterTrackedWorkDrained) {
2680
+ const drained = await runtime.actorWaitForTrackedShutdownWork(ctx);
2681
+ if (!drained) {
2682
+ await closeNativeDatabaseClient(runtime, ctx);
2683
+ await closeNativeSqlDatabase(runtime, ctx);
2684
+ void runtime.actorWaitForTrackedShutdownWorkUnbounded(ctx).then(async () => {
2685
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
2686
+ clearNativeRuntimeState(runtime, ctx);
2687
+ }).catch((error) => {
2688
+ logger2().warn({
2689
+ msg: "deferred native sleep cleanup failed",
2690
+ error: stringifyError(error)
2691
+ });
2692
+ });
2693
+ return;
2694
+ }
2695
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
2426
2696
  await closeNativeDatabaseClient(runtime, ctx);
2427
2697
  await closeNativeSqlDatabase(runtime, ctx);
2428
2698
  clearNativeRuntimeState(runtime, ctx);
2429
2699
  }
2430
- async function cleanupDeferredNativeSleepRuntimeState(runtime, ctx, runtimeState) {
2431
- runtimeState.deferSleepCleanupUntilKeepAwakeIdle = false;
2432
- const actorCtx = runtimeState.deferredSleepCleanupActorCtx;
2433
- runtimeState.deferredSleepCleanupActorCtx = void 0;
2434
- try {
2435
- await cleanupNativeSleepRuntimeState(runtime, ctx);
2436
- } finally {
2437
- await (actorCtx == null ? void 0 : actorCtx.dispose());
2438
- }
2439
- }
2440
2700
  function closeNativeSqlDatabase(runtime, ctx) {
2441
2701
  const runtimeState = getNativeRuntimeState(runtime, ctx);
2442
2702
  const database = runtimeState.sql;
@@ -2464,8 +2724,17 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
2464
2724
  return cachedDatabase;
2465
2725
  }
2466
2726
  const database = wrapJsNativeDatabase({
2467
- exec: (sql) => runtime.actorSqlExec(ctx, sql),
2468
- execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
2727
+ exec: (sql, leaseKey, leaseTimeoutMs) => runtime.actorSqlExec(
2728
+ ctx,
2729
+ sql,
2730
+ leaseKey === void 0 ? void 0 : { key: leaseKey, timeoutMs: leaseTimeoutMs }
2731
+ ),
2732
+ execute: (sql, params, leaseKey, leaseTimeoutMs) => runtime.actorSqlExecute(
2733
+ ctx,
2734
+ sql,
2735
+ params,
2736
+ leaseKey === void 0 ? void 0 : { key: leaseKey, timeoutMs: leaseTimeoutMs }
2737
+ ),
2469
2738
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
2470
2739
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
2471
2740
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -2537,11 +2806,14 @@ function decodeValue(value) {
2537
2806
  if (!value || value.length === 0) {
2538
2807
  return void 0;
2539
2808
  }
2540
- return decodeCborJsonCompat(value);
2809
+ return decodeCborCompat(value);
2541
2810
  }
2542
2811
  function encodeValue(value) {
2543
2812
  return encodeCborCompat(value);
2544
2813
  }
2814
+ function normalizeArgs(value) {
2815
+ return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
2816
+ }
2545
2817
  function unwrapTsfnPayload(error, payload) {
2546
2818
  if (error !== null && error !== void 0) {
2547
2819
  throw error;
@@ -2573,27 +2845,7 @@ function isStructuredBridgeError(error) {
2573
2845
  return isRivetErrorLike(error) && "__type" in error && (error.__type === "RivetError" || error.__type === "ActorError");
2574
2846
  }
2575
2847
  function encodeNativeCallbackError(error) {
2576
- const structuredError = isStructuredBridgeError(error) ? error : deconstructError(error, logger2(), {
2577
- bridge: "native_callback"
2578
- });
2579
- let stack;
2580
- if (error instanceof Error) {
2581
- try {
2582
- stack = error.stack;
2583
- } catch {
2584
- stack = void 0;
2585
- }
2586
- }
2587
- logger2().warn({
2588
- msg: "native callback error encoded for bridge",
2589
- group: structuredError.group,
2590
- code: structuredError.code,
2591
- message: structuredError.message,
2592
- metadata: structuredError.metadata,
2593
- originalError: stringifyError(error),
2594
- stack,
2595
- bridge: "native_callback"
2596
- });
2848
+ const structuredError = isStructuredBridgeError(error) ? error : deconstructError(error, true);
2597
2849
  const bridgeError = new Error(encodeBridgeRivetError(structuredError), {
2598
2850
  cause: error instanceof Error ? error : void 0
2599
2851
  });
@@ -2617,12 +2869,6 @@ function callNativeSync(invoke) {
2617
2869
  throw normalizeNativeBridgeError(error);
2618
2870
  }
2619
2871
  }
2620
- function actorAbortedError() {
2621
- return Object.assign(new Error("Actor aborted"), {
2622
- group: "actor",
2623
- code: "aborted"
2624
- });
2625
- }
2626
2872
  function isClosedTaskRegistrationError(error) {
2627
2873
  const metadata = error instanceof RivetError ? error.metadata : void 0;
2628
2874
  const metadataError = metadata && typeof metadata === "object" && "error" in metadata ? metadata.error : void 0;
@@ -2748,6 +2994,14 @@ function serializeWorkflowEntryKind(kind) {
2748
2994
  originalName: kind.val.originalName
2749
2995
  }
2750
2996
  };
2997
+ case "WorkflowVersionCheckEntry":
2998
+ return {
2999
+ tag: kind.tag,
3000
+ val: {
3001
+ resolved: kind.val.resolved,
3002
+ latest: kind.val.latest
3003
+ }
3004
+ };
2751
3005
  }
2752
3006
  }
2753
3007
  function serializeWorkflowHistoryForJson(data) {
@@ -2755,7 +3009,7 @@ function serializeWorkflowHistoryForJson(data) {
2755
3009
  return null;
2756
3010
  }
2757
3011
  const history = decodeWorkflowHistoryTransport(data);
2758
- return {
3012
+ return jsonSafe({
2759
3013
  nameRegistry: [...history.nameRegistry],
2760
3014
  entries: history.entries.map((entry) => ({
2761
3015
  id: entry.id,
@@ -2779,7 +3033,7 @@ function serializeWorkflowHistoryForJson(data) {
2779
3033
  ]
2780
3034
  )
2781
3035
  )
2782
- };
3036
+ });
2783
3037
  }
2784
3038
  function toHttpJsonCompatible(value) {
2785
3039
  return JSON.parse(
@@ -2830,45 +3084,7 @@ function wrapNativeCallback(callback) {
2830
3084
  }
2831
3085
  function decodeArgs(value) {
2832
3086
  const decoded = decodeValue(value);
2833
- return Array.isArray(decoded) ? decoded : decoded === void 0 ? [] : [decoded];
2834
- }
2835
- function createWriteThroughProxy(value, commit, beforeChange) {
2836
- if (!value || typeof value !== "object") {
2837
- return value;
2838
- }
2839
- const proxies = /* @__PURE__ */ new WeakMap();
2840
- const wrap = (target) => {
2841
- const cached = proxies.get(target);
2842
- if (cached) {
2843
- return cached;
2844
- }
2845
- const proxy = new Proxy(target, {
2846
- get(innerTarget, property, receiver) {
2847
- const result = Reflect.get(innerTarget, property, receiver);
2848
- return result && typeof result === "object" ? wrap(result) : result;
2849
- },
2850
- set(innerTarget, property, nextValue, receiver) {
2851
- beforeChange == null ? void 0 : beforeChange();
2852
- const updated = Reflect.set(
2853
- innerTarget,
2854
- property,
2855
- nextValue,
2856
- receiver
2857
- );
2858
- commit(value);
2859
- return updated;
2860
- },
2861
- deleteProperty(innerTarget, property) {
2862
- beforeChange == null ? void 0 : beforeChange();
2863
- const updated = Reflect.deleteProperty(innerTarget, property);
2864
- commit(value);
2865
- return updated;
2866
- }
2867
- });
2868
- proxies.set(target, proxy);
2869
- return proxy;
2870
- };
2871
- return wrap(value);
3087
+ return normalizeArgs(decoded);
2872
3088
  }
2873
3089
  function buildRequest(init) {
2874
3090
  const url = init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString();
@@ -2922,13 +3138,23 @@ var NativeConnAdapter = class {
2922
3138
  decodeValue(this.#runtime.connParams(this.#conn))
2923
3139
  );
2924
3140
  }
3141
+ [RAW_STATE_SYMBOL]() {
3142
+ return this.#readState();
3143
+ }
2925
3144
  get state() {
2926
3145
  const nextState = this.#readState();
2927
- return createWriteThroughProxy(nextState, (nextValue) => {
2928
- this.#writeState(nextValue, { writeNative: true });
2929
- });
3146
+ return createWriteThroughProxy(
3147
+ nextState,
3148
+ (nextValue) => {
3149
+ this.#writeState(nextValue, { writeNative: true });
3150
+ },
3151
+ (newValue) => {
3152
+ assertJsonCompatValue(newValue);
3153
+ }
3154
+ );
2930
3155
  }
2931
3156
  set state(value) {
3157
+ assertJsonCompatValue(value);
2932
3158
  this.#writeState(value, { writeNative: true });
2933
3159
  }
2934
3160
  initializeState(value) {
@@ -3280,44 +3506,23 @@ var NativeQueueAdapter = class {
3280
3506
  }
3281
3507
  }
3282
3508
  async waitForNamesAvailable(names, options) {
3283
- if (!(options == null ? void 0 : options.signal)) {
3509
+ const { token, cleanup } = await createCancellationTokenHandle(
3510
+ this.#runtime,
3511
+ options == null ? void 0 : options.signal
3512
+ );
3513
+ try {
3284
3514
  await callNative(
3285
3515
  () => this.#runtime.actorQueueWaitForNamesAvailable(
3286
3516
  this.#ctx,
3287
3517
  [...names],
3288
3518
  {
3289
3519
  timeoutMs: options == null ? void 0 : options.timeout
3290
- }
3520
+ },
3521
+ token
3291
3522
  )
3292
3523
  );
3293
- return;
3294
- }
3295
- const deadline = options.timeout === void 0 ? void 0 : Date.now() + options.timeout;
3296
- for (; ; ) {
3297
- if (options.signal.aborted) {
3298
- throw actorAbortedError();
3299
- }
3300
- const remainingTimeout = deadline === void 0 ? void 0 : Math.max(0, deadline - Date.now());
3301
- const sliceTimeout = remainingTimeout === void 0 ? 100 : Math.min(remainingTimeout, 100);
3302
- try {
3303
- await callNative(
3304
- () => this.#runtime.actorQueueWaitForNamesAvailable(
3305
- this.#ctx,
3306
- [...names],
3307
- {
3308
- timeoutMs: sliceTimeout
3309
- }
3310
- )
3311
- );
3312
- return;
3313
- } catch (error) {
3314
- if (error.group === "queue" && error.code === "timed_out") {
3315
- if (remainingTimeout === void 0 || remainingTimeout > 100) {
3316
- continue;
3317
- }
3318
- }
3319
- throw error;
3320
- }
3524
+ } finally {
3525
+ cleanup == null ? void 0 : cleanup();
3321
3526
  }
3322
3527
  }
3323
3528
  async enqueueAndWait(name, body, options) {
@@ -3387,7 +3592,7 @@ var NativeQueueAdapter = class {
3387
3592
  }
3388
3593
  yield message;
3389
3594
  } catch (error) {
3390
- if (isRivetErrorLike(error) && error.group === "actor" && error.code === "aborted") {
3595
+ if (isActorAbortedError(error)) {
3391
3596
  return;
3392
3597
  }
3393
3598
  throw error;
@@ -3752,6 +3957,68 @@ var TrackedWebSocketHandleAdapter = class {
3752
3957
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
3753
3958
  }
3754
3959
  };
3960
+ var NativeConnectionMap = class {
3961
+ #runtime;
3962
+ #ctx;
3963
+ #schemas;
3964
+ constructor(runtime, ctx, schemas) {
3965
+ this.#runtime = runtime;
3966
+ this.#ctx = ctx;
3967
+ this.#schemas = schemas;
3968
+ }
3969
+ #connToAdapter(conn) {
3970
+ return new NativeConnAdapter(
3971
+ this.#runtime,
3972
+ conn,
3973
+ this.#schemas,
3974
+ this.#ctx,
3975
+ (connId) => callNativeSync(
3976
+ () => this.#runtime.actorQueueHibernationRemoval(
3977
+ this.#ctx,
3978
+ connId
3979
+ )
3980
+ )
3981
+ );
3982
+ }
3983
+ get size() {
3984
+ return callNativeSync(() => this.#runtime.actorConns(this.#ctx)).length;
3985
+ }
3986
+ get(key) {
3987
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
3988
+ const conn = conns.find((c) => this.#runtime.connId(c) === key);
3989
+ if (!conn) return void 0;
3990
+ return this.#connToAdapter(conn);
3991
+ }
3992
+ has(key) {
3993
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
3994
+ return conns.some((c) => this.#runtime.connId(c) === key);
3995
+ }
3996
+ keys() {
3997
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
3998
+ return conns.map((c) => this.#runtime.connId(c))[Symbol.iterator]();
3999
+ }
4000
+ values() {
4001
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4002
+ return conns.map((c) => this.#connToAdapter(c))[Symbol.iterator]();
4003
+ }
4004
+ entries() {
4005
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4006
+ return conns.map(
4007
+ (c) => [this.#runtime.connId(c), this.#connToAdapter(c)]
4008
+ )[Symbol.iterator]();
4009
+ }
4010
+ forEach(callback, thisArg) {
4011
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4012
+ for (const conn of conns) {
4013
+ const id = this.#runtime.connId(conn);
4014
+ callback.call(thisArg, this.#connToAdapter(conn), id, this);
4015
+ }
4016
+ }
4017
+ [Symbol.iterator]() {
4018
+ return this.entries();
4019
+ }
4020
+ [Symbol.toStringTag] = "NativeConnectionMap";
4021
+ };
3755
4022
  var ActorContextHandleAdapter = class {
3756
4023
  #runtime;
3757
4024
  #ctx;
@@ -3760,9 +4027,9 @@ var ActorContextHandleAdapter = class {
3760
4027
  #abortSignalCleanup;
3761
4028
  #client;
3762
4029
  #clientFactory;
4030
+ #connMap;
3763
4031
  #databaseProvider;
3764
4032
  #db;
3765
- #dbProxy;
3766
4033
  #dispatchCancelToken;
3767
4034
  #kv;
3768
4035
  #queue;
@@ -3801,55 +4068,57 @@ var ActorContextHandleAdapter = class {
3801
4068
  }
3802
4069
  return this.#sql;
3803
4070
  }
4071
+ async actorUds() {
4072
+ return await this.#runtime.actorUdsProvision(this.#ctx);
4073
+ }
3804
4074
  get db() {
3805
4075
  if (!this.#databaseProvider) {
3806
4076
  throw databaseNotConfiguredError();
3807
4077
  }
3808
- if (!this.#dbProxy) {
3809
- this.#dbProxy = new Proxy(
3810
- {},
3811
- {
3812
- get: (_target, property) => {
3813
- if (property === "then") {
3814
- return void 0;
3815
- }
3816
- return async (...args) => {
3817
- const client = await this.ensureDatabaseClient();
3818
- const value = Reflect.get(
3819
- client,
3820
- property
3821
- );
3822
- if (typeof value !== "function") {
3823
- return value;
3824
- }
3825
- return await value.apply(client, args);
3826
- };
3827
- }
3828
- }
3829
- );
4078
+ if (this.#db) {
4079
+ return this.#db;
4080
+ }
4081
+ const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4082
+ const cachedClient = runtimeState.databaseClient;
4083
+ if (cachedClient) {
4084
+ this.#db = cachedClient.client;
4085
+ return this.#db;
3830
4086
  }
3831
- return this.#dbProxy;
4087
+ throw databaseClientNotReadyError();
4088
+ }
4089
+ [RAW_STATE_SYMBOL]() {
4090
+ if (!this.#stateEnabled) {
4091
+ throw stateNotEnabledError();
4092
+ }
4093
+ return this.#readState();
3832
4094
  }
3833
4095
  get state() {
3834
4096
  if (!this.#stateEnabled) {
3835
4097
  throw stateNotEnabledError();
3836
4098
  }
4099
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3837
4100
  const nextState = this.#readState();
3838
- return createWriteThroughProxy(
3839
- nextState,
3840
- (nextValue) => {
3841
- this.#writeState(nextValue, { scheduleSave: true });
3842
- },
3843
- () => {
3844
- this.#assertCanMutateState();
3845
- }
3846
- );
4101
+ if (actorState.stateProxy === void 0 || actorState.stateProxyTarget !== nextState) {
4102
+ actorState.stateProxyTarget = nextState;
4103
+ actorState.stateProxy = createWriteThroughProxy(
4104
+ nextState,
4105
+ (nextValue) => {
4106
+ this.#writeState(nextValue, { scheduleSave: true });
4107
+ },
4108
+ (newValue) => {
4109
+ this.#assertCanMutateState();
4110
+ assertJsonCompatValue(newValue);
4111
+ }
4112
+ );
4113
+ }
4114
+ return actorState.stateProxy;
3847
4115
  }
3848
4116
  set state(value) {
3849
4117
  if (!this.#stateEnabled) {
3850
4118
  throw stateNotEnabledError();
3851
4119
  }
3852
4120
  this.#assertCanMutateState();
4121
+ assertJsonCompatValue(value);
3853
4122
  this.#writeState(value, { scheduleSave: true });
3854
4123
  }
3855
4124
  initializeState(value) {
@@ -3906,25 +4175,14 @@ var ActorContextHandleAdapter = class {
3906
4175
  return callNativeSync(() => this.#runtime.actorRegion(this.#ctx));
3907
4176
  }
3908
4177
  get conns() {
3909
- return new Map(
3910
- callNativeSync(() => this.#runtime.actorConns(this.#ctx)).map(
3911
- (conn) => [
3912
- this.#runtime.connId(conn),
3913
- new NativeConnAdapter(
3914
- this.#runtime,
3915
- conn,
3916
- this.#schemas,
3917
- this.#ctx,
3918
- (connId) => callNativeSync(
3919
- () => this.#runtime.actorQueueHibernationRemoval(
3920
- this.#ctx,
3921
- connId
3922
- )
3923
- )
3924
- )
3925
- ]
3926
- )
3927
- );
4178
+ if (!this.#connMap) {
4179
+ this.#connMap = new NativeConnectionMap(
4180
+ this.#runtime,
4181
+ this.#ctx,
4182
+ this.#schemas
4183
+ );
4184
+ }
4185
+ return this.#connMap;
3928
4186
  }
3929
4187
  get log() {
3930
4188
  return logger2();
@@ -4122,40 +4380,17 @@ var ActorContextHandleAdapter = class {
4122
4380
  });
4123
4381
  }
4124
4382
  keepAwake(promise) {
4125
- const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4126
- runtimeState.keepAwakeCount = (runtimeState.keepAwakeCount ?? 0) + 1;
4127
- let registered = false;
4128
4383
  const trackedPromise = Promise.resolve(promise).catch((error) => {
4129
4384
  logger2().warn({
4130
4385
  msg: "keepAwake promise rejected",
4131
4386
  error: stringifyError(error)
4132
4387
  });
4133
- }).finally(async () => {
4134
- if (!registered) {
4135
- return;
4136
- }
4137
- runtimeState.keepAwakeCount = Math.max(
4138
- (runtimeState.keepAwakeCount ?? 1) - 1,
4139
- 0
4140
- );
4141
- if (runtimeState.keepAwakeCount === 0 && runtimeState.deferSleepCleanupUntilKeepAwakeIdle) {
4142
- await cleanupDeferredNativeSleepRuntimeState(
4143
- this.#runtime,
4144
- this.#ctx,
4145
- runtimeState
4146
- );
4147
- }
4148
4388
  }).then(() => null);
4149
4389
  try {
4150
4390
  callNativeSync(
4151
4391
  () => this.#runtime.actorKeepAwake(this.#ctx, trackedPromise)
4152
4392
  );
4153
- registered = true;
4154
4393
  } catch (error) {
4155
- runtimeState.keepAwakeCount = Math.max(
4156
- (runtimeState.keepAwakeCount ?? 1) - 1,
4157
- 0
4158
- );
4159
4394
  if (!isClosedTaskRegistrationError(error)) {
4160
4395
  throw error;
4161
4396
  }
@@ -4168,7 +4403,10 @@ var ActorContextHandleAdapter = class {
4168
4403
  }
4169
4404
  internalKeepAwake(run) {
4170
4405
  const promise = typeof run === "function" ? run() : run;
4171
- const trackedPromise = promise.then(() => null);
4406
+ const trackedPromise = promise.then(
4407
+ () => null,
4408
+ () => null
4409
+ );
4172
4410
  try {
4173
4411
  callNativeSync(
4174
4412
  () => this.#runtime.actorRegisterTask(this.#ctx, trackedPromise)
@@ -4224,6 +4462,7 @@ var ActorContextHandleAdapter = class {
4224
4462
  return false;
4225
4463
  }
4226
4464
  sleep() {
4465
+ this.#flushStateChange();
4227
4466
  callNativeSync(() => this.#runtime.actorSleep(this.#ctx));
4228
4467
  }
4229
4468
  destroy() {
@@ -4241,6 +4480,7 @@ var ActorContextHandleAdapter = class {
4241
4480
  }
4242
4481
  async dispose() {
4243
4482
  var _a;
4483
+ this.#flushStateChange();
4244
4484
  (_a = this.#abortSignalCleanup) == null ? void 0 : _a.call(this);
4245
4485
  this.#sql = void 0;
4246
4486
  }
@@ -4268,13 +4508,12 @@ var ActorContextHandleAdapter = class {
4268
4508
  return actorState.state;
4269
4509
  }
4270
4510
  #writeState(value, options) {
4271
- encodeValue(value);
4272
4511
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4273
4512
  actorState.state = value;
4274
4513
  if (!options.scheduleSave) {
4275
4514
  return;
4276
4515
  }
4277
- this.#handleStateChange();
4516
+ this.#scheduleSave();
4278
4517
  }
4279
4518
  #assertCanMutateState() {
4280
4519
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -4282,9 +4521,31 @@ var ActorContextHandleAdapter = class {
4282
4521
  throw stateMutationReentrantError();
4283
4522
  }
4284
4523
  }
4285
- #handleStateChange() {
4524
+ // Coalesce the request-save and onStateChange work to once per event loop
4525
+ // tick. A synchronous burst of mutations (for example
4526
+ // `Object.assign(c.state, ...)`) would otherwise cross the NAPI boundary and
4527
+ // run onStateChange once per field, re-serializing the whole state each time
4528
+ // and pinning the event loop on large state.
4529
+ #scheduleSave() {
4286
4530
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4287
- encodeValue(actorState.state);
4531
+ if (actorState.saveScheduled) {
4532
+ return;
4533
+ }
4534
+ actorState.saveScheduled = true;
4535
+ actorState.pendingSaveHandle = setImmediate(() => {
4536
+ this.#flushStateChange();
4537
+ });
4538
+ }
4539
+ #flushStateChange() {
4540
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
4541
+ if (!actorState.saveScheduled) {
4542
+ return;
4543
+ }
4544
+ actorState.saveScheduled = false;
4545
+ if (actorState.pendingSaveHandle !== void 0) {
4546
+ clearImmediate(actorState.pendingSaveHandle);
4547
+ actorState.pendingSaveHandle = void 0;
4548
+ }
4288
4549
  callNativeSync(
4289
4550
  () => this.#runtime.actorRequestSave(this.#ctx, { immediate: false })
4290
4551
  );
@@ -4462,40 +4723,7 @@ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databa
4462
4723
  }
4463
4724
  );
4464
4725
  }
4465
- function buildNativeRequestErrorResponse(encoding, path, error) {
4466
- const { statusCode, group, code, message, metadata } = deconstructError(
4467
- error,
4468
- logger2(),
4469
- {
4470
- path,
4471
- runtime: "native"
4472
- },
4473
- false
4474
- );
4475
- const body = serializeWithEncoding(
4476
- encoding,
4477
- { group, code, message, metadata },
4478
- HTTP_RESPONSE_ERROR_VERSIONED,
4479
- CURRENT_VERSION,
4480
- HttpResponseErrorSchema,
4481
- (value) => value,
4482
- (value) => ({
4483
- group: value.group,
4484
- code: value.code,
4485
- message: value.message,
4486
- metadata: value.metadata === void 0 ? null : runtimeBytesToArrayBuffer(
4487
- encodeCborCompat(value.metadata)
4488
- )
4489
- })
4490
- );
4491
- return new Response(body, {
4492
- status: statusCode,
4493
- headers: {
4494
- "Content-Type": contentTypeForEncoding(encoding)
4495
- }
4496
- });
4497
- }
4498
- function buildActorConfig(definition, registryConfig) {
4726
+ function buildActorConfig(definition, registryConfig, runtimeKind) {
4499
4727
  const config = definition.config;
4500
4728
  const options = config.options ?? {};
4501
4729
  const canHibernate = options.canHibernateWebSocket;
@@ -4504,6 +4732,7 @@ function buildActorConfig(definition, registryConfig) {
4504
4732
  icon: options.icon,
4505
4733
  hasDatabase: config.db !== void 0,
4506
4734
  remoteSqlite: config.db !== void 0 && sqliteBackendForConfig(registryConfig) === "remote",
4735
+ experimentalActorUds: registryConfig.experimentalActorUds,
4507
4736
  hasState: config.state !== void 0 || typeof config.createState === "function",
4508
4737
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
4509
4738
  stateSaveIntervalMs: options.stateSaveInterval,
@@ -4524,9 +4753,79 @@ function buildActorConfig(definition, registryConfig) {
4524
4753
  maxOutgoingMessageSize: registryConfig.maxOutgoingMessageSize,
4525
4754
  preloadMaxWorkflowBytes: options.preloadMaxWorkflowBytes,
4526
4755
  preloadMaxConnectionsBytes: options.preloadMaxConnectionsBytes,
4527
- actions: Object.keys(config.actions ?? {}).sort().map((name) => ({ name }))
4756
+ actions: Object.keys(config.actions ?? {}).sort().map((name) => ({ name })),
4757
+ inspectorTabs: buildInspectorTabs(config.inspector, runtimeKind)
4528
4758
  };
4529
4759
  }
4760
+ function buildInspectorTabs(inspector, runtimeKind) {
4761
+ if (!inspector || typeof inspector !== "object") return void 0;
4762
+ const tabs = inspector.tabs;
4763
+ if (!Array.isArray(tabs) || tabs.length === 0) return void 0;
4764
+ return tabs.map((raw) => {
4765
+ const entry = raw;
4766
+ if (entry.hidden === true) {
4767
+ return { id: entry.id, hidden: true };
4768
+ }
4769
+ if (runtimeKind === "wasm") {
4770
+ if (entry.source !== void 0) {
4771
+ logger2().warn(
4772
+ {
4773
+ tabId: entry.id,
4774
+ runtimeKind
4775
+ },
4776
+ "inspector.tabs[].source is not supported on wasm runners (current host: wasm). Tab descriptors will still appear in the dashboard strip but the tab body will render a not-available placeholder."
4777
+ );
4778
+ }
4779
+ return {
4780
+ id: entry.id,
4781
+ label: entry.label,
4782
+ icon: entry.icon,
4783
+ source: void 0
4784
+ };
4785
+ }
4786
+ const resolved = entry.source !== void 0 ? getNodePath().resolve(entry.source) : void 0;
4787
+ if (resolved !== void 0) {
4788
+ validateInspectorTabSource(entry.id, resolved);
4789
+ }
4790
+ return {
4791
+ id: entry.id,
4792
+ label: entry.label,
4793
+ icon: entry.icon,
4794
+ source: resolved
4795
+ };
4796
+ });
4797
+ }
4798
+ function validateInspectorTabSource(tabId, resolved) {
4799
+ if (resolved === getNodePath().parse(resolved).root) {
4800
+ throw new Error(
4801
+ `inspector.tabs[id="${tabId}"].source resolves to the filesystem root (${resolved}). Point it at the tab's own static-asset directory instead.`
4802
+ );
4803
+ }
4804
+ let stat;
4805
+ try {
4806
+ stat = getNodeFsSync().statSync(resolved);
4807
+ } catch (err) {
4808
+ const code = err == null ? void 0 : err.code;
4809
+ if (code === "ENOENT") {
4810
+ throw new Error(
4811
+ `inspector.tabs[id="${tabId}"].source (${resolved}) does not exist.`
4812
+ );
4813
+ }
4814
+ if (code === "EACCES") {
4815
+ throw new Error(
4816
+ `inspector.tabs[id="${tabId}"].source (${resolved}) is not readable (EACCES).`
4817
+ );
4818
+ }
4819
+ throw new Error(
4820
+ `inspector.tabs[id="${tabId}"].source (${resolved}) could not be stat'd: ${(err == null ? void 0 : err.message) ?? err}`
4821
+ );
4822
+ }
4823
+ if (!stat.isDirectory()) {
4824
+ throw new Error(
4825
+ `inspector.tabs[id="${tabId}"].source (${resolved}) must be a directory, got ${stat.isFile() ? "file" : "non-directory"}.`
4826
+ );
4827
+ }
4828
+ }
4530
4829
  function buildNativeFactory(runtime, registryConfig, definition) {
4531
4830
  var _a;
4532
4831
  const config = definition.config;
@@ -4618,13 +4917,16 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4618
4917
  }
4619
4918
  );
4620
4919
  };
4621
- try {
4622
- await runtime.actorVerifyInspectorAuth(
4623
- ctx,
4624
- ((_a2 = jsRequest.headers.get("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")) ?? null
4625
- );
4626
- } catch (error) {
4627
- return errorResponse(error, 401);
4920
+ const isPublicPerActorPath = jsRequest.method === "GET" && url.pathname.startsWith("/inspector/custom-tabs/");
4921
+ if (!isPublicPerActorPath) {
4922
+ try {
4923
+ await runtime.actorVerifyInspectorAuth(
4924
+ ctx,
4925
+ ((_a2 = jsRequest.headers.get("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")) ?? null
4926
+ );
4927
+ } catch (error) {
4928
+ return errorResponse(error, 401);
4929
+ }
4628
4930
  }
4629
4931
  const workflowHistory = () => {
4630
4932
  var _a3;
@@ -4691,6 +4993,47 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4691
4993
  messages
4692
4994
  });
4693
4995
  }
4996
+ if (url.pathname === "/inspector/queue" && jsRequest.method === "DELETE") {
4997
+ await runtime.actorQueueReset(ctx);
4998
+ return jsonResponse({});
4999
+ }
5000
+ if (url.pathname === "/inspector/queue" && jsRequest.method === "POST") {
5001
+ let body;
5002
+ try {
5003
+ body = await jsRequest.json();
5004
+ } catch {
5005
+ return errorResponse(
5006
+ new RivetError(
5007
+ "actor",
5008
+ "invalid_request",
5009
+ "Invalid inspector JSON body",
5010
+ { public: true }
5011
+ ),
5012
+ 400
5013
+ );
5014
+ }
5015
+ const name = body.name ?? "";
5016
+ if (name === "") {
5017
+ return errorResponse(
5018
+ new RivetError(
5019
+ "actor",
5020
+ "invalid_request",
5021
+ "Queue message name must not be empty",
5022
+ { public: true }
5023
+ ),
5024
+ 400
5025
+ );
5026
+ }
5027
+ const cbor = encodeCborCompat(
5028
+ body.body ?? null
5029
+ );
5030
+ const message = await runtime.actorQueueSend(ctx, name, cbor);
5031
+ return jsonResponse({
5032
+ id: message.id().toString(),
5033
+ name: message.name(),
5034
+ createdAtMs: message.createdAt()
5035
+ });
5036
+ }
4694
5037
  if (url.pathname === "/inspector/traces" && jsRequest.method === "GET") {
4695
5038
  return jsonResponse({ otlp: [], clamped: false });
4696
5039
  }
@@ -4715,6 +5058,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4715
5058
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0
4716
5059
  });
4717
5060
  } catch (error) {
5061
+ logger2().error({
5062
+ msg: "error replaying workflow history",
5063
+ error
5064
+ });
4718
5065
  return errorResponse(error);
4719
5066
  }
4720
5067
  }
@@ -4855,17 +5202,34 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4855
5202
  );
4856
5203
  }
4857
5204
  const body = await jsRequest.json();
5205
+ if (body.args !== void 0 && body.properties !== void 0) {
5206
+ return jsonResponse(
5207
+ { error: "use either args or properties, not both" },
5208
+ { status: 400 }
5209
+ );
5210
+ }
5211
+ if (body.properties !== void 0 && (body.properties === null || typeof body.properties !== "object" || Array.isArray(body.properties))) {
5212
+ return jsonResponse(
5213
+ { error: "properties must be an object" },
5214
+ { status: 400 }
5215
+ );
5216
+ }
5217
+ const args = body.properties !== void 0 ? [body.properties] : normalizeArgs(body.args);
4858
5218
  try {
4859
5219
  const output = await action(
4860
5220
  actorCtx,
4861
5221
  ...validateActionArgs(
4862
5222
  schemaConfig.actionInputSchemas,
4863
5223
  actionName,
4864
- body.args ?? []
5224
+ args
4865
5225
  )
4866
5226
  );
4867
5227
  return jsonResponse({ output });
4868
5228
  } catch (error) {
5229
+ logger2().error({
5230
+ msg: "Error handling inspector action request",
5231
+ error
5232
+ });
4869
5233
  return errorResponse(error);
4870
5234
  }
4871
5235
  }
@@ -4879,6 +5243,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4879
5243
  { status: 404 }
4880
5244
  );
4881
5245
  } catch (error) {
5246
+ logger2().error({
5247
+ msg: "Error handling inspector request",
5248
+ error
5249
+ });
4882
5250
  return errorResponse(error);
4883
5251
  } finally {
4884
5252
  await actorCtx.dispose();
@@ -5001,28 +5369,31 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5001
5369
  async (error, payload) => {
5002
5370
  const { ctx } = unwrapTsfnPayload(error, payload);
5003
5371
  const actorCtx = makeActorCtx(ctx);
5372
+ const saveActorState = async () => {
5373
+ if (runtime.kind === "wasm") {
5374
+ await runtime.actorSaveState(
5375
+ ctx,
5376
+ actorCtx.serializeForTick("save")
5377
+ );
5378
+ } else {
5379
+ await actorCtx.saveState({
5380
+ immediate: true
5381
+ });
5382
+ }
5383
+ };
5004
5384
  try {
5005
5385
  if (onSleep) {
5006
- try {
5007
- await onSleep(actorCtx);
5008
- } finally {
5009
- if (runtime.kind === "wasm") {
5010
- await runtime.actorSaveState(
5011
- ctx,
5012
- actorCtx.serializeForTick("save")
5013
- );
5014
- } else {
5015
- await actorCtx.saveState({ immediate: true });
5016
- }
5017
- }
5386
+ await onSleep(actorCtx);
5018
5387
  }
5388
+ await saveActorState();
5019
5389
  } finally {
5020
- const runtimeState = getNativeRuntimeState(runtime, ctx);
5021
- if ((runtimeState.keepAwakeCount ?? 0) > 0) {
5022
- runtimeState.deferSleepCleanupUntilKeepAwakeIdle = true;
5023
- runtimeState.deferredSleepCleanupActorCtx = actorCtx;
5024
- } else {
5025
- await cleanupNativeSleepRuntimeState(runtime, ctx);
5390
+ try {
5391
+ await cleanupNativeSleepRuntimeState(
5392
+ runtime,
5393
+ ctx,
5394
+ saveActorState
5395
+ );
5396
+ } finally {
5026
5397
  await actorCtx.dispose();
5027
5398
  }
5028
5399
  }
@@ -5037,6 +5408,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5037
5408
  await config.onDestroy(actorCtx);
5038
5409
  }
5039
5410
  } finally {
5411
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
5412
+ nativeRunHandlerActiveByActorId.delete(actorId);
5413
+ disposeRunInspector(config.run, actorId);
5040
5414
  resolveNativeDestroy(runtime, ctx);
5041
5415
  await actorCtx.closeDatabase();
5042
5416
  clearNativeRuntimeState(runtime, ctx);
@@ -5263,17 +5637,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5263
5637
  );
5264
5638
  }
5265
5639
  return await toRuntimeHttpResponse(response);
5266
- } catch (error2) {
5267
- const encodingHeader = jsRequest.headers.get(HEADER_ENCODING);
5268
- const encoding = encodingHeader === "cbor" || encodingHeader === "bare" ? encodingHeader : "json";
5269
- const path = new URL(jsRequest.url).pathname;
5270
- return await toRuntimeHttpResponse(
5271
- buildNativeRequestErrorResponse(
5272
- encoding,
5273
- path,
5274
- error2
5275
- )
5276
- );
5277
5640
  } finally {
5278
5641
  await (requestCtx == null ? void 0 : requestCtx.dispose());
5279
5642
  if (conn) {
@@ -5321,7 +5684,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5321
5684
  try {
5322
5685
  await run(actorCtx);
5323
5686
  } finally {
5324
- nativeRunHandlerActiveByActorId.set(actorId, false);
5687
+ nativeRunHandlerActiveByActorId.delete(actorId);
5325
5688
  await actorCtx.dispose();
5326
5689
  }
5327
5690
  }
@@ -5454,7 +5817,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5454
5817
  };
5455
5818
  return runtime.createActorFactory(
5456
5819
  callbacks,
5457
- buildActorConfig(definition, registryConfig)
5820
+ buildActorConfig(definition, registryConfig, runtime.kind)
5458
5821
  );
5459
5822
  }
5460
5823
  async function buildServeConfig(config) {
@@ -5477,10 +5840,17 @@ async function buildServeConfig(config) {
5477
5840
  serverlessValidateEndpoint: config.validateServerlessEndpoint,
5478
5841
  serverlessMaxStartPayloadBytes: config.serverless.maxStartPayloadBytes
5479
5842
  };
5480
- if (config.startEngine) {
5843
+ try {
5481
5844
  const { getEnginePath } = await loadEngineCli();
5482
5845
  serveConfig.engineBinaryPath = getEnginePath();
5846
+ } catch (error) {
5847
+ logger2().warn({
5848
+ msg: "could not resolve a local engine binary; if a local engine must be spawned it will fail with engine.binary_unavailable \u2014 set RIVET_ENGINE_BINARY_PATH or install the @rivetkit/engine-cli platform package",
5849
+ error: stringifyError(error)
5850
+ });
5483
5851
  }
5852
+ serveConfig.engineHost = config.engineHost;
5853
+ serveConfig.enginePort = config.enginePort;
5484
5854
  if ((_a = config.test) == null ? void 0 : _a.enabled) {
5485
5855
  serveConfig.inspectorTestToken = getEnvUniversal("_RIVET_TEST_INSPECTOR_TOKEN") ?? "token";
5486
5856
  }
@@ -5491,6 +5861,9 @@ async function buildRegistryWithRuntime(config, runtime) {
5491
5861
  if (((_a = config.test) == null ? void 0 : _a.enabled) && getEnvUniversal("_RIVET_TEST_INSPECTOR_TOKEN") === void 0) {
5492
5862
  trySetProcessEnv("_RIVET_TEST_INSPECTOR_TOKEN", "token");
5493
5863
  }
5864
+ if (runtime.kind === "napi") {
5865
+ importNodeDependencies();
5866
+ }
5494
5867
  const registry = runtime.createRegistry();
5495
5868
  for (const [name, definition] of Object.entries(config.use)) {
5496
5869
  runtime.registerActor(
@@ -5514,8 +5887,24 @@ async function buildConfiguredRegistry(config) {
5514
5887
  }
5515
5888
 
5516
5889
  // src/registry/index.ts
5890
+ function signalExitCode(signal) {
5891
+ switch (signal) {
5892
+ case "SIGINT":
5893
+ return 130;
5894
+ case "SIGTERM":
5895
+ return 143;
5896
+ }
5897
+ }
5898
+ function finishShutdownSignal(signal) {
5899
+ if (process.pid === 1) {
5900
+ process.exit(signalExitCode(signal));
5901
+ }
5902
+ process.kill(process.pid, signal);
5903
+ }
5517
5904
  var Registry = class {
5518
5905
  #config;
5906
+ #buildConfiguredRegistry;
5907
+ routes;
5519
5908
  get config() {
5520
5909
  return this.#config;
5521
5910
  }
@@ -5530,18 +5919,34 @@ var Registry = class {
5530
5919
  #shutdownInstalled = false;
5531
5920
  #shutdownInFlight = null;
5532
5921
  #signalHandlers = {};
5533
- constructor(config) {
5922
+ constructor(config, deps) {
5923
+ var _a;
5534
5924
  this.#config = config;
5925
+ if ((_a = config.logging) == null ? void 0 : _a.baseLogger) {
5926
+ configureBaseLogger(config.logging.baseLogger);
5927
+ }
5928
+ this.#buildConfiguredRegistry = (deps == null ? void 0 : deps.buildConfiguredRegistry) ?? buildConfiguredRegistry;
5929
+ this.routes = {
5930
+ health: () => this.#healthRoute(),
5931
+ metadata: () => this.#metadataRoute(),
5932
+ prometheusMetrics: (request) => this.#prometheusMetricsRoute(request)
5933
+ };
5535
5934
  }
5935
+ /**
5936
+ * Fires `configureServerlessPool` once per process when the registry
5937
+ * config opts into it. Cached on the instance so repeated calls (from
5938
+ * `handler()` and `listen()`) only run the upsert once. The retry loop
5939
+ * inside `configureServerlessPool` tolerates the engine still warming up.
5940
+ */
5536
5941
  #ensureServerlessPoolConfigured(config) {
5537
5942
  if (!config.configurePool) return void 0;
5538
5943
  if (!this.#configureServerlessPoolPromise) {
5539
- this.#configureServerlessPoolPromise = configureServerlessPool(config).catch(
5540
- (error) => {
5541
- this.#configureServerlessPoolPromise = void 0;
5542
- throw error;
5543
- }
5544
- );
5944
+ this.#configureServerlessPoolPromise = configureServerlessPool(
5945
+ config
5946
+ ).catch((error) => {
5947
+ this.#configureServerlessPoolPromise = void 0;
5948
+ throw error;
5949
+ });
5545
5950
  this.#configureServerlessPoolPromise.catch(() => {
5546
5951
  });
5547
5952
  }
@@ -5562,7 +5967,7 @@ var Registry = class {
5562
5967
  const config = this.parseConfig();
5563
5968
  this.#printWelcome(config, "serverless");
5564
5969
  if (!this.#runtimeServerlessPromise) {
5565
- this.#runtimeServerlessPromise = buildConfiguredRegistry(config);
5970
+ this.#runtimeServerlessPromise = this.#buildConfiguredRegistry(config);
5566
5971
  }
5567
5972
  const { runtime, registry, serveConfig } = await this.#runtimeServerlessPromise;
5568
5973
  const isStartRequest = isServerlessStartRequest(
@@ -5577,7 +5982,7 @@ var Registry = class {
5577
5982
  if (isStartRequest) {
5578
5983
  try {
5579
5984
  await this.#ensureServerlessPoolConfigured(config);
5580
- } catch (error) {
5985
+ } catch (_error) {
5581
5986
  return new Response(
5582
5987
  JSON.stringify({
5583
5988
  group: "guard",
@@ -5691,7 +6096,7 @@ var Registry = class {
5691
6096
  if (isMetadataRequest && !isEngineMetadataRequest) {
5692
6097
  try {
5693
6098
  await this.#ensureServerlessPoolConfigured(config);
5694
- } catch (error) {
6099
+ } catch (_error) {
5695
6100
  return new Response(
5696
6101
  JSON.stringify({
5697
6102
  group: "guard",
@@ -5724,40 +6129,147 @@ var Registry = class {
5724
6129
  fetch: (request) => this.handler(request)
5725
6130
  };
5726
6131
  }
5727
- async diagnostics() {
5728
- var _a;
6132
+ /**
6133
+ * Bind an HTTP listener provided by the native (Rust) runtime and serve
6134
+ * the registry's serverless endpoints over it. Resolves only after the
6135
+ * registry is shut down (SIGINT/SIGTERM or `nativeRegistry.shutdown()`).
6136
+ *
6137
+ * @param opts.port Port to listen on. Defaults to `process.env.RIVET_PORT`
6138
+ * if set, otherwise 3000.
6139
+ * @param opts.host Address to bind. Defaults to `0.0.0.0`.
6140
+ * @param opts.publicDir If set, serves static files from this directory
6141
+ * as a fallback below the framework routes.
6142
+ *
6143
+ * @example
6144
+ * ```ts
6145
+ * await registry.listen();
6146
+ * await registry.listen({ port: 8080, publicDir: "./public" });
6147
+ * ```
6148
+ */
6149
+ async listen(opts = {}) {
6150
+ const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3e3;
6151
+ const publicDir = opts.publicDir ?? getRivetkitPublicDir();
6152
+ const config = this.parseConfig();
6153
+ const configuredRegistryPromise = buildConfiguredRegistry(config);
6154
+ this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
6155
+ this.#runtimeServerlessPromise = configuredRegistryPromise;
6156
+ this.#installSignalHandlers(config);
6157
+ this.#printWelcome(config, "serverless", {
6158
+ port,
6159
+ host: opts.host,
6160
+ publicDir
6161
+ });
6162
+ this.#ensureServerlessPoolConfigured(config);
6163
+ const { runtime, registry, serveConfig } = await configuredRegistryPromise;
6164
+ await runtime.serveListener(
6165
+ registry,
6166
+ { port, host: opts.host, publicDir },
6167
+ serveConfig
6168
+ );
6169
+ }
6170
+ /**
6171
+ * Returns a health response suitable for mounting in a user-owned router.
6172
+ */
6173
+ async #healthRoute() {
6174
+ const configured = await this.#activeConfiguredRegistry();
6175
+ if (!configured) {
6176
+ return jsonRouteResponse(503, {
6177
+ status: "not_started",
6178
+ runtime: "rivetkit",
6179
+ version: VERSION
6180
+ });
6181
+ }
6182
+ const { runtime, registry } = configured;
6183
+ if (!runtime.registryHealth) {
6184
+ return jsonRouteResponse(501, {
6185
+ status: "unsupported",
6186
+ runtime: "rivetkit",
6187
+ version: VERSION
6188
+ });
6189
+ }
6190
+ const response = await runtime.registryHealth(registry);
6191
+ return new Response(new Uint8Array(response.body), {
6192
+ status: response.status,
6193
+ headers: response.headers
6194
+ });
6195
+ }
6196
+ /**
6197
+ * Returns serverless metadata suitable for mounting in a user-owned router.
6198
+ */
6199
+ async #metadataRoute() {
6200
+ const configured = await this.#activeConfiguredRegistry();
6201
+ if (!configured) {
6202
+ return new Response("registry not started\n", {
6203
+ status: 503,
6204
+ headers: { "content-type": "text/plain; charset=utf-8" }
6205
+ });
6206
+ }
6207
+ const { runtime, registry } = configured;
6208
+ if (!runtime.registryMetadata) {
6209
+ return new Response("metadata is not supported by this runtime\n", {
6210
+ status: 501,
6211
+ headers: { "content-type": "text/plain; charset=utf-8" }
6212
+ });
6213
+ }
6214
+ const response = await runtime.registryMetadata(registry);
6215
+ return new Response(new Uint8Array(response.body), {
6216
+ status: response.status,
6217
+ headers: response.headers
6218
+ });
6219
+ }
6220
+ /**
6221
+ * Returns a Prometheus metrics response suitable for mounting in a user-owned router.
6222
+ */
6223
+ async #prometheusMetricsRoute(_request) {
6224
+ const configured = await this.#activeConfiguredRegistry();
6225
+ if (!configured) {
6226
+ return new Response("registry not started\n", {
6227
+ status: 503,
6228
+ headers: { "content-type": "text/plain; charset=utf-8" }
6229
+ });
6230
+ }
6231
+ const { runtime, registry } = configured;
6232
+ if (!runtime.registryMetrics) {
6233
+ return new Response("metrics are not supported by this runtime\n", {
6234
+ status: 501,
6235
+ headers: { "content-type": "text/plain; charset=utf-8" }
6236
+ });
6237
+ }
6238
+ const response = await runtime.registryMetrics(registry);
6239
+ return new Response(new Uint8Array(response.body), {
6240
+ status: response.status,
6241
+ headers: response.headers
6242
+ });
6243
+ }
6244
+ async #activeConfiguredRegistry() {
5729
6245
  const candidates = [
5730
6246
  this.#runtimeServerlessPromise,
5731
6247
  this.#runtimeServeConfiguredPromise
5732
6248
  ].filter(
5733
6249
  (candidate) => candidate !== void 0
5734
6250
  );
5735
- for (const candidate of candidates) {
5736
- const { runtime, registry } = await candidate;
5737
- const diagnostics = await ((_a = runtime.registryDiagnostics) == null ? void 0 : _a.call(runtime, registry));
5738
- if (diagnostics) return diagnostics;
5739
- }
5740
- return { mode: "not_started", envoyActiveActorCount: null };
6251
+ if (candidates.length === 0) return void 0;
6252
+ return await candidates[0];
5741
6253
  }
5742
6254
  /**
5743
6255
  * Starts an actor envoy for standalone server deployments.
5744
6256
  */
5745
6257
  #startEnvoy(config, printWelcome) {
5746
6258
  if (!this.#runtimeServePromise) {
5747
- const configuredRegistryPromise = buildConfiguredRegistry(config);
6259
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config);
5748
6260
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
5749
6261
  this.#runtimeServePromise = configuredRegistryPromise.then(async ({ runtime, registry, serveConfig }) => {
5750
6262
  await runtime.serveRegistry(registry, serveConfig);
5751
- }).catch((err) => {
5752
- logger2().warn({ err }, "runtime registry serve errored");
6263
+ }).catch((error) => {
6264
+ logger2().warn({ error }, "runtime registry serve errored");
5753
6265
  });
5754
- this.#installSignalHandlers(config, configuredRegistryPromise);
6266
+ this.#installSignalHandlers(config);
5755
6267
  }
5756
6268
  if (printWelcome) {
5757
6269
  this.#printWelcome(config, "serverful");
5758
6270
  }
5759
6271
  }
5760
- #installSignalHandlers(config, configuredRegistryPromise) {
6272
+ #installSignalHandlers(config) {
5761
6273
  var _a;
5762
6274
  if (this.#shutdownInstalled) return;
5763
6275
  if ((_a = config.shutdown) == null ? void 0 : _a.disableSignalHandlers) return;
@@ -5766,58 +6278,86 @@ var Registry = class {
5766
6278
  }
5767
6279
  this.#shutdownInstalled = true;
5768
6280
  const install = (signal) => {
5769
- const handler = () => this.#onShutdownSignal(
5770
- signal,
5771
- config,
5772
- configuredRegistryPromise
5773
- );
6281
+ const handler = () => this.#onShutdownSignal(signal, config);
5774
6282
  this.#signalHandlers[signal] = handler;
5775
6283
  process.on(signal, handler);
5776
6284
  };
5777
6285
  install("SIGINT");
5778
6286
  install("SIGTERM");
5779
6287
  }
5780
- #onShutdownSignal(signal, config, configuredRegistryPromise) {
6288
+ #onShutdownSignal(signal, config) {
5781
6289
  if (this.#shutdownInFlight !== null) {
5782
6290
  this.#removeSignalHandlers();
5783
- process.kill(process.pid, signal);
6291
+ finishShutdownSignal(signal);
5784
6292
  return;
5785
6293
  }
5786
- this.#shutdownInFlight = this.#runShutdown(
5787
- signal,
5788
- config,
5789
- configuredRegistryPromise
5790
- ).catch((err) => {
6294
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
5791
6295
  logger2().warn({ err }, "shutdown error");
6296
+ }).then(() => {
6297
+ this.#removeSignalHandlers();
6298
+ finishShutdownSignal(signal);
5792
6299
  });
5793
6300
  }
5794
- async #runShutdown(signal, config, configuredRegistryPromise) {
6301
+ /**
6302
+ * Gracefully drains all live registries.
6303
+ *
6304
+ * Programmatic counterpart to the SIGINT/SIGTERM handlers: tears down
6305
+ * every live `CoreRegistry` (both `start()` and `handler()` modes) and
6306
+ * waits for the serve promise to resolve, all bounded by the shutdown
6307
+ * grace period. Unlike a signal-driven shutdown, this does not re-raise a
6308
+ * signal or exit the process. The caller owns process lifetime.
6309
+ *
6310
+ * Idempotent: concurrent or repeated calls share a single drain. Safe to
6311
+ * call even if nothing has been started.
6312
+ *
6313
+ * @example
6314
+ * ```ts
6315
+ * const registry = setup({ use: { counter } });
6316
+ * registry.start();
6317
+ * // ...later, on your own shutdown trigger:
6318
+ * await registry.shutdown();
6319
+ * ```
6320
+ */
6321
+ async shutdown() {
6322
+ if (this.#shutdownInFlight !== null) return this.#shutdownInFlight;
6323
+ const config = this.parseConfig();
6324
+ this.#removeSignalHandlers();
6325
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
6326
+ logger2().warn({ err }, "shutdown error");
6327
+ });
6328
+ return this.#shutdownInFlight;
6329
+ }
6330
+ async #drain(config) {
5795
6331
  var _a;
5796
- const gracePeriodMs = ((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs) ?? 3e4;
6332
+ const modeAPromise = this.#runtimeServeConfiguredPromise;
6333
+ const modeBPromise = this.#runtimeServerlessPromise;
6334
+ const gracePeriodMs = ((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs) ?? await this.#actorStopThresholdMs(modeAPromise ?? modeBPromise) ?? 30 * 60 * 1e3;
5797
6335
  const drain = async () => {
5798
- const registries = [
5799
- (async () => {
5800
- try {
5801
- const { runtime, registry } = await configuredRegistryPromise;
5802
- await runtime.shutdownRegistry(registry);
5803
- } catch (err) {
5804
- logger2().warn(
5805
- { err },
5806
- "runtime registry shutdown errored (mode A)"
5807
- );
5808
- }
5809
- })()
5810
- ];
5811
- const runtimeServerlessPromise = this.#runtimeServerlessPromise;
5812
- if (runtimeServerlessPromise !== void 0) {
6336
+ const registries = [];
6337
+ if (modeAPromise !== void 0) {
5813
6338
  registries.push(
5814
6339
  (async () => {
5815
6340
  try {
5816
- const { runtime, registry } = await runtimeServerlessPromise;
6341
+ const { runtime, registry } = await modeAPromise;
5817
6342
  await runtime.shutdownRegistry(registry);
5818
6343
  } catch (err) {
5819
6344
  logger2().warn(
5820
6345
  { err },
6346
+ "runtime registry shutdown errored (mode A)"
6347
+ );
6348
+ }
6349
+ })()
6350
+ );
6351
+ }
6352
+ if (modeBPromise !== void 0) {
6353
+ registries.push(
6354
+ (async () => {
6355
+ try {
6356
+ const { runtime, registry } = await modeBPromise;
6357
+ await runtime.shutdownRegistry(registry);
6358
+ } catch (err) {
6359
+ logger2().warn(
6360
+ { error: err },
5821
6361
  "runtime registry shutdown errored (mode B)"
5822
6362
  );
5823
6363
  }
@@ -5839,8 +6379,23 @@ var Registry = class {
5839
6379
  }
5840
6380
  )
5841
6381
  ]);
5842
- this.#removeSignalHandlers();
5843
- process.kill(process.pid, signal);
6382
+ }
6383
+ async #actorStopThresholdMs(configuredRegistryPromise) {
6384
+ var _a;
6385
+ if (configuredRegistryPromise === void 0) return void 0;
6386
+ try {
6387
+ const { runtime, registry } = await configuredRegistryPromise;
6388
+ const thresholdMs = await ((_a = runtime.registryActorStopThresholdMs) == null ? void 0 : _a.call(runtime, registry));
6389
+ if (thresholdMs !== void 0 && Number.isFinite(thresholdMs) && thresholdMs > 0) {
6390
+ return thresholdMs;
6391
+ }
6392
+ } catch (err) {
6393
+ logger2().warn(
6394
+ { err },
6395
+ "failed to read actor stop threshold for shutdown grace"
6396
+ );
6397
+ }
6398
+ return void 0;
5844
6399
  }
5845
6400
  #removeSignalHandlers() {
5846
6401
  for (const [signal, handler] of Object.entries(
@@ -5856,6 +6411,10 @@ var Registry = class {
5856
6411
  /**
5857
6412
  * Starts the actor envoy for standalone server deployments.
5858
6413
  *
6414
+ * Set `RIVETKIT_RUNTIME_MODE=serverless` to instead bind an HTTP listener
6415
+ * via `listen()` (Mode B). Mode A (envoy) and Mode B (listener) are
6416
+ * mutually exclusive per registry instance.
6417
+ *
5859
6418
  * @example
5860
6419
  * ```ts
5861
6420
  * const registry = setup({ use: { counter } });
@@ -5863,10 +6422,20 @@ var Registry = class {
5863
6422
  * ```
5864
6423
  */
5865
6424
  start() {
6425
+ if (getRivetkitRuntimeMode() === "serverless") {
6426
+ const publicDir = getRivetkitPublicDir() ?? "/public";
6427
+ this.listen({ publicDir }).catch((error) => {
6428
+ logger2().error({ error }, "auto-listen failed; exiting");
6429
+ if (typeof process !== "undefined" && typeof process.exit === "function") {
6430
+ process.exit(1);
6431
+ }
6432
+ });
6433
+ return;
6434
+ }
5866
6435
  const config = this.parseConfig();
5867
6436
  this.#startEnvoy(config, true);
5868
6437
  }
5869
- #printWelcome(config, kind) {
6438
+ #printWelcome(config, kind, listener) {
5870
6439
  if (config.noWelcome || this.#welcomePrinted) return;
5871
6440
  this.#welcomePrinted = true;
5872
6441
  const logLine = (label, value) => {
@@ -5881,13 +6450,20 @@ var Registry = class {
5881
6450
  logLine("Namespace", config.namespace);
5882
6451
  }
5883
6452
  if (config.endpoint) {
5884
- const endpointType = config.endpoint === ENGINE_ENDPOINT ? "local native" : "remote";
6453
+ const endpointType = config.startEngine || isLocalEngineEndpoint(config.endpoint) ? "local native" : "remote";
5885
6454
  logLine("Endpoint", `${config.endpoint} (${endpointType})`);
5886
6455
  }
5887
6456
  if (kind === "serverless" && config.publicEndpoint) {
5888
6457
  logLine("Client", config.publicEndpoint);
5889
6458
  }
5890
6459
  logLine("Actors", Object.keys(config.use).length.toString());
6460
+ if (listener) {
6461
+ const host = listener.host ?? "0.0.0.0";
6462
+ logLine("Listening", `http://${host}:${listener.port}`);
6463
+ if (listener.publicDir) {
6464
+ logLine("Public Dir", listener.publicDir);
6465
+ }
6466
+ }
5891
6467
  console.log();
5892
6468
  }
5893
6469
  };
@@ -5903,6 +6479,12 @@ function isServerlessMetadataRequest(request, basePath) {
5903
6479
  const normalizedBase = basePath === "/" ? "" : `/${basePath.replace(/^\/+|\/+$/g, "")}`;
5904
6480
  return parsed.pathname === `${normalizedBase}/metadata`;
5905
6481
  }
6482
+ function jsonRouteResponse(status, body) {
6483
+ return new Response(JSON.stringify(body), {
6484
+ status,
6485
+ headers: { "content-type": "application/json" }
6486
+ });
6487
+ }
5906
6488
  function setup(input) {
5907
6489
  return new Registry(input);
5908
6490
  }