rivetkit 0.0.0-skip-ready-wait-flatten-client-options.1cae221 → 0.0.0-sql-metrics.eac581d

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 (274) hide show
  1. package/dist/browser/client.d.ts +778 -98
  2. package/dist/browser/client.js +1415 -757
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +126 -3
  5. package/dist/browser/inspector/client.js +2067 -233
  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 +2371 -2093
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +772 -94
  15. package/dist/tsup/agent-os/index.d.ts +772 -94
  16. package/dist/tsup/agent-os/index.js +2375 -2097
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-OIKOPSXQ.js → chunk-3Q3KETKF.js} +13 -7
  19. package/dist/tsup/chunk-3Q3KETKF.js.map +1 -0
  20. package/dist/tsup/{chunk-V3QNBJ7N.cjs → chunk-4FC7TVS6.cjs} +35 -10
  21. package/dist/tsup/chunk-4FC7TVS6.cjs.map +1 -0
  22. package/dist/tsup/{chunk-XNZR7UD2.cjs → chunk-6ADBGIKV.cjs} +484 -66
  23. package/dist/tsup/chunk-6ADBGIKV.cjs.map +1 -0
  24. package/dist/tsup/{chunk-4ZIWB4CQ.js → chunk-DZ7KAOCW.js} +2 -2
  25. package/dist/tsup/{chunk-22XU3BVY.cjs → chunk-EI3JQYAW.cjs} +1083 -480
  26. package/dist/tsup/chunk-EI3JQYAW.cjs.map +1 -0
  27. package/dist/tsup/{chunk-LNMB25HW.js → chunk-FMMENOAT.js} +952 -349
  28. package/dist/tsup/chunk-FMMENOAT.js.map +1 -0
  29. package/dist/tsup/{chunk-AK57AL7S.cjs → chunk-HNHLBM3Y.cjs} +198 -19
  30. package/dist/tsup/chunk-HNHLBM3Y.cjs.map +1 -0
  31. package/dist/tsup/{chunk-D2TLG75Y.cjs → chunk-IW3TD3AZ.cjs} +10 -10
  32. package/dist/tsup/chunk-IW3TD3AZ.cjs.map +1 -0
  33. package/dist/tsup/{chunk-3BFYSYRU.js → chunk-JI6GZ2C2.js} +4 -12
  34. package/dist/tsup/chunk-JI6GZ2C2.js.map +1 -0
  35. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-JTHHCZCZ.js} +24 -1
  36. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  37. package/dist/tsup/{chunk-POTPHU3P.cjs → chunk-KTH2ZCJ7.cjs} +3 -3
  38. package/dist/tsup/chunk-KTH2ZCJ7.cjs.map +1 -0
  39. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-KVFIONKQ.cjs} +25 -2
  40. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  41. package/dist/tsup/{chunk-IOYKCB6Y.cjs → chunk-MCRNU6ZS.cjs} +46 -9
  42. package/dist/tsup/chunk-MCRNU6ZS.cjs.map +1 -0
  43. package/dist/tsup/{chunk-LLD2D5LO.cjs → chunk-MYWZCDML.cjs} +4 -12
  44. package/dist/tsup/chunk-MYWZCDML.cjs.map +1 -0
  45. package/dist/tsup/{chunk-7MRGNVSR.js → chunk-QWLJCP3X.js} +196 -17
  46. package/dist/tsup/chunk-QWLJCP3X.js.map +1 -0
  47. package/dist/tsup/{chunk-D4TSTM6C.js → chunk-VHZ2ICIB.js} +476 -58
  48. package/dist/tsup/chunk-VHZ2ICIB.js.map +1 -0
  49. package/dist/tsup/{chunk-NFC5VU36.cjs → chunk-XFAJRV5B.cjs} +17 -11
  50. package/dist/tsup/chunk-XFAJRV5B.cjs.map +1 -0
  51. package/dist/tsup/{chunk-RZEJJJKU.js → chunk-XUBFECDW.js} +45 -8
  52. package/dist/tsup/chunk-XUBFECDW.js.map +1 -0
  53. package/dist/tsup/{chunk-KSG2COSQ.js → chunk-ZKM6KFU7.js} +6 -6
  54. package/dist/tsup/chunk-ZKM6KFU7.js.map +1 -0
  55. package/dist/tsup/{chunk-K34B3OVG.js → chunk-ZZ3WBRPD.js} +34 -9
  56. package/dist/tsup/chunk-ZZ3WBRPD.js.map +1 -0
  57. package/dist/tsup/client/mod.cjs +8 -9
  58. package/dist/tsup/client/mod.cjs.map +1 -1
  59. package/dist/tsup/client/mod.d.cts +10 -10
  60. package/dist/tsup/client/mod.d.ts +10 -10
  61. package/dist/tsup/client/mod.js +7 -8
  62. package/dist/tsup/common/log.cjs +5 -3
  63. package/dist/tsup/common/log.cjs.map +1 -1
  64. package/dist/tsup/common/log.d.cts +5 -1
  65. package/dist/tsup/common/log.d.ts +5 -1
  66. package/dist/tsup/common/log.js +6 -4
  67. package/dist/tsup/common/websocket.cjs +4 -4
  68. package/dist/tsup/common/websocket.cjs.map +1 -1
  69. package/dist/tsup/common/websocket.js +3 -3
  70. package/dist/tsup/{config-kxXbtrJU.d.ts → config-BiFJvUlm.d.cts} +48 -4
  71. package/dist/tsup/{config-kxXbtrJU.d.cts → config-BiFJvUlm.d.ts} +48 -4
  72. package/dist/tsup/{config-CRdGwwbr.d.cts → config-Dc-M9yZ2.d.cts} +772 -62
  73. package/dist/tsup/{config-DIpBWm5C.d.ts → config-gT4c5si9.d.ts} +772 -62
  74. package/dist/tsup/context-DIes1x7n.d.cts +129 -0
  75. package/dist/tsup/context-DKoLp07T.d.ts +129 -0
  76. package/dist/tsup/db/drizzle.cjs +146 -72
  77. package/dist/tsup/db/drizzle.cjs.map +1 -1
  78. package/dist/tsup/db/drizzle.d.cts +8 -4
  79. package/dist/tsup/db/drizzle.d.ts +8 -4
  80. package/dist/tsup/db/drizzle.js +146 -72
  81. package/dist/tsup/db/drizzle.js.map +1 -1
  82. package/dist/tsup/db/mod.cjs +83 -18
  83. package/dist/tsup/db/mod.cjs.map +1 -1
  84. package/dist/tsup/db/mod.d.cts +12 -4
  85. package/dist/tsup/db/mod.d.ts +12 -4
  86. package/dist/tsup/db/mod.js +83 -18
  87. package/dist/tsup/db/mod.js.map +1 -1
  88. package/dist/tsup/dynamic/mod.cjs +24 -0
  89. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  90. package/dist/tsup/dynamic/mod.d.cts +37 -0
  91. package/dist/tsup/dynamic/mod.d.ts +37 -0
  92. package/dist/tsup/dynamic/mod.js +24 -0
  93. package/dist/tsup/dynamic/mod.js.map +1 -0
  94. package/dist/tsup/inspector/mod.cjs +46 -12
  95. package/dist/tsup/inspector/mod.cjs.map +1 -1
  96. package/dist/tsup/inspector/mod.d.cts +30 -6
  97. package/dist/tsup/inspector/mod.d.ts +30 -6
  98. package/dist/tsup/inspector/mod.js +45 -11
  99. package/dist/tsup/inspector/mod.js.map +1 -1
  100. package/dist/tsup/inspector-tab/mod.cjs +162 -0
  101. package/dist/tsup/inspector-tab/mod.cjs.map +1 -0
  102. package/dist/tsup/inspector-tab/mod.d.cts +240 -0
  103. package/dist/tsup/inspector-tab/mod.d.ts +240 -0
  104. package/dist/tsup/inspector-tab/mod.js +162 -0
  105. package/dist/tsup/inspector-tab/mod.js.map +1 -0
  106. package/dist/tsup/mod.cjs +1848 -538
  107. package/dist/tsup/mod.cjs.map +1 -1
  108. package/dist/tsup/mod.d.cts +6 -7
  109. package/dist/tsup/mod.d.ts +6 -7
  110. package/dist/tsup/mod.js +1778 -468
  111. package/dist/tsup/mod.js.map +1 -1
  112. package/dist/tsup/test/mod.cjs +26 -21
  113. package/dist/tsup/test/mod.cjs.map +1 -1
  114. package/dist/tsup/test/mod.d.cts +5 -6
  115. package/dist/tsup/test/mod.d.ts +5 -6
  116. package/dist/tsup/test/mod.js +25 -20
  117. package/dist/tsup/test/mod.js.map +1 -1
  118. package/dist/tsup/unstable/migrations.cjs +101 -0
  119. package/dist/tsup/unstable/migrations.cjs.map +1 -0
  120. package/dist/tsup/unstable/migrations.d.cts +29 -0
  121. package/dist/tsup/unstable/migrations.d.ts +29 -0
  122. package/dist/tsup/unstable/migrations.js +101 -0
  123. package/dist/tsup/unstable/migrations.js.map +1 -0
  124. package/dist/tsup/utils-CV0akuDD.d.ts +162 -0
  125. package/dist/tsup/utils-CqDnC_PS.d.cts +104 -0
  126. package/dist/tsup/utils-CqDnC_PS.d.ts +104 -0
  127. package/dist/tsup/utils-DQDCphrl.d.cts +162 -0
  128. package/dist/tsup/utils.cjs +7 -3
  129. package/dist/tsup/utils.cjs.map +1 -1
  130. package/dist/tsup/utils.d.cts +4 -147
  131. package/dist/tsup/utils.d.ts +4 -147
  132. package/dist/tsup/utils.js +6 -2
  133. package/dist/tsup/workflow/mod.cjs +486 -375
  134. package/dist/tsup/workflow/mod.cjs.map +1 -1
  135. package/dist/tsup/workflow/mod.d.cts +9 -10
  136. package/dist/tsup/workflow/mod.d.ts +9 -10
  137. package/dist/tsup/workflow/mod.js +478 -367
  138. package/dist/tsup/workflow/mod.js.map +1 -1
  139. package/package.json +51 -15
  140. package/src/actor/actions.ts +119 -0
  141. package/src/actor/config.test.ts +14 -0
  142. package/src/actor/config.ts +351 -93
  143. package/src/actor/contexts/index.ts +7 -2
  144. package/src/actor/definition.ts +38 -26
  145. package/src/actor/errors.ts +70 -7
  146. package/src/actor/keys.ts +2 -1
  147. package/src/actor/mod.ts +22 -20
  148. package/src/actor/schema.ts +2 -2
  149. package/src/agent-os/actor/index.ts +39 -19
  150. package/src/agent-os/actor/preview.ts +1 -2
  151. package/src/agent-os/actor/session.ts +2 -2
  152. package/src/agent-os/config.ts +1 -1
  153. package/src/agent-os/fs/database-vfs.ts +1 -1
  154. package/src/agent-os/index.ts +16 -15
  155. package/src/client/actor-common.ts +90 -62
  156. package/src/client/actor-conn.ts +59 -64
  157. package/src/client/actor-handle.ts +125 -71
  158. package/src/client/actor-query.ts +5 -5
  159. package/src/client/client.ts +35 -11
  160. package/src/client/config.ts +3 -3
  161. package/src/client/errors.ts +2 -1
  162. package/src/client/lifecycle-errors.ts +2 -4
  163. package/src/client/query.ts +3 -1
  164. package/src/client/queue.ts +8 -3
  165. package/src/client/raw-utils.ts +13 -12
  166. package/src/client/resolve-gateway-target.ts +3 -1
  167. package/src/client/utils.ts +34 -10
  168. package/src/common/actor-router-consts.ts +7 -4
  169. package/src/common/actor-websocket.ts +3 -1
  170. package/src/common/bare/actor-persist/v1.ts +205 -163
  171. package/src/common/bare/actor-persist/v2.ts +265 -213
  172. package/src/common/bare/actor-persist/v3.ts +176 -172
  173. package/src/common/bare/actor-persist/v4.ts +254 -253
  174. package/src/common/bare/generated/actor-runtime-socket-protocol/v1.ts +848 -0
  175. package/src/common/bare/generated/client-protocol/v4.ts +599 -0
  176. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  177. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  178. package/src/common/bare/transport/v1.ts +694 -542
  179. package/src/common/client-protocol-versioned.ts +176 -67
  180. package/src/common/client-protocol-zod.ts +7 -0
  181. package/src/common/client-protocol.ts +1 -1
  182. package/src/common/database/config.ts +63 -9
  183. package/src/common/database/mod.test.ts +201 -40
  184. package/src/common/database/mod.ts +111 -30
  185. package/src/common/database/native-database.test.ts +44 -22
  186. package/src/common/database/native-database.ts +162 -6
  187. package/src/common/database/shared.ts +25 -0
  188. package/src/common/encoding.ts +278 -34
  189. package/src/common/engine.ts +28 -1
  190. package/src/common/eventsource.ts +1 -1
  191. package/src/common/fetch-like.ts +49 -0
  192. package/src/common/inline-websocket-adapter.ts +14 -13
  193. package/src/common/inspector-transport.ts +12 -2
  194. package/src/common/log.ts +15 -8
  195. package/src/common/router.ts +49 -23
  196. package/src/common/utils.ts +10 -202
  197. package/src/common/websocket-interface.ts +1 -1
  198. package/src/db/drizzle.test.ts +164 -0
  199. package/src/db/drizzle.ts +187 -89
  200. package/src/db/mod.ts +3 -1
  201. package/src/devtools-loader/index.ts +4 -7
  202. package/src/devtools-loader/serve-devtools.ts +26 -0
  203. package/src/dynamic/instance.ts +32 -0
  204. package/src/dynamic/internal.ts +50 -0
  205. package/src/dynamic/isolate-runtime.ts +64 -0
  206. package/src/dynamic/mod.ts +32 -0
  207. package/src/engine-client/actor-http-client.ts +6 -9
  208. package/src/engine-client/actor-websocket-client.ts +14 -13
  209. package/src/engine-client/api-endpoints.ts +51 -2
  210. package/src/engine-client/api-utils.ts +2 -2
  211. package/src/engine-client/driver.ts +7 -19
  212. package/src/engine-client/mod.ts +30 -55
  213. package/src/engine-client/ws-proxy.ts +9 -4
  214. package/src/inspector/client.browser.ts +127 -15
  215. package/src/inspector/mod.ts +2 -4
  216. package/src/inspector-tab/mod.ts +301 -0
  217. package/src/registry/config/envoy.ts +1 -2
  218. package/src/registry/config/index.ts +41 -54
  219. package/src/registry/index.ts +554 -91
  220. package/src/registry/napi-runtime.ts +340 -23
  221. package/src/registry/native-validation.ts +10 -12
  222. package/src/registry/native.ts +849 -393
  223. package/src/registry/process-metrics.ts +250 -0
  224. package/src/registry/runtime.ts +243 -9
  225. package/src/registry/wasm-runtime.ts +290 -9
  226. package/src/registry/write-through-proxy.ts +141 -0
  227. package/src/serde.ts +2 -2
  228. package/src/serverless/configure.ts +19 -8
  229. package/src/test/mod.ts +2 -17
  230. package/src/test/ready.ts +22 -0
  231. package/src/unstable/migrations.test.ts +170 -0
  232. package/src/unstable/migrations.ts +141 -0
  233. package/src/utils/crypto.ts +14 -0
  234. package/src/utils/endpoint-parser.ts +1 -1
  235. package/src/utils/env-vars.ts +37 -0
  236. package/src/utils/router.ts +1 -1
  237. package/src/utils.ts +4 -2
  238. package/src/workflow/context.ts +683 -242
  239. package/src/workflow/driver.test.ts +62 -0
  240. package/src/workflow/driver.ts +248 -119
  241. package/src/workflow/inspector.ts +21 -16
  242. package/src/workflow/mod.ts +39 -25
  243. package/dist/tsup/chunk-22XU3BVY.cjs.map +0 -1
  244. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  245. package/dist/tsup/chunk-3BFYSYRU.js.map +0 -1
  246. package/dist/tsup/chunk-7MRGNVSR.js.map +0 -1
  247. package/dist/tsup/chunk-AK57AL7S.cjs.map +0 -1
  248. package/dist/tsup/chunk-D2TLG75Y.cjs.map +0 -1
  249. package/dist/tsup/chunk-D4TSTM6C.js.map +0 -1
  250. package/dist/tsup/chunk-IOYKCB6Y.cjs.map +0 -1
  251. package/dist/tsup/chunk-K34B3OVG.js.map +0 -1
  252. package/dist/tsup/chunk-KSG2COSQ.js.map +0 -1
  253. package/dist/tsup/chunk-LLD2D5LO.cjs.map +0 -1
  254. package/dist/tsup/chunk-LNMB25HW.js.map +0 -1
  255. package/dist/tsup/chunk-NFC5VU36.cjs.map +0 -1
  256. package/dist/tsup/chunk-OIKOPSXQ.js.map +0 -1
  257. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  258. package/dist/tsup/chunk-POTPHU3P.cjs.map +0 -1
  259. package/dist/tsup/chunk-RZEJJJKU.js.map +0 -1
  260. package/dist/tsup/chunk-TPBHXFB2.cjs +0 -268
  261. package/dist/tsup/chunk-TPBHXFB2.cjs.map +0 -1
  262. package/dist/tsup/chunk-V3QNBJ7N.cjs.map +0 -1
  263. package/dist/tsup/chunk-W54QCENI.js +0 -268
  264. package/dist/tsup/chunk-W54QCENI.js.map +0 -1
  265. package/dist/tsup/chunk-XNZR7UD2.cjs.map +0 -1
  266. package/dist/tsup/context-B7G6sk7x.d.ts +0 -92
  267. package/dist/tsup/context-DzMRHkjC.d.cts +0 -92
  268. package/dist/tsup/utils-fwx3o3K9.d.cts +0 -18
  269. package/dist/tsup/utils-fwx3o3K9.d.ts +0 -18
  270. package/src/actor/driver.ts +0 -141
  271. package/src/actor/instance/mod.ts +0 -2501
  272. package/src/drivers/engine/actor-driver.ts +0 -2470
  273. package/src/utils/serve.ts +0 -217
  274. /package/dist/tsup/{chunk-4ZIWB4CQ.js.map → chunk-DZ7KAOCW.js.map} +0 -0
package/dist/tsup/mod.js CHANGED
@@ -1,48 +1,43 @@
1
+ import {
2
+ decodeWorkflowHistoryTransport
3
+ } from "./chunk-XUBFECDW.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,
10
+ flattenActionHandlers,
11
+ flattenActionInputSchemas,
5
12
  getRunFunction,
6
13
  getRunInspectorConfig,
7
14
  getRunMetadata
8
- } from "./chunk-7MRGNVSR.js";
9
- import {
10
- decodeWorkflowHistoryTransport
11
- } from "./chunk-RZEJJJKU.js";
15
+ } from "./chunk-QWLJCP3X.js";
12
16
  import {
13
17
  ALLOWED_PUBLIC_HEADERS,
14
- CURRENT_VERSION,
15
18
  HEADER_CONN_PARAMS,
16
- HEADER_ENCODING,
17
- HTTP_RESPONSE_ERROR_VERSIONED,
18
- HttpResponseErrorSchema,
19
19
  RemoteEngineControlClient,
20
20
  convertRegistryConfigToClientConfig,
21
21
  createClientWithDriver,
22
22
  getDatacenters,
23
+ isResponseLike,
23
24
  tryParseEndpoint,
24
25
  updateRunnerConfig
25
- } from "./chunk-LNMB25HW.js";
26
+ } from "./chunk-FMMENOAT.js";
26
27
  import {
27
- KEYS,
28
28
  makePrefixedKey,
29
- queueMessagesPrefix,
30
- queueMetadataKey,
31
- removePrefixFromKey,
32
- workflowStoragePrefix
33
- } from "./chunk-3BFYSYRU.js";
34
- import {
35
- contentTypeForEncoding,
36
- decodeCborCompat,
37
- decodeCborJsonCompat,
38
- encodeCborCompat,
39
- serializeWithEncoding
40
- } from "./chunk-W54QCENI.js";
41
- import "./chunk-4ZIWB4CQ.js";
29
+ removePrefixFromKey
30
+ } from "./chunk-JI6GZ2C2.js";
31
+ import "./chunk-JTHHCZCZ.js";
32
+ import "./chunk-DZ7KAOCW.js";
42
33
  import {
43
34
  LogLevelSchema,
44
35
  VERSION,
36
+ assertJsonCompatValue,
37
+ configureBaseLogger,
38
+ decodeCborCompat,
45
39
  deconstructError,
40
+ encodeCborCompat,
46
41
  getEnvUniversal,
47
42
  getLogger,
48
43
  getNodeEnv,
@@ -54,15 +49,20 @@ import {
54
49
  getRivetPublicEndpoint,
55
50
  getRivetPublicToken,
56
51
  getRivetRunEngine,
52
+ getRivetRunEngineHost,
53
+ getRivetRunEnginePort,
57
54
  getRivetRunEngineVersion,
58
55
  getRivetToken,
59
56
  getRivetTotalSlots,
57
+ getRivetkitPublicDir,
60
58
  getRivetkitRuntime,
59
+ getRivetkitRuntimeMode,
61
60
  isDev,
62
61
  noopNext,
62
+ parsePortEnv,
63
63
  stringifyError,
64
64
  toUint8Array
65
- } from "./chunk-D4TSTM6C.js";
65
+ } from "./chunk-VHZ2ICIB.js";
66
66
  import {
67
67
  INTERNAL_ERROR_CODE,
68
68
  RivetError,
@@ -70,11 +70,11 @@ import {
70
70
  decodeBridgeRivetError,
71
71
  encodeBridgeRivetError,
72
72
  forbiddenError,
73
+ isActorAbortedError,
73
74
  isRivetErrorLike,
74
75
  toRivetError,
75
76
  unsupportedFeature
76
- } from "./chunk-K34B3OVG.js";
77
- import "./chunk-PCBNKI2J.js";
77
+ } from "./chunk-ZZ3WBRPD.js";
78
78
 
79
79
  // src/actor/log.ts
80
80
  function loggerWithoutContext() {
@@ -82,15 +82,21 @@ function loggerWithoutContext() {
82
82
  }
83
83
 
84
84
  // src/actor/definition.ts
85
- var warnedDeprecatedTimeoutKeys = /* @__PURE__ */ new Set();
86
- function warnDeprecatedShutdownTimeoutKeys(options) {
85
+ var warnedDeprecatedOptionKeys = /* @__PURE__ */ new Set();
86
+ var DEPRECATED_OPTION_MESSAGES = {
87
+ onDestroyTimeout: "Configure `sleepGracePeriod` instead, which bounds the entire graceful shutdown window for both sleep and destroy.",
88
+ waitUntilTimeout: "Configure `sleepGracePeriod` instead, which bounds the entire graceful shutdown window for both sleep and destroy.",
89
+ preloadMaxWorkflowBytes: "Internal storage moved to SQLite and no longer uses KV preloading.",
90
+ preloadMaxConnectionsBytes: "Internal storage moved to SQLite and no longer uses KV preloading."
91
+ };
92
+ function warnDeprecatedOptionKeys(options) {
87
93
  if (!options || typeof options !== "object") return;
88
94
  const opts = options;
89
- for (const key of ["onDestroyTimeout", "waitUntilTimeout"]) {
90
- if (opts[key] !== void 0 && !warnedDeprecatedTimeoutKeys.has(key)) {
91
- warnedDeprecatedTimeoutKeys.add(key);
95
+ for (const [key, detail] of Object.entries(DEPRECATED_OPTION_MESSAGES)) {
96
+ if (opts[key] !== void 0 && !warnedDeprecatedOptionKeys.has(key)) {
97
+ warnedDeprecatedOptionKeys.add(key);
92
98
  loggerWithoutContext().warn({
93
- msg: `actor option \`${key}\` is deprecated and is now ignored. Configure \`sleepGracePeriod\` instead, which bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0.`
99
+ msg: `actor option \`${key}\` is deprecated and is now ignored. ${detail} Will be removed in 2.2.0.`
94
100
  });
95
101
  }
96
102
  }
@@ -108,10 +114,12 @@ function isStaticActorInstance(_actor) {
108
114
  return true;
109
115
  }
110
116
  function actor(input) {
111
- warnDeprecatedShutdownTimeoutKeys(
117
+ warnDeprecatedOptionKeys(
112
118
  input == null ? void 0 : input.options
113
119
  );
114
120
  const config = ActorConfigSchema.parse(input);
121
+ flattenActionHandlers(config.actions);
122
+ flattenActionInputSchemas(config.actions, config.actionInputSchemas);
115
123
  return new ActorDefinition(config);
116
124
  }
117
125
  function isStaticActorDefinition(definition) {
@@ -146,7 +154,7 @@ function hasSchemaConfigKey(schemas, key) {
146
154
  if (!schemas) {
147
155
  return false;
148
156
  }
149
- return Object.prototype.hasOwnProperty.call(schemas, key);
157
+ return Object.hasOwn(schemas, key);
150
158
  }
151
159
  function getEventCanSubscribe(schemas, key) {
152
160
  const schema = schemas == null ? void 0 : schemas[key];
@@ -207,8 +215,8 @@ function validateSchemaSync(schemas, key, data) {
207
215
  }
208
216
 
209
217
  // src/common/inline-websocket-adapter.ts
210
- import { WSContext } from "hono/ws";
211
218
  import { VirtualWebSocket } from "@rivetkit/virtual-websocket";
219
+ import { WSContext } from "hono/ws";
212
220
  function logger() {
213
221
  return getLogger("inline-websocket-adapter");
214
222
  }
@@ -320,24 +328,24 @@ var InlineWebSocketAdapter = class {
320
328
  this.#close(1011, "Internal error during initialization");
321
329
  }
322
330
  }
323
- #handleError(err) {
324
- console.error("INLINE_WEBSOCKET_ADAPTER_ERROR", err);
331
+ #handleError(error) {
332
+ console.error("INLINE_WEBSOCKET_ADAPTER_ERROR", error);
325
333
  logger().error({
326
334
  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
335
+ error,
336
+ errorMessage: error instanceof Error ? error.message : String(error),
337
+ stack: error instanceof Error ? error.stack : void 0
330
338
  });
331
339
  try {
332
- this.#handler.onError(err, this.#wsContext);
333
- } catch (handlerErr) {
340
+ this.#handler.onError(error, this.#wsContext);
341
+ } catch (error2) {
334
342
  logger().error({
335
343
  msg: "error in onError handler",
336
- error: handlerErr
344
+ error: error2
337
345
  });
338
346
  }
339
- this.#clientWs.triggerError(err);
340
- this.#actorWs.triggerError(err);
347
+ this.#clientWs.triggerError(error);
348
+ this.#actorWs.triggerError(error);
341
349
  }
342
350
  #close(code, reason) {
343
351
  if (this.#readyState === 3 || this.#readyState === 2) {
@@ -350,8 +358,8 @@ var InlineWebSocketAdapter = class {
350
358
  { code, reason, wasClean: true },
351
359
  this.#wsContext
352
360
  );
353
- } catch (err) {
354
- logger().error({ msg: "error closing websocket", error: err });
361
+ } catch (error) {
362
+ logger().error({ msg: "error closing websocket", error });
355
363
  } finally {
356
364
  this.#readyState = 3;
357
365
  this.#clientWs.triggerClose(code, reason);
@@ -361,8 +369,23 @@ var InlineWebSocketAdapter = class {
361
369
  };
362
370
 
363
371
  // src/common/engine.ts
372
+ var ENGINE_HOST = "127.0.0.1";
364
373
  var ENGINE_PORT = 6420;
365
- var ENGINE_ENDPOINT = `http://127.0.0.1:${ENGINE_PORT}`;
374
+ var ENGINE_ENDPOINT = buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT);
375
+ function buildEngineEndpoint(host, port) {
376
+ const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
377
+ return `http://${urlHost}:${port}`;
378
+ }
379
+ function isLocalEngineEndpoint(endpoint) {
380
+ let url;
381
+ try {
382
+ url = new URL(endpoint);
383
+ } catch {
384
+ return false;
385
+ }
386
+ const hostname = url.hostname.toLowerCase();
387
+ return hostname === "localhost" || hostname === "0.0.0.0" || hostname === "::" || hostname === "[::]" || hostname === "::1" || hostname === "[::1]" || /^127(?:\.\d{1,3}){0,3}$/.test(hostname);
388
+ }
366
389
 
367
390
  // src/registry/log.ts
368
391
  function logger2() {
@@ -377,10 +400,13 @@ function sleep(ms) {
377
400
  }
378
401
  function configureTimeoutMs() {
379
402
  const value = process.env.RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS;
380
- if (value === void 0 || value === "") return DEFAULT_CONFIGURE_TIMEOUT_MS;
403
+ if (value === void 0 || value === "")
404
+ return DEFAULT_CONFIGURE_TIMEOUT_MS;
381
405
  const parsed = Number(value);
382
406
  if (!Number.isFinite(parsed) || parsed < 0) {
383
- throw new Error("RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS must be a finite non-negative number");
407
+ throw new Error(
408
+ "RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS must be a finite non-negative number"
409
+ );
384
410
  }
385
411
  return parsed;
386
412
  }
@@ -394,13 +420,19 @@ async function configureServerlessPool(config) {
394
420
  attempts += 1;
395
421
  try {
396
422
  if (!config.namespace) {
397
- throw new Error("namespace is required for serverless configuration");
423
+ throw new Error(
424
+ "namespace is required for serverless configuration"
425
+ );
398
426
  }
399
427
  if (!config.endpoint) {
400
- throw new Error("endpoint is required for serverless configuration");
428
+ throw new Error(
429
+ "endpoint is required for serverless configuration"
430
+ );
401
431
  }
402
432
  if (!config.configurePool) {
403
- throw new Error("configurePool is required for serverless configuration");
433
+ throw new Error(
434
+ "configurePool is required for serverless configuration"
435
+ );
404
436
  }
405
437
  const customConfig = config.configurePool;
406
438
  const clientConfig = convertRegistryConfigToClientConfig(config);
@@ -415,7 +447,7 @@ async function configureServerlessPool(config) {
415
447
  serverless: {
416
448
  url: customConfig.url,
417
449
  headers,
418
- request_lifespan: customConfig.requestLifespan ?? 15 * 60,
450
+ request_lifespan: customConfig.requestLifespan ?? 60 * 60,
419
451
  drain_grace_period: customConfig.drainGracePeriod,
420
452
  metadata_poll_interval: customConfig.metadataPollInterval ?? 1e3,
421
453
  max_runners: 1e5,
@@ -674,6 +706,18 @@ var RegistryConfigSchema = z3.object({
674
706
  * Starts the full Rust engine process locally.
675
707
  */
676
708
  startEngine: z3.boolean().default(() => getRivetRunEngine()),
709
+ /**
710
+ * @experimental
711
+ *
712
+ * Host to bind the spawned local engine process to.
713
+ */
714
+ engineHost: z3.string().optional().default(() => getRivetRunEngineHost() ?? ENGINE_HOST),
715
+ /**
716
+ * @experimental
717
+ *
718
+ * Port to bind the spawned local engine process to.
719
+ */
720
+ enginePort: z3.number().int().min(1).max(65535).optional().default(() => getRivetRunEnginePort() ?? ENGINE_PORT),
677
721
  /** @experimental */
678
722
  engineVersion: z3.string().optional().default(() => getRivetRunEngineVersion() ?? VERSION),
679
723
  /**
@@ -706,12 +750,12 @@ var RegistryConfigSchema = z3.object({
706
750
  shutdown: z3.object({
707
751
  /**
708
752
  * Wait this many milliseconds for the serve promise to resolve
709
- * after calling `CoreRegistry::shutdown()`. Defaults to 30s,
710
- * matching Kubernetes `terminationGracePeriodSeconds`.
753
+ * after calling `CoreRegistry::shutdown()`. Defaults to the
754
+ * engine-provided actor stop threshold once the envoy connects.
711
755
  *
712
- * Must be >= rivetkit-core's drain timeout (20s) + margin.
756
+ * Must be long enough for rivetkit-core to drain the envoy.
713
757
  */
714
- gracePeriodMs: z3.number().int().min(1e3).optional().default(3e4),
758
+ gracePeriodMs: z3.number().int().min(1e3).optional(),
715
759
  /**
716
760
  * If true, rivetkit will not install SIGINT/SIGTERM handlers.
717
761
  * Use when the host application owns signal policy and will
@@ -719,7 +763,6 @@ var RegistryConfigSchema = z3.object({
719
763
  */
720
764
  disableSignalHandlers: z3.boolean().optional().default(false)
721
765
  }).optional().default(() => ({
722
- gracePeriodMs: 3e4,
723
766
  disableSignalHandlers: false
724
767
  }))
725
768
  }).transform((config, ctx) => {
@@ -752,7 +795,11 @@ var RegistryConfigSchema = z3.object({
752
795
  message: "configurePool requires either endpoint or startEngine"
753
796
  });
754
797
  }
755
- const endpoint = config.startEngine ? ENGINE_ENDPOINT : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? ENGINE_ENDPOINT : void 0);
798
+ const localEngineEndpoint = buildEngineEndpoint(
799
+ config.engineHost,
800
+ config.enginePort
801
+ );
802
+ const endpoint = config.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? localEngineEndpoint : void 0);
756
803
  const validateServerlessEndpoint = Boolean(
757
804
  config.startEngine || parsedEndpoint
758
805
  );
@@ -769,7 +816,7 @@ var RegistryConfigSchema = z3.object({
769
816
  path: ["serverless", "publicEndpoint"]
770
817
  });
771
818
  }
772
- const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && config.startEngine ? ENGINE_ENDPOINT : void 0);
819
+ const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && !parsedEndpoint ? endpoint : void 0);
773
820
  const publicNamespace = parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.namespace;
774
821
  const publicToken = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.token) ?? config.serverless.publicToken;
775
822
  return {
@@ -797,30 +844,6 @@ function buildActorNames(config) {
797
844
  const metadata = {};
798
845
  metadata.icon = options.icon ?? runMeta.icon;
799
846
  metadata.name = options.name ?? runMeta.name;
800
- metadata.preload = {
801
- keys: [
802
- Array.from(KEYS.PERSIST_DATA),
803
- Array.from(KEYS.INSPECTOR_TOKEN),
804
- Array.from(queueMetadataKey())
805
- ],
806
- prefixes: [
807
- {
808
- prefix: Array.from(workflowStoragePrefix()),
809
- maxBytes: options.preloadMaxWorkflowBytes ?? 131072,
810
- partial: false
811
- },
812
- {
813
- prefix: Array.from(KEYS.CONN_PREFIX),
814
- maxBytes: options.preloadMaxConnectionsBytes ?? 65536,
815
- partial: false
816
- },
817
- {
818
- prefix: Array.from(queueMessagesPrefix()),
819
- maxBytes: 65536,
820
- partial: false
821
- }
822
- ]
823
- };
824
847
  if (!metadata.icon) delete metadata.icon;
825
848
  if (!metadata.name) delete metadata.name;
826
849
  return [actorName, { metadata }];
@@ -929,7 +952,8 @@ function shouldAttachNativeKvError(message) {
929
952
  }
930
953
  function enrichNativeDatabaseError(database, error) {
931
954
  var _a;
932
- const bridged = typeof error === "string" ? decodeBridgeRivetError(error) : error instanceof Error ? decodeBridgeRivetError(error.message) : void 0;
955
+ const bridgeReason = typeof error === "string" ? error : error instanceof Error ? error.message : void 0;
956
+ const bridged = bridgeReason === void 0 ? void 0 : decodeBridgeRivetError(bridgeReason);
933
957
  if (bridged) {
934
958
  throw bridged;
935
959
  }
@@ -1012,6 +1036,12 @@ function toNativeBindings(sql, params) {
1012
1036
  return toNativeBinding(value);
1013
1037
  });
1014
1038
  }
1039
+ function toNativeBatchStatement(statement) {
1040
+ return {
1041
+ sql: statement.sql,
1042
+ params: toNativeBindings(statement.sql, statement.params)
1043
+ };
1044
+ }
1015
1045
  function normalizeNativeMetrics(metrics) {
1016
1046
  if (!metrics) return null;
1017
1047
  const raw = metrics;
@@ -1125,6 +1155,60 @@ function wrapJsNativeDatabase(database) {
1125
1155
  async execute(sql, params) {
1126
1156
  return await executeNative(sql, params);
1127
1157
  },
1158
+ async executeBatch(statements) {
1159
+ const nativeStatements = statements.map(toNativeBatchStatement);
1160
+ const release = gate.enter();
1161
+ let transaction;
1162
+ try {
1163
+ const results = database.executeBatch ? await database.executeBatch(nativeStatements) : await (async () => {
1164
+ transaction = await database.beginTransaction();
1165
+ const transactionResults = [];
1166
+ for (const statement of nativeStatements) {
1167
+ transactionResults.push(
1168
+ await transaction.execute(
1169
+ statement.sql,
1170
+ statement.params
1171
+ )
1172
+ );
1173
+ }
1174
+ await transaction.commit();
1175
+ transaction = void 0;
1176
+ return transactionResults;
1177
+ })();
1178
+ for (const result of results) {
1179
+ if (result.lastInsertRowId !== void 0) {
1180
+ lastInsertRowId = result.lastInsertRowId;
1181
+ }
1182
+ }
1183
+ return results;
1184
+ } catch (error) {
1185
+ if (transaction) {
1186
+ try {
1187
+ await transaction.rollback();
1188
+ } catch {
1189
+ }
1190
+ }
1191
+ enrichNativeDatabaseError(database, error);
1192
+ } finally {
1193
+ release();
1194
+ }
1195
+ },
1196
+ async beginTransaction(timeoutMs, name) {
1197
+ const release = gate.enter();
1198
+ let transaction;
1199
+ try {
1200
+ transaction = await database.beginTransaction(timeoutMs, name);
1201
+ } catch (error) {
1202
+ enrichNativeDatabaseError(database, error);
1203
+ } finally {
1204
+ release();
1205
+ }
1206
+ return wrapTransaction(database, transaction, gate, (result) => {
1207
+ if (result.lastInsertRowId !== void 0) {
1208
+ lastInsertRowId = result.lastInsertRowId;
1209
+ }
1210
+ });
1211
+ },
1128
1212
  async run(sql, params) {
1129
1213
  await executeNative(sql, params);
1130
1214
  },
@@ -1132,9 +1216,6 @@ function wrapJsNativeDatabase(database) {
1132
1216
  const { columns, rows } = await executeNative(sql, params);
1133
1217
  return { columns, rows };
1134
1218
  },
1135
- async writeMode(callback) {
1136
- return await callback();
1137
- },
1138
1219
  nativeMetrics() {
1139
1220
  var _a;
1140
1221
  return normalizeNativeMetrics((_a = database.metrics) == null ? void 0 : _a.call(database));
@@ -1145,6 +1226,59 @@ function wrapJsNativeDatabase(database) {
1145
1226
  }
1146
1227
  };
1147
1228
  }
1229
+ function wrapTransaction(database, transaction, gate, onExecute) {
1230
+ return {
1231
+ async exec(sql, callback) {
1232
+ const release = gate.enter();
1233
+ let result;
1234
+ try {
1235
+ result = await transaction.exec(sql);
1236
+ } catch (error) {
1237
+ enrichNativeDatabaseError(database, error);
1238
+ } finally {
1239
+ release();
1240
+ }
1241
+ if (callback) {
1242
+ for (const row of result.rows) callback(row, result.columns);
1243
+ }
1244
+ },
1245
+ async execute(sql, params) {
1246
+ const release = gate.enter();
1247
+ try {
1248
+ const result = await transaction.execute(
1249
+ sql,
1250
+ toNativeBindings(sql, params)
1251
+ );
1252
+ onExecute(result);
1253
+ return result;
1254
+ } catch (error) {
1255
+ enrichNativeDatabaseError(database, error);
1256
+ } finally {
1257
+ release();
1258
+ }
1259
+ },
1260
+ async commit() {
1261
+ const release = gate.enter();
1262
+ try {
1263
+ await transaction.commit();
1264
+ } catch (error) {
1265
+ enrichNativeDatabaseError(database, error);
1266
+ } finally {
1267
+ release();
1268
+ }
1269
+ },
1270
+ async rollback() {
1271
+ const release = gate.enter();
1272
+ try {
1273
+ await transaction.rollback();
1274
+ } catch (error) {
1275
+ enrichNativeDatabaseError(database, error);
1276
+ } finally {
1277
+ release();
1278
+ }
1279
+ }
1280
+ };
1281
+ }
1148
1282
  function lastInsertRowIdColumnName(sql) {
1149
1283
  const match = sql.match(
1150
1284
  /^\s*SELECT\s+last_insert_rowid\s*\(\s*\)\s*(?:AS\s+("[^"]+"|`[^`]+`|\[[^\]]+\]|\w+))?\s*;?\s*$/i
@@ -1162,6 +1296,82 @@ function lastInsertRowIdColumnName(sql) {
1162
1296
  return alias;
1163
1297
  }
1164
1298
 
1299
+ // src/utils/node.ts
1300
+ import { createRequire } from "module";
1301
+ var nodeCrypto;
1302
+ var nodeFsSync;
1303
+ var nodeFs;
1304
+ var nodePath;
1305
+ var nodeOs;
1306
+ var nodeChildProcess;
1307
+ var nodeStream;
1308
+ var nodeUrl;
1309
+ var hasImportedDependencies = false;
1310
+ function getRequireFn() {
1311
+ return createRequire(import.meta.url);
1312
+ }
1313
+ function importNodeDependencies() {
1314
+ if (hasImportedDependencies) return;
1315
+ try {
1316
+ const requireFn = getRequireFn();
1317
+ nodeCrypto = requireFn(
1318
+ /* webpackIgnore: true */
1319
+ "node:crypto"
1320
+ );
1321
+ nodeFsSync = requireFn(
1322
+ /* webpackIgnore: true */
1323
+ "node:fs"
1324
+ );
1325
+ nodeFs = requireFn(
1326
+ /* webpackIgnore: true */
1327
+ "node:fs/promises"
1328
+ );
1329
+ nodePath = requireFn(
1330
+ /* webpackIgnore: true */
1331
+ "node:path"
1332
+ );
1333
+ nodeOs = requireFn(
1334
+ /* webpackIgnore: true */
1335
+ "node:os"
1336
+ );
1337
+ nodeChildProcess = requireFn(
1338
+ /* webpackIgnore: true */
1339
+ "node:child_process"
1340
+ );
1341
+ nodeStream = requireFn(
1342
+ /* webpackIgnore: true */
1343
+ "node:stream/promises"
1344
+ );
1345
+ nodeUrl = requireFn(
1346
+ /* webpackIgnore: true */
1347
+ "node:url"
1348
+ );
1349
+ hasImportedDependencies = true;
1350
+ } catch (err) {
1351
+ console.warn(
1352
+ "Node.js modules not available, file system driver will not work",
1353
+ err
1354
+ );
1355
+ throw err;
1356
+ }
1357
+ }
1358
+ function getNodeFsSync() {
1359
+ if (!nodeFsSync) {
1360
+ throw new Error(
1361
+ "Node fs module not loaded. Ensure importNodeDependencies() has been called."
1362
+ );
1363
+ }
1364
+ return nodeFsSync;
1365
+ }
1366
+ function getNodePath() {
1367
+ if (!nodePath) {
1368
+ throw new Error(
1369
+ "Node path module not loaded. Ensure importNodeDependencies() has been called."
1370
+ );
1371
+ }
1372
+ return nodePath;
1373
+ }
1374
+
1165
1375
  // src/registry/runtime.ts
1166
1376
  function normalizeRuntimeSqlExecuteResult(result) {
1167
1377
  return result;
@@ -1183,6 +1393,9 @@ function asNativeConn(handle) {
1183
1393
  function asNativeWebSocket(handle) {
1184
1394
  return handle;
1185
1395
  }
1396
+ function asNativeSqlTransaction(handle) {
1397
+ return handle;
1398
+ }
1186
1399
  function asNativeCancellationToken(handle) {
1187
1400
  return handle;
1188
1401
  }
@@ -1212,9 +1425,31 @@ function toNapiSqlBindParams(params) {
1212
1425
  }
1213
1426
  return params.map((param) => toNapiSqlBindParam(param));
1214
1427
  }
1428
+ function toNapiSqlBatchStatement(statement) {
1429
+ return {
1430
+ sql: statement.sql,
1431
+ params: toNapiSqlBindParams(statement.params) ?? void 0
1432
+ };
1433
+ }
1215
1434
  function toNapiBuffer(value) {
1216
1435
  return Buffer.from(value);
1217
1436
  }
1437
+ function toNapiApplication(application) {
1438
+ return async (error, request) => {
1439
+ if (error) throw error;
1440
+ if (!request) {
1441
+ throw new Error("application fetch callback received no request");
1442
+ }
1443
+ const response = await application({
1444
+ ...request,
1445
+ body: new Uint8Array(request.body)
1446
+ });
1447
+ return {
1448
+ ...response,
1449
+ body: toNapiBuffer(response.body)
1450
+ };
1451
+ };
1452
+ }
1218
1453
  function toNapiHttpRequest(request) {
1219
1454
  if (!request) {
1220
1455
  return request;
@@ -1279,14 +1514,37 @@ var NapiCoreRuntime = class {
1279
1514
  async serveRegistry(registry, config) {
1280
1515
  await asNativeRegistry(registry).serve(config);
1281
1516
  }
1517
+ async waitRegistryReady(registry) {
1518
+ await asNativeRegistry(registry).waitReady();
1519
+ }
1282
1520
  async shutdownRegistry(registry) {
1283
1521
  await asNativeRegistry(registry).shutdown();
1284
1522
  }
1285
- async registryDiagnostics(registry) {
1286
- const diagnostics = await asNativeRegistry(registry).diagnostics();
1523
+ async registryActorStopThresholdMs(registry) {
1524
+ return await asNativeRegistry(registry).actorStopThresholdMs() ?? void 0;
1525
+ }
1526
+ async registryHealth(registry) {
1527
+ const response = await asNativeRegistry(registry).health();
1528
+ return {
1529
+ status: response.status,
1530
+ headers: response.headers,
1531
+ body: response.body
1532
+ };
1533
+ }
1534
+ async registryMetadata(registry) {
1535
+ const response = asNativeRegistry(registry).metadata();
1536
+ return {
1537
+ status: response.status,
1538
+ headers: response.headers,
1539
+ body: response.body
1540
+ };
1541
+ }
1542
+ async registryMetrics(registry) {
1543
+ const response = asNativeRegistry(registry).metrics();
1287
1544
  return {
1288
- mode: diagnostics.mode,
1289
- envoyActiveActorCount: diagnostics.envoyActiveActorCount
1545
+ status: response.status,
1546
+ headers: response.headers,
1547
+ body: response.body
1290
1548
  };
1291
1549
  }
1292
1550
  async handleServerlessRequest(registry, req, onStreamEvent, cancelToken, config) {
@@ -1297,6 +1555,29 @@ var NapiCoreRuntime = class {
1297
1555
  config
1298
1556
  );
1299
1557
  }
1558
+ async serveListener(registry, listener, config) {
1559
+ const application = listener.application ? toNapiApplication(listener.application) : void 0;
1560
+ await asNativeRegistry(registry).serveListener(
1561
+ {
1562
+ port: listener.port,
1563
+ host: listener.host,
1564
+ publicDir: listener.publicDir
1565
+ },
1566
+ config,
1567
+ application
1568
+ );
1569
+ }
1570
+ async serveApplicationListener(registry, listener, config) {
1571
+ await asNativeRegistry(registry).serveApplicationListener(
1572
+ {
1573
+ port: listener.port,
1574
+ host: listener.host,
1575
+ publicDir: listener.publicDir
1576
+ },
1577
+ toNapiApplication(listener.application),
1578
+ config
1579
+ );
1580
+ }
1300
1581
  createActorFactory(callbacks, config) {
1301
1582
  return asActorFactoryHandle(
1302
1583
  new this.#bindings.NapiActorFactory(callbacks, config)
@@ -1305,11 +1586,16 @@ var NapiCoreRuntime = class {
1305
1586
  createCancellationToken() {
1306
1587
  return new this.#bindings.CancellationToken();
1307
1588
  }
1308
- createTestActorContext(actorId, name, region) {
1309
- return new this.#bindings.ActorContext(
1310
- actorId,
1311
- name,
1312
- region
1589
+ decodeInspectorRequest(bytes, advertisedVersion) {
1590
+ return this.#bindings.decodeInspectorRequest(
1591
+ toNapiBuffer(bytes),
1592
+ advertisedVersion
1593
+ );
1594
+ }
1595
+ encodeInspectorResponse(bytes, targetVersion) {
1596
+ return this.#bindings.encodeInspectorResponse(
1597
+ toNapiBuffer(bytes),
1598
+ targetVersion
1313
1599
  );
1314
1600
  }
1315
1601
  cancellationTokenAborted(token) {
@@ -1373,6 +1659,14 @@ var NapiCoreRuntime = class {
1373
1659
  toNapiStateDeltaPayload(payload)
1374
1660
  );
1375
1661
  }
1662
+ async actorSaveStateAndWorkflowBatch(ctx, writes) {
1663
+ await asNativeActorContext(ctx).saveStateAndWorkflowBatch(
1664
+ writes.map((write) => ({
1665
+ key: toNapiBuffer(write.key),
1666
+ value: toNapiBuffer(write.value)
1667
+ }))
1668
+ );
1669
+ }
1376
1670
  actorId(ctx) {
1377
1671
  return asNativeActorContext(ctx).actorId();
1378
1672
  }
@@ -1409,6 +1703,12 @@ var NapiCoreRuntime = class {
1409
1703
  actorWaitUntil(ctx, promise) {
1410
1704
  asNativeActorContext(ctx).waitUntil(promise);
1411
1705
  }
1706
+ async actorWaitForTrackedShutdownWork(ctx) {
1707
+ return await asNativeActorContext(ctx).waitForTrackedShutdownWork();
1708
+ }
1709
+ async actorWaitForTrackedShutdownWorkUnbounded(ctx) {
1710
+ await asNativeActorContext(ctx).waitForTrackedShutdownWorkUnbounded();
1711
+ }
1412
1712
  actorKeepAwake(ctx, promise) {
1413
1713
  asNativeActorContext(ctx).keepAwake(promise);
1414
1714
  }
@@ -1473,6 +1773,34 @@ var NapiCoreRuntime = class {
1473
1773
  );
1474
1774
  return normalizeRuntimeSqlExecuteResult(result);
1475
1775
  }
1776
+ async actorSqlExecuteBatch(ctx, statements) {
1777
+ const results = await this.#actorSql(ctx).executeBatch(
1778
+ statements.map(toNapiSqlBatchStatement)
1779
+ );
1780
+ return results.map(normalizeRuntimeSqlExecuteResult);
1781
+ }
1782
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
1783
+ return await this.#actorSql(ctx).beginTransaction(
1784
+ timeoutMs,
1785
+ name
1786
+ );
1787
+ }
1788
+ async actorSqlTransactionExec(transaction, sql) {
1789
+ return await asNativeSqlTransaction(transaction).exec(sql);
1790
+ }
1791
+ async actorSqlTransactionExecute(transaction, sql, params) {
1792
+ const result = await asNativeSqlTransaction(transaction).execute(
1793
+ sql,
1794
+ toNapiSqlBindParams(params)
1795
+ );
1796
+ return normalizeRuntimeSqlExecuteResult(result);
1797
+ }
1798
+ async actorSqlTransactionCommit(transaction) {
1799
+ await asNativeSqlTransaction(transaction).commit();
1800
+ }
1801
+ async actorSqlTransactionRollback(transaction) {
1802
+ await asNativeSqlTransaction(transaction).rollback();
1803
+ }
1476
1804
  async actorSqlQuery(ctx, sql, params) {
1477
1805
  return await this.#actorSql(ctx).query(
1478
1806
  sql,
@@ -1499,6 +1827,9 @@ var NapiCoreRuntime = class {
1499
1827
  this.#sql.delete(nativeCtx);
1500
1828
  await database.close();
1501
1829
  }
1830
+ async actorRuntimeSocketProvision(ctx) {
1831
+ return await asNativeActorContext(ctx).provisionActorRuntimeSocket();
1832
+ }
1502
1833
  async actorQueueSend(ctx, name, body) {
1503
1834
  return toNapiQueueMessage(
1504
1835
  await asNativeActorContext(ctx).queue().send(name, toNapiBuffer(body))
@@ -1520,8 +1851,12 @@ var NapiCoreRuntime = class {
1520
1851
  )
1521
1852
  );
1522
1853
  }
1523
- async actorQueueWaitForNamesAvailable(ctx, names, options) {
1524
- await asNativeActorContext(ctx).queue().waitForNamesAvailable(names, options);
1854
+ async actorQueueWaitForNamesAvailable(ctx, names, options, signal) {
1855
+ await asNativeActorContext(ctx).queue().waitForNamesAvailable(
1856
+ names,
1857
+ options,
1858
+ signal ? asNativeCancellationToken(signal) : signal
1859
+ );
1525
1860
  }
1526
1861
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
1527
1862
  return await asNativeActorContext(ctx).queue().enqueueAndWait(
@@ -1540,11 +1875,54 @@ var NapiCoreRuntime = class {
1540
1875
  async actorQueueInspectMessages(ctx) {
1541
1876
  return await asNativeActorContext(ctx).queue().inspectMessages();
1542
1877
  }
1543
- actorScheduleAfter(ctx, durationMs, actionName, args) {
1544
- asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
1878
+ async actorQueueReset(ctx) {
1879
+ await asNativeActorContext(ctx).queue().reset();
1880
+ }
1881
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
1882
+ return await asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
1883
+ }
1884
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
1885
+ return await asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
1886
+ }
1887
+ async actorScheduleCancel(ctx, id) {
1888
+ return await asNativeActorContext(ctx).schedule().cancel(id);
1889
+ }
1890
+ async actorScheduleGet(ctx, id) {
1891
+ return await asNativeActorContext(ctx).schedule().get(id) ?? void 0;
1892
+ }
1893
+ async actorScheduleList(ctx) {
1894
+ return await asNativeActorContext(ctx).schedule().list();
1545
1895
  }
1546
- actorScheduleAt(ctx, timestampMs, actionName, args) {
1547
- asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
1896
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
1897
+ await asNativeActorContext(ctx).schedule().cronSet(
1898
+ name,
1899
+ expression,
1900
+ timezone,
1901
+ actionName,
1902
+ toNapiBuffer(args),
1903
+ maxHistory
1904
+ );
1905
+ }
1906
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
1907
+ await asNativeActorContext(ctx).schedule().cronEvery(
1908
+ name,
1909
+ intervalMs,
1910
+ actionName,
1911
+ toNapiBuffer(args),
1912
+ maxHistory
1913
+ );
1914
+ }
1915
+ async actorCronGet(ctx, name) {
1916
+ return await asNativeActorContext(ctx).schedule().cronGet(name) ?? void 0;
1917
+ }
1918
+ async actorCronList(ctx) {
1919
+ return await asNativeActorContext(ctx).schedule().cronList();
1920
+ }
1921
+ async actorCronDelete(ctx, name) {
1922
+ return await asNativeActorContext(ctx).schedule().cronDelete(name);
1923
+ }
1924
+ async actorCronHistory(ctx, name, limit) {
1925
+ return await asNativeActorContext(ctx).schedule().cronHistory(name, limit);
1548
1926
  }
1549
1927
  connId(conn) {
1550
1928
  return asNativeConn(conn).id();
@@ -1655,20 +2033,18 @@ function validateQueueComplete(schemas, name, response) {
1655
2033
  response
1656
2034
  );
1657
2035
  if (!result.success) {
1658
- throw validationError(`queue \`${name}\` completion response`, result.issues);
2036
+ throw validationError(
2037
+ `queue \`${name}\` completion response`,
2038
+ result.issues
2039
+ );
1659
2040
  }
1660
2041
  return result.data;
1661
2042
  }
1662
2043
  function validationError(target, issues) {
1663
- return new RivetError(
1664
- "actor",
1665
- "validation_error",
1666
- `Invalid ${target}`,
1667
- {
1668
- public: true,
1669
- metadata: { issues }
1670
- }
1671
- );
2044
+ return new RivetError("actor", "validation_error", `Invalid ${target}`, {
2045
+ public: true,
2046
+ metadata: { issues }
2047
+ });
1672
2048
  }
1673
2049
 
1674
2050
  // src/registry/wasm-runtime.ts
@@ -1823,11 +2199,26 @@ var WasmCoreRuntime = class {
1823
2199
  async serveRegistry(registry, config) {
1824
2200
  await callWasm(() => asWasmRegistry(registry).serve(config));
1825
2201
  }
2202
+ async waitRegistryReady() {
2203
+ throw new Error(
2204
+ "registry.startAndWait() is not supported by the WASM runtime"
2205
+ );
2206
+ }
1826
2207
  async shutdownRegistry(registry) {
1827
2208
  await callWasm(() => asWasmRegistry(registry).shutdown());
1828
2209
  }
1829
- async registryDiagnostics() {
1830
- return { mode: "wasm", envoyActiveActorCount: null };
2210
+ async registryHealth() {
2211
+ return {
2212
+ status: 200,
2213
+ headers: { "content-type": "application/json" },
2214
+ body: new TextEncoder().encode(
2215
+ JSON.stringify({
2216
+ status: "ok",
2217
+ runtime: "rivetkit",
2218
+ version: "wasm"
2219
+ })
2220
+ )
2221
+ };
1831
2222
  }
1832
2223
  async handleServerlessRequest(registry, req, onStreamEvent, cancelToken, config) {
1833
2224
  return await callHandleAsync(
@@ -1839,6 +2230,16 @@ var WasmCoreRuntime = class {
1839
2230
  config
1840
2231
  );
1841
2232
  }
2233
+ async serveListener(_registry, _listener, _config) {
2234
+ throw new Error(
2235
+ "registry.listen() is not supported on the wasm runtime; use registry.serve() and mount the handler in your platform's HTTP server instead"
2236
+ );
2237
+ }
2238
+ async serveApplicationListener(_registry, _listener, _config) {
2239
+ throw new Error(
2240
+ "registry.listen() is not supported on the wasm runtime; use an application-owned HTTP server instead"
2241
+ );
2242
+ }
1842
2243
  createActorFactory(callbacks, config) {
1843
2244
  return callWasmSync(
1844
2245
  () => asActorFactoryHandle2(
@@ -1938,6 +2339,13 @@ var WasmCoreRuntime = class {
1938
2339
  async actorSaveState(ctx, payload) {
1939
2340
  await callHandleAsync(asWasmActorContext(ctx), "saveState", payload);
1940
2341
  }
2342
+ async actorSaveStateAndWorkflowBatch(ctx, writes) {
2343
+ await callHandleAsync(
2344
+ asWasmActorContext(ctx),
2345
+ "saveStateAndWorkflowBatch",
2346
+ writes
2347
+ );
2348
+ }
1941
2349
  actorId(ctx) {
1942
2350
  return callHandle(asWasmActorContext(ctx), "actorId");
1943
2351
  }
@@ -1976,6 +2384,18 @@ var WasmCoreRuntime = class {
1976
2384
  actorWaitUntil(ctx, promise) {
1977
2385
  callHandle(asWasmActorContext(ctx), "waitUntil", promise);
1978
2386
  }
2387
+ async actorWaitForTrackedShutdownWork(ctx) {
2388
+ return await callHandle(
2389
+ asWasmActorContext(ctx),
2390
+ "waitForTrackedShutdownWork"
2391
+ );
2392
+ }
2393
+ async actorWaitForTrackedShutdownWorkUnbounded(ctx) {
2394
+ await callHandle(
2395
+ asWasmActorContext(ctx),
2396
+ "waitForTrackedShutdownWorkUnbounded"
2397
+ );
2398
+ }
1979
2399
  actorKeepAwake(ctx, promise) {
1980
2400
  const wasmCtx = asWasmActorContext(ctx);
1981
2401
  const regionId = callHandle(wasmCtx, "beginKeepAwake");
@@ -2072,6 +2492,38 @@ var WasmCoreRuntime = class {
2072
2492
  );
2073
2493
  return normalizeRuntimeSqlExecuteResult(result);
2074
2494
  }
2495
+ async actorSqlExecuteBatch(ctx, statements) {
2496
+ const results = await callWasm(
2497
+ () => this.#actorSql(ctx).executeBatch(statements)
2498
+ );
2499
+ return results.map(normalizeRuntimeSqlExecuteResult);
2500
+ }
2501
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
2502
+ return await callWasm(
2503
+ () => this.#actorSql(ctx).beginTransaction(timeoutMs, name)
2504
+ );
2505
+ }
2506
+ async actorSqlTransactionExec(transaction, sql) {
2507
+ return await callWasm(
2508
+ () => transaction.exec(sql)
2509
+ );
2510
+ }
2511
+ async actorSqlTransactionExecute(transaction, sql, params) {
2512
+ const result = await callWasm(
2513
+ () => transaction.execute(sql, params)
2514
+ );
2515
+ return normalizeRuntimeSqlExecuteResult(result);
2516
+ }
2517
+ async actorSqlTransactionCommit(transaction) {
2518
+ await callWasm(
2519
+ () => transaction.commit()
2520
+ );
2521
+ }
2522
+ async actorSqlTransactionRollback(transaction) {
2523
+ await callWasm(
2524
+ () => transaction.rollback()
2525
+ );
2526
+ }
2075
2527
  async actorSqlQuery(ctx, sql, params) {
2076
2528
  return await callWasm(() => this.#actorSql(ctx).query(sql, params));
2077
2529
  }
@@ -2095,6 +2547,17 @@ var WasmCoreRuntime = class {
2095
2547
  this.#sql.delete(wasmCtx);
2096
2548
  await callWasm(() => database.close());
2097
2549
  }
2550
+ async actorRuntimeSocketProvision(_ctx) {
2551
+ throw new RivetError(
2552
+ "actor_runtime_socket",
2553
+ "unsupported",
2554
+ "Actor Runtime Socket is only available on Unix native runtimes.",
2555
+ {
2556
+ public: true,
2557
+ metadata: { runtime: "wasm" }
2558
+ }
2559
+ );
2560
+ }
2098
2561
  async actorQueueSend(ctx, name, body) {
2099
2562
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2100
2563
  return normalizeQueueMessage(
@@ -2123,9 +2586,15 @@ var WasmCoreRuntime = class {
2123
2586
  )
2124
2587
  );
2125
2588
  }
2126
- async actorQueueWaitForNamesAvailable(ctx, names, options) {
2589
+ async actorQueueWaitForNamesAvailable(ctx, names, options, signal) {
2127
2590
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2128
- await callHandleAsync(queue2, "waitForNamesAvailable", names, options);
2591
+ await callHandleAsync(
2592
+ queue2,
2593
+ "waitForNamesAvailable",
2594
+ names,
2595
+ options,
2596
+ signal
2597
+ );
2129
2598
  }
2130
2599
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
2131
2600
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
@@ -2156,13 +2625,101 @@ var WasmCoreRuntime = class {
2156
2625
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2157
2626
  return await callHandleAsync(queue2, "inspectMessages");
2158
2627
  }
2159
- actorScheduleAfter(ctx, durationMs, actionName, args) {
2160
- const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2161
- callHandle(schedule, "after", wasmNumber(durationMs), actionName, args);
2628
+ async actorQueueReset(ctx) {
2629
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2630
+ await callHandleAsync(queue2, "reset");
2162
2631
  }
2163
- actorScheduleAt(ctx, timestampMs, actionName, args) {
2632
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
2164
2633
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2165
- callHandle(schedule, "at", wasmNumber(timestampMs), actionName, args);
2634
+ return await callHandleAsync(
2635
+ schedule,
2636
+ "after",
2637
+ wasmNumber(durationMs),
2638
+ actionName,
2639
+ args
2640
+ );
2641
+ }
2642
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
2643
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2644
+ return await callHandleAsync(
2645
+ schedule,
2646
+ "at",
2647
+ wasmNumber(timestampMs),
2648
+ actionName,
2649
+ args
2650
+ );
2651
+ }
2652
+ async actorScheduleCancel(ctx, id) {
2653
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2654
+ return await callHandleAsync(schedule, "cancel", id);
2655
+ }
2656
+ async actorScheduleGet(ctx, id) {
2657
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2658
+ return await callHandleAsync(
2659
+ schedule,
2660
+ "get",
2661
+ id
2662
+ );
2663
+ }
2664
+ async actorScheduleList(ctx) {
2665
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2666
+ return await callHandleAsync(
2667
+ schedule,
2668
+ "list"
2669
+ );
2670
+ }
2671
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
2672
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2673
+ await callHandleAsync(
2674
+ schedule,
2675
+ "cronSet",
2676
+ name,
2677
+ expression,
2678
+ timezone,
2679
+ actionName,
2680
+ args,
2681
+ maxHistory
2682
+ );
2683
+ }
2684
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
2685
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2686
+ await callHandleAsync(
2687
+ schedule,
2688
+ "cronEvery",
2689
+ name,
2690
+ intervalMs,
2691
+ actionName,
2692
+ args,
2693
+ maxHistory
2694
+ );
2695
+ }
2696
+ async actorCronGet(ctx, name) {
2697
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2698
+ return await callHandleAsync(
2699
+ schedule,
2700
+ "cronGet",
2701
+ name
2702
+ );
2703
+ }
2704
+ async actorCronList(ctx) {
2705
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2706
+ return await callHandleAsync(
2707
+ schedule,
2708
+ "cronList"
2709
+ );
2710
+ }
2711
+ async actorCronDelete(ctx, name) {
2712
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2713
+ return await callHandleAsync(schedule, "cronDelete", name);
2714
+ }
2715
+ async actorCronHistory(ctx, name, limit) {
2716
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2717
+ return await callHandleAsync(
2718
+ schedule,
2719
+ "cronHistory",
2720
+ name,
2721
+ limit
2722
+ );
2166
2723
  }
2167
2724
  connId(conn) {
2168
2725
  return callHandle(asWasmConn(conn), "id");
@@ -2217,6 +2774,106 @@ async function loadWasmRuntime(config) {
2217
2774
  };
2218
2775
  }
2219
2776
 
2777
+ // src/registry/write-through-proxy.ts
2778
+ import onChange from "@rivetkit/on-change";
2779
+ function createWriteThroughProxy(value, commit, beforeChange) {
2780
+ if (!value || typeof value !== "object") {
2781
+ return value;
2782
+ }
2783
+ return onChange(
2784
+ value,
2785
+ () => {
2786
+ commit(value);
2787
+ },
2788
+ {
2789
+ // Rejection is throw-based: beforeChange throws to prevent the
2790
+ // mutation. We always return true so on-change applies the change
2791
+ // if beforeChange did not throw.
2792
+ onValidate(_path, newValue) {
2793
+ beforeChange == null ? void 0 : beforeChange(newValue);
2794
+ return true;
2795
+ }
2796
+ }
2797
+ );
2798
+ }
2799
+ function unwrapProxy(value) {
2800
+ let current = value;
2801
+ while (current !== null && typeof current === "object") {
2802
+ const target = onChange.target(current);
2803
+ if (target === current) {
2804
+ break;
2805
+ }
2806
+ current = target;
2807
+ }
2808
+ return current;
2809
+ }
2810
+ function isPlainObject(value) {
2811
+ const proto = Object.getPrototypeOf(value);
2812
+ return proto === Object.prototype || proto === null;
2813
+ }
2814
+ function unwrapDeep(value, seen) {
2815
+ const unwrapped = unwrapProxy(value);
2816
+ if (!unwrapped || typeof unwrapped !== "object") {
2817
+ return unwrapped;
2818
+ }
2819
+ if (seen.has(unwrapped)) {
2820
+ return unwrapped;
2821
+ }
2822
+ seen.add(unwrapped);
2823
+ if (Array.isArray(unwrapped)) {
2824
+ for (let i = 0; i < unwrapped.length; i++) {
2825
+ const child = unwrapDeep(unwrapped[i], seen);
2826
+ if (child !== unwrapped[i]) {
2827
+ unwrapped[i] = child;
2828
+ }
2829
+ }
2830
+ return unwrapped;
2831
+ }
2832
+ if (unwrapped instanceof Map) {
2833
+ const replacements = [];
2834
+ for (const [key, child] of unwrapped.entries()) {
2835
+ const nextKey = unwrapDeep(key, seen);
2836
+ const nextChild = unwrapDeep(child, seen);
2837
+ if (nextKey !== key || nextChild !== child) {
2838
+ replacements.push([key, nextKey, nextChild]);
2839
+ }
2840
+ }
2841
+ for (const [key, nextKey, nextChild] of replacements) {
2842
+ if (nextKey !== key) {
2843
+ unwrapped.delete(key);
2844
+ }
2845
+ unwrapped.set(nextKey, nextChild);
2846
+ }
2847
+ return unwrapped;
2848
+ }
2849
+ if (unwrapped instanceof Set) {
2850
+ const replacements = [];
2851
+ for (const child of unwrapped.values()) {
2852
+ const next = unwrapDeep(child, seen);
2853
+ if (next !== child) {
2854
+ replacements.push([child, next]);
2855
+ }
2856
+ }
2857
+ for (const [child, next] of replacements) {
2858
+ unwrapped.delete(child);
2859
+ unwrapped.add(next);
2860
+ }
2861
+ return unwrapped;
2862
+ }
2863
+ if (isPlainObject(unwrapped)) {
2864
+ for (const key of Object.keys(unwrapped)) {
2865
+ const child = unwrapDeep(unwrapped[key], seen);
2866
+ if (child !== unwrapped[key]) {
2867
+ unwrapped[key] = child;
2868
+ }
2869
+ }
2870
+ }
2871
+ return unwrapped;
2872
+ }
2873
+ function unwrapWriteThroughProxy(value) {
2874
+ return unwrapDeep(value, /* @__PURE__ */ new Set());
2875
+ }
2876
+
2220
2877
  // src/registry/native.ts
2221
2878
  var textEncoder = new TextEncoder();
2222
2879
  var textDecoder = new TextDecoder();
@@ -2370,6 +3027,14 @@ function databaseNotConfiguredError() {
2370
3027
  { public: true }
2371
3028
  );
2372
3029
  }
3030
+ function databaseClientNotReadyError() {
3031
+ return new RivetError(
3032
+ "actor",
3033
+ "database_client_not_ready",
3034
+ "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.",
3035
+ { public: true }
3036
+ );
3037
+ }
2373
3038
  function stateNotEnabledError() {
2374
3039
  return new RivetError(
2375
3040
  "actor",
@@ -2421,7 +3086,23 @@ function resolveNativeDestroy(runtime, ctx) {
2421
3086
  function clearNativeRuntimeState(runtime, ctx) {
2422
3087
  callNativeSync(() => runtime.actorClearRuntimeState(ctx));
2423
3088
  }
2424
- async function cleanupNativeSleepRuntimeState(runtime, ctx) {
3089
+ async function cleanupNativeSleepRuntimeState(runtime, ctx, afterTrackedWorkDrained) {
3090
+ const drained = await runtime.actorWaitForTrackedShutdownWork(ctx);
3091
+ if (!drained) {
3092
+ await closeNativeDatabaseClient(runtime, ctx);
3093
+ await closeNativeSqlDatabase(runtime, ctx);
3094
+ void runtime.actorWaitForTrackedShutdownWorkUnbounded(ctx).then(async () => {
3095
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
3096
+ clearNativeRuntimeState(runtime, ctx);
3097
+ }).catch((error) => {
3098
+ logger2().warn({
3099
+ msg: "deferred native sleep cleanup failed",
3100
+ error: stringifyError(error)
3101
+ });
3102
+ });
3103
+ return;
3104
+ }
3105
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
2425
3106
  await closeNativeDatabaseClient(runtime, ctx);
2426
3107
  await closeNativeSqlDatabase(runtime, ctx);
2427
3108
  clearNativeRuntimeState(runtime, ctx);
@@ -2455,6 +3136,24 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
2455
3136
  const database = wrapJsNativeDatabase({
2456
3137
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
2457
3138
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
3139
+ executeBatch: (statements) => runtime.actorSqlExecuteBatch(ctx, statements),
3140
+ beginTransaction: async (timeoutMs, name) => {
3141
+ const transaction = await runtime.actorSqlBeginTransaction(
3142
+ ctx,
3143
+ timeoutMs,
3144
+ name
3145
+ );
3146
+ return {
3147
+ exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
3148
+ execute: (sql, params) => runtime.actorSqlTransactionExecute(
3149
+ transaction,
3150
+ sql,
3151
+ params
3152
+ ),
3153
+ commit: () => runtime.actorSqlTransactionCommit(transaction),
3154
+ rollback: () => runtime.actorSqlTransactionRollback(transaction)
3155
+ };
3156
+ },
2458
3157
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
2459
3158
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
2460
3159
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -2526,11 +3225,14 @@ function decodeValue(value) {
2526
3225
  if (!value || value.length === 0) {
2527
3226
  return void 0;
2528
3227
  }
2529
- return decodeCborJsonCompat(value);
3228
+ return decodeCborCompat(value);
2530
3229
  }
2531
3230
  function encodeValue(value) {
2532
3231
  return encodeCborCompat(value);
2533
3232
  }
3233
+ function normalizeArgs(value) {
3234
+ return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
3235
+ }
2534
3236
  function unwrapTsfnPayload(error, payload) {
2535
3237
  if (error !== null && error !== void 0) {
2536
3238
  throw error;
@@ -2562,27 +3264,7 @@ function isStructuredBridgeError(error) {
2562
3264
  return isRivetErrorLike(error) && "__type" in error && (error.__type === "RivetError" || error.__type === "ActorError");
2563
3265
  }
2564
3266
  function encodeNativeCallbackError(error) {
2565
- const structuredError = isStructuredBridgeError(error) ? error : deconstructError(error, logger2(), {
2566
- bridge: "native_callback"
2567
- });
2568
- let stack;
2569
- if (error instanceof Error) {
2570
- try {
2571
- stack = error.stack;
2572
- } catch {
2573
- stack = void 0;
2574
- }
2575
- }
2576
- logger2().warn({
2577
- msg: "native callback error encoded for bridge",
2578
- group: structuredError.group,
2579
- code: structuredError.code,
2580
- message: structuredError.message,
2581
- metadata: structuredError.metadata,
2582
- originalError: stringifyError(error),
2583
- stack,
2584
- bridge: "native_callback"
2585
- });
3267
+ const structuredError = isStructuredBridgeError(error) ? error : deconstructError(error, true);
2586
3268
  const bridgeError = new Error(encodeBridgeRivetError(structuredError), {
2587
3269
  cause: error instanceof Error ? error : void 0
2588
3270
  });
@@ -2606,12 +3288,6 @@ function callNativeSync(invoke) {
2606
3288
  throw normalizeNativeBridgeError(error);
2607
3289
  }
2608
3290
  }
2609
- function actorAbortedError() {
2610
- return Object.assign(new Error("Actor aborted"), {
2611
- group: "actor",
2612
- code: "aborted"
2613
- });
2614
- }
2615
3291
  function isClosedTaskRegistrationError(error) {
2616
3292
  const metadata = error instanceof RivetError ? error.metadata : void 0;
2617
3293
  const metadataError = metadata && typeof metadata === "object" && "error" in metadata ? metadata.error : void 0;
@@ -2737,6 +3413,14 @@ function serializeWorkflowEntryKind(kind) {
2737
3413
  originalName: kind.val.originalName
2738
3414
  }
2739
3415
  };
3416
+ case "WorkflowVersionCheckEntry":
3417
+ return {
3418
+ tag: kind.tag,
3419
+ val: {
3420
+ resolved: kind.val.resolved,
3421
+ latest: kind.val.latest
3422
+ }
3423
+ };
2740
3424
  }
2741
3425
  }
2742
3426
  function serializeWorkflowHistoryForJson(data) {
@@ -2744,7 +3428,7 @@ function serializeWorkflowHistoryForJson(data) {
2744
3428
  return null;
2745
3429
  }
2746
3430
  const history = decodeWorkflowHistoryTransport(data);
2747
- return {
3431
+ return jsonSafe({
2748
3432
  nameRegistry: [...history.nameRegistry],
2749
3433
  entries: history.entries.map((entry) => ({
2750
3434
  id: entry.id,
@@ -2768,7 +3452,7 @@ function serializeWorkflowHistoryForJson(data) {
2768
3452
  ]
2769
3453
  )
2770
3454
  )
2771
- };
3455
+ });
2772
3456
  }
2773
3457
  function toHttpJsonCompatible(value) {
2774
3458
  return JSON.parse(
@@ -2819,45 +3503,7 @@ function wrapNativeCallback(callback) {
2819
3503
  }
2820
3504
  function decodeArgs(value) {
2821
3505
  const decoded = decodeValue(value);
2822
- return Array.isArray(decoded) ? decoded : decoded === void 0 ? [] : [decoded];
2823
- }
2824
- function createWriteThroughProxy(value, commit, beforeChange) {
2825
- if (!value || typeof value !== "object") {
2826
- return value;
2827
- }
2828
- const proxies = /* @__PURE__ */ new WeakMap();
2829
- const wrap = (target) => {
2830
- const cached = proxies.get(target);
2831
- if (cached) {
2832
- return cached;
2833
- }
2834
- const proxy = new Proxy(target, {
2835
- get(innerTarget, property, receiver) {
2836
- const result = Reflect.get(innerTarget, property, receiver);
2837
- return result && typeof result === "object" ? wrap(result) : result;
2838
- },
2839
- set(innerTarget, property, nextValue, receiver) {
2840
- beforeChange == null ? void 0 : beforeChange();
2841
- const updated = Reflect.set(
2842
- innerTarget,
2843
- property,
2844
- nextValue,
2845
- receiver
2846
- );
2847
- commit(value);
2848
- return updated;
2849
- },
2850
- deleteProperty(innerTarget, property) {
2851
- beforeChange == null ? void 0 : beforeChange();
2852
- const updated = Reflect.deleteProperty(innerTarget, property);
2853
- commit(value);
2854
- return updated;
2855
- }
2856
- });
2857
- proxies.set(target, proxy);
2858
- return proxy;
2859
- };
2860
- return wrap(value);
3506
+ return normalizeArgs(decoded);
2861
3507
  }
2862
3508
  function buildRequest(init) {
2863
3509
  const url = init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString();
@@ -2911,17 +3557,45 @@ var NativeConnAdapter = class {
2911
3557
  decodeValue(this.#runtime.connParams(this.#conn))
2912
3558
  );
2913
3559
  }
3560
+ [RAW_STATE_SYMBOL]() {
3561
+ return this.#readState();
3562
+ }
2914
3563
  get state() {
2915
3564
  const nextState = this.#readState();
2916
- return createWriteThroughProxy(nextState, (nextValue) => {
2917
- this.#writeState(nextValue, { writeNative: true });
2918
- });
3565
+ if (!this.#ctx) {
3566
+ return this.#createStateProxy(nextState);
3567
+ }
3568
+ const connState = getNativeConnPersistState(
3569
+ this.#runtime,
3570
+ this.#ctx,
3571
+ this.#conn
3572
+ );
3573
+ if (connState.stateProxy === void 0 || connState.stateProxyTarget !== nextState) {
3574
+ connState.stateProxyTarget = nextState;
3575
+ connState.stateProxy = this.#createStateProxy(nextState);
3576
+ }
3577
+ return connState.stateProxy;
3578
+ }
3579
+ #createStateProxy(state) {
3580
+ return createWriteThroughProxy(
3581
+ state,
3582
+ (nextValue) => {
3583
+ this.#writeState(nextValue, { writeNative: true });
3584
+ },
3585
+ (newValue) => {
3586
+ assertJsonCompatValue(newValue);
3587
+ }
3588
+ );
2919
3589
  }
2920
3590
  set state(value) {
2921
- this.#writeState(value, { writeNative: true });
3591
+ const nextValue = unwrapWriteThroughProxy(value);
3592
+ assertJsonCompatValue(nextValue);
3593
+ this.#writeState(nextValue, { writeNative: true });
2922
3594
  }
2923
3595
  initializeState(value) {
2924
- this.#writeState(value, { writeNative: false });
3596
+ this.#writeState(unwrapWriteThroughProxy(value), {
3597
+ writeNative: false
3598
+ });
2925
3599
  }
2926
3600
  get isHibernatable() {
2927
3601
  return callNativeSync(
@@ -2991,26 +3665,116 @@ var NativeScheduleAdapter = class {
2991
3665
  this.#ctx = ctx;
2992
3666
  }
2993
3667
  async after(duration, action, ...args) {
2994
- callNativeSync(
2995
- () => this.#runtime.actorScheduleAfter(
2996
- this.#ctx,
2997
- duration,
2998
- action,
2999
- encodeValue(args)
3000
- )
3668
+ return await this.#runtime.actorScheduleAfter(
3669
+ this.#ctx,
3670
+ duration,
3671
+ action,
3672
+ encodeValue(args)
3001
3673
  );
3002
3674
  }
3003
3675
  async at(timestamp, action, ...args) {
3004
- callNativeSync(
3005
- () => this.#runtime.actorScheduleAt(
3006
- this.#ctx,
3007
- timestamp,
3008
- action,
3009
- encodeValue(args)
3010
- )
3676
+ return await this.#runtime.actorScheduleAt(
3677
+ this.#ctx,
3678
+ timestamp,
3679
+ action,
3680
+ encodeValue(args)
3681
+ );
3682
+ }
3683
+ async cancel(id) {
3684
+ return await this.#runtime.actorScheduleCancel(this.#ctx, id);
3685
+ }
3686
+ async get(id) {
3687
+ const event2 = await this.#runtime.actorScheduleGet(this.#ctx, id);
3688
+ return event2 ? decodeScheduledEventInfo(event2) : void 0;
3689
+ }
3690
+ async list() {
3691
+ return (await this.#runtime.actorScheduleList(this.#ctx)).map(
3692
+ decodeScheduledEventInfo
3693
+ );
3694
+ }
3695
+ };
3696
+ var NativeCronAdapter = class {
3697
+ #runtime;
3698
+ #ctx;
3699
+ constructor(runtime, ctx) {
3700
+ this.#runtime = runtime;
3701
+ this.#ctx = ctx;
3702
+ }
3703
+ async set(options) {
3704
+ await this.#runtime.actorCronSet(
3705
+ this.#ctx,
3706
+ options.name,
3707
+ options.expression,
3708
+ options.timezone,
3709
+ options.action,
3710
+ encodeValue(options.args ?? []),
3711
+ options.maxHistory
3712
+ );
3713
+ }
3714
+ async every(options) {
3715
+ await this.#runtime.actorCronEvery(
3716
+ this.#ctx,
3717
+ options.name,
3718
+ options.interval,
3719
+ options.action,
3720
+ encodeValue(options.args ?? []),
3721
+ options.maxHistory
3722
+ );
3723
+ }
3724
+ async get(name) {
3725
+ const job = await this.#runtime.actorCronGet(this.#ctx, name);
3726
+ return job ? decodeCronJobInfo(job) : void 0;
3727
+ }
3728
+ async list() {
3729
+ return (await this.#runtime.actorCronList(this.#ctx)).map(
3730
+ decodeCronJobInfo
3011
3731
  );
3012
3732
  }
3733
+ async delete(name) {
3734
+ return await this.#runtime.actorCronDelete(this.#ctx, name);
3735
+ }
3736
+ async history(name, options) {
3737
+ return (await this.#runtime.actorCronHistory(
3738
+ this.#ctx,
3739
+ name,
3740
+ options == null ? void 0 : options.limit
3741
+ )).map(decodeCronFire);
3742
+ }
3013
3743
  };
3744
+ function decodeScheduledEventInfo(event2) {
3745
+ return {
3746
+ id: event2.id,
3747
+ action: event2.action,
3748
+ args: decodeArgs(event2.args),
3749
+ runAt: event2.runAt
3750
+ };
3751
+ }
3752
+ function decodeCronJobInfo(job) {
3753
+ const base = {
3754
+ name: job.name,
3755
+ action: job.action,
3756
+ args: decodeArgs(job.args),
3757
+ nextRunAt: job.nextRunAt,
3758
+ lastRunAt: job.lastRunAt,
3759
+ maxHistory: job.maxHistory
3760
+ };
3761
+ if (job.kind === "cron") {
3762
+ return {
3763
+ ...base,
3764
+ kind: "cron",
3765
+ expression: job.expression,
3766
+ timezone: job.timezone
3767
+ };
3768
+ }
3769
+ return {
3770
+ ...base,
3771
+ kind: "every",
3772
+ interval: job.intervalMs
3773
+ };
3774
+ }
3775
+ function decodeCronFire(fire) {
3776
+ return { ...fire };
3777
+ }
3014
3778
  var NativeKvAdapter = class {
3015
3779
  #runtime;
3016
3780
  #ctx;
@@ -3269,44 +4033,23 @@ var NativeQueueAdapter = class {
3269
4033
  }
3270
4034
  }
3271
4035
  async waitForNamesAvailable(names, options) {
3272
- if (!(options == null ? void 0 : options.signal)) {
4036
+ const { token, cleanup } = await createCancellationTokenHandle(
4037
+ this.#runtime,
4038
+ options == null ? void 0 : options.signal
4039
+ );
4040
+ try {
3273
4041
  await callNative(
3274
4042
  () => this.#runtime.actorQueueWaitForNamesAvailable(
3275
4043
  this.#ctx,
3276
4044
  [...names],
3277
4045
  {
3278
4046
  timeoutMs: options == null ? void 0 : options.timeout
3279
- }
4047
+ },
4048
+ token
3280
4049
  )
3281
4050
  );
3282
- return;
3283
- }
3284
- const deadline = options.timeout === void 0 ? void 0 : Date.now() + options.timeout;
3285
- for (; ; ) {
3286
- if (options.signal.aborted) {
3287
- throw actorAbortedError();
3288
- }
3289
- const remainingTimeout = deadline === void 0 ? void 0 : Math.max(0, deadline - Date.now());
3290
- const sliceTimeout = remainingTimeout === void 0 ? 100 : Math.min(remainingTimeout, 100);
3291
- try {
3292
- await callNative(
3293
- () => this.#runtime.actorQueueWaitForNamesAvailable(
3294
- this.#ctx,
3295
- [...names],
3296
- {
3297
- timeoutMs: sliceTimeout
3298
- }
3299
- )
3300
- );
3301
- return;
3302
- } catch (error) {
3303
- if (error.group === "queue" && error.code === "timed_out") {
3304
- if (remainingTimeout === void 0 || remainingTimeout > 100) {
3305
- continue;
3306
- }
3307
- }
3308
- throw error;
3309
- }
4051
+ } finally {
4052
+ cleanup == null ? void 0 : cleanup();
3310
4053
  }
3311
4054
  }
3312
4055
  async enqueueAndWait(name, body, options) {
@@ -3376,7 +4119,7 @@ var NativeQueueAdapter = class {
3376
4119
  }
3377
4120
  yield message;
3378
4121
  } catch (error) {
3379
- if (isRivetErrorLike(error) && error.group === "actor" && error.code === "aborted") {
4122
+ if (isActorAbortedError(error)) {
3380
4123
  return;
3381
4124
  }
3382
4125
  throw error;
@@ -3741,6 +4484,68 @@ var TrackedWebSocketHandleAdapter = class {
3741
4484
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
3742
4485
  }
3743
4486
  };
4487
+ var NativeConnectionMap = class {
4488
+ #runtime;
4489
+ #ctx;
4490
+ #schemas;
4491
+ constructor(runtime, ctx, schemas) {
4492
+ this.#runtime = runtime;
4493
+ this.#ctx = ctx;
4494
+ this.#schemas = schemas;
4495
+ }
4496
+ #connToAdapter(conn) {
4497
+ return new NativeConnAdapter(
4498
+ this.#runtime,
4499
+ conn,
4500
+ this.#schemas,
4501
+ this.#ctx,
4502
+ (connId) => callNativeSync(
4503
+ () => this.#runtime.actorQueueHibernationRemoval(
4504
+ this.#ctx,
4505
+ connId
4506
+ )
4507
+ )
4508
+ );
4509
+ }
4510
+ get size() {
4511
+ return callNativeSync(() => this.#runtime.actorConns(this.#ctx)).length;
4512
+ }
4513
+ get(key) {
4514
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4515
+ const conn = conns.find((c) => this.#runtime.connId(c) === key);
4516
+ if (!conn) return void 0;
4517
+ return this.#connToAdapter(conn);
4518
+ }
4519
+ has(key) {
4520
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4521
+ return conns.some((c) => this.#runtime.connId(c) === key);
4522
+ }
4523
+ keys() {
4524
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4525
+ return conns.map((c) => this.#runtime.connId(c))[Symbol.iterator]();
4526
+ }
4527
+ values() {
4528
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4529
+ return conns.map((c) => this.#connToAdapter(c))[Symbol.iterator]();
4530
+ }
4531
+ entries() {
4532
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4533
+ return conns.map(
4534
+ (c) => [this.#runtime.connId(c), this.#connToAdapter(c)]
4535
+ )[Symbol.iterator]();
4536
+ }
4537
+ forEach(callback, thisArg) {
4538
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4539
+ for (const conn of conns) {
4540
+ const id = this.#runtime.connId(conn);
4541
+ callback.call(thisArg, this.#connToAdapter(conn), id, this);
4542
+ }
4543
+ }
4544
+ [Symbol.iterator]() {
4545
+ return this.entries();
4546
+ }
4547
+ [Symbol.toStringTag] = "NativeConnectionMap";
4548
+ };
3744
4549
  var ActorContextHandleAdapter = class {
3745
4550
  #runtime;
3746
4551
  #ctx;
@@ -3749,9 +4554,10 @@ var ActorContextHandleAdapter = class {
3749
4554
  #abortSignalCleanup;
3750
4555
  #client;
3751
4556
  #clientFactory;
4557
+ #connMap;
4558
+ #cron;
3752
4559
  #databaseProvider;
3753
4560
  #db;
3754
- #dbProxy;
3755
4561
  #dispatchCancelToken;
3756
4562
  #kv;
3757
4563
  #queue;
@@ -3790,62 +4596,69 @@ var ActorContextHandleAdapter = class {
3790
4596
  }
3791
4597
  return this.#sql;
3792
4598
  }
4599
+ async actorRuntimeSocket() {
4600
+ return await callNative(
4601
+ () => this.#runtime.actorRuntimeSocketProvision(this.#ctx)
4602
+ );
4603
+ }
3793
4604
  get db() {
3794
4605
  if (!this.#databaseProvider) {
3795
4606
  throw databaseNotConfiguredError();
3796
4607
  }
3797
- if (!this.#dbProxy) {
3798
- this.#dbProxy = new Proxy(
3799
- {},
3800
- {
3801
- get: (_target, property) => {
3802
- if (property === "then") {
3803
- return void 0;
3804
- }
3805
- return async (...args) => {
3806
- const client = await this.ensureDatabaseClient();
3807
- const value = Reflect.get(
3808
- client,
3809
- property
3810
- );
3811
- if (typeof value !== "function") {
3812
- return value;
3813
- }
3814
- return await value.apply(client, args);
3815
- };
3816
- }
3817
- }
3818
- );
4608
+ if (this.#db) {
4609
+ return this.#db;
4610
+ }
4611
+ const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4612
+ const cachedClient = runtimeState.databaseClient;
4613
+ if (cachedClient) {
4614
+ this.#db = cachedClient.client;
4615
+ return this.#db;
3819
4616
  }
3820
- return this.#dbProxy;
4617
+ throw databaseClientNotReadyError();
3821
4618
  }
3822
- get state() {
4619
+ [RAW_STATE_SYMBOL]() {
3823
4620
  if (!this.#stateEnabled) {
3824
4621
  throw stateNotEnabledError();
3825
4622
  }
3826
- const nextState = this.#readState();
3827
- return createWriteThroughProxy(
3828
- nextState,
3829
- (nextValue) => {
3830
- this.#writeState(nextValue, { scheduleSave: true });
3831
- },
3832
- () => {
3833
- this.#assertCanMutateState();
3834
- }
3835
- );
4623
+ return this.#readState();
3836
4624
  }
3837
- set state(value) {
4625
+ get state() {
4626
+ if (!this.#stateEnabled) {
4627
+ throw stateNotEnabledError();
4628
+ }
4629
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
4630
+ const nextState = this.#readState();
4631
+ if (actorState.stateProxy === void 0 || actorState.stateProxyTarget !== nextState) {
4632
+ actorState.stateProxyTarget = nextState;
4633
+ actorState.stateProxy = createWriteThroughProxy(
4634
+ nextState,
4635
+ (nextValue) => {
4636
+ this.#writeState(nextValue, { scheduleSave: true });
4637
+ },
4638
+ (newValue) => {
4639
+ this.#assertCanMutateState();
4640
+ assertJsonCompatValue(newValue);
4641
+ }
4642
+ );
4643
+ }
4644
+ return actorState.stateProxy;
4645
+ }
4646
+ set state(value) {
3838
4647
  if (!this.#stateEnabled) {
3839
4648
  throw stateNotEnabledError();
3840
4649
  }
3841
4650
  this.#assertCanMutateState();
3842
- this.#writeState(value, { scheduleSave: true });
4651
+ const nextValue = unwrapWriteThroughProxy(value);
4652
+ assertJsonCompatValue(nextValue);
4653
+ this.#writeState(nextValue, { scheduleSave: true });
3843
4654
  }
3844
4655
  initializeState(value) {
3845
4656
  if (!this.#stateEnabled) {
3846
4657
  return;
3847
4658
  }
3848
- this.#writeState(value, { scheduleSave: false });
4659
+ this.#writeState(unwrapWriteThroughProxy(value), {
4660
+ scheduleSave: false
4661
+ });
3849
4662
  }
3850
4663
  get vars() {
3851
4664
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
@@ -3880,6 +4693,12 @@ var ActorContextHandleAdapter = class {
3880
4693
  }
3881
4694
  return this.#schedule;
3882
4695
  }
4696
+ get cron() {
4697
+ if (!this.#cron) {
4698
+ this.#cron = new NativeCronAdapter(this.#runtime, this.#ctx);
4699
+ }
4700
+ return this.#cron;
4701
+ }
3883
4702
  get actorId() {
3884
4703
  return callNativeSync(() => this.#runtime.actorId(this.#ctx));
3885
4704
  }
@@ -3895,25 +4714,14 @@ var ActorContextHandleAdapter = class {
3895
4714
  return callNativeSync(() => this.#runtime.actorRegion(this.#ctx));
3896
4715
  }
3897
4716
  get conns() {
3898
- return new Map(
3899
- callNativeSync(() => this.#runtime.actorConns(this.#ctx)).map(
3900
- (conn) => [
3901
- this.#runtime.connId(conn),
3902
- new NativeConnAdapter(
3903
- this.#runtime,
3904
- conn,
3905
- this.#schemas,
3906
- this.#ctx,
3907
- (connId) => callNativeSync(
3908
- () => this.#runtime.actorQueueHibernationRemoval(
3909
- this.#ctx,
3910
- connId
3911
- )
3912
- )
3913
- )
3914
- ]
3915
- )
3916
- );
4717
+ if (!this.#connMap) {
4718
+ this.#connMap = new NativeConnectionMap(
4719
+ this.#runtime,
4720
+ this.#ctx,
4721
+ this.#schemas
4722
+ );
4723
+ }
4724
+ return this.#connMap;
3917
4725
  }
3918
4726
  get log() {
3919
4727
  return logger2();
@@ -4075,6 +4883,11 @@ var ActorContextHandleAdapter = class {
4075
4883
  () => this.#runtime.actorRequestSave(this.#ctx, { immediate: false })
4076
4884
  );
4077
4885
  }
4886
+ async saveStateAndWorkflowBatch(writes) {
4887
+ await callNative(
4888
+ () => this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes)
4889
+ );
4890
+ }
4078
4891
  serializeForTick(reason) {
4079
4892
  void reason;
4080
4893
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -4111,35 +4924,17 @@ var ActorContextHandleAdapter = class {
4111
4924
  });
4112
4925
  }
4113
4926
  keepAwake(promise) {
4114
- const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4115
- runtimeState.keepAwakeCount = (runtimeState.keepAwakeCount ?? 0) + 1;
4116
4927
  const trackedPromise = Promise.resolve(promise).catch((error) => {
4117
4928
  logger2().warn({
4118
4929
  msg: "keepAwake promise rejected",
4119
4930
  error: stringifyError(error)
4120
4931
  });
4121
- }).finally(async () => {
4122
- runtimeState.keepAwakeCount = Math.max(
4123
- (runtimeState.keepAwakeCount ?? 1) - 1,
4124
- 0
4125
- );
4126
- if (runtimeState.keepAwakeCount === 0 && runtimeState.deferSleepCleanupUntilKeepAwakeIdle) {
4127
- runtimeState.deferSleepCleanupUntilKeepAwakeIdle = false;
4128
- await cleanupNativeSleepRuntimeState(
4129
- this.#runtime,
4130
- this.#ctx
4131
- );
4132
- }
4133
4932
  }).then(() => null);
4134
4933
  try {
4135
4934
  callNativeSync(
4136
4935
  () => this.#runtime.actorKeepAwake(this.#ctx, trackedPromise)
4137
4936
  );
4138
4937
  } catch (error) {
4139
- runtimeState.keepAwakeCount = Math.max(
4140
- (runtimeState.keepAwakeCount ?? 1) - 1,
4141
- 0
4142
- );
4143
4938
  if (!isClosedTaskRegistrationError(error)) {
4144
4939
  throw error;
4145
4940
  }
@@ -4152,7 +4947,10 @@ var ActorContextHandleAdapter = class {
4152
4947
  }
4153
4948
  internalKeepAwake(run) {
4154
4949
  const promise = typeof run === "function" ? run() : run;
4155
- const trackedPromise = promise.then(() => null);
4950
+ const trackedPromise = promise.then(
4951
+ () => null,
4952
+ () => null
4953
+ );
4156
4954
  try {
4157
4955
  callNativeSync(
4158
4956
  () => this.#runtime.actorRegisterTask(this.#ctx, trackedPromise)
@@ -4208,6 +5006,7 @@ var ActorContextHandleAdapter = class {
4208
5006
  return false;
4209
5007
  }
4210
5008
  sleep() {
5009
+ this.#flushStateChange();
4211
5010
  callNativeSync(() => this.#runtime.actorSleep(this.#ctx));
4212
5011
  }
4213
5012
  destroy() {
@@ -4225,6 +5024,7 @@ var ActorContextHandleAdapter = class {
4225
5024
  }
4226
5025
  async dispose() {
4227
5026
  var _a;
5027
+ this.#flushStateChange();
4228
5028
  (_a = this.#abortSignalCleanup) == null ? void 0 : _a.call(this);
4229
5029
  this.#sql = void 0;
4230
5030
  }
@@ -4252,13 +5052,12 @@ var ActorContextHandleAdapter = class {
4252
5052
  return actorState.state;
4253
5053
  }
4254
5054
  #writeState(value, options) {
4255
- encodeValue(value);
4256
5055
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4257
5056
  actorState.state = value;
4258
5057
  if (!options.scheduleSave) {
4259
5058
  return;
4260
5059
  }
4261
- this.#handleStateChange();
5060
+ this.#scheduleSave();
4262
5061
  }
4263
5062
  #assertCanMutateState() {
4264
5063
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -4266,9 +5065,31 @@ var ActorContextHandleAdapter = class {
4266
5065
  throw stateMutationReentrantError();
4267
5066
  }
4268
5067
  }
4269
- #handleStateChange() {
5068
+ // Coalesce the request-save and onStateChange work to once per event loop
5069
+ // tick. A synchronous burst of mutations (for example
5070
+ // `Object.assign(c.state, ...)`) would otherwise cross the NAPI boundary and
5071
+ // run onStateChange once per field, re-serializing the whole state each time
5072
+ // and pinning the event loop on large state.
5073
+ #scheduleSave() {
5074
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5075
+ if (actorState.saveScheduled) {
5076
+ return;
5077
+ }
5078
+ actorState.saveScheduled = true;
5079
+ actorState.pendingSaveHandle = setImmediate(() => {
5080
+ this.#flushStateChange();
5081
+ });
5082
+ }
5083
+ #flushStateChange() {
4270
5084
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4271
- encodeValue(actorState.state);
5085
+ if (!actorState.saveScheduled) {
5086
+ return;
5087
+ }
5088
+ actorState.saveScheduled = false;
5089
+ if (actorState.pendingSaveHandle !== void 0) {
5090
+ clearImmediate(actorState.pendingSaveHandle);
5091
+ actorState.pendingSaveHandle = void 0;
5092
+ }
4272
5093
  callNativeSync(
4273
5094
  () => this.#runtime.actorRequestSave(this.#ctx, { immediate: false })
4274
5095
  );
@@ -4381,6 +5202,9 @@ var NativeWorkflowRuntimeAdapter = class {
4381
5202
  this.stateManager = {
4382
5203
  saveState: async (opts) => {
4383
5204
  await this.#ctx.saveState(opts);
5205
+ },
5206
+ saveStateAndWorkflowBatch: async (writes) => {
5207
+ await this.#ctx.saveStateAndWorkflowBatch(writes);
4384
5208
  }
4385
5209
  };
4386
5210
  }
@@ -4446,48 +5270,20 @@ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databa
4446
5270
  }
4447
5271
  );
4448
5272
  }
4449
- function buildNativeRequestErrorResponse(encoding, path, error) {
4450
- const { statusCode, group, code, message, metadata } = deconstructError(
4451
- error,
4452
- logger2(),
4453
- {
4454
- path,
4455
- runtime: "native"
4456
- },
4457
- false
4458
- );
4459
- const body = serializeWithEncoding(
4460
- encoding,
4461
- { group, code, message, metadata },
4462
- HTTP_RESPONSE_ERROR_VERSIONED,
4463
- CURRENT_VERSION,
4464
- HttpResponseErrorSchema,
4465
- (value) => value,
4466
- (value) => ({
4467
- group: value.group,
4468
- code: value.code,
4469
- message: value.message,
4470
- metadata: value.metadata === void 0 ? null : runtimeBytesToArrayBuffer(
4471
- encodeCborCompat(value.metadata)
4472
- )
4473
- })
4474
- );
4475
- return new Response(body, {
4476
- status: statusCode,
4477
- headers: {
4478
- "Content-Type": contentTypeForEncoding(encoding)
4479
- }
4480
- });
4481
- }
4482
- function buildActorConfig(definition, registryConfig) {
5273
+ function buildActorConfig(definition, registryConfig, runtimeKind) {
5274
+ var _a;
4483
5275
  const config = definition.config;
4484
5276
  const options = config.options ?? {};
4485
5277
  const canHibernate = options.canHibernateWebSocket;
5278
+ const usesRemoteSqlite = sqliteBackendForConfig(registryConfig) === "remote";
5279
+ const sqliteProfiling = (_a = config.db) == null ? void 0 : _a.sqliteProfiling;
4486
5280
  return {
4487
5281
  name: options.name,
4488
5282
  icon: options.icon,
4489
- hasDatabase: config.db !== void 0,
4490
- remoteSqlite: config.db !== void 0 && sqliteBackendForConfig(registryConfig) === "remote",
5283
+ hasDatabase: config.db !== void 0 || usesRemoteSqlite,
5284
+ remoteSqlite: usesRemoteSqlite,
5285
+ sqliteProfiling,
5286
+ enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
4491
5287
  hasState: config.state !== void 0 || typeof config.createState === "function",
4492
5288
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
4493
5289
  stateSaveIntervalMs: options.stateSaveInterval,
@@ -4503,27 +5299,99 @@ function buildActorConfig(definition, registryConfig) {
4503
5299
  connectionLivenessTimeoutMs: options.connectionLivenessTimeout,
4504
5300
  connectionLivenessIntervalMs: options.connectionLivenessInterval,
4505
5301
  maxQueueSize: options.maxQueueSize,
5302
+ maxSchedules: options.maxSchedules,
4506
5303
  maxQueueMessageSize: options.maxQueueMessageSize,
4507
5304
  maxIncomingMessageSize: registryConfig.maxIncomingMessageSize,
4508
5305
  maxOutgoingMessageSize: registryConfig.maxOutgoingMessageSize,
4509
5306
  preloadMaxWorkflowBytes: options.preloadMaxWorkflowBytes,
4510
5307
  preloadMaxConnectionsBytes: options.preloadMaxConnectionsBytes,
4511
- actions: Object.keys(config.actions ?? {}).sort().map((name) => ({ name }))
5308
+ actions: Object.keys(flattenActionHandlers(config.actions)).sort().map((name) => ({ name })),
5309
+ inspectorTabs: buildInspectorTabs(config.inspector, runtimeKind)
4512
5310
  };
4513
5311
  }
5312
+ function buildInspectorTabs(inspector, runtimeKind) {
5313
+ if (!inspector || typeof inspector !== "object") return void 0;
5314
+ const tabs = inspector.tabs;
5315
+ if (!Array.isArray(tabs) || tabs.length === 0) return void 0;
5316
+ return tabs.map((raw) => {
5317
+ const entry = raw;
5318
+ if (entry.hidden === true) {
5319
+ return { id: entry.id, hidden: true };
5320
+ }
5321
+ if (runtimeKind === "wasm") {
5322
+ if (entry.source !== void 0) {
5323
+ logger2().warn(
5324
+ {
5325
+ tabId: entry.id,
5326
+ runtimeKind
5327
+ },
5328
+ "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."
5329
+ );
5330
+ }
5331
+ return {
5332
+ id: entry.id,
5333
+ label: entry.label,
5334
+ icon: entry.icon,
5335
+ source: void 0
5336
+ };
5337
+ }
5338
+ const resolved = entry.source !== void 0 ? getNodePath().resolve(entry.source) : void 0;
5339
+ if (resolved !== void 0) {
5340
+ validateInspectorTabSource(entry.id, resolved);
5341
+ }
5342
+ return {
5343
+ id: entry.id,
5344
+ label: entry.label,
5345
+ icon: entry.icon,
5346
+ source: resolved
5347
+ };
5348
+ });
5349
+ }
5350
+ function validateInspectorTabSource(tabId, resolved) {
5351
+ if (resolved === getNodePath().parse(resolved).root) {
5352
+ throw new Error(
5353
+ `inspector.tabs[id="${tabId}"].source resolves to the filesystem root (${resolved}). Point it at the tab's own static-asset directory instead.`
5354
+ );
5355
+ }
5356
+ let stat;
5357
+ try {
5358
+ stat = getNodeFsSync().statSync(resolved);
5359
+ } catch (err) {
5360
+ const code = err == null ? void 0 : err.code;
5361
+ if (code === "ENOENT") {
5362
+ throw new Error(
5363
+ `inspector.tabs[id="${tabId}"].source (${resolved}) does not exist.`
5364
+ );
5365
+ }
5366
+ if (code === "EACCES") {
5367
+ throw new Error(
5368
+ `inspector.tabs[id="${tabId}"].source (${resolved}) is not readable (EACCES).`
5369
+ );
5370
+ }
5371
+ throw new Error(
5372
+ `inspector.tabs[id="${tabId}"].source (${resolved}) could not be stat'd: ${(err == null ? void 0 : err.message) ?? err}`
5373
+ );
5374
+ }
5375
+ if (!stat.isDirectory()) {
5376
+ throw new Error(
5377
+ `inspector.tabs[id="${tabId}"].source (${resolved}) must be a directory, got ${stat.isFile() ? "file" : "non-directory"}.`
5378
+ );
5379
+ }
5380
+ }
4514
5381
  function buildNativeFactory(runtime, registryConfig, definition) {
4515
5382
  var _a;
4516
5383
  const config = definition.config;
4517
5384
  const databaseProvider = config.db;
5385
+ const actionHandlers = flattenActionHandlers(config.actions);
4518
5386
  const schemaConfig = {
4519
- actionInputSchemas: config.actionInputSchemas,
5387
+ actionInputSchemas: flattenActionInputSchemas(
5388
+ config.actions,
5389
+ config.actionInputSchemas
5390
+ ),
4520
5391
  connParamsSchema: config.connParamsSchema,
4521
5392
  events: config.events,
4522
5393
  queues: config.queues
4523
5394
  };
4524
- const actionHandlers = Object.fromEntries(
4525
- Object.entries(config.actions ?? {}).map(([name, handler]) => [name, handler])
4526
- );
4527
5395
  const createClient = () => createClientWithDriver(
4528
5396
  new RemoteEngineControlClient(
4529
5397
  convertRegistryConfigToClientConfig(registryConfig)
@@ -4602,13 +5470,16 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4602
5470
  }
4603
5471
  );
4604
5472
  };
4605
- try {
4606
- await runtime.actorVerifyInspectorAuth(
4607
- ctx,
4608
- ((_a2 = jsRequest.headers.get("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")) ?? null
4609
- );
4610
- } catch (error) {
4611
- return errorResponse(error, 401);
5473
+ const isPublicPerActorPath = jsRequest.method === "GET" && url.pathname.startsWith("/inspector/custom-tabs/");
5474
+ if (!isPublicPerActorPath) {
5475
+ try {
5476
+ await runtime.actorVerifyInspectorAuth(
5477
+ ctx,
5478
+ ((_a2 = jsRequest.headers.get("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")) ?? null
5479
+ );
5480
+ } catch (error) {
5481
+ return errorResponse(error, 401);
5482
+ }
4612
5483
  }
4613
5484
  const workflowHistory = () => {
4614
5485
  var _a3;
@@ -4675,6 +5546,47 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4675
5546
  messages
4676
5547
  });
4677
5548
  }
5549
+ if (url.pathname === "/inspector/queue" && jsRequest.method === "DELETE") {
5550
+ await runtime.actorQueueReset(ctx);
5551
+ return jsonResponse({});
5552
+ }
5553
+ if (url.pathname === "/inspector/queue" && jsRequest.method === "POST") {
5554
+ let body;
5555
+ try {
5556
+ body = await jsRequest.json();
5557
+ } catch {
5558
+ return errorResponse(
5559
+ new RivetError(
5560
+ "actor",
5561
+ "invalid_request",
5562
+ "Invalid inspector JSON body",
5563
+ { public: true }
5564
+ ),
5565
+ 400
5566
+ );
5567
+ }
5568
+ const name = body.name ?? "";
5569
+ if (name === "") {
5570
+ return errorResponse(
5571
+ new RivetError(
5572
+ "actor",
5573
+ "invalid_request",
5574
+ "Queue message name must not be empty",
5575
+ { public: true }
5576
+ ),
5577
+ 400
5578
+ );
5579
+ }
5580
+ const cbor = encodeCborCompat(
5581
+ body.body ?? null
5582
+ );
5583
+ const message = await runtime.actorQueueSend(ctx, name, cbor);
5584
+ return jsonResponse({
5585
+ id: message.id().toString(),
5586
+ name: message.name(),
5587
+ createdAtMs: message.createdAt()
5588
+ });
5589
+ }
4678
5590
  if (url.pathname === "/inspector/traces" && jsRequest.method === "GET") {
4679
5591
  return jsonResponse({ otlp: [], clamped: false });
4680
5592
  }
@@ -4699,6 +5611,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4699
5611
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0
4700
5612
  });
4701
5613
  } catch (error) {
5614
+ logger2().error({
5615
+ msg: "error replaying workflow history",
5616
+ error
5617
+ });
4702
5618
  return errorResponse(error);
4703
5619
  }
4704
5620
  }
@@ -4839,17 +5755,34 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4839
5755
  );
4840
5756
  }
4841
5757
  const body = await jsRequest.json();
5758
+ if (body.args !== void 0 && body.properties !== void 0) {
5759
+ return jsonResponse(
5760
+ { error: "use either args or properties, not both" },
5761
+ { status: 400 }
5762
+ );
5763
+ }
5764
+ if (body.properties !== void 0 && (body.properties === null || typeof body.properties !== "object" || Array.isArray(body.properties))) {
5765
+ return jsonResponse(
5766
+ { error: "properties must be an object" },
5767
+ { status: 400 }
5768
+ );
5769
+ }
5770
+ const args = body.properties !== void 0 ? [body.properties] : normalizeArgs(body.args);
4842
5771
  try {
4843
5772
  const output = await action(
4844
5773
  actorCtx,
4845
5774
  ...validateActionArgs(
4846
5775
  schemaConfig.actionInputSchemas,
4847
5776
  actionName,
4848
- body.args ?? []
5777
+ args
4849
5778
  )
4850
5779
  );
4851
5780
  return jsonResponse({ output });
4852
5781
  } catch (error) {
5782
+ logger2().error({
5783
+ msg: "Error handling inspector action request",
5784
+ error
5785
+ });
4853
5786
  return errorResponse(error);
4854
5787
  }
4855
5788
  }
@@ -4863,6 +5796,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4863
5796
  { status: 404 }
4864
5797
  );
4865
5798
  } catch (error) {
5799
+ logger2().error({
5800
+ msg: "Error handling inspector request",
5801
+ error
5802
+ });
4866
5803
  return errorResponse(error);
4867
5804
  } finally {
4868
5805
  await actorCtx.dispose();
@@ -4985,29 +5922,33 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4985
5922
  async (error, payload) => {
4986
5923
  const { ctx } = unwrapTsfnPayload(error, payload);
4987
5924
  const actorCtx = makeActorCtx(ctx);
5925
+ const saveActorState = async () => {
5926
+ if (runtime.kind === "wasm") {
5927
+ await runtime.actorSaveState(
5928
+ ctx,
5929
+ actorCtx.serializeForTick("save")
5930
+ );
5931
+ } else {
5932
+ await actorCtx.saveState({
5933
+ immediate: true
5934
+ });
5935
+ }
5936
+ };
4988
5937
  try {
4989
5938
  if (onSleep) {
4990
- try {
4991
- await onSleep(actorCtx);
4992
- } finally {
4993
- if (runtime.kind === "wasm") {
4994
- await runtime.actorSaveState(
4995
- ctx,
4996
- actorCtx.serializeForTick("save")
4997
- );
4998
- } else {
4999
- await actorCtx.saveState({ immediate: true });
5000
- }
5001
- }
5939
+ await onSleep(actorCtx);
5002
5940
  }
5941
+ await saveActorState();
5003
5942
  } finally {
5004
- const runtimeState = getNativeRuntimeState(runtime, ctx);
5005
- if ((runtimeState.keepAwakeCount ?? 0) > 0) {
5006
- runtimeState.deferSleepCleanupUntilKeepAwakeIdle = true;
5007
- } else {
5008
- await cleanupNativeSleepRuntimeState(runtime, ctx);
5943
+ try {
5944
+ await cleanupNativeSleepRuntimeState(
5945
+ runtime,
5946
+ ctx,
5947
+ saveActorState
5948
+ );
5949
+ } finally {
5950
+ await actorCtx.dispose();
5009
5951
  }
5010
- await actorCtx.dispose();
5011
5952
  }
5012
5953
  }
5013
5954
  ),
@@ -5020,6 +5961,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5020
5961
  await config.onDestroy(actorCtx);
5021
5962
  }
5022
5963
  } finally {
5964
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
5965
+ nativeRunHandlerActiveByActorId.delete(actorId);
5966
+ disposeRunInspector(config.run, actorId);
5023
5967
  resolveNativeDestroy(runtime, ctx);
5024
5968
  await actorCtx.closeDatabase();
5025
5969
  clearNativeRuntimeState(runtime, ctx);
@@ -5240,23 +6184,12 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5240
6184
  requestCtx,
5241
6185
  jsRequest
5242
6186
  );
5243
- if (!(response instanceof Response)) {
6187
+ if (!isResponseLike(response)) {
5244
6188
  throw new Error(
5245
6189
  "onRequest handler must return a Response"
5246
6190
  );
5247
6191
  }
5248
6192
  return await toRuntimeHttpResponse(response);
5249
- } catch (error2) {
5250
- const encodingHeader = jsRequest.headers.get(HEADER_ENCODING);
5251
- const encoding = encodingHeader === "cbor" || encodingHeader === "bare" ? encodingHeader : "json";
5252
- const path = new URL(jsRequest.url).pathname;
5253
- return await toRuntimeHttpResponse(
5254
- buildNativeRequestErrorResponse(
5255
- encoding,
5256
- path,
5257
- error2
5258
- )
5259
- );
5260
6193
  } finally {
5261
6194
  await (requestCtx == null ? void 0 : requestCtx.dispose());
5262
6195
  if (conn) {
@@ -5304,7 +6237,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5304
6237
  try {
5305
6238
  await run(actorCtx);
5306
6239
  } finally {
5307
- nativeRunHandlerActiveByActorId.set(actorId, false);
6240
+ nativeRunHandlerActiveByActorId.delete(actorId);
5308
6241
  await actorCtx.dispose();
5309
6242
  }
5310
6243
  }
@@ -5315,7 +6248,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5315
6248
  var _a2;
5316
6249
  const { ctx } = unwrapTsfnPayload(error, payload);
5317
6250
  const history = (_a2 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a2.getHistory();
5318
- return history == null ? void 0 : encodeValue(history);
6251
+ return history == null ? void 0 : toUint8Array(history);
5319
6252
  }
5320
6253
  ) : void 0,
5321
6254
  replayWorkflow: getRunInspectorConfig(config.run) !== void 0 ? wrapNativeCallback(
@@ -5331,7 +6264,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5331
6264
  const history = await workflowInspector.replayFromStep(
5332
6265
  entryId
5333
6266
  ) ?? null;
5334
- return history == null ? void 0 : encodeValue(history);
6267
+ return history == null ? void 0 : toUint8Array(history);
5335
6268
  }
5336
6269
  ) : void 0,
5337
6270
  actions: Object.fromEntries(
@@ -5339,7 +6272,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5339
6272
  name,
5340
6273
  wrapNativeCallback(
5341
6274
  async (error, payload) => {
5342
- const { ctx, conn, args, cancelToken } = unwrapTsfnPayload(error, payload);
6275
+ const { ctx, conn, args, scheduledFire, cancelToken } = unwrapTsfnPayload(error, payload);
5343
6276
  const actorCtx = conn != null ? makeConnCtx(ctx, conn, void 0, cancelToken) : makeActorCtx(ctx, void 0, cancelToken);
5344
6277
  try {
5345
6278
  return encodeValue(
@@ -5349,7 +6282,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5349
6282
  schemaConfig.actionInputSchemas,
5350
6283
  name,
5351
6284
  decodeArgs(args)
5352
- )
6285
+ ),
6286
+ ...scheduledFire ? [scheduledFire] : []
5353
6287
  )
5354
6288
  );
5355
6289
  } finally {
@@ -5437,7 +6371,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5437
6371
  };
5438
6372
  return runtime.createActorFactory(
5439
6373
  callbacks,
5440
- buildActorConfig(definition, registryConfig)
6374
+ buildActorConfig(definition, registryConfig, runtime.kind)
5441
6375
  );
5442
6376
  }
5443
6377
  async function buildServeConfig(config) {
@@ -5460,10 +6394,17 @@ async function buildServeConfig(config) {
5460
6394
  serverlessValidateEndpoint: config.validateServerlessEndpoint,
5461
6395
  serverlessMaxStartPayloadBytes: config.serverless.maxStartPayloadBytes
5462
6396
  };
5463
- if (config.startEngine) {
6397
+ try {
5464
6398
  const { getEnginePath } = await loadEngineCli();
5465
6399
  serveConfig.engineBinaryPath = getEnginePath();
6400
+ } catch (error) {
6401
+ logger2().warn({
6402
+ 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",
6403
+ error: stringifyError(error)
6404
+ });
5466
6405
  }
6406
+ serveConfig.engineHost = config.engineHost;
6407
+ serveConfig.enginePort = config.enginePort;
5467
6408
  if ((_a = config.test) == null ? void 0 : _a.enabled) {
5468
6409
  serveConfig.inspectorTestToken = getEnvUniversal("_RIVET_TEST_INSPECTOR_TOKEN") ?? "token";
5469
6410
  }
@@ -5474,6 +6415,9 @@ async function buildRegistryWithRuntime(config, runtime) {
5474
6415
  if (((_a = config.test) == null ? void 0 : _a.enabled) && getEnvUniversal("_RIVET_TEST_INSPECTOR_TOKEN") === void 0) {
5475
6416
  trySetProcessEnv("_RIVET_TEST_INSPECTOR_TOKEN", "token");
5476
6417
  }
6418
+ if (runtime.kind === "napi") {
6419
+ importNodeDependencies();
6420
+ }
5477
6421
  const registry = runtime.createRegistry();
5478
6422
  for (const [name, definition] of Object.entries(config.use)) {
5479
6423
  runtime.registerActor(
@@ -5497,8 +6441,48 @@ async function buildConfiguredRegistry(config) {
5497
6441
  }
5498
6442
 
5499
6443
  // src/registry/index.ts
6444
+ var REGISTRY_READY_TIMEOUT_MS = 3e4;
6445
+ function signalExitCode(signal) {
6446
+ switch (signal) {
6447
+ case "SIGINT":
6448
+ return 130;
6449
+ case "SIGTERM":
6450
+ return 143;
6451
+ }
6452
+ }
6453
+ function finishShutdownSignal(signal) {
6454
+ if (process.pid === 1) {
6455
+ process.exit(signalExitCode(signal));
6456
+ }
6457
+ process.kill(process.pid, signal);
6458
+ }
6459
+ function createApplicationFetch(application) {
6460
+ return async (request) => {
6461
+ const method2 = request.method.toUpperCase();
6462
+ const body = method2 === "GET" || method2 === "HEAD" || request.body.length === 0 ? void 0 : Uint8Array.from(request.body).buffer;
6463
+ const response = await application.fetch(
6464
+ new Request(request.url, {
6465
+ method: method2,
6466
+ headers: request.headers,
6467
+ body
6468
+ })
6469
+ );
6470
+ if (!isResponseLike(response)) {
6471
+ throw new TypeError(
6472
+ "registry.listen() application fetch must return a Response"
6473
+ );
6474
+ }
6475
+ return {
6476
+ status: response.status,
6477
+ headers: Object.fromEntries(response.headers.entries()),
6478
+ body: new Uint8Array(await response.arrayBuffer())
6479
+ };
6480
+ };
6481
+ }
5500
6482
  var Registry = class {
5501
6483
  #config;
6484
+ #buildConfiguredRegistry;
6485
+ routes;
5502
6486
  get config() {
5503
6487
  return this.#config;
5504
6488
  }
@@ -5506,25 +6490,44 @@ var Registry = class {
5506
6490
  return RegistryConfigSchema.parse(this.#config);
5507
6491
  }
5508
6492
  #runtimeServePromise;
6493
+ #runtimeServeLifecyclePromise;
6494
+ #runtimeReadyPromise;
5509
6495
  #runtimeServeConfiguredPromise;
5510
6496
  #runtimeServerlessPromise;
6497
+ #applicationListenerPromise;
5511
6498
  #configureServerlessPoolPromise;
5512
6499
  #welcomePrinted = false;
5513
6500
  #shutdownInstalled = false;
5514
6501
  #shutdownInFlight = null;
5515
6502
  #signalHandlers = {};
5516
- constructor(config) {
6503
+ constructor(config, deps) {
6504
+ var _a;
5517
6505
  this.#config = config;
6506
+ if ((_a = config.logging) == null ? void 0 : _a.baseLogger) {
6507
+ configureBaseLogger(config.logging.baseLogger);
6508
+ }
6509
+ this.#buildConfiguredRegistry = (deps == null ? void 0 : deps.buildConfiguredRegistry) ?? buildConfiguredRegistry;
6510
+ this.routes = {
6511
+ health: () => this.#healthRoute(),
6512
+ metadata: () => this.#metadataRoute(),
6513
+ prometheusMetrics: (request) => this.#prometheusMetricsRoute(request)
6514
+ };
5518
6515
  }
6516
+ /**
6517
+ * Fires `configureServerlessPool` once per process when the registry
6518
+ * config opts into it. Cached on the instance so repeated calls (from
6519
+ * `handler()` and `listen()`) only run the upsert once. The retry loop
6520
+ * inside `configureServerlessPool` tolerates the engine still warming up.
6521
+ */
5519
6522
  #ensureServerlessPoolConfigured(config) {
5520
6523
  if (!config.configurePool) return void 0;
5521
6524
  if (!this.#configureServerlessPoolPromise) {
5522
- this.#configureServerlessPoolPromise = configureServerlessPool(config).catch(
5523
- (error) => {
5524
- this.#configureServerlessPoolPromise = void 0;
5525
- throw error;
5526
- }
5527
- );
6525
+ this.#configureServerlessPoolPromise = configureServerlessPool(
6526
+ config
6527
+ ).catch((error) => {
6528
+ this.#configureServerlessPoolPromise = void 0;
6529
+ throw error;
6530
+ });
5528
6531
  this.#configureServerlessPoolPromise.catch(() => {
5529
6532
  });
5530
6533
  }
@@ -5545,7 +6548,7 @@ var Registry = class {
5545
6548
  const config = this.parseConfig();
5546
6549
  this.#printWelcome(config, "serverless");
5547
6550
  if (!this.#runtimeServerlessPromise) {
5548
- this.#runtimeServerlessPromise = buildConfiguredRegistry(config);
6551
+ this.#runtimeServerlessPromise = this.#buildConfiguredRegistry(config);
5549
6552
  }
5550
6553
  const { runtime, registry, serveConfig } = await this.#runtimeServerlessPromise;
5551
6554
  const isStartRequest = isServerlessStartRequest(
@@ -5560,7 +6563,7 @@ var Registry = class {
5560
6563
  if (isStartRequest) {
5561
6564
  try {
5562
6565
  await this.#ensureServerlessPoolConfigured(config);
5563
- } catch (error) {
6566
+ } catch (_error) {
5564
6567
  return new Response(
5565
6568
  JSON.stringify({
5566
6569
  group: "guard",
@@ -5674,7 +6677,7 @@ var Registry = class {
5674
6677
  if (isMetadataRequest && !isEngineMetadataRequest) {
5675
6678
  try {
5676
6679
  await this.#ensureServerlessPoolConfigured(config);
5677
- } catch (error) {
6680
+ } catch (_error) {
5678
6681
  return new Response(
5679
6682
  JSON.stringify({
5680
6683
  group: "guard",
@@ -5707,40 +6710,201 @@ var Registry = class {
5707
6710
  fetch: (request) => this.handler(request)
5708
6711
  };
5709
6712
  }
5710
- async diagnostics() {
5711
- var _a;
6713
+ /**
6714
+ * Bind an HTTP listener provided by the native (Rust) runtime and serve
6715
+ * the registry's serverless endpoints over it. Resolves only after the
6716
+ * registry is shut down (SIGINT/SIGTERM or `nativeRegistry.shutdown()`).
6717
+ *
6718
+ * @param opts.port Port to listen on. Defaults to `process.env.RIVET_PORT`
6719
+ * if set, otherwise 3000.
6720
+ * @param opts.host Address to bind. Defaults to `0.0.0.0`.
6721
+ * @param opts.publicDir If set, serves static files from this directory
6722
+ * as a fallback below the framework routes.
6723
+ * @param opts.application If set, handles requests that do not match a
6724
+ * framework route.
6725
+ *
6726
+ * @example
6727
+ * ```ts
6728
+ * await registry.listen();
6729
+ * await registry.listen({ application: app });
6730
+ * ```
6731
+ */
6732
+ async listen(opts = {}) {
6733
+ const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3e3;
6734
+ const publicDir = opts.publicDir ?? getRivetkitPublicDir();
6735
+ const config = this.parseConfig();
6736
+ const application = opts.application ? createApplicationFetch(opts.application) : void 0;
6737
+ if (application && getRivetkitRuntimeMode() !== "serverless") {
6738
+ if (config.runtime === "wasm") {
6739
+ throw new Error(
6740
+ "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly"
6741
+ );
6742
+ }
6743
+ this.#installSignalHandlers(config);
6744
+ this.#printWelcome(config, "serverful", {
6745
+ port,
6746
+ host: opts.host,
6747
+ publicDir
6748
+ });
6749
+ this.#startEnvoy(config, true);
6750
+ const readyPromise = this.startAndWait();
6751
+ const configuredRegistryPromise2 = this.#runtimeServeConfiguredPromise;
6752
+ if (!configuredRegistryPromise2) {
6753
+ throw new Error("registry envoy startup did not initialize");
6754
+ }
6755
+ const { runtime: runtime2, registry: registry2, serveConfig: serveConfig2 } = await configuredRegistryPromise2;
6756
+ const listenerPromise = runtime2.serveApplicationListener(
6757
+ registry2,
6758
+ {
6759
+ port,
6760
+ host: opts.host,
6761
+ publicDir,
6762
+ application
6763
+ },
6764
+ serveConfig2
6765
+ );
6766
+ this.#applicationListenerPromise = listenerPromise;
6767
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
6768
+ if (!serveLifecyclePromise) {
6769
+ throw new Error(
6770
+ "registry envoy serve lifecycle did not initialize"
6771
+ );
6772
+ }
6773
+ await Promise.all([
6774
+ readyPromise,
6775
+ listenerPromise,
6776
+ serveLifecyclePromise
6777
+ ]);
6778
+ return;
6779
+ }
6780
+ const configuredRegistryPromise = buildConfiguredRegistry(config);
6781
+ this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
6782
+ this.#runtimeServerlessPromise = configuredRegistryPromise;
6783
+ this.#installSignalHandlers(config);
6784
+ this.#printWelcome(config, "serverless", {
6785
+ port,
6786
+ host: opts.host,
6787
+ publicDir
6788
+ });
6789
+ this.#ensureServerlessPoolConfigured(config);
6790
+ const { runtime, registry, serveConfig } = await configuredRegistryPromise;
6791
+ await runtime.serveListener(
6792
+ registry,
6793
+ {
6794
+ port,
6795
+ host: opts.host,
6796
+ publicDir,
6797
+ application
6798
+ },
6799
+ serveConfig
6800
+ );
6801
+ }
6802
+ /**
6803
+ * Returns a health response suitable for mounting in a user-owned router.
6804
+ */
6805
+ async #healthRoute() {
6806
+ const configured = await this.#activeConfiguredRegistry();
6807
+ if (!configured) {
6808
+ return jsonRouteResponse(503, {
6809
+ status: "not_started",
6810
+ runtime: "rivetkit",
6811
+ version: VERSION
6812
+ });
6813
+ }
6814
+ const { runtime, registry } = configured;
6815
+ if (!runtime.registryHealth) {
6816
+ return jsonRouteResponse(501, {
6817
+ status: "unsupported",
6818
+ runtime: "rivetkit",
6819
+ version: VERSION
6820
+ });
6821
+ }
6822
+ const response = await runtime.registryHealth(registry);
6823
+ return new Response(new Uint8Array(response.body), {
6824
+ status: response.status,
6825
+ headers: response.headers
6826
+ });
6827
+ }
6828
+ /**
6829
+ * Returns serverless metadata suitable for mounting in a user-owned router.
6830
+ */
6831
+ async #metadataRoute() {
6832
+ const configured = await this.#activeConfiguredRegistry();
6833
+ if (!configured) {
6834
+ return new Response("registry not started\n", {
6835
+ status: 503,
6836
+ headers: { "content-type": "text/plain; charset=utf-8" }
6837
+ });
6838
+ }
6839
+ const { runtime, registry } = configured;
6840
+ if (!runtime.registryMetadata) {
6841
+ return new Response("metadata is not supported by this runtime\n", {
6842
+ status: 501,
6843
+ headers: { "content-type": "text/plain; charset=utf-8" }
6844
+ });
6845
+ }
6846
+ const response = await runtime.registryMetadata(registry);
6847
+ return new Response(new Uint8Array(response.body), {
6848
+ status: response.status,
6849
+ headers: response.headers
6850
+ });
6851
+ }
6852
+ /**
6853
+ * Returns a Prometheus metrics response suitable for mounting in a user-owned router.
6854
+ */
6855
+ async #prometheusMetricsRoute(_request) {
6856
+ const configured = await this.#activeConfiguredRegistry();
6857
+ if (!configured) {
6858
+ return new Response("registry not started\n", {
6859
+ status: 503,
6860
+ headers: { "content-type": "text/plain; charset=utf-8" }
6861
+ });
6862
+ }
6863
+ const { runtime, registry } = configured;
6864
+ if (!runtime.registryMetrics) {
6865
+ return new Response("metrics are not supported by this runtime\n", {
6866
+ status: 501,
6867
+ headers: { "content-type": "text/plain; charset=utf-8" }
6868
+ });
6869
+ }
6870
+ const response = await runtime.registryMetrics(registry);
6871
+ return new Response(new Uint8Array(response.body), {
6872
+ status: response.status,
6873
+ headers: response.headers
6874
+ });
6875
+ }
6876
+ async #activeConfiguredRegistry() {
5712
6877
  const candidates = [
5713
6878
  this.#runtimeServerlessPromise,
5714
6879
  this.#runtimeServeConfiguredPromise
5715
6880
  ].filter(
5716
6881
  (candidate) => candidate !== void 0
5717
6882
  );
5718
- for (const candidate of candidates) {
5719
- const { runtime, registry } = await candidate;
5720
- const diagnostics = await ((_a = runtime.registryDiagnostics) == null ? void 0 : _a.call(runtime, registry));
5721
- if (diagnostics) return diagnostics;
5722
- }
5723
- return { mode: "not_started", envoyActiveActorCount: null };
6883
+ if (candidates.length === 0) return void 0;
6884
+ return await candidates[0];
5724
6885
  }
5725
6886
  /**
5726
6887
  * Starts an actor envoy for standalone server deployments.
5727
6888
  */
5728
6889
  #startEnvoy(config, printWelcome) {
5729
6890
  if (!this.#runtimeServePromise) {
5730
- const configuredRegistryPromise = buildConfiguredRegistry(config);
6891
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config);
5731
6892
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
5732
- this.#runtimeServePromise = configuredRegistryPromise.then(async ({ runtime, registry, serveConfig }) => {
5733
- await runtime.serveRegistry(registry, serveConfig);
5734
- }).catch((err) => {
5735
- logger2().warn({ err }, "runtime registry serve errored");
6893
+ this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(
6894
+ async ({ runtime, registry, serveConfig }) => {
6895
+ await runtime.serveRegistry(registry, serveConfig);
6896
+ }
6897
+ );
6898
+ this.#runtimeServePromise = this.#runtimeServeLifecyclePromise.catch((error) => {
6899
+ logger2().warn({ error }, "runtime registry serve errored");
5736
6900
  });
5737
- this.#installSignalHandlers(config, configuredRegistryPromise);
6901
+ this.#installSignalHandlers(config);
5738
6902
  }
5739
6903
  if (printWelcome) {
5740
6904
  this.#printWelcome(config, "serverful");
5741
6905
  }
5742
6906
  }
5743
- #installSignalHandlers(config, configuredRegistryPromise) {
6907
+ #installSignalHandlers(config) {
5744
6908
  var _a;
5745
6909
  if (this.#shutdownInstalled) return;
5746
6910
  if ((_a = config.shutdown) == null ? void 0 : _a.disableSignalHandlers) return;
@@ -5749,58 +6913,86 @@ var Registry = class {
5749
6913
  }
5750
6914
  this.#shutdownInstalled = true;
5751
6915
  const install = (signal) => {
5752
- const handler = () => this.#onShutdownSignal(
5753
- signal,
5754
- config,
5755
- configuredRegistryPromise
5756
- );
6916
+ const handler = () => this.#onShutdownSignal(signal, config);
5757
6917
  this.#signalHandlers[signal] = handler;
5758
6918
  process.on(signal, handler);
5759
6919
  };
5760
6920
  install("SIGINT");
5761
6921
  install("SIGTERM");
5762
6922
  }
5763
- #onShutdownSignal(signal, config, configuredRegistryPromise) {
6923
+ #onShutdownSignal(signal, config) {
5764
6924
  if (this.#shutdownInFlight !== null) {
5765
6925
  this.#removeSignalHandlers();
5766
- process.kill(process.pid, signal);
6926
+ finishShutdownSignal(signal);
5767
6927
  return;
5768
6928
  }
5769
- this.#shutdownInFlight = this.#runShutdown(
5770
- signal,
5771
- config,
5772
- configuredRegistryPromise
5773
- ).catch((err) => {
6929
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
5774
6930
  logger2().warn({ err }, "shutdown error");
6931
+ }).then(() => {
6932
+ this.#removeSignalHandlers();
6933
+ finishShutdownSignal(signal);
5775
6934
  });
5776
6935
  }
5777
- async #runShutdown(signal, config, configuredRegistryPromise) {
6936
+ /**
6937
+ * Gracefully drains all live registries.
6938
+ *
6939
+ * Programmatic counterpart to the SIGINT/SIGTERM handlers: tears down
6940
+ * every live `CoreRegistry` (both `start()` and `handler()` modes) and
6941
+ * waits for the serve promise to resolve, all bounded by the shutdown
6942
+ * grace period. Unlike a signal-driven shutdown, this does not re-raise a
6943
+ * signal or exit the process. The caller owns process lifetime.
6944
+ *
6945
+ * Idempotent: concurrent or repeated calls share a single drain. Safe to
6946
+ * call even if nothing has been started.
6947
+ *
6948
+ * @example
6949
+ * ```ts
6950
+ * const registry = setup({ use: { counter } });
6951
+ * registry.start();
6952
+ * // ...later, on your own shutdown trigger:
6953
+ * await registry.shutdown();
6954
+ * ```
6955
+ */
6956
+ async shutdown() {
6957
+ if (this.#shutdownInFlight !== null) return this.#shutdownInFlight;
6958
+ const config = this.parseConfig();
6959
+ this.#removeSignalHandlers();
6960
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
6961
+ logger2().warn({ err }, "shutdown error");
6962
+ });
6963
+ return this.#shutdownInFlight;
6964
+ }
6965
+ async #drain(config) {
5778
6966
  var _a;
5779
- const gracePeriodMs = ((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs) ?? 3e4;
6967
+ const modeAPromise = this.#runtimeServeConfiguredPromise;
6968
+ const modeBPromise = this.#runtimeServerlessPromise;
6969
+ const gracePeriodMs = ((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs) ?? await this.#actorStopThresholdMs(modeAPromise ?? modeBPromise) ?? 30 * 60 * 1e3;
5780
6970
  const drain = async () => {
5781
- const registries = [
5782
- (async () => {
5783
- try {
5784
- const { runtime, registry } = await configuredRegistryPromise;
5785
- await runtime.shutdownRegistry(registry);
5786
- } catch (err) {
5787
- logger2().warn(
5788
- { err },
5789
- "runtime registry shutdown errored (mode A)"
5790
- );
5791
- }
5792
- })()
5793
- ];
5794
- const runtimeServerlessPromise = this.#runtimeServerlessPromise;
5795
- if (runtimeServerlessPromise !== void 0) {
6971
+ const registries = [];
6972
+ if (modeAPromise !== void 0) {
5796
6973
  registries.push(
5797
6974
  (async () => {
5798
6975
  try {
5799
- const { runtime, registry } = await runtimeServerlessPromise;
6976
+ const { runtime, registry } = await modeAPromise;
5800
6977
  await runtime.shutdownRegistry(registry);
5801
6978
  } catch (err) {
5802
6979
  logger2().warn(
5803
6980
  { err },
6981
+ "runtime registry shutdown errored (mode A)"
6982
+ );
6983
+ }
6984
+ })()
6985
+ );
6986
+ }
6987
+ if (modeBPromise !== void 0) {
6988
+ registries.push(
6989
+ (async () => {
6990
+ try {
6991
+ const { runtime, registry } = await modeBPromise;
6992
+ await runtime.shutdownRegistry(registry);
6993
+ } catch (err) {
6994
+ logger2().warn(
6995
+ { error: err },
5804
6996
  "runtime registry shutdown errored (mode B)"
5805
6997
  );
5806
6998
  }
@@ -5812,6 +7004,9 @@ var Registry = class {
5812
7004
  if (runtimeServePromise !== void 0) {
5813
7005
  await runtimeServePromise.catch(() => void 0);
5814
7006
  }
7007
+ if (this.#applicationListenerPromise !== void 0) {
7008
+ await this.#applicationListenerPromise.catch(() => void 0);
7009
+ }
5815
7010
  };
5816
7011
  await Promise.race([
5817
7012
  drain(),
@@ -5822,8 +7017,23 @@ var Registry = class {
5822
7017
  }
5823
7018
  )
5824
7019
  ]);
5825
- this.#removeSignalHandlers();
5826
- process.kill(process.pid, signal);
7020
+ }
7021
+ async #actorStopThresholdMs(configuredRegistryPromise) {
7022
+ var _a;
7023
+ if (configuredRegistryPromise === void 0) return void 0;
7024
+ try {
7025
+ const { runtime, registry } = await configuredRegistryPromise;
7026
+ const thresholdMs = await ((_a = runtime.registryActorStopThresholdMs) == null ? void 0 : _a.call(runtime, registry));
7027
+ if (thresholdMs !== void 0 && Number.isFinite(thresholdMs) && thresholdMs > 0) {
7028
+ return thresholdMs;
7029
+ }
7030
+ } catch (err) {
7031
+ logger2().warn(
7032
+ { err },
7033
+ "failed to read actor stop threshold for shutdown grace"
7034
+ );
7035
+ }
7036
+ return void 0;
5827
7037
  }
5828
7038
  #removeSignalHandlers() {
5829
7039
  for (const [signal, handler] of Object.entries(
@@ -5836,9 +7046,86 @@ var Registry = class {
5836
7046
  startEnvoy() {
5837
7047
  this.#startEnvoy(this.parseConfig(), true);
5838
7048
  }
7049
+ /**
7050
+ * Starts the serverful registry if needed and waits until its envoy has
7051
+ * registered with the Engine. Repeated and concurrent calls share one
7052
+ * startup lifecycle and readiness promise.
7053
+ *
7054
+ * Unlike {@link start}, this reports startup failures and does not resolve
7055
+ * merely because an HTTP health endpoint is listening.
7056
+ */
7057
+ startAndWait() {
7058
+ if (this.#shutdownInFlight !== null) {
7059
+ return Promise.reject(
7060
+ new Error(
7061
+ "registry.startAndWait() cannot run after shutdown has begun"
7062
+ )
7063
+ );
7064
+ }
7065
+ if (this.#runtimeReadyPromise) return this.#runtimeReadyPromise;
7066
+ if (getRivetkitRuntimeMode() === "serverless") {
7067
+ return Promise.reject(
7068
+ new Error(
7069
+ "registry.startAndWait() requires envoy runtime mode; serverless registries become ready per request"
7070
+ )
7071
+ );
7072
+ }
7073
+ const config = this.parseConfig();
7074
+ if (config.runtime === "wasm") {
7075
+ return Promise.reject(
7076
+ new Error(
7077
+ "registry.startAndWait() requires the native runtime; WebAssembly registries do not host an envoy"
7078
+ )
7079
+ );
7080
+ }
7081
+ this.#startEnvoy(config, true);
7082
+ const configuredRegistryPromise = this.#runtimeServeConfiguredPromise;
7083
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
7084
+ if (!configuredRegistryPromise || !serveLifecyclePromise) {
7085
+ throw new Error("registry envoy startup did not initialize");
7086
+ }
7087
+ let timeout;
7088
+ const timeoutPromise = new Promise((_resolve, reject) => {
7089
+ var _a;
7090
+ timeout = setTimeout(
7091
+ () => reject(
7092
+ new Error(
7093
+ `RivetKit registry did not register with the Engine within ${REGISTRY_READY_TIMEOUT_MS}ms`
7094
+ )
7095
+ ),
7096
+ REGISTRY_READY_TIMEOUT_MS
7097
+ );
7098
+ (_a = timeout.unref) == null ? void 0 : _a.call(timeout);
7099
+ });
7100
+ const readinessPromise = (async () => {
7101
+ const { runtime, registry } = await configuredRegistryPromise;
7102
+ const stoppedBeforeReady = serveLifecyclePromise.then(() => {
7103
+ throw new Error(
7104
+ "RivetKit registry stopped before becoming ready"
7105
+ );
7106
+ });
7107
+ await Promise.race([
7108
+ runtime.waitRegistryReady(registry),
7109
+ stoppedBeforeReady
7110
+ ]);
7111
+ })();
7112
+ this.#runtimeReadyPromise = Promise.race([
7113
+ readinessPromise,
7114
+ timeoutPromise
7115
+ ]).finally(() => {
7116
+ if (timeout !== void 0) clearTimeout(timeout);
7117
+ });
7118
+ this.#runtimeReadyPromise.catch(() => {
7119
+ });
7120
+ return this.#runtimeReadyPromise;
7121
+ }
5839
7122
  /**
5840
7123
  * Starts the actor envoy for standalone server deployments.
5841
7124
  *
7125
+ * Set `RIVETKIT_RUNTIME_MODE=serverless` to instead bind an HTTP listener
7126
+ * via `listen()` (Mode B). Mode A (envoy) and Mode B (listener) are
7127
+ * mutually exclusive per registry instance.
7128
+ *
5842
7129
  * @example
5843
7130
  * ```ts
5844
7131
  * const registry = setup({ use: { counter } });
@@ -5846,10 +7133,20 @@ var Registry = class {
5846
7133
  * ```
5847
7134
  */
5848
7135
  start() {
7136
+ if (getRivetkitRuntimeMode() === "serverless") {
7137
+ const publicDir = getRivetkitPublicDir() ?? "/public";
7138
+ this.listen({ publicDir }).catch((error) => {
7139
+ logger2().error({ error }, "auto-listen failed; exiting");
7140
+ if (typeof process !== "undefined" && typeof process.exit === "function") {
7141
+ process.exit(1);
7142
+ }
7143
+ });
7144
+ return;
7145
+ }
5849
7146
  const config = this.parseConfig();
5850
7147
  this.#startEnvoy(config, true);
5851
7148
  }
5852
- #printWelcome(config, kind) {
7149
+ #printWelcome(config, kind, listener) {
5853
7150
  if (config.noWelcome || this.#welcomePrinted) return;
5854
7151
  this.#welcomePrinted = true;
5855
7152
  const logLine = (label, value) => {
@@ -5864,13 +7161,20 @@ var Registry = class {
5864
7161
  logLine("Namespace", config.namespace);
5865
7162
  }
5866
7163
  if (config.endpoint) {
5867
- const endpointType = config.endpoint === ENGINE_ENDPOINT ? "local native" : "remote";
7164
+ const endpointType = config.startEngine || isLocalEngineEndpoint(config.endpoint) ? "local native" : "remote";
5868
7165
  logLine("Endpoint", `${config.endpoint} (${endpointType})`);
5869
7166
  }
5870
7167
  if (kind === "serverless" && config.publicEndpoint) {
5871
7168
  logLine("Client", config.publicEndpoint);
5872
7169
  }
5873
7170
  logLine("Actors", Object.keys(config.use).length.toString());
7171
+ if (listener) {
7172
+ const host = listener.host ?? "0.0.0.0";
7173
+ logLine("Listening", `http://${host}:${listener.port}`);
7174
+ if (listener.publicDir) {
7175
+ logLine("Public Dir", listener.publicDir);
7176
+ }
7177
+ }
5874
7178
  console.log();
5875
7179
  }
5876
7180
  };
@@ -5886,6 +7190,12 @@ function isServerlessMetadataRequest(request, basePath) {
5886
7190
  const normalizedBase = basePath === "/" ? "" : `/${basePath.replace(/^\/+|\/+$/g, "")}`;
5887
7191
  return parsed.pathname === `${normalizedBase}/metadata`;
5888
7192
  }
7193
+ function jsonRouteResponse(status, body) {
7194
+ return new Response(JSON.stringify(body), {
7195
+ status,
7196
+ headers: { "content-type": "application/json" }
7197
+ });
7198
+ }
5889
7199
  function setup(input) {
5890
7200
  return new Registry(input);
5891
7201
  }