rivetkit 0.0.0-sqlite-profiling-compat.4a9a623 → 0.0.0-sqlite-sync-3x-release.a00b07f

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 (277) hide show
  1. package/dist/browser/client.d.ts +1317 -765
  2. package/dist/browser/client.js +1457 -737
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +252 -129
  5. package/dist/browser/inspector/client.js +2042 -228
  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 -1
  10. package/dist/tsup/actor/errors.d.ts +1 -1
  11. package/dist/tsup/actor/errors.js +5 -1
  12. package/dist/tsup/agent-os/index.cjs +3 -2367
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +1 -2277
  15. package/dist/tsup/agent-os/index.d.ts +1 -2277
  16. package/dist/tsup/agent-os/index.js +3 -2367
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-7QKCGUTJ.cjs → chunk-2MOLY6AM.cjs} +444 -29
  19. package/dist/tsup/chunk-2MOLY6AM.cjs.map +1 -0
  20. package/dist/tsup/{chunk-IICIOTML.js → chunk-3DONDAMG.js} +2 -2
  21. package/dist/tsup/{chunk-XIX5DOZN.js → chunk-6FEYCVZC.js} +196 -20
  22. package/dist/tsup/chunk-6FEYCVZC.js.map +1 -0
  23. package/dist/tsup/chunk-6KXVLIXL.cjs +14 -0
  24. package/dist/tsup/chunk-6KXVLIXL.cjs.map +1 -0
  25. package/dist/tsup/chunk-73RNTXHB.cjs +243 -0
  26. package/dist/tsup/chunk-73RNTXHB.cjs.map +1 -0
  27. package/dist/tsup/{chunk-HXUEHHJF.js → chunk-A2CF6PFH.js} +19 -11
  28. package/dist/tsup/chunk-A2CF6PFH.js.map +1 -0
  29. package/dist/tsup/{chunk-75UE45DE.js → chunk-BRH4PQS5.js} +436 -21
  30. package/dist/tsup/chunk-BRH4PQS5.js.map +1 -0
  31. package/dist/tsup/{chunk-2WMYYG4R.cjs → chunk-BTSDFFDC.cjs} +18 -11
  32. package/dist/tsup/chunk-BTSDFFDC.cjs.map +1 -0
  33. package/dist/tsup/{chunk-RIT7N3TX.js → chunk-D5WUPE47.js} +50 -3
  34. package/dist/tsup/chunk-D5WUPE47.js.map +1 -0
  35. package/dist/tsup/{chunk-4PX3ZKJR.js → chunk-DJUBJQEQ.js} +3 -3
  36. package/dist/tsup/chunk-DJUBJQEQ.js.map +1 -0
  37. package/dist/tsup/{chunk-3MHDOUD7.cjs → chunk-HDVZ6YZG.cjs} +197 -21
  38. package/dist/tsup/chunk-HDVZ6YZG.cjs.map +1 -0
  39. package/dist/tsup/{chunk-JZ7TWV65.js → chunk-JTHHCZCZ.js} +24 -1
  40. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  41. package/dist/tsup/{chunk-ND567FR5.cjs → chunk-JUHXV3HF.cjs} +3 -3
  42. package/dist/tsup/chunk-JUHXV3HF.cjs.map +1 -0
  43. package/dist/tsup/chunk-JUWMP5O3.js +14 -0
  44. package/dist/tsup/chunk-JUWMP5O3.js.map +1 -0
  45. package/dist/tsup/{chunk-ZA7FLHKH.cjs → chunk-KVFIONKQ.cjs} +25 -2
  46. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  47. package/dist/tsup/{chunk-4FC7TVS6.cjs → chunk-MGI2VVF6.cjs} +39 -7
  48. package/dist/tsup/chunk-MGI2VVF6.cjs.map +1 -0
  49. package/dist/tsup/{chunk-NHUTYWKU.cjs → chunk-OTVJYZ2L.cjs} +1139 -470
  50. package/dist/tsup/chunk-OTVJYZ2L.cjs.map +1 -0
  51. package/dist/tsup/{chunk-VE2X4KMG.cjs → chunk-RTWH3AX3.cjs} +18 -10
  52. package/dist/tsup/chunk-RTWH3AX3.cjs.map +1 -0
  53. package/dist/tsup/{chunk-QAVN4QNO.cjs → chunk-TM76Z7XT.cjs} +7 -7
  54. package/dist/tsup/chunk-TM76Z7XT.cjs.map +1 -0
  55. package/dist/tsup/{chunk-AGDY6TKH.js → chunk-TRUHDXOU.js} +1023 -354
  56. package/dist/tsup/chunk-TRUHDXOU.js.map +1 -0
  57. package/dist/tsup/{chunk-XFYEVYHG.js → chunk-TSQTI6H6.js} +16 -9
  58. package/dist/tsup/chunk-TSQTI6H6.js.map +1 -0
  59. package/dist/tsup/{chunk-2CICCOBL.cjs → chunk-Z7E2G3JZ.cjs} +52 -5
  60. package/dist/tsup/chunk-Z7E2G3JZ.cjs.map +1 -0
  61. package/dist/tsup/{chunk-ZZ3WBRPD.js → chunk-ZOVJDAOW.js} +38 -6
  62. package/dist/tsup/chunk-ZOVJDAOW.js.map +1 -0
  63. package/dist/tsup/chunk-ZYK4B5WV.js +243 -0
  64. package/dist/tsup/chunk-ZYK4B5WV.js.map +1 -0
  65. package/dist/tsup/client/mod.cjs +8 -9
  66. package/dist/tsup/client/mod.cjs.map +1 -1
  67. package/dist/tsup/client/mod.d.cts +32 -6
  68. package/dist/tsup/client/mod.d.ts +32 -6
  69. package/dist/tsup/client/mod.js +7 -8
  70. package/dist/tsup/common/log.cjs +5 -3
  71. package/dist/tsup/common/log.cjs.map +1 -1
  72. package/dist/tsup/common/log.d.cts +5 -1
  73. package/dist/tsup/common/log.d.ts +5 -1
  74. package/dist/tsup/common/log.js +6 -4
  75. package/dist/tsup/common/websocket.cjs +4 -4
  76. package/dist/tsup/common/websocket.cjs.map +1 -1
  77. package/dist/tsup/common/websocket.js +3 -3
  78. package/dist/tsup/{config-BR1Nn0QQ.d.ts → config-B4erdavw.d.ts} +571 -65
  79. package/dist/tsup/{config-B0LNDrLY.d.ts → config-BfG1qpYz.d.cts} +80 -14
  80. package/dist/tsup/{config-B0LNDrLY.d.cts → config-BfG1qpYz.d.ts} +80 -14
  81. package/dist/tsup/{config-tCvkwzyN.d.cts → config-DK144OAw.d.cts} +571 -65
  82. package/dist/tsup/{context-oc9zhA3x.d.ts → context-Cvnf3BRe.d.cts} +3 -2
  83. package/dist/tsup/{context-D4WDwf9m.d.cts → context-Oxi6YWcG.d.ts} +3 -2
  84. package/dist/tsup/db/drizzle.cjs +127 -67
  85. package/dist/tsup/db/drizzle.cjs.map +1 -1
  86. package/dist/tsup/db/drizzle.d.cts +8 -4
  87. package/dist/tsup/db/drizzle.d.ts +8 -4
  88. package/dist/tsup/db/drizzle.js +127 -67
  89. package/dist/tsup/db/drizzle.js.map +1 -1
  90. package/dist/tsup/db/mod.cjs +6 -126
  91. package/dist/tsup/db/mod.cjs.map +1 -1
  92. package/dist/tsup/db/mod.d.cts +8 -4
  93. package/dist/tsup/db/mod.d.ts +8 -4
  94. package/dist/tsup/db/mod.js +5 -125
  95. package/dist/tsup/db/mod.js.map +1 -1
  96. package/dist/tsup/dynamic/mod.cjs +2 -2
  97. package/dist/tsup/dynamic/mod.cjs.map +1 -1
  98. package/dist/tsup/dynamic/mod.d.cts +6 -4
  99. package/dist/tsup/dynamic/mod.d.ts +6 -4
  100. package/dist/tsup/dynamic/mod.js +1 -1
  101. package/dist/tsup/inspector/mod.cjs +47 -12
  102. package/dist/tsup/inspector/mod.cjs.map +1 -1
  103. package/dist/tsup/inspector/mod.d.cts +26 -136
  104. package/dist/tsup/inspector/mod.d.ts +26 -136
  105. package/dist/tsup/inspector/mod.js +46 -11
  106. package/dist/tsup/inspector/mod.js.map +1 -1
  107. package/dist/tsup/inspector/workflow.cjs +21 -0
  108. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  109. package/dist/tsup/inspector/workflow.d.cts +144 -0
  110. package/dist/tsup/inspector/workflow.d.ts +144 -0
  111. package/dist/tsup/inspector/workflow.js +21 -0
  112. package/dist/tsup/inspector/workflow.js.map +1 -0
  113. package/dist/tsup/inspector-tab/mod.cjs +2 -13
  114. package/dist/tsup/inspector-tab/mod.cjs.map +1 -1
  115. package/dist/tsup/inspector-tab/mod.d.cts +9 -17
  116. package/dist/tsup/inspector-tab/mod.d.ts +9 -17
  117. package/dist/tsup/inspector-tab/mod.js +1 -12
  118. package/dist/tsup/inspector-tab/mod.js.map +1 -1
  119. package/dist/tsup/mod.cjs +2724 -611
  120. package/dist/tsup/mod.cjs.map +1 -1
  121. package/dist/tsup/mod.d.cts +9 -7
  122. package/dist/tsup/mod.d.ts +9 -7
  123. package/dist/tsup/mod.js +2641 -528
  124. package/dist/tsup/mod.js.map +1 -1
  125. package/dist/tsup/test/mod.cjs +19 -17
  126. package/dist/tsup/test/mod.cjs.map +1 -1
  127. package/dist/tsup/test/mod.d.cts +6 -4
  128. package/dist/tsup/test/mod.d.ts +6 -4
  129. package/dist/tsup/test/mod.js +18 -16
  130. package/dist/tsup/test/mod.js.map +1 -1
  131. package/dist/tsup/unstable/migrations.cjs +101 -0
  132. package/dist/tsup/unstable/migrations.cjs.map +1 -0
  133. package/dist/tsup/unstable/migrations.d.cts +29 -0
  134. package/dist/tsup/unstable/migrations.d.ts +29 -0
  135. package/dist/tsup/unstable/migrations.js +101 -0
  136. package/dist/tsup/unstable/migrations.js.map +1 -0
  137. package/dist/tsup/{utils-CqDnC_PS.d.cts → utils-3rsE0JvI.d.cts} +25 -2
  138. package/dist/tsup/{utils-CqDnC_PS.d.ts → utils-3rsE0JvI.d.ts} +25 -2
  139. package/dist/tsup/utils-C1O-SklO.d.ts +162 -0
  140. package/dist/tsup/utils-C6b0aYUM.d.cts +162 -0
  141. package/dist/tsup/utils.cjs +7 -3
  142. package/dist/tsup/utils.cjs.map +1 -1
  143. package/dist/tsup/utils.d.cts +4 -147
  144. package/dist/tsup/utils.d.ts +4 -147
  145. package/dist/tsup/utils.js +6 -2
  146. package/dist/tsup/workflow/mod.cjs +260 -200
  147. package/dist/tsup/workflow/mod.cjs.map +1 -1
  148. package/dist/tsup/workflow/mod.d.cts +8 -6
  149. package/dist/tsup/workflow/mod.d.ts +8 -6
  150. package/dist/tsup/workflow/mod.js +249 -189
  151. package/dist/tsup/workflow/mod.js.map +1 -1
  152. package/package.json +34 -14
  153. package/src/actor/actions.ts +155 -0
  154. package/src/actor/config.ts +403 -43
  155. package/src/actor/definition.ts +26 -7
  156. package/src/actor/errors.ts +87 -5
  157. package/src/actor/keys.ts +86 -0
  158. package/src/actor/mod.ts +15 -1
  159. package/src/actor/tracing.ts +28 -0
  160. package/src/agent-os/index.ts +5 -65
  161. package/src/client/actor-common.ts +8 -15
  162. package/src/client/actor-conn.ts +135 -8
  163. package/src/client/actor-handle.ts +180 -42
  164. package/src/client/actor-query.ts +8 -1
  165. package/src/client/auth.ts +37 -0
  166. package/src/client/client.ts +89 -21
  167. package/src/client/config.ts +27 -2
  168. package/src/client/errors.ts +2 -1
  169. package/src/client/lifecycle-errors.ts +16 -1
  170. package/src/client/mod.ts +9 -0
  171. package/src/client/outbound-telemetry.ts +66 -0
  172. package/src/client/query.ts +2 -0
  173. package/src/client/queue.ts +3 -0
  174. package/src/client/raw-utils.ts +37 -8
  175. package/src/client/resolve-gateway-target.ts +2 -0
  176. package/src/client/retry-budget.ts +78 -0
  177. package/src/client/token-provider.ts +93 -0
  178. package/src/client/utils.ts +16 -2
  179. package/src/common/actor-router-consts.ts +5 -0
  180. package/src/common/actor-telemetry-context.ts +19 -0
  181. package/src/common/bare/generated/actor-runtime-socket-protocol/v1.ts +848 -0
  182. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  183. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  184. package/src/common/bare/transport/v1.ts +36 -0
  185. package/src/common/database/config.ts +108 -15
  186. package/src/common/database/mod.ts +247 -76
  187. package/src/common/database/native-database.ts +433 -23
  188. package/src/common/database/shared.ts +24 -0
  189. package/src/common/encoding.ts +31 -21
  190. package/src/common/fetch-like.ts +63 -0
  191. package/src/common/inspector-transport.ts +12 -2
  192. package/src/common/log.ts +14 -8
  193. package/src/common/otel-context.ts +99 -0
  194. package/src/common/router.ts +1 -1
  195. package/src/common/utils.ts +7 -19
  196. package/src/db/drizzle.ts +182 -80
  197. package/src/db/mod.ts +2 -0
  198. package/src/dynamic/isolate-runtime.ts +0 -2
  199. package/src/engine-api/actors.ts +3 -3
  200. package/src/engine-client/actor-http-client.ts +29 -20
  201. package/src/engine-client/actor-websocket-client.ts +6 -3
  202. package/src/engine-client/api-endpoints.ts +72 -14
  203. package/src/engine-client/driver.ts +8 -15
  204. package/src/engine-client/mod.ts +248 -112
  205. package/src/inspector/client.browser.ts +134 -16
  206. package/src/inspector/mod.ts +1 -1
  207. package/src/inspector/workflow.ts +61 -0
  208. package/src/inspector-tab/mod.ts +1 -15
  209. package/src/registry/config/envoy.ts +2 -18
  210. package/src/registry/config/index.ts +53 -61
  211. package/src/registry/index.ts +311 -21
  212. package/src/registry/napi-runtime.ts +583 -39
  213. package/src/registry/native-http.ts +225 -0
  214. package/src/registry/native.ts +1365 -414
  215. package/src/registry/run-handler-coordinator.ts +219 -0
  216. package/src/registry/runtime.ts +372 -7
  217. package/src/registry/wasm-runtime.ts +490 -21
  218. package/src/registry/write-through-proxy.ts +101 -0
  219. package/src/test/mod.ts +1 -19
  220. package/src/test/ready.ts +22 -0
  221. package/src/unstable/migrations.ts +141 -0
  222. package/src/utils/env-vars.ts +15 -6
  223. package/src/utils/node.ts +44 -28
  224. package/src/utils.ts +3 -0
  225. package/src/workflow/context.ts +9 -27
  226. package/src/workflow/driver.ts +253 -116
  227. package/src/workflow/inspector.ts +23 -24
  228. package/src/workflow/mod.ts +50 -72
  229. package/dist/tsup/chunk-2CICCOBL.cjs.map +0 -1
  230. package/dist/tsup/chunk-2WMYYG4R.cjs.map +0 -1
  231. package/dist/tsup/chunk-3MHDOUD7.cjs.map +0 -1
  232. package/dist/tsup/chunk-4FC7TVS6.cjs.map +0 -1
  233. package/dist/tsup/chunk-4PX3ZKJR.js.map +0 -1
  234. package/dist/tsup/chunk-75UE45DE.js.map +0 -1
  235. package/dist/tsup/chunk-7QKCGUTJ.cjs.map +0 -1
  236. package/dist/tsup/chunk-AGDY6TKH.js.map +0 -1
  237. package/dist/tsup/chunk-HXUEHHJF.js.map +0 -1
  238. package/dist/tsup/chunk-JZ7TWV65.js.map +0 -1
  239. package/dist/tsup/chunk-ND567FR5.cjs.map +0 -1
  240. package/dist/tsup/chunk-NHUTYWKU.cjs.map +0 -1
  241. package/dist/tsup/chunk-QAVN4QNO.cjs.map +0 -1
  242. package/dist/tsup/chunk-RIT7N3TX.js.map +0 -1
  243. package/dist/tsup/chunk-RV5MAFDT.cjs +0 -382
  244. package/dist/tsup/chunk-RV5MAFDT.cjs.map +0 -1
  245. package/dist/tsup/chunk-VE2X4KMG.cjs.map +0 -1
  246. package/dist/tsup/chunk-XFYEVYHG.js.map +0 -1
  247. package/dist/tsup/chunk-XHGDS3DZ.js +0 -382
  248. package/dist/tsup/chunk-XHGDS3DZ.js.map +0 -1
  249. package/dist/tsup/chunk-XIX5DOZN.js.map +0 -1
  250. package/dist/tsup/chunk-ZA7FLHKH.cjs.map +0 -1
  251. package/dist/tsup/chunk-ZZ3WBRPD.js.map +0 -1
  252. package/src/actor/driver.ts +0 -141
  253. package/src/actor/instance/mod.ts +0 -2484
  254. package/src/actor/keys.test.ts +0 -275
  255. package/src/actor/utils.test.ts +0 -48
  256. package/src/agent-os/actor/cron.ts +0 -84
  257. package/src/agent-os/actor/db.ts +0 -54
  258. package/src/agent-os/actor/filesystem.ts +0 -131
  259. package/src/agent-os/actor/index.ts +0 -285
  260. package/src/agent-os/actor/network.ts +0 -58
  261. package/src/agent-os/actor/preview.ts +0 -190
  262. package/src/agent-os/actor/process.ts +0 -177
  263. package/src/agent-os/actor/session.ts +0 -518
  264. package/src/agent-os/actor/shell.ts +0 -60
  265. package/src/agent-os/config.ts +0 -79
  266. package/src/agent-os/fs/database-vfs.ts +0 -624
  267. package/src/agent-os/types.ts +0 -148
  268. package/src/client/test.ts +0 -44
  269. package/src/common/database/mod.test.ts +0 -137
  270. package/src/common/database/native-database.test.ts +0 -211
  271. package/src/common/inline-websocket-adapter.test.ts +0 -51
  272. package/src/drivers/engine/actor-driver.ts +0 -2473
  273. package/src/registry/process-metrics.ts +0 -250
  274. package/src/registry/runtime.test.ts +0 -50
  275. package/src/utils/endpoint-parser.test.ts +0 -206
  276. package/src/utils.test.ts +0 -34
  277. /package/dist/tsup/{chunk-IICIOTML.js.map → chunk-3DONDAMG.js.map} +0 -0
package/dist/tsup/mod.js CHANGED
@@ -1,45 +1,60 @@
1
- import {
2
- decodeWorkflowHistoryTransport
3
- } from "./chunk-RIT7N3TX.js";
4
1
  import {
5
2
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
6
3
  ActorConfigSchema,
7
4
  CONN_STATE_MANAGER_SYMBOL,
8
5
  RAW_STATE_SYMBOL,
6
+ createRunInspector,
7
+ defineRunHandler,
9
8
  disposeRunInspector,
9
+ flattenActionHandlers,
10
+ flattenActionInputSchemas,
11
+ flattenActionTraceSamplers,
10
12
  getRunFunction,
11
13
  getRunInspectorConfig,
12
- getRunMetadata
13
- } from "./chunk-XIX5DOZN.js";
14
+ getRunInspectorKind,
15
+ getRunMetadata,
16
+ hasRunInspectorConfig
17
+ } from "./chunk-6FEYCVZC.js";
18
+ import {
19
+ decodeWorkflowHistoryTransport
20
+ } from "./chunk-D5WUPE47.js";
14
21
  import {
15
22
  ALLOWED_PUBLIC_HEADERS,
23
+ ENGINE_HOST,
24
+ ENGINE_PORT,
16
25
  HEADER_CONN_PARAMS,
26
+ HEADER_ORIGINAL_REQUEST_URL,
17
27
  RemoteEngineControlClient,
28
+ buildEngineEndpoint,
18
29
  convertRegistryConfigToClientConfig,
19
30
  createClientWithDriver,
20
31
  getDatacenters,
32
+ isLocalEngineEndpoint,
33
+ isResponseLike,
34
+ readActiveTraceHeaders,
35
+ runWithActorInvocationSpan,
21
36
  tryParseEndpoint,
22
37
  updateRunnerConfig
23
- } from "./chunk-AGDY6TKH.js";
38
+ } from "./chunk-TRUHDXOU.js";
24
39
  import {
25
- KEYS,
26
40
  makePrefixedKey,
27
- queueMessagesPrefix,
28
- queueMetadataKey,
29
- removePrefixFromKey,
30
- workflowStoragePrefix
31
- } from "./chunk-HXUEHHJF.js";
41
+ removePrefixFromKey
42
+ } from "./chunk-A2CF6PFH.js";
43
+ import "./chunk-3DONDAMG.js";
32
44
  import {
33
- assertJsonCompatValue,
34
- decodeCborCompat,
35
- encodeCborCompat
36
- } from "./chunk-XHGDS3DZ.js";
37
- import "./chunk-JZ7TWV65.js";
38
- import "./chunk-IICIOTML.js";
45
+ bindNativeStateTransactionContext,
46
+ db,
47
+ registerNativeStateTransactionOpener
48
+ } from "./chunk-ZYK4B5WV.js";
49
+ import "./chunk-JTHHCZCZ.js";
39
50
  import {
40
51
  LogLevelSchema,
41
52
  VERSION,
53
+ assertJsonCompatValue,
54
+ configureBaseLogger,
55
+ decodeCborCompat,
42
56
  deconstructError,
57
+ encodeCborCompat,
43
58
  getEnvUniversal,
44
59
  getLogger,
45
60
  getNodeEnv,
@@ -54,6 +69,7 @@ import {
54
69
  getRivetRunEngineHost,
55
70
  getRivetRunEnginePort,
56
71
  getRivetRunEngineVersion,
72
+ getRivetRunServices,
57
73
  getRivetToken,
58
74
  getRivetTotalSlots,
59
75
  getRivetkitPublicDir,
@@ -64,19 +80,21 @@ import {
64
80
  parsePortEnv,
65
81
  stringifyError,
66
82
  toUint8Array
67
- } from "./chunk-75UE45DE.js";
83
+ } from "./chunk-BRH4PQS5.js";
68
84
  import {
69
85
  INTERNAL_ERROR_CODE,
70
86
  RivetError,
71
87
  UserError,
88
+ actorStopping,
72
89
  decodeBridgeRivetError,
73
90
  encodeBridgeRivetError,
91
+ encodeErrorForBridge,
74
92
  forbiddenError,
75
93
  isActorAbortedError,
76
94
  isRivetErrorLike,
77
95
  toRivetError,
78
96
  unsupportedFeature
79
- } from "./chunk-ZZ3WBRPD.js";
97
+ } from "./chunk-ZOVJDAOW.js";
80
98
 
81
99
  // src/actor/log.ts
82
100
  function loggerWithoutContext() {
@@ -84,15 +102,21 @@ function loggerWithoutContext() {
84
102
  }
85
103
 
86
104
  // src/actor/definition.ts
87
- var warnedDeprecatedTimeoutKeys = /* @__PURE__ */ new Set();
88
- function warnDeprecatedShutdownTimeoutKeys(options) {
105
+ var warnedDeprecatedOptionKeys = /* @__PURE__ */ new Set();
106
+ var DEPRECATED_OPTION_MESSAGES = {
107
+ onDestroyTimeout: "Configure `sleepGracePeriod` instead, which bounds the entire graceful shutdown window for both sleep and destroy.",
108
+ waitUntilTimeout: "Configure `sleepGracePeriod` instead, which bounds the entire graceful shutdown window for both sleep and destroy.",
109
+ preloadMaxWorkflowBytes: "Internal storage moved to SQLite and no longer uses KV preloading.",
110
+ preloadMaxConnectionsBytes: "Internal storage moved to SQLite and no longer uses KV preloading."
111
+ };
112
+ function warnDeprecatedOptionKeys(options) {
89
113
  if (!options || typeof options !== "object") return;
90
114
  const opts = options;
91
- for (const key of ["onDestroyTimeout", "waitUntilTimeout"]) {
92
- if (opts[key] !== void 0 && !warnedDeprecatedTimeoutKeys.has(key)) {
93
- warnedDeprecatedTimeoutKeys.add(key);
115
+ for (const [key, detail] of Object.entries(DEPRECATED_OPTION_MESSAGES)) {
116
+ if (opts[key] !== void 0 && !warnedDeprecatedOptionKeys.has(key)) {
117
+ warnedDeprecatedOptionKeys.add(key);
94
118
  loggerWithoutContext().warn({
95
- 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.`
119
+ msg: `actor option \`${key}\` is deprecated and is now ignored. ${detail} Will be removed in 2.2.0.`
96
120
  });
97
121
  }
98
122
  }
@@ -110,10 +134,14 @@ function isStaticActorInstance(_actor) {
110
134
  return true;
111
135
  }
112
136
  function actor(input) {
113
- warnDeprecatedShutdownTimeoutKeys(
137
+ var _a;
138
+ warnDeprecatedOptionKeys(
114
139
  input == null ? void 0 : input.options
115
140
  );
116
141
  const config = ActorConfigSchema.parse(input);
142
+ flattenActionHandlers(config.actions);
143
+ flattenActionInputSchemas(config.actions, config.actionInputSchemas);
144
+ flattenActionTraceSamplers(config.actions, (_a = config.tracing) == null ? void 0 : _a.actions);
117
145
  return new ActorDefinition(config);
118
146
  }
119
147
  function isStaticActorDefinition(definition) {
@@ -362,25 +390,6 @@ var InlineWebSocketAdapter = class {
362
390
  }
363
391
  };
364
392
 
365
- // src/common/engine.ts
366
- var ENGINE_HOST = "127.0.0.1";
367
- var ENGINE_PORT = 6420;
368
- var ENGINE_ENDPOINT = buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT);
369
- function buildEngineEndpoint(host, port) {
370
- const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
371
- return `http://${urlHost}:${port}`;
372
- }
373
- function isLocalEngineEndpoint(endpoint) {
374
- let url;
375
- try {
376
- url = new URL(endpoint);
377
- } catch {
378
- return false;
379
- }
380
- const hostname = url.hostname.toLowerCase();
381
- return hostname === "localhost" || hostname === "0.0.0.0" || hostname === "::" || hostname === "[::]" || hostname === "::1" || hostname === "[::1]" || /^127(?:\.\d{1,3}){0,3}$/.test(hostname);
382
- }
383
-
384
393
  // src/registry/log.ts
385
394
  function logger2() {
386
395
  return getLogger("registry");
@@ -487,23 +496,12 @@ import { z as z3 } from "zod";
487
496
 
488
497
  // src/registry/config/envoy.ts
489
498
  import { z } from "zod/v4";
490
- var warnedMissingVersion = false;
491
499
  var EnvoyConfigSchema = z.object({
492
500
  poolName: z.string().default(() => getRivetPool() ?? "default"),
493
- version: z.number().default(() => {
494
- const version = getRivetEnvoyVersion();
495
- if (version !== void 0) return version;
496
- if (getNodeEnv() === "production" && !warnedMissingVersion) {
497
- warnedMissingVersion = true;
498
- getLogger("rivetkit").error(
499
- "RIVET_ENVOY_VERSION is not set. Actors will not be versioned, which means they won't be drained on deploy. This is only needed when self-hosting or using a custom envoy (not needed for Rivet Compute). Set this as a build arg in your Dockerfile. See https://rivet.dev/docs/actors/versions"
500
- );
501
- }
502
- return 1;
503
- }),
501
+ version: z.number().default(() => getRivetEnvoyVersion() ?? 1),
504
502
  // Deprecated.
505
503
  totalSlots: z.number().default(() => getRivetTotalSlots() ?? 1e5),
506
- envoyKey: z.string().optional()
504
+ nodeKey: z.string().optional()
507
505
  });
508
506
 
509
507
  // src/registry/config/serverless.ts
@@ -647,7 +645,7 @@ var RegistryConfigSchema = z3.object({
647
645
  // // (specifically Node.js) can sometimes only be specified after the router is
648
646
  // // created or must be imported async using `await import(...)`
649
647
  // getUpgradeWebSocket: z.custom<GetUpgradeWebSocket>().optional(),
650
- // MARK: Runner Configuration
648
+ // MARK: Node Configuration
651
649
  /**
652
650
  * Endpoint to connect to for Rivet Engine.
653
651
  *
@@ -714,26 +712,32 @@ var RegistryConfigSchema = z3.object({
714
712
  enginePort: z3.number().int().min(1).max(65535).optional().default(() => getRivetRunEnginePort() ?? ENGINE_PORT),
715
713
  /** @experimental */
716
714
  engineVersion: z3.string().optional().default(() => getRivetRunEngineVersion() ?? VERSION),
715
+ /**
716
+ * Starts the first-party Services actor host when RivetKit manages
717
+ * a local engine. Disabled by default. Set RIVET_RUN_SERVICES=1
718
+ * or startServices: true to enable it.
719
+ */
720
+ startServices: z3.boolean().optional(),
717
721
  /**
718
722
  * @experimental
719
723
  *
720
- * Automatically configure serverless envoys in the engine.
724
+ * Automatically configure serverless nodes in the engine.
721
725
  */
722
726
  configurePool: ConfigurePoolSchema.optional(),
723
727
  // MARK: Runtime-specific
724
728
  serverless: ServerlessConfigSchema.optional().default(
725
729
  () => ServerlessConfigSchema.parse({})
726
730
  ),
727
- envoy: EnvoyConfigSchema.optional().default(
731
+ node: EnvoyConfigSchema.optional().default(
728
732
  () => EnvoyConfigSchema.parse({})
729
733
  ),
730
734
  // MARK: Shutdown
731
735
  /**
732
736
  * Graceful shutdown configuration for SIGINT/SIGTERM.
733
737
  *
734
- * When a persistent envoy is running (Mode A, started via `registry.start()`),
738
+ * When a persistent node is running (Mode A, started via `registry.start()`),
735
739
  * rivetkit installs Node SIGINT/SIGTERM handlers that call into core's
736
- * `shutdown()` and wait up to `gracePeriodMs` for the envoy to drain
740
+ * `shutdown()` and wait up to `gracePeriodMs` for the node to drain
737
741
  * before re-raising the signal to let Node exit via its default path.
738
742
  *
739
743
  * Handlers are NOT installed when `handler(request)` is used alone
@@ -745,9 +749,11 @@ var RegistryConfigSchema = z3.object({
745
749
  /**
746
750
  * Wait this many milliseconds for the serve promise to resolve
747
751
  * after calling `CoreRegistry::shutdown()`. Defaults to the
748
- * engine-provided actor stop threshold once the envoy connects.
752
+ * engine-provided actor stop threshold once the node connects. A
753
+ * signal-driven shutdown of a managed local development engine waits
754
+ * one second by default so a file watcher can restart promptly.
749
755
  *
750
- * Must be long enough for rivetkit-core to drain the envoy.
756
+ * Set a longer period when a complete graceful node drain is required.
751
757
  */
752
758
  gracePeriodMs: z3.number().int().min(1e3).optional(),
753
759
  /**
@@ -783,22 +789,24 @@ var RegistryConfigSchema = z3.object({
783
789
  message: "cannot specify both startEngine and endpoint"
784
790
  });
785
791
  }
786
- if (config.configurePool && !parsedEndpoint && !config.startEngine) {
792
+ if (config.configurePool) {
787
793
  ctx.addIssue({
788
794
  code: "custom",
789
- message: "configurePool requires either endpoint or startEngine"
795
+ message: "serverless is disabled in this version",
796
+ path: ["configurePool"]
790
797
  });
791
798
  }
792
799
  const localEngineEndpoint = buildEngineEndpoint(
793
800
  config.engineHost,
794
801
  config.enginePort
795
802
  );
796
- const endpoint = config.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT) : void 0);
803
+ const endpoint = config.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? localEngineEndpoint : void 0);
804
+ const startServices = config.startServices ?? getRivetRunServices();
797
805
  const validateServerlessEndpoint = Boolean(
798
806
  config.startEngine || parsedEndpoint
799
807
  );
800
808
  const namespace = (parsedEndpoint == null ? void 0 : parsedEndpoint.namespace) ?? config.namespace ?? "default";
801
- const token = (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config.token;
809
+ const token = (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config.token ?? (endpoint && isLocalEngineEndpoint(endpoint) ? "default" : void 0);
802
810
  const parsedPublicEndpoint = config.serverless.publicEndpoint ? tryParseEndpoint(ctx, {
803
811
  endpoint: config.serverless.publicEndpoint,
804
812
  path: ["serverless", "publicEndpoint"]
@@ -810,13 +818,15 @@ var RegistryConfigSchema = z3.object({
810
818
  path: ["serverless", "publicEndpoint"]
811
819
  });
812
820
  }
813
- const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && config.startEngine ? endpoint : void 0);
821
+ const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && !parsedEndpoint ? endpoint : void 0);
814
822
  const publicNamespace = parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.namespace;
815
823
  const publicToken = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.token) ?? config.serverless.publicToken;
816
824
  return {
817
825
  ...config,
818
826
  sqlite,
819
827
  endpoint,
828
+ engineSpawn: !parsedEndpoint && Boolean(endpoint),
829
+ startServices,
820
830
  namespace,
821
831
  token,
822
832
  publicEndpoint,
@@ -838,31 +848,6 @@ function buildActorNames(config) {
838
848
  const metadata = {};
839
849
  metadata.icon = options.icon ?? runMeta.icon;
840
850
  metadata.name = options.name ?? runMeta.name;
841
- metadata.preload = {
842
- keys: [
843
- Array.from(KEYS.PERSIST_DATA),
844
- Array.from(KEYS.INSPECTOR_TOKEN),
845
- Array.from(queueMetadataKey()),
846
- Array.from(KEYS.LAST_PUSHED_ALARM)
847
- ],
848
- prefixes: [
849
- {
850
- prefix: Array.from(workflowStoragePrefix()),
851
- maxBytes: options.preloadMaxWorkflowBytes ?? 131072,
852
- partial: false
853
- },
854
- {
855
- prefix: Array.from(KEYS.CONN_PREFIX),
856
- maxBytes: options.preloadMaxConnectionsBytes ?? 65536,
857
- partial: false
858
- },
859
- {
860
- prefix: Array.from(queueMessagesPrefix()),
861
- maxBytes: 65536,
862
- partial: false
863
- }
864
- ]
865
- };
866
851
  if (!metadata.icon) delete metadata.icon;
867
852
  if (!metadata.name) delete metadata.name;
868
853
  return [actorName, { metadata }];
@@ -870,8 +855,8 @@ function buildActorNames(config) {
870
855
  );
871
856
  }
872
857
  var DocConfigurePoolSchema = z3.object({
873
- name: z3.string().optional().describe("Name of the runner pool."),
874
- url: z3.string().describe("URL of the serverless platform to configure runners."),
858
+ name: z3.string().optional().describe("Name of the node pool."),
859
+ url: z3.string().describe("URL of the serverless platform to configure nodes."),
875
860
  headers: z3.record(z3.string(), z3.string()).optional().describe(
876
861
  "Headers to include in requests to the serverless platform."
877
862
  ),
@@ -886,7 +871,7 @@ var DocConfigurePoolSchema = z3.object({
886
871
  "Interval in milliseconds between metadata polls from the engine. Defaults to 10000 milliseconds (10 seconds)."
887
872
  ),
888
873
  drainOnVersionUpgrade: z3.boolean().optional().describe(
889
- "Drain runners when a new version is deployed. Defaults to true."
874
+ "Drain nodes when a new version is deployed. Defaults to true."
890
875
  )
891
876
  }).optional();
892
877
  var DocServerlessConfigSchema = z3.object({
@@ -905,10 +890,10 @@ var DocServerlessConfigSchema = z3.object({
905
890
  }).describe("Configuration for serverless deployment mode.");
906
891
  var DocEnvoyConfigSchema = z3.object({
907
892
  totalSlots: z3.number().optional().describe("Total number of actor slots available. Default: 100000"),
908
- poolName: z3.string().optional().describe("Name of this envoy pool. Default: 'default'"),
909
- envoyKey: z3.string().optional().describe("Deprecated. Authentication key for the envoy."),
910
- version: z3.number().optional().describe("Version number of this envoy. Default: 1")
911
- }).describe("Configuration for envoy mode.");
893
+ poolName: z3.string().optional().describe("Name of this node pool. Default: 'default'"),
894
+ nodeKey: z3.string().optional().describe("Deprecated. Authentication key for the node."),
895
+ version: z3.number().optional().describe("Version number of this node. Default: 1")
896
+ }).describe("Configuration for node mode.");
912
897
  var DocSqliteConfigSchema = z3.object({
913
898
  backend: SqliteBackendSchema.optional().describe(
914
899
  "SQLite backend to use. Native defaults to local. Wasm defaults to remote and cannot use local."
@@ -955,17 +940,24 @@ var DocRegistryConfigSchema = z3.object({
955
940
  engineVersion: z3.string().optional().describe(
956
941
  "Version of the local engine package to use. Defaults to the current RivetKit version."
957
942
  ),
943
+ startServices: z3.boolean().optional().describe(
944
+ "Starts Services when RivetKit manages a local Engine. Disabled by default. Set RIVET_RUN_SERVICES=1 or startServices: true to enable."
945
+ ),
958
946
  configurePool: DocConfigurePoolSchema.describe(
959
- "Automatically configure serverless runners in the engine."
947
+ "Automatically configure serverless nodes in the engine."
960
948
  ),
961
949
  serverless: DocServerlessConfigSchema.optional(),
962
- envoy: DocEnvoyConfigSchema.optional()
950
+ node: DocEnvoyConfigSchema.optional()
963
951
  }).describe("RivetKit registry configuration.");
964
952
 
965
953
  // src/registry/native.ts
966
954
  import { VirtualWebSocket as VirtualWebSocket2 } from "@rivetkit/virtual-websocket";
967
955
 
968
956
  // src/common/database/native-database.ts
957
+ function isSynchronousTransaction(transaction) {
958
+ const candidate = transaction;
959
+ return typeof candidate.commitSync === "function" && typeof candidate.rollbackSync === "function";
960
+ }
969
961
  function shouldAttachNativeKvError(message) {
970
962
  return /i\/o error|unable to open database file/i.test(message);
971
963
  }
@@ -986,13 +978,16 @@ function toNativeBinding(arg) {
986
978
  if (arg === null || arg === void 0) {
987
979
  return { kind: "null" };
988
980
  }
989
- if (typeof arg === "bigint") {
990
- return { kind: "int", intValue: Number(arg) };
981
+ if (typeof arg === "bigint" || typeof arg === "number" && Number.isInteger(arg)) {
982
+ const value = Number(arg);
983
+ if (!Number.isSafeInteger(value)) {
984
+ throw new RangeError(
985
+ "SQLite integer bindings must be within the JavaScript safe integer range."
986
+ );
987
+ }
988
+ return { kind: "int", intValue: value };
991
989
  }
992
990
  if (typeof arg === "number") {
993
- if (Number.isInteger(arg)) {
994
- return { kind: "int", intValue: arg };
995
- }
996
991
  return { kind: "float", floatValue: arg };
997
992
  }
998
993
  if (typeof arg === "string") {
@@ -1009,9 +1004,10 @@ function toNativeBinding(arg) {
1009
1004
  function extractNamedSqliteParameters(sql) {
1010
1005
  const orderedNames = [];
1011
1006
  const seen = /* @__PURE__ */ new Set();
1012
- const pattern = /([:@$][A-Za-z_][A-Za-z0-9_]*)/g;
1007
+ const pattern = /'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]|--[^\n]*|\/\*[\s\S]*?(?:\*\/|$)|([:@$][\w$\u0080-\u{10FFFF}]+(?:::[\w$\u0080-\u{10FFFF}]+)*(?:\([^)]*\))?)|[A-Za-z_\u0080-\u{10FFFF}][\w$\u0080-\u{10FFFF}]*/gu;
1013
1008
  for (const match of sql.matchAll(pattern)) {
1014
1009
  const name = match[1];
1010
+ if (!name) continue;
1015
1011
  if (seen.has(name)) {
1016
1012
  continue;
1017
1013
  }
@@ -1055,6 +1051,12 @@ function toNativeBindings(sql, params) {
1055
1051
  return toNativeBinding(value);
1056
1052
  });
1057
1053
  }
1054
+ function toNativeBatchStatement(statement) {
1055
+ return {
1056
+ sql: statement.sql,
1057
+ params: toNativeBindings(statement.sql, statement.params)
1058
+ };
1059
+ }
1058
1060
  function normalizeNativeMetrics(metrics) {
1059
1061
  if (!metrics) return null;
1060
1062
  const raw = metrics;
@@ -1116,28 +1118,52 @@ var NativeCloseGate = class {
1116
1118
  if (this.#active > 0) {
1117
1119
  await new Promise((resolve) => this.#waiters.push(resolve));
1118
1120
  }
1119
- await callback();
1121
+ await (callback == null ? void 0 : callback());
1120
1122
  }
1121
1123
  };
1122
1124
  function wrapJsNativeDatabase(database) {
1123
1125
  const gate = new NativeCloseGate();
1124
- let closePromise;
1126
+ let terminalPromise;
1125
1127
  let lastInsertRowId = null;
1126
1128
  const executeNative = async (sql, params) => {
1127
- const lastInsertRowIdColumn = lastInsertRowIdColumnName(sql);
1128
- if (lastInsertRowIdColumn) {
1129
- return {
1130
- columns: [lastInsertRowIdColumn],
1131
- rows: [[lastInsertRowId ?? 0]],
1132
- changes: 0,
1133
- lastInsertRowId
1134
- };
1135
- }
1136
1129
  const release = gate.enter();
1137
1130
  try {
1131
+ const lastInsertRowIdColumn = lastInsertRowIdColumnName(sql);
1132
+ if (lastInsertRowIdColumn) {
1133
+ return {
1134
+ columns: [lastInsertRowIdColumn],
1135
+ rows: [[lastInsertRowId ?? 0]],
1136
+ changes: 0,
1137
+ lastInsertRowId
1138
+ };
1139
+ }
1138
1140
  const nativeParams = toNativeBindings(sql, params);
1139
1141
  const result = await database.execute(sql, nativeParams);
1140
- if (result.lastInsertRowId !== void 0) {
1142
+ if (result.lastInsertRowId != null) {
1143
+ lastInsertRowId = result.lastInsertRowId;
1144
+ }
1145
+ return result;
1146
+ } catch (error) {
1147
+ enrichNativeDatabaseError(database, error);
1148
+ } finally {
1149
+ release();
1150
+ }
1151
+ };
1152
+ const executeNativeSync = (sql, params) => {
1153
+ const release = gate.enter();
1154
+ try {
1155
+ const nativeParams = toNativeBindings(sql, params);
1156
+ const result = database.executeSync(sql, nativeParams);
1157
+ const rowIdColumn = lastInsertRowIdColumnName(sql);
1158
+ if (rowIdColumn) {
1159
+ return {
1160
+ columns: [rowIdColumn],
1161
+ rows: [[lastInsertRowId ?? 0]],
1162
+ changes: 0,
1163
+ lastInsertRowId
1164
+ };
1165
+ }
1166
+ if (result.lastInsertRowId != null) {
1141
1167
  lastInsertRowId = result.lastInsertRowId;
1142
1168
  }
1143
1169
  return result;
@@ -1165,9 +1191,120 @@ function wrapJsNativeDatabase(database) {
1165
1191
  callback(row, result.columns);
1166
1192
  }
1167
1193
  },
1194
+ execSync(sql, callback) {
1195
+ const release = gate.enter();
1196
+ let result;
1197
+ try {
1198
+ result = database.execSync(sql);
1199
+ } catch (error) {
1200
+ enrichNativeDatabaseError(database, error);
1201
+ } finally {
1202
+ release();
1203
+ }
1204
+ if (callback) {
1205
+ for (const row of result.rows) {
1206
+ callback(row, result.columns);
1207
+ }
1208
+ }
1209
+ },
1168
1210
  async execute(sql, params) {
1169
1211
  return await executeNative(sql, params);
1170
1212
  },
1213
+ executeSync(sql, params) {
1214
+ return executeNativeSync(sql, params);
1215
+ },
1216
+ async executeBatch(statements) {
1217
+ const nativeStatements = statements.map(toNativeBatchStatement);
1218
+ const release = gate.enter();
1219
+ let transaction;
1220
+ try {
1221
+ const results = database.executeBatch ? await database.executeBatch(nativeStatements) : await (async () => {
1222
+ transaction = await database.beginTransaction();
1223
+ const transactionResults = [];
1224
+ for (const statement of nativeStatements) {
1225
+ transactionResults.push(
1226
+ await transaction.execute(
1227
+ statement.sql,
1228
+ statement.params
1229
+ )
1230
+ );
1231
+ }
1232
+ await transaction.commit();
1233
+ transaction = void 0;
1234
+ return transactionResults;
1235
+ })();
1236
+ for (const result of results) {
1237
+ if (result.lastInsertRowId != null) {
1238
+ lastInsertRowId = result.lastInsertRowId;
1239
+ }
1240
+ }
1241
+ return results;
1242
+ } catch (error) {
1243
+ if (transaction) {
1244
+ try {
1245
+ await transaction.rollback();
1246
+ } catch {
1247
+ }
1248
+ }
1249
+ enrichNativeDatabaseError(database, error);
1250
+ } finally {
1251
+ release();
1252
+ }
1253
+ },
1254
+ async beginTransaction(timeoutMs, name) {
1255
+ const release = gate.enter();
1256
+ let transaction;
1257
+ try {
1258
+ transaction = await database.beginTransaction(timeoutMs, name);
1259
+ } catch (error) {
1260
+ enrichNativeDatabaseError(database, error);
1261
+ } finally {
1262
+ release();
1263
+ }
1264
+ return wrapTransaction(database, transaction, gate, (result) => {
1265
+ if (result.lastInsertRowId != null) {
1266
+ lastInsertRowId = result.lastInsertRowId;
1267
+ }
1268
+ });
1269
+ },
1270
+ beginTransactionSync(timeoutMs, name) {
1271
+ const release = gate.enter();
1272
+ let transaction;
1273
+ try {
1274
+ transaction = database.beginTransactionSync(timeoutMs, name);
1275
+ } catch (error) {
1276
+ enrichNativeDatabaseError(database, error);
1277
+ } finally {
1278
+ release();
1279
+ }
1280
+ return wrapTransaction(database, transaction, gate, (result) => {
1281
+ if (result.lastInsertRowId != null) {
1282
+ lastInsertRowId = result.lastInsertRowId;
1283
+ }
1284
+ });
1285
+ },
1286
+ async beginStateTransaction(timeoutMs, context) {
1287
+ if (!database.beginStateTransaction) {
1288
+ throw new Error("actor state transactions are not configured");
1289
+ }
1290
+ const release = gate.enter();
1291
+ let transaction;
1292
+ try {
1293
+ transaction = await database.beginStateTransaction(
1294
+ timeoutMs,
1295
+ context
1296
+ );
1297
+ } catch (error) {
1298
+ enrichNativeDatabaseError(database, error);
1299
+ } finally {
1300
+ release();
1301
+ }
1302
+ return wrapTransaction(database, transaction, gate, (result) => {
1303
+ if (result.lastInsertRowId != null) {
1304
+ lastInsertRowId = result.lastInsertRowId;
1305
+ }
1306
+ });
1307
+ },
1171
1308
  async run(sql, params) {
1172
1309
  await executeNative(sql, params);
1173
1310
  },
@@ -1179,11 +1316,142 @@ function wrapJsNativeDatabase(database) {
1179
1316
  var _a;
1180
1317
  return normalizeNativeMetrics((_a = database.metrics) == null ? void 0 : _a.call(database));
1181
1318
  },
1319
+ async open() {
1320
+ const release = gate.enter();
1321
+ try {
1322
+ await database.open();
1323
+ } catch (error) {
1324
+ enrichNativeDatabaseError(database, error);
1325
+ } finally {
1326
+ release();
1327
+ }
1328
+ },
1329
+ commitTicket() {
1330
+ return database.commitTicket();
1331
+ },
1332
+ async whenDurable(ticket) {
1333
+ await database.whenDurable(ticket);
1334
+ },
1335
+ abortGeneration(reason) {
1336
+ database.abortGeneration(reason);
1337
+ },
1182
1338
  async close() {
1183
- closePromise ??= gate.close(() => database.close());
1184
- await closePromise;
1339
+ terminalPromise ??= gate.close(() => database.close());
1340
+ await terminalPromise;
1341
+ },
1342
+ async detachForShutdown() {
1343
+ terminalPromise ??= gate.close();
1344
+ await terminalPromise;
1345
+ }
1346
+ };
1347
+ }
1348
+ function wrapTransaction(database, transaction, gate, onExecute) {
1349
+ const wrapped = {
1350
+ async exec(sql, callback) {
1351
+ const release = gate.enter();
1352
+ let result;
1353
+ try {
1354
+ result = await transaction.exec(sql);
1355
+ } catch (error) {
1356
+ enrichNativeDatabaseError(database, error);
1357
+ } finally {
1358
+ release();
1359
+ }
1360
+ if (callback) {
1361
+ for (const row of result.rows) callback(row, result.columns);
1362
+ }
1363
+ },
1364
+ async execute(sql, params) {
1365
+ const release = gate.enter();
1366
+ try {
1367
+ const result = await transaction.execute(
1368
+ sql,
1369
+ toNativeBindings(sql, params)
1370
+ );
1371
+ onExecute(result);
1372
+ return result;
1373
+ } catch (error) {
1374
+ enrichNativeDatabaseError(database, error);
1375
+ } finally {
1376
+ release();
1377
+ }
1378
+ },
1379
+ async commit() {
1380
+ const release = gate.enter();
1381
+ try {
1382
+ await transaction.commit();
1383
+ } catch (error) {
1384
+ enrichNativeDatabaseError(database, error);
1385
+ } finally {
1386
+ release();
1387
+ }
1388
+ },
1389
+ async rollback() {
1390
+ const release = gate.enter();
1391
+ try {
1392
+ await transaction.rollback();
1393
+ } catch (error) {
1394
+ enrichNativeDatabaseError(database, error);
1395
+ } finally {
1396
+ release();
1397
+ }
1185
1398
  }
1186
1399
  };
1400
+ if (isSynchronousTransaction(transaction)) {
1401
+ return Object.assign(wrapped, {
1402
+ execSync(sql, callback) {
1403
+ const release = gate.enter();
1404
+ let result;
1405
+ try {
1406
+ result = transaction.execSync(sql);
1407
+ } catch (error) {
1408
+ enrichNativeDatabaseError(database, error);
1409
+ } finally {
1410
+ release();
1411
+ }
1412
+ if (callback) {
1413
+ for (const row of result.rows)
1414
+ callback(row, result.columns);
1415
+ }
1416
+ },
1417
+ executeSync(sql, params) {
1418
+ const release = gate.enter();
1419
+ try {
1420
+ const result = transaction.executeSync(
1421
+ sql,
1422
+ toNativeBindings(sql, params)
1423
+ );
1424
+ onExecute(result);
1425
+ return result;
1426
+ } catch (error) {
1427
+ enrichNativeDatabaseError(database, error);
1428
+ } finally {
1429
+ release();
1430
+ }
1431
+ },
1432
+ commitSync() {
1433
+ const release = gate.enter();
1434
+ try {
1435
+ transaction.commitSync();
1436
+ } catch (error) {
1437
+ enrichNativeDatabaseError(database, error);
1438
+ } finally {
1439
+ release();
1440
+ }
1441
+ },
1442
+ rollbackSync() {
1443
+ const release = gate.enter();
1444
+ try {
1445
+ transaction.rollbackSync();
1446
+ } catch (error) {
1447
+ enrichNativeDatabaseError(database, error);
1448
+ } finally {
1449
+ release();
1450
+ }
1451
+ }
1452
+ });
1453
+ }
1454
+ return wrapped;
1187
1455
  }
1188
1456
  function lastInsertRowIdColumnName(sql) {
1189
1457
  const match = sql.match(
@@ -1213,45 +1481,37 @@ var nodeChildProcess;
1213
1481
  var nodeStream;
1214
1482
  var nodeUrl;
1215
1483
  var hasImportedDependencies = false;
1216
- function getRequireFn() {
1217
- return createRequire(import.meta.url);
1484
+ var fallbackRequire;
1485
+ function loadNodeBuiltin(id) {
1486
+ var _a;
1487
+ const nodeProcess = globalThis.process;
1488
+ const builtin = (_a = nodeProcess == null ? void 0 : nodeProcess.getBuiltinModule) == null ? void 0 : _a.call(nodeProcess, id);
1489
+ if (builtin !== void 0) {
1490
+ return builtin;
1491
+ }
1492
+ if (!(nodeProcess == null ? void 0 : nodeProcess.execPath)) {
1493
+ throw new Error("Node.js built-ins are not available");
1494
+ }
1495
+ fallbackRequire ??= createRequire(nodeProcess.execPath);
1496
+ return fallbackRequire(id);
1218
1497
  }
1219
1498
  function importNodeDependencies() {
1220
1499
  if (hasImportedDependencies) return;
1221
1500
  try {
1222
- const requireFn = getRequireFn();
1223
- nodeCrypto = requireFn(
1224
- /* webpackIgnore: true */
1225
- "node:crypto"
1226
- );
1227
- nodeFsSync = requireFn(
1228
- /* webpackIgnore: true */
1229
- "node:fs"
1230
- );
1231
- nodeFs = requireFn(
1232
- /* webpackIgnore: true */
1501
+ nodeCrypto = loadNodeBuiltin("node:crypto");
1502
+ nodeFsSync = loadNodeBuiltin("node:fs");
1503
+ nodeFs = loadNodeBuiltin(
1233
1504
  "node:fs/promises"
1234
1505
  );
1235
- nodePath = requireFn(
1236
- /* webpackIgnore: true */
1237
- "node:path"
1238
- );
1239
- nodeOs = requireFn(
1240
- /* webpackIgnore: true */
1241
- "node:os"
1242
- );
1243
- nodeChildProcess = requireFn(
1244
- /* webpackIgnore: true */
1506
+ nodePath = loadNodeBuiltin("node:path");
1507
+ nodeOs = loadNodeBuiltin("node:os");
1508
+ nodeChildProcess = loadNodeBuiltin(
1245
1509
  "node:child_process"
1246
1510
  );
1247
- nodeStream = requireFn(
1248
- /* webpackIgnore: true */
1511
+ nodeStream = loadNodeBuiltin(
1249
1512
  "node:stream/promises"
1250
1513
  );
1251
- nodeUrl = requireFn(
1252
- /* webpackIgnore: true */
1253
- "node:url"
1254
- );
1514
+ nodeUrl = loadNodeBuiltin("node:url");
1255
1515
  hasImportedDependencies = true;
1256
1516
  } catch (err) {
1257
1517
  console.warn(
@@ -1282,6 +1542,12 @@ function getNodePath() {
1282
1542
  function normalizeRuntimeSqlExecuteResult(result) {
1283
1543
  return result;
1284
1544
  }
1545
+ function servicesBinaryUnavailable(cause) {
1546
+ return new Error(
1547
+ "services.binary_unavailable: Install @rivet-dev/services yourself to run local Services, or set RIVET_SERVICES_BINARY to its executable path.",
1548
+ { cause }
1549
+ );
1550
+ }
1285
1551
 
1286
1552
  // src/registry/napi-runtime.ts
1287
1553
  function asNativeRegistry(handle) {
@@ -1299,6 +1565,12 @@ function asNativeConn(handle) {
1299
1565
  function asNativeWebSocket(handle) {
1300
1566
  return handle;
1301
1567
  }
1568
+ function asNativeSqlTransaction(handle) {
1569
+ return handle;
1570
+ }
1571
+ function asNativeActorStateTransaction(handle) {
1572
+ return handle;
1573
+ }
1302
1574
  function asNativeCancellationToken(handle) {
1303
1575
  return handle;
1304
1576
  }
@@ -1328,9 +1600,45 @@ function toNapiSqlBindParams(params) {
1328
1600
  }
1329
1601
  return params.map((param) => toNapiSqlBindParam(param));
1330
1602
  }
1603
+ function toNapiSqlBatchStatement(statement) {
1604
+ return {
1605
+ sql: statement.sql,
1606
+ params: toNapiSqlBindParams(statement.params) ?? void 0
1607
+ };
1608
+ }
1331
1609
  function toNapiBuffer(value) {
1332
1610
  return Buffer.from(value);
1333
1611
  }
1612
+ function toNapiApplication(application) {
1613
+ return async (error, request) => {
1614
+ if (error) throw error;
1615
+ if (!request) {
1616
+ throw new Error("application fetch callback received no request");
1617
+ }
1618
+ const response = await application(
1619
+ {
1620
+ ...request,
1621
+ body: new Uint8Array(request.body),
1622
+ cancelToken: request.cancelToken
1623
+ },
1624
+ request.responseBodyStream ? fromNapiHttpResponseBodyStream(
1625
+ request.responseBodyStream
1626
+ ) : void 0
1627
+ );
1628
+ return {
1629
+ ...response,
1630
+ body: response.body === void 0 ? void 0 : toNapiBuffer(response.body)
1631
+ };
1632
+ };
1633
+ }
1634
+ function fromNapiHttpResponseBodyStream(stream) {
1635
+ return {
1636
+ cancelled: () => stream.cancelled(),
1637
+ write: (chunk) => stream.write(Buffer.from(chunk)),
1638
+ end: () => stream.end(),
1639
+ error: (message) => stream.error(message)
1640
+ };
1641
+ }
1334
1642
  function toNapiHttpRequest(request) {
1335
1643
  if (!request) {
1336
1644
  return request;
@@ -1373,20 +1681,43 @@ function toNapiQueueMessage(message) {
1373
1681
  var NapiCoreRuntime = class {
1374
1682
  kind = "napi";
1375
1683
  #bindings;
1376
- #sql = /* @__PURE__ */ new WeakMap();
1377
- constructor(bindings) {
1684
+ #sqlOpened = /* @__PURE__ */ new WeakSet();
1685
+ #invocationContext;
1686
+ constructor(bindings, invocationContext) {
1378
1687
  this.#bindings = bindings;
1688
+ this.#invocationContext = invocationContext;
1379
1689
  }
1380
- #actorSql(ctx) {
1381
- const nativeCtx = asNativeActorContext(ctx);
1382
- let database = this.#sql.get(nativeCtx);
1383
- if (!database) {
1384
- database = nativeCtx.sql();
1385
- this.#sql.set(nativeCtx, database);
1690
+ #actorContextForOperation(owner) {
1691
+ const ownerCtx = asNativeActorContext(owner);
1692
+ const active = this.#invocationContext.getStore();
1693
+ if (!(active == null ? void 0 : active.sameActorInstance(ownerCtx))) {
1694
+ return ownerCtx;
1386
1695
  }
1387
- return database;
1696
+ const applicationSpan = readActiveTraceHeaders();
1697
+ if (!applicationSpan) {
1698
+ return active;
1699
+ }
1700
+ return active.withApplicationSpan(
1701
+ applicationSpan.traceparent,
1702
+ applicationSpan.tracestate ?? null
1703
+ );
1704
+ }
1705
+ #actorSql(ctx) {
1706
+ this.#sqlOpened.add(asNativeActorContext(ctx));
1707
+ return this.#actorContextForOperation(ctx).sql();
1388
1708
  }
1389
1709
  createRegistry() {
1710
+ this.#bindings.setTelemetryLogSink(
1711
+ (event2) => {
1712
+ const fields = { otelEvent: event2.name };
1713
+ const message = event2.message || event2.name;
1714
+ if (event2.level === "error") {
1715
+ logger2().error(fields, message);
1716
+ } else {
1717
+ logger2().warn(fields, message);
1718
+ }
1719
+ }
1720
+ );
1390
1721
  return asRegistryHandle(new this.#bindings.CoreRegistry());
1391
1722
  }
1392
1723
  registerActor(registry, name, factory) {
@@ -1395,9 +1726,15 @@ var NapiCoreRuntime = class {
1395
1726
  async serveRegistry(registry, config) {
1396
1727
  await asNativeRegistry(registry).serve(config);
1397
1728
  }
1729
+ async waitRegistryReady(registry) {
1730
+ await asNativeRegistry(registry).waitReady();
1731
+ }
1398
1732
  async shutdownRegistry(registry) {
1399
1733
  await asNativeRegistry(registry).shutdown();
1400
1734
  }
1735
+ async shutdownTelemetry() {
1736
+ await this.#bindings.shutdownTelemetry();
1737
+ }
1401
1738
  async registryActorStopThresholdMs(registry) {
1402
1739
  return await asNativeRegistry(registry).actorStopThresholdMs() ?? void 0;
1403
1740
  }
@@ -1434,12 +1771,25 @@ var NapiCoreRuntime = class {
1434
1771
  );
1435
1772
  }
1436
1773
  async serveListener(registry, listener, config) {
1774
+ const application = listener.application ? toNapiApplication(listener.application) : void 0;
1437
1775
  await asNativeRegistry(registry).serveListener(
1438
1776
  {
1439
1777
  port: listener.port,
1440
1778
  host: listener.host,
1441
1779
  publicDir: listener.publicDir
1442
1780
  },
1781
+ config,
1782
+ application
1783
+ );
1784
+ }
1785
+ async serveApplicationListener(registry, listener, config) {
1786
+ await asNativeRegistry(registry).serveApplicationListener(
1787
+ {
1788
+ port: listener.port,
1789
+ host: listener.host,
1790
+ publicDir: listener.publicDir
1791
+ },
1792
+ toNapiApplication(listener.application),
1443
1793
  config
1444
1794
  );
1445
1795
  }
@@ -1451,11 +1801,16 @@ var NapiCoreRuntime = class {
1451
1801
  createCancellationToken() {
1452
1802
  return new this.#bindings.CancellationToken();
1453
1803
  }
1454
- createTestActorContext(actorId, name, region) {
1455
- return new this.#bindings.ActorContext(
1456
- actorId,
1457
- name,
1458
- region
1804
+ decodeInspectorRequest(bytes, advertisedVersion) {
1805
+ return this.#bindings.decodeInspectorRequest(
1806
+ toNapiBuffer(bytes),
1807
+ advertisedVersion
1808
+ );
1809
+ }
1810
+ encodeInspectorResponse(bytes, targetVersion) {
1811
+ return this.#bindings.encodeInspectorResponse(
1812
+ toNapiBuffer(bytes),
1813
+ targetVersion
1459
1814
  );
1460
1815
  }
1461
1816
  cancellationTokenAborted(token) {
@@ -1465,7 +1820,8 @@ var NapiCoreRuntime = class {
1465
1820
  asNativeCancellationToken(token).cancel();
1466
1821
  }
1467
1822
  onCancellationTokenCancelled(token, callback) {
1468
- asNativeCancellationToken(token).onCancelled(callback);
1823
+ const listener = asNativeCancellationToken(token).onCancelled(callback);
1824
+ return () => listener.release();
1469
1825
  }
1470
1826
  actorState(ctx) {
1471
1827
  return asNativeActorContext(ctx).state();
@@ -1479,6 +1835,9 @@ var NapiCoreRuntime = class {
1479
1835
  actorSetAlarm(ctx, timestampMs) {
1480
1836
  asNativeActorContext(ctx).setAlarm(timestampMs);
1481
1837
  }
1838
+ async actorSetRunWakeAt(ctx, timestampMs) {
1839
+ await asNativeActorContext(ctx).setRunWakeAt(timestampMs);
1840
+ }
1482
1841
  actorRequestSave(ctx, opts) {
1483
1842
  asNativeActorContext(ctx).requestSave(opts);
1484
1843
  }
@@ -1519,9 +1878,68 @@ var NapiCoreRuntime = class {
1519
1878
  toNapiStateDeltaPayload(payload)
1520
1879
  );
1521
1880
  }
1522
- actorId(ctx) {
1881
+ async actorSaveStateAndWorkflowBatch(ctx, writes) {
1882
+ await asNativeActorContext(ctx).saveStateAndWorkflowBatch(
1883
+ writes.map((write) => ({
1884
+ key: toNapiBuffer(write.key),
1885
+ value: toNapiBuffer(write.value)
1886
+ }))
1887
+ );
1888
+ }
1889
+ actorId(ctx) {
1523
1890
  return asNativeActorContext(ctx).actorId();
1524
1891
  }
1892
+ runWithActorInvocationContext(ctx, run) {
1893
+ return this.#runAs(asNativeActorContext(ctx), run);
1894
+ }
1895
+ #runAs(nativeCtx, run) {
1896
+ var _a;
1897
+ const span = (_a = nativeCtx.invocationTraceContext()) == null ? void 0 : _a.span;
1898
+ return this.#invocationContext.run(
1899
+ nativeCtx,
1900
+ () => runWithActorInvocationSpan(span, run)
1901
+ );
1902
+ }
1903
+ actorInvocationTraceContext(ctx) {
1904
+ return this.#actorContextForOperation(ctx).invocationTraceContext() ?? void 0;
1905
+ }
1906
+ startCallSpan(ctx, actorName, actionName) {
1907
+ const call = this.#actorContextForOperation(ctx).startCallSpan(
1908
+ actorName,
1909
+ actionName
1910
+ );
1911
+ if (!call) return void 0;
1912
+ return {
1913
+ span: call.spanContext() ?? void 0,
1914
+ finish: (error) => call.finish(error)
1915
+ };
1916
+ }
1917
+ async startWorkflowSpan(ctx) {
1918
+ const span = await asNativeActorContext(ctx).startWorkflowSpan();
1919
+ const spanCtx = span.ctx();
1920
+ return {
1921
+ run: (body) => this.#runAs(spanCtx, body),
1922
+ startStep: (name, attempt) => {
1923
+ const step = spanCtx.startWorkflowStepSpan(name, attempt);
1924
+ if (!step) return void 0;
1925
+ const stepCtx = step.ctx();
1926
+ return {
1927
+ run: (body) => this.#runAs(stepCtx, body),
1928
+ finish: (outcome, error) => step.finish(
1929
+ outcome,
1930
+ error === void 0 ? void 0 : encodeErrorForBridge(error)
1931
+ )
1932
+ };
1933
+ },
1934
+ finish: (outcome) => span.finish(outcome)
1935
+ };
1936
+ }
1937
+ runOutsideActorInvocationContext(run) {
1938
+ return this.#invocationContext.exit(run);
1939
+ }
1940
+ currentInvocationScope() {
1941
+ return this.#invocationContext.getStore();
1942
+ }
1525
1943
  actorName(ctx) {
1526
1944
  return asNativeActorContext(ctx).name();
1527
1945
  }
@@ -1553,7 +1971,7 @@ var NapiCoreRuntime = class {
1553
1971
  asNativeActorContext(ctx).broadcast(name, toNapiBuffer(args));
1554
1972
  }
1555
1973
  actorWaitUntil(ctx, promise) {
1556
- asNativeActorContext(ctx).waitUntil(promise);
1974
+ this.#actorContextForOperation(ctx).waitUntil(promise);
1557
1975
  }
1558
1976
  async actorWaitForTrackedShutdownWork(ctx) {
1559
1977
  return await asNativeActorContext(ctx).waitForTrackedShutdownWork();
@@ -1618,6 +2036,9 @@ var NapiCoreRuntime = class {
1618
2036
  async actorSqlExec(ctx, sql) {
1619
2037
  return await this.#actorSql(ctx).exec(sql);
1620
2038
  }
2039
+ actorSqlExecSync(ctx, sql) {
2040
+ return this.#actorSql(ctx).execSync(sql);
2041
+ }
1621
2042
  async actorSqlExecute(ctx, sql, params) {
1622
2043
  const result = await this.#actorSql(ctx).execute(
1623
2044
  sql,
@@ -1625,6 +2046,83 @@ var NapiCoreRuntime = class {
1625
2046
  );
1626
2047
  return normalizeRuntimeSqlExecuteResult(result);
1627
2048
  }
2049
+ actorSqlExecuteSync(ctx, sql, params) {
2050
+ const result = this.#actorSql(ctx).executeSync(
2051
+ sql,
2052
+ toNapiSqlBindParams(params)
2053
+ );
2054
+ return normalizeRuntimeSqlExecuteResult(result);
2055
+ }
2056
+ async actorSqlExecuteBatch(ctx, statements) {
2057
+ const results = await this.#actorSql(ctx).executeBatch(
2058
+ statements.map(toNapiSqlBatchStatement)
2059
+ );
2060
+ return results.map(normalizeRuntimeSqlExecuteResult);
2061
+ }
2062
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
2063
+ return await this.#actorSql(ctx).beginTransaction(
2064
+ timeoutMs,
2065
+ name
2066
+ );
2067
+ }
2068
+ actorSqlBeginTransactionSync(ctx, timeoutMs, name) {
2069
+ return this.#actorSql(ctx).beginTransactionSync(
2070
+ timeoutMs,
2071
+ name
2072
+ );
2073
+ }
2074
+ async actorSqlTransactionExec(transaction, sql) {
2075
+ return await asNativeSqlTransaction(transaction).exec(sql);
2076
+ }
2077
+ actorSqlTransactionExecSync(transaction, sql) {
2078
+ return asNativeSqlTransaction(transaction).execSync(sql);
2079
+ }
2080
+ async actorSqlTransactionExecute(transaction, sql, params) {
2081
+ const result = await asNativeSqlTransaction(transaction).execute(
2082
+ sql,
2083
+ toNapiSqlBindParams(params)
2084
+ );
2085
+ return normalizeRuntimeSqlExecuteResult(result);
2086
+ }
2087
+ actorSqlTransactionExecuteSync(transaction, sql, params) {
2088
+ const result = asNativeSqlTransaction(transaction).executeSync(
2089
+ sql,
2090
+ toNapiSqlBindParams(params)
2091
+ );
2092
+ return normalizeRuntimeSqlExecuteResult(result);
2093
+ }
2094
+ async actorSqlTransactionCommit(transaction) {
2095
+ await asNativeSqlTransaction(transaction).commit();
2096
+ }
2097
+ actorSqlTransactionCommitSync(transaction) {
2098
+ asNativeSqlTransaction(transaction).commitSync();
2099
+ }
2100
+ async actorSqlTransactionRollback(transaction) {
2101
+ await asNativeSqlTransaction(transaction).rollback();
2102
+ }
2103
+ actorSqlTransactionRollbackSync(transaction) {
2104
+ asNativeSqlTransaction(transaction).rollbackSync();
2105
+ }
2106
+ async actorBeginStateTransaction(ctx, timeoutMs) {
2107
+ return await this.#actorContextForOperation(ctx).beginStateTransaction(
2108
+ timeoutMs
2109
+ );
2110
+ }
2111
+ async actorStateTransactionExecute(transaction, sql, params) {
2112
+ const result = await asNativeActorStateTransaction(transaction).execute(
2113
+ sql,
2114
+ toNapiSqlBindParams(params)
2115
+ );
2116
+ return normalizeRuntimeSqlExecuteResult(result);
2117
+ }
2118
+ async actorStateTransactionCommit(transaction, payload) {
2119
+ await asNativeActorStateTransaction(transaction).commit(
2120
+ toNapiStateDeltaPayload(payload)
2121
+ );
2122
+ }
2123
+ async actorStateTransactionRollback(transaction) {
2124
+ await asNativeActorStateTransaction(transaction).rollback();
2125
+ }
1628
2126
  async actorSqlQuery(ctx, sql, params) {
1629
2127
  return await this.#actorSql(ctx).query(
1630
2128
  sql,
@@ -1642,22 +2140,35 @@ var NapiCoreRuntime = class {
1642
2140
  var _a, _b;
1643
2141
  return ((_b = (_a = this.#actorSql(ctx)).takeLastKvError) == null ? void 0 : _b.call(_a)) ?? null;
1644
2142
  }
2143
+ async actorSqlOpen(ctx) {
2144
+ await this.#actorSql(ctx).open();
2145
+ }
2146
+ actorSqlCommitTicket(ctx) {
2147
+ return this.#actorSql(ctx).commitTicket();
2148
+ }
2149
+ actorSqlAbortGeneration(ctx, reason) {
2150
+ this.#actorSql(ctx).abortGeneration(reason);
2151
+ }
2152
+ async actorSqlWhenDurable(ctx, ticket) {
2153
+ await this.#actorSql(ctx).whenDurable(ticket);
2154
+ }
1645
2155
  async actorSqlClose(ctx) {
1646
2156
  const nativeCtx = asNativeActorContext(ctx);
1647
- const database = this.#sql.get(nativeCtx);
1648
- if (!database) {
2157
+ if (!this.#sqlOpened.delete(nativeCtx)) {
1649
2158
  return;
1650
2159
  }
1651
- this.#sql.delete(nativeCtx);
1652
- await database.close();
2160
+ await nativeCtx.sql().close();
2161
+ }
2162
+ async actorRuntimeSocketProvision(ctx) {
2163
+ return await asNativeActorContext(ctx).provisionActorRuntimeSocket();
1653
2164
  }
1654
2165
  async actorQueueSend(ctx, name, body) {
1655
2166
  return toNapiQueueMessage(
1656
- await asNativeActorContext(ctx).queue().send(name, toNapiBuffer(body))
2167
+ await this.#actorContextForOperation(ctx).queue().send(name, toNapiBuffer(body))
1657
2168
  );
1658
2169
  }
1659
2170
  async actorQueueNextBatch(ctx, options, signal) {
1660
- const messages = await asNativeActorContext(ctx).queue().nextBatch(
2171
+ const messages = await this.#actorContextForOperation(ctx).queue().nextBatch(
1661
2172
  options,
1662
2173
  signal ? asNativeCancellationToken(signal) : signal
1663
2174
  );
@@ -1665,7 +2176,7 @@ var NapiCoreRuntime = class {
1665
2176
  }
1666
2177
  async actorQueueWaitForNames(ctx, names, options, signal) {
1667
2178
  return toNapiQueueMessage(
1668
- await asNativeActorContext(ctx).queue().waitForNames(
2179
+ await this.#actorContextForOperation(ctx).queue().waitForNames(
1669
2180
  names,
1670
2181
  options,
1671
2182
  signal ? asNativeCancellationToken(signal) : signal
@@ -1679,8 +2190,15 @@ var NapiCoreRuntime = class {
1679
2190
  signal ? asNativeCancellationToken(signal) : signal
1680
2191
  );
1681
2192
  }
2193
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
2194
+ return await asNativeActorContext(ctx).queue().completePersisted(
2195
+ messageId,
2196
+ expectedName,
2197
+ response == null ? response : toNapiBuffer(response)
2198
+ );
2199
+ }
1682
2200
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
1683
- return await asNativeActorContext(ctx).queue().enqueueAndWait(
2201
+ return await this.#actorContextForOperation(ctx).queue().enqueueAndWait(
1684
2202
  name,
1685
2203
  toNapiBuffer(body),
1686
2204
  options,
@@ -1696,11 +2214,54 @@ var NapiCoreRuntime = class {
1696
2214
  async actorQueueInspectMessages(ctx) {
1697
2215
  return await asNativeActorContext(ctx).queue().inspectMessages();
1698
2216
  }
1699
- actorScheduleAfter(ctx, durationMs, actionName, args) {
1700
- asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
2217
+ async actorQueueReset(ctx) {
2218
+ await asNativeActorContext(ctx).queue().reset();
2219
+ }
2220
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
2221
+ return await this.#actorContextForOperation(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
2222
+ }
2223
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
2224
+ return await this.#actorContextForOperation(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
2225
+ }
2226
+ async actorScheduleCancel(ctx, id) {
2227
+ return await this.#actorContextForOperation(ctx).schedule().cancel(id);
2228
+ }
2229
+ async actorScheduleGet(ctx, id) {
2230
+ return await this.#actorContextForOperation(ctx).schedule().get(id) ?? void 0;
2231
+ }
2232
+ async actorScheduleList(ctx) {
2233
+ return await this.#actorContextForOperation(ctx).schedule().list();
1701
2234
  }
1702
- actorScheduleAt(ctx, timestampMs, actionName, args) {
1703
- asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
2235
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
2236
+ await this.#actorContextForOperation(ctx).schedule().cronSet(
2237
+ name,
2238
+ expression,
2239
+ timezone,
2240
+ actionName,
2241
+ toNapiBuffer(args),
2242
+ maxHistory
2243
+ );
2244
+ }
2245
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
2246
+ await this.#actorContextForOperation(ctx).schedule().cronEvery(
2247
+ name,
2248
+ intervalMs,
2249
+ actionName,
2250
+ toNapiBuffer(args),
2251
+ maxHistory
2252
+ );
2253
+ }
2254
+ async actorCronGet(ctx, name) {
2255
+ return await this.#actorContextForOperation(ctx).schedule().cronGet(name) ?? void 0;
2256
+ }
2257
+ async actorCronList(ctx) {
2258
+ return await this.#actorContextForOperation(ctx).schedule().cronList();
2259
+ }
2260
+ async actorCronDelete(ctx, name) {
2261
+ return await this.#actorContextForOperation(ctx).schedule().cronDelete(name);
2262
+ }
2263
+ async actorCronHistory(ctx, name, limit) {
2264
+ return await this.#actorContextForOperation(ctx).schedule().cronHistory(name, limit);
1704
2265
  }
1705
2266
  connId(conn) {
1706
2267
  return asNativeConn(conn).id();
@@ -1734,10 +2295,156 @@ var NapiCoreRuntime = class {
1734
2295
  }
1735
2296
  };
1736
2297
  async function loadNapiRuntime() {
1737
- const bindings = await import(["@rivetkit", "rivetkit-napi"].join("/"));
2298
+ const [{ AsyncLocalStorage }, bindings] = await Promise.all([
2299
+ import("async_hooks"),
2300
+ import(["@rivetkit", "rivetkit-napi"].join("/"))
2301
+ ]);
1738
2302
  return {
1739
2303
  bindings,
1740
- runtime: new NapiCoreRuntime(bindings)
2304
+ runtime: new NapiCoreRuntime(bindings, new AsyncLocalStorage())
2305
+ };
2306
+ }
2307
+
2308
+ // src/registry/native-http.ts
2309
+ var HTTP_BODY_CHUNK_SIZE = 64 * 1024;
2310
+ function runtimeBytesToArrayBuffer(value) {
2311
+ return value.buffer.slice(
2312
+ value.byteOffset,
2313
+ value.byteOffset + value.byteLength
2314
+ );
2315
+ }
2316
+ function buildNativeHttpRequest(init) {
2317
+ var _a;
2318
+ const headers = new Headers(init.headers);
2319
+ const originalUrl = headers.get(HEADER_ORIGINAL_REQUEST_URL);
2320
+ headers.delete(HEADER_ORIGINAL_REQUEST_URL);
2321
+ const url = originalUrl ?? (init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString());
2322
+ const method2 = init.method.toUpperCase();
2323
+ const bodyForbidden = method2 === "GET" || method2 === "HEAD";
2324
+ const body = bodyForbidden ? void 0 : init.bodyStream ? new ReadableStream({
2325
+ async pull(controller) {
2326
+ var _a2, _b;
2327
+ try {
2328
+ if (init.body && init.body.length > 0) {
2329
+ controller.enqueue(new Uint8Array(init.body));
2330
+ init.body = void 0;
2331
+ return;
2332
+ }
2333
+ const chunk = await ((_a2 = init.bodyStream) == null ? void 0 : _a2.read());
2334
+ if (!chunk) {
2335
+ controller.close();
2336
+ } else {
2337
+ controller.enqueue(new Uint8Array(chunk));
2338
+ }
2339
+ } catch (error) {
2340
+ (_b = init.abortController) == null ? void 0 : _b.abort(error);
2341
+ controller.error(error);
2342
+ }
2343
+ },
2344
+ async cancel() {
2345
+ var _a2;
2346
+ await ((_a2 = init.bodyStream) == null ? void 0 : _a2.cancel());
2347
+ }
2348
+ }) : init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
2349
+ const streamInit = init.bodyStream && !bodyForbidden ? { duplex: "half" } : {};
2350
+ return new Request(url, {
2351
+ method: method2,
2352
+ headers,
2353
+ body,
2354
+ signal: ((_a = init.abortController) == null ? void 0 : _a.signal) ?? init.signal,
2355
+ ...streamInit
2356
+ });
2357
+ }
2358
+ async function cancelNativeHttpRequestBody(bodyStream) {
2359
+ await (bodyStream == null ? void 0 : bodyStream.cancel());
2360
+ }
2361
+ async function writeResponseChunk(stream, chunk) {
2362
+ for (let offset = 0; offset < chunk.byteLength; offset += HTTP_BODY_CHUNK_SIZE) {
2363
+ await stream.write(
2364
+ chunk.subarray(offset, offset + HTTP_BODY_CHUNK_SIZE)
2365
+ );
2366
+ }
2367
+ }
2368
+ async function pumpResponseBody(reader, stream) {
2369
+ var _a;
2370
+ const cancelled = stream.cancelled().then(() => ({ cancelled: true }));
2371
+ try {
2372
+ for (; ; ) {
2373
+ const read = reader.read().then((next2) => ({ cancelled: false, next: next2 }));
2374
+ const result = await Promise.race([read, cancelled]);
2375
+ if (result.cancelled) {
2376
+ void reader.cancel(
2377
+ new Error(
2378
+ "native http response stream receiver dropped"
2379
+ )
2380
+ ).catch((error) => {
2381
+ logger2().debug({
2382
+ msg: "failed to cancel native http response reader",
2383
+ error
2384
+ });
2385
+ });
2386
+ return;
2387
+ }
2388
+ const { next } = result;
2389
+ if (next.done) {
2390
+ await stream.end();
2391
+ return;
2392
+ }
2393
+ if ((_a = next.value) == null ? void 0 : _a.byteLength) {
2394
+ await writeResponseChunk(stream, next.value);
2395
+ }
2396
+ }
2397
+ } catch (error) {
2398
+ try {
2399
+ await stream.error(stringifyError(error));
2400
+ } catch (streamError) {
2401
+ logger2().debug({
2402
+ msg: "failed to report native http response stream error",
2403
+ error: streamError
2404
+ });
2405
+ }
2406
+ void reader.cancel(error).catch(() => {
2407
+ });
2408
+ } finally {
2409
+ try {
2410
+ reader.releaseLock();
2411
+ } catch (error) {
2412
+ logger2().debug({
2413
+ msg: "failed to release native http response reader lock",
2414
+ error
2415
+ });
2416
+ }
2417
+ }
2418
+ }
2419
+ async function convertNativeHttpResponse(response, responseBodyStream) {
2420
+ const headers = Object.fromEntries(response.headers.entries());
2421
+ if (!response.body) {
2422
+ return {
2423
+ response: {
2424
+ status: response.status,
2425
+ headers,
2426
+ body: new Uint8Array()
2427
+ }
2428
+ };
2429
+ }
2430
+ if (responseBodyStream) {
2431
+ const reader = response.body.getReader();
2432
+ const bodyCompletion = pumpResponseBody(reader, responseBodyStream);
2433
+ return {
2434
+ response: {
2435
+ status: response.status,
2436
+ headers,
2437
+ stream: true
2438
+ },
2439
+ bodyCompletion
2440
+ };
2441
+ }
2442
+ return {
2443
+ response: {
2444
+ status: response.status,
2445
+ headers,
2446
+ body: new Uint8Array(await response.arrayBuffer())
2447
+ }
1741
2448
  };
1742
2449
  }
1743
2450
 
@@ -1825,7 +2532,167 @@ function validationError(target, issues) {
1825
2532
  });
1826
2533
  }
1827
2534
 
2535
+ // src/registry/run-handler-coordinator.ts
2536
+ function runUnavailable(actorId, reason) {
2537
+ return new RivetError(
2538
+ "actor",
2539
+ "run_handler_unavailable",
2540
+ `Run handler control is unavailable for actor ${actorId}: ${reason}.`,
2541
+ {
2542
+ public: true,
2543
+ statusCode: 409,
2544
+ metadata: { actorId, reason }
2545
+ }
2546
+ );
2547
+ }
2548
+ function notifyStateChanged(state) {
2549
+ const waiters = [...state.waiters];
2550
+ state.waiters.clear();
2551
+ for (const waiter of waiters) {
2552
+ waiter();
2553
+ }
2554
+ }
2555
+ function waitForStateChange(state) {
2556
+ return new Promise((resolve) => {
2557
+ state.waiters.add(resolve);
2558
+ });
2559
+ }
2560
+ var RunHandlerCoordinator = class {
2561
+ #run;
2562
+ #states = /* @__PURE__ */ new Map();
2563
+ constructor(run) {
2564
+ this.#run = run;
2565
+ }
2566
+ get inspectorKind() {
2567
+ return getRunInspectorKind(this.#run);
2568
+ }
2569
+ async run(actorId, restart, callback) {
2570
+ const state = this.#getOrCreate(actorId);
2571
+ state.restart = restart;
2572
+ this.#initializeInspector(actorId, state);
2573
+ state.queued += 1;
2574
+ const blockedGeneration = state.exclusive ? state.exclusiveGeneration : void 0;
2575
+ try {
2576
+ while (!state.closed && (state.exclusive || state.active)) {
2577
+ await waitForStateChange(state);
2578
+ }
2579
+ } finally {
2580
+ state.queued -= 1;
2581
+ }
2582
+ if (state.closed) {
2583
+ return "closed";
2584
+ }
2585
+ if (blockedGeneration !== void 0 && state.exclusiveGeneration === blockedGeneration && state.exclusiveOutcome === "failure") {
2586
+ return "suppressed";
2587
+ }
2588
+ state.active = true;
2589
+ try {
2590
+ await callback();
2591
+ return "ran";
2592
+ } finally {
2593
+ state.active = false;
2594
+ notifyStateChanged(state);
2595
+ }
2596
+ }
2597
+ getInspector(actorId, restart) {
2598
+ var _a;
2599
+ const state = this.#getOrCreate(actorId);
2600
+ state.restart = restart;
2601
+ this.#initializeInspector(actorId, state);
2602
+ return (_a = state.inspector) == null ? void 0 : _a.inspector;
2603
+ }
2604
+ destroy(actorId) {
2605
+ var _a, _b;
2606
+ const state = this.#states.get(actorId);
2607
+ if (!state) return;
2608
+ state.closed = true;
2609
+ (_b = (_a = state.inspector) == null ? void 0 : _a.dispose) == null ? void 0 : _b.call(_a);
2610
+ state.inspector = void 0;
2611
+ notifyStateChanged(state);
2612
+ this.#states.delete(actorId);
2613
+ }
2614
+ #control(actorId, state) {
2615
+ return {
2616
+ run: {
2617
+ withInactive: async (options, callback) => {
2618
+ if (state.closed) {
2619
+ throw runUnavailable(actorId, "actor is destroyed");
2620
+ }
2621
+ if (state.active || state.queued > 0 || state.exclusive) {
2622
+ throw runUnavailable(
2623
+ actorId,
2624
+ "the run handler is active or waiting to start"
2625
+ );
2626
+ }
2627
+ state.exclusive = true;
2628
+ state.exclusiveGeneration += 1;
2629
+ state.exclusiveOutcome = void 0;
2630
+ try {
2631
+ const result = await callback();
2632
+ if (state.closed) {
2633
+ throw runUnavailable(actorId, "actor is destroyed");
2634
+ }
2635
+ state.exclusiveOutcome = "success";
2636
+ if (options.restartOnSuccess && state.queued === 0) {
2637
+ if (!state.restart) {
2638
+ throw runUnavailable(
2639
+ actorId,
2640
+ "the runtime restart callback is not available"
2641
+ );
2642
+ }
2643
+ await state.restart();
2644
+ }
2645
+ return result;
2646
+ } catch (error) {
2647
+ state.exclusiveOutcome = "failure";
2648
+ throw error;
2649
+ } finally {
2650
+ state.exclusive = false;
2651
+ notifyStateChanged(state);
2652
+ }
2653
+ }
2654
+ }
2655
+ };
2656
+ }
2657
+ #getOrCreate(actorId) {
2658
+ let state = this.#states.get(actorId);
2659
+ if (!state) {
2660
+ state = {
2661
+ active: false,
2662
+ closed: false,
2663
+ exclusive: false,
2664
+ exclusiveGeneration: 0,
2665
+ inspectorInitialized: false,
2666
+ queued: 0,
2667
+ waiters: /* @__PURE__ */ new Set()
2668
+ };
2669
+ this.#states.set(actorId, state);
2670
+ }
2671
+ return state;
2672
+ }
2673
+ #initializeInspector(actorId, state) {
2674
+ if (state.inspectorInitialized) return;
2675
+ const inspector = createRunInspector(this.#run, {
2676
+ actorId,
2677
+ control: this.#control(actorId, state)
2678
+ });
2679
+ if (this.inspectorKind === "workflow") {
2680
+ const workflow = inspector === void 0 ? void 0 : inspector.inspector.workflow;
2681
+ if (!workflow || typeof workflow.getHistory !== "function" || typeof workflow.getState !== "function" || typeof workflow.onHistoryUpdated !== "function" || typeof workflow.replayFromStep !== "function") {
2682
+ throw new TypeError(
2683
+ `defineRunHandler createInspector returned an invalid workflow adapter for actor ${actorId}`
2684
+ );
2685
+ }
2686
+ }
2687
+ state.inspector = inspector;
2688
+ state.inspectorInitialized = true;
2689
+ }
2690
+ };
2691
+
1828
2692
  // src/registry/wasm-runtime.ts
2693
+ function asWasmConstructors(bindings) {
2694
+ return bindings;
2695
+ }
1829
2696
  function asWasmRegistry(handle) {
1830
2697
  return handle;
1831
2698
  }
@@ -1868,6 +2735,17 @@ function optionalWasmNumber(value) {
1868
2735
  function wasmNumber(value) {
1869
2736
  return typeof value === "bigint" ? Number(value) : value;
1870
2737
  }
2738
+ function synchronousSqliteUnavailable() {
2739
+ throw new RivetError(
2740
+ "sqlite",
2741
+ "sync_unsupported",
2742
+ "Synchronous SQLite is unavailable because the actor runs on the wasm runtime.",
2743
+ {
2744
+ public: true,
2745
+ metadata: { runtime: "wasm" }
2746
+ }
2747
+ );
2748
+ }
1871
2749
  function normalizeKvEntry(entry) {
1872
2750
  return {
1873
2751
  key: toBytes(entry.key),
@@ -1950,10 +2828,10 @@ function childHandle(handle, name) {
1950
2828
  }
1951
2829
  var WasmCoreRuntime = class {
1952
2830
  kind = "wasm";
1953
- #bindings;
2831
+ #constructors;
1954
2832
  #sql = /* @__PURE__ */ new WeakMap();
1955
2833
  constructor(bindings) {
1956
- this.#bindings = bindings;
2834
+ this.#constructors = asWasmConstructors(bindings);
1957
2835
  }
1958
2836
  #actorSql(ctx) {
1959
2837
  const wasmCtx = asWasmActorContext(ctx);
@@ -1966,7 +2844,7 @@ var WasmCoreRuntime = class {
1966
2844
  }
1967
2845
  createRegistry() {
1968
2846
  return callWasmSync(
1969
- () => asRegistryHandle2(new this.#bindings.CoreRegistry())
2847
+ () => asRegistryHandle2(new this.#constructors.CoreRegistry())
1970
2848
  );
1971
2849
  }
1972
2850
  registerActor(registry, name, factory) {
@@ -1977,6 +2855,11 @@ var WasmCoreRuntime = class {
1977
2855
  async serveRegistry(registry, config) {
1978
2856
  await callWasm(() => asWasmRegistry(registry).serve(config));
1979
2857
  }
2858
+ async waitRegistryReady() {
2859
+ throw new Error(
2860
+ "registry.startAndWait() is not supported by the WASM runtime"
2861
+ );
2862
+ }
1980
2863
  async shutdownRegistry(registry) {
1981
2864
  await callWasm(() => asWasmRegistry(registry).shutdown());
1982
2865
  }
@@ -2008,16 +2891,29 @@ var WasmCoreRuntime = class {
2008
2891
  "registry.listen() is not supported on the wasm runtime; use registry.serve() and mount the handler in your platform's HTTP server instead"
2009
2892
  );
2010
2893
  }
2894
+ async serveApplicationListener(_registry, _listener, _config) {
2895
+ throw new Error(
2896
+ "registry.listen() is not supported on the wasm runtime; use an application-owned HTTP server instead"
2897
+ );
2898
+ }
2011
2899
  createActorFactory(callbacks, config) {
2900
+ if (config == null ? void 0 : config.sqliteDeferredCommits) {
2901
+ throw new RivetError(
2902
+ "sqlite",
2903
+ "deferred_commits_unsupported",
2904
+ "SQLite deferred commits require local native SQLite, but the wasm runtime uses remote SQLite.",
2905
+ { metadata: { runtime: "wasm" } }
2906
+ );
2907
+ }
2012
2908
  return callWasmSync(
2013
2909
  () => asActorFactoryHandle2(
2014
- new this.#bindings.ActorFactory(callbacks, config)
2910
+ new this.#constructors.ActorFactory(callbacks, config)
2015
2911
  )
2016
2912
  );
2017
2913
  }
2018
2914
  createCancellationToken() {
2019
2915
  return callWasmSync(
2020
- () => new this.#bindings.CancellationToken()
2916
+ () => new this.#constructors.CancellationToken()
2021
2917
  );
2022
2918
  }
2023
2919
  cancellationTokenAborted(token) {
@@ -2027,9 +2923,10 @@ var WasmCoreRuntime = class {
2027
2923
  callWasmSync(() => asWasmCancellationToken(token).cancel());
2028
2924
  }
2029
2925
  onCancellationTokenCancelled(token, callback) {
2030
- callWasmSync(
2926
+ const listener = callWasmSync(
2031
2927
  () => asWasmCancellationToken(token).onCancelled(callback)
2032
2928
  );
2929
+ return () => callWasmSync(() => listener.release());
2033
2930
  }
2034
2931
  actorState(ctx) {
2035
2932
  return toBytes(
@@ -2052,6 +2949,13 @@ var WasmCoreRuntime = class {
2052
2949
  optionalWasmNumber(timestampMs)
2053
2950
  );
2054
2951
  }
2952
+ async actorSetRunWakeAt(ctx, timestampMs) {
2953
+ await callHandleAsync(
2954
+ asWasmActorContext(ctx),
2955
+ "setRunWakeAt",
2956
+ optionalWasmNumber(timestampMs)
2957
+ );
2958
+ }
2055
2959
  actorRequestSave(ctx, opts) {
2056
2960
  callHandle(asWasmActorContext(ctx), "requestSave", opts);
2057
2961
  }
@@ -2107,9 +3011,39 @@ var WasmCoreRuntime = class {
2107
3011
  async actorSaveState(ctx, payload) {
2108
3012
  await callHandleAsync(asWasmActorContext(ctx), "saveState", payload);
2109
3013
  }
3014
+ async actorSaveStateAndWorkflowBatch(ctx, writes) {
3015
+ await callHandleAsync(
3016
+ asWasmActorContext(ctx),
3017
+ "saveStateAndWorkflowBatch",
3018
+ writes
3019
+ );
3020
+ }
2110
3021
  actorId(ctx) {
2111
3022
  return callHandle(asWasmActorContext(ctx), "actorId");
2112
3023
  }
3024
+ runWithActorInvocationContext(_ctx, run) {
3025
+ return run();
3026
+ }
3027
+ actorInvocationTraceContext(_ctx) {
3028
+ return void 0;
3029
+ }
3030
+ startCallSpan(_ctx, _actorName, _actionName) {
3031
+ return void 0;
3032
+ }
3033
+ async startWorkflowSpan(_ctx) {
3034
+ return {
3035
+ run: (body) => body(),
3036
+ startStep: () => void 0,
3037
+ finish: async () => {
3038
+ }
3039
+ };
3040
+ }
3041
+ runOutsideActorInvocationContext(run) {
3042
+ return run();
3043
+ }
3044
+ currentInvocationScope() {
3045
+ return void 0;
3046
+ }
2113
3047
  actorName(ctx) {
2114
3048
  return callHandle(asWasmActorContext(ctx), "name");
2115
3049
  }
@@ -2247,12 +3181,86 @@ var WasmCoreRuntime = class {
2247
3181
  async actorSqlExec(ctx, sql) {
2248
3182
  return await callWasm(() => this.#actorSql(ctx).exec(sql));
2249
3183
  }
3184
+ actorSqlExecSync(_ctx, _sql) {
3185
+ return synchronousSqliteUnavailable();
3186
+ }
2250
3187
  async actorSqlExecute(ctx, sql, params) {
2251
3188
  const result = await callWasm(
2252
3189
  () => this.#actorSql(ctx).execute(sql, params)
2253
3190
  );
2254
3191
  return normalizeRuntimeSqlExecuteResult(result);
2255
3192
  }
3193
+ actorSqlExecuteSync(_ctx, _sql, _params) {
3194
+ return synchronousSqliteUnavailable();
3195
+ }
3196
+ async actorSqlExecuteBatch(ctx, statements) {
3197
+ const results = await callWasm(
3198
+ () => this.#actorSql(ctx).executeBatch(statements)
3199
+ );
3200
+ return results.map(normalizeRuntimeSqlExecuteResult);
3201
+ }
3202
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
3203
+ return await callWasm(
3204
+ () => this.#actorSql(ctx).beginTransaction(timeoutMs, name)
3205
+ );
3206
+ }
3207
+ actorSqlBeginTransactionSync(_ctx, _timeoutMs, _name) {
3208
+ return synchronousSqliteUnavailable();
3209
+ }
3210
+ async actorSqlTransactionExec(transaction, sql) {
3211
+ return await callWasm(
3212
+ () => transaction.exec(sql)
3213
+ );
3214
+ }
3215
+ actorSqlTransactionExecSync(_transaction, _sql) {
3216
+ return synchronousSqliteUnavailable();
3217
+ }
3218
+ async actorSqlTransactionExecute(transaction, sql, params) {
3219
+ const result = await callWasm(
3220
+ () => transaction.execute(sql, params)
3221
+ );
3222
+ return normalizeRuntimeSqlExecuteResult(result);
3223
+ }
3224
+ actorSqlTransactionExecuteSync(_transaction, _sql, _params) {
3225
+ return synchronousSqliteUnavailable();
3226
+ }
3227
+ async actorSqlTransactionCommit(transaction) {
3228
+ await callWasm(
3229
+ () => transaction.commit()
3230
+ );
3231
+ }
3232
+ actorSqlTransactionCommitSync(_transaction) {
3233
+ synchronousSqliteUnavailable();
3234
+ }
3235
+ async actorSqlTransactionRollback(transaction) {
3236
+ await callWasm(
3237
+ () => transaction.rollback()
3238
+ );
3239
+ }
3240
+ actorSqlTransactionRollbackSync(_transaction) {
3241
+ synchronousSqliteUnavailable();
3242
+ }
3243
+ async actorBeginStateTransaction(ctx, timeoutMs) {
3244
+ return await callWasm(
3245
+ () => asWasmActorContext(ctx).beginStateTransaction(timeoutMs)
3246
+ );
3247
+ }
3248
+ async actorStateTransactionExecute(transaction, sql, params) {
3249
+ const result = await callWasm(
3250
+ () => transaction.execute(sql, params)
3251
+ );
3252
+ return normalizeRuntimeSqlExecuteResult(result);
3253
+ }
3254
+ async actorStateTransactionCommit(transaction, payload) {
3255
+ await callWasm(
3256
+ () => transaction.commit(payload)
3257
+ );
3258
+ }
3259
+ async actorStateTransactionRollback(transaction) {
3260
+ await callWasm(
3261
+ () => transaction.rollback()
3262
+ );
3263
+ }
2256
3264
  async actorSqlQuery(ctx, sql, params) {
2257
3265
  return await callWasm(() => this.#actorSql(ctx).query(sql, params));
2258
3266
  }
@@ -2267,6 +3275,17 @@ var WasmCoreRuntime = class {
2267
3275
  var _a, _b;
2268
3276
  return ((_b = (_a = this.#actorSql(ctx)).takeLastKvError) == null ? void 0 : _b.call(_a)) ?? null;
2269
3277
  }
3278
+ async actorSqlOpen(_ctx) {
3279
+ }
3280
+ actorSqlCommitTicket(_ctx) {
3281
+ return synchronousSqliteUnavailable();
3282
+ }
3283
+ actorSqlAbortGeneration(_ctx, _reason) {
3284
+ synchronousSqliteUnavailable();
3285
+ }
3286
+ async actorSqlWhenDurable(_ctx, _ticket) {
3287
+ synchronousSqliteUnavailable();
3288
+ }
2270
3289
  async actorSqlClose(ctx) {
2271
3290
  const wasmCtx = asWasmActorContext(ctx);
2272
3291
  const database = this.#sql.get(wasmCtx);
@@ -2276,6 +3295,17 @@ var WasmCoreRuntime = class {
2276
3295
  this.#sql.delete(wasmCtx);
2277
3296
  await callWasm(() => database.close());
2278
3297
  }
3298
+ async actorRuntimeSocketProvision(_ctx) {
3299
+ throw new RivetError(
3300
+ "actor_runtime_socket",
3301
+ "unsupported",
3302
+ "Actor Runtime Socket is only available on Unix native runtimes.",
3303
+ {
3304
+ public: true,
3305
+ metadata: { runtime: "wasm" }
3306
+ }
3307
+ );
3308
+ }
2279
3309
  async actorQueueSend(ctx, name, body) {
2280
3310
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2281
3311
  return normalizeQueueMessage(
@@ -2314,6 +3344,16 @@ var WasmCoreRuntime = class {
2314
3344
  signal
2315
3345
  );
2316
3346
  }
3347
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
3348
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
3349
+ return await callHandleAsync(
3350
+ queue2,
3351
+ "completePersisted",
3352
+ messageId,
3353
+ expectedName,
3354
+ response
3355
+ );
3356
+ }
2317
3357
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
2318
3358
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2319
3359
  return optionalBytes(
@@ -2327,29 +3367,117 @@ var WasmCoreRuntime = class {
2327
3367
  )
2328
3368
  );
2329
3369
  }
2330
- actorQueueTryNextBatch(ctx, options) {
2331
- const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2332
- return callHandle(
2333
- queue2,
2334
- "tryNextBatch",
2335
- options
2336
- ).map(normalizeQueueMessage);
2337
- }
2338
- actorQueueMaxSize(ctx) {
2339
- const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2340
- return callHandle(queue2, "maxSize");
3370
+ actorQueueTryNextBatch(ctx, options) {
3371
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
3372
+ return callHandle(
3373
+ queue2,
3374
+ "tryNextBatch",
3375
+ options
3376
+ ).map(normalizeQueueMessage);
3377
+ }
3378
+ actorQueueMaxSize(ctx) {
3379
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
3380
+ return callHandle(queue2, "maxSize");
3381
+ }
3382
+ async actorQueueInspectMessages(ctx) {
3383
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
3384
+ return await callHandleAsync(queue2, "inspectMessages");
3385
+ }
3386
+ async actorQueueReset(ctx) {
3387
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
3388
+ await callHandleAsync(queue2, "reset");
3389
+ }
3390
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
3391
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3392
+ return await callHandleAsync(
3393
+ schedule,
3394
+ "after",
3395
+ wasmNumber(durationMs),
3396
+ actionName,
3397
+ args
3398
+ );
3399
+ }
3400
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
3401
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3402
+ return await callHandleAsync(
3403
+ schedule,
3404
+ "at",
3405
+ wasmNumber(timestampMs),
3406
+ actionName,
3407
+ args
3408
+ );
3409
+ }
3410
+ async actorScheduleCancel(ctx, id) {
3411
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3412
+ return await callHandleAsync(schedule, "cancel", id);
3413
+ }
3414
+ async actorScheduleGet(ctx, id) {
3415
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3416
+ return await callHandleAsync(
3417
+ schedule,
3418
+ "get",
3419
+ id
3420
+ );
3421
+ }
3422
+ async actorScheduleList(ctx) {
3423
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3424
+ return await callHandleAsync(
3425
+ schedule,
3426
+ "list"
3427
+ );
3428
+ }
3429
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
3430
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3431
+ await callHandleAsync(
3432
+ schedule,
3433
+ "cronSet",
3434
+ name,
3435
+ expression,
3436
+ timezone,
3437
+ actionName,
3438
+ args,
3439
+ maxHistory
3440
+ );
3441
+ }
3442
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
3443
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3444
+ await callHandleAsync(
3445
+ schedule,
3446
+ "cronEvery",
3447
+ name,
3448
+ intervalMs,
3449
+ actionName,
3450
+ args,
3451
+ maxHistory
3452
+ );
3453
+ }
3454
+ async actorCronGet(ctx, name) {
3455
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3456
+ return await callHandleAsync(
3457
+ schedule,
3458
+ "cronGet",
3459
+ name
3460
+ );
2341
3461
  }
2342
- async actorQueueInspectMessages(ctx) {
2343
- const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2344
- return await callHandleAsync(queue2, "inspectMessages");
3462
+ async actorCronList(ctx) {
3463
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3464
+ return await callHandleAsync(
3465
+ schedule,
3466
+ "cronList"
3467
+ );
2345
3468
  }
2346
- actorScheduleAfter(ctx, durationMs, actionName, args) {
3469
+ async actorCronDelete(ctx, name) {
2347
3470
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2348
- callHandle(schedule, "after", wasmNumber(durationMs), actionName, args);
3471
+ return await callHandleAsync(schedule, "cronDelete", name);
2349
3472
  }
2350
- actorScheduleAt(ctx, timestampMs, actionName, args) {
3473
+ async actorCronHistory(ctx, name, limit) {
2351
3474
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2352
- callHandle(schedule, "at", wasmNumber(timestampMs), actionName, args);
3475
+ return await callHandleAsync(
3476
+ schedule,
3477
+ "cronHistory",
3478
+ name,
3479
+ limit
3480
+ );
2353
3481
  }
2354
3482
  connId(conn) {
2355
3483
  return callHandle(asWasmConn(conn), "id");
@@ -2426,6 +3554,83 @@ function createWriteThroughProxy(value, commit, beforeChange) {
2426
3554
  }
2427
3555
  );
2428
3556
  }
3557
+ function unwrapProxy(value) {
3558
+ let current = value;
3559
+ while (current !== null && typeof current === "object") {
3560
+ const target = onChange.target(current);
3561
+ if (target === current) {
3562
+ break;
3563
+ }
3564
+ current = target;
3565
+ }
3566
+ return current;
3567
+ }
3568
+ function isPlainObject(value) {
3569
+ const proto = Object.getPrototypeOf(value);
3570
+ return proto === Object.prototype || proto === null;
3571
+ }
3572
+ function unwrapDeep(value, seen) {
3573
+ const unwrapped = unwrapProxy(value);
3574
+ if (!unwrapped || typeof unwrapped !== "object") {
3575
+ return unwrapped;
3576
+ }
3577
+ if (seen.has(unwrapped)) {
3578
+ return unwrapped;
3579
+ }
3580
+ seen.add(unwrapped);
3581
+ if (Array.isArray(unwrapped)) {
3582
+ for (let i = 0; i < unwrapped.length; i++) {
3583
+ const child = unwrapDeep(unwrapped[i], seen);
3584
+ if (child !== unwrapped[i]) {
3585
+ unwrapped[i] = child;
3586
+ }
3587
+ }
3588
+ return unwrapped;
3589
+ }
3590
+ if (unwrapped instanceof Map) {
3591
+ const replacements = [];
3592
+ for (const [key, child] of unwrapped.entries()) {
3593
+ const nextKey = unwrapDeep(key, seen);
3594
+ const nextChild = unwrapDeep(child, seen);
3595
+ if (nextKey !== key || nextChild !== child) {
3596
+ replacements.push([key, nextKey, nextChild]);
3597
+ }
3598
+ }
3599
+ for (const [key, nextKey, nextChild] of replacements) {
3600
+ if (nextKey !== key) {
3601
+ unwrapped.delete(key);
3602
+ }
3603
+ unwrapped.set(nextKey, nextChild);
3604
+ }
3605
+ return unwrapped;
3606
+ }
3607
+ if (unwrapped instanceof Set) {
3608
+ const replacements = [];
3609
+ for (const child of unwrapped.values()) {
3610
+ const next = unwrapDeep(child, seen);
3611
+ if (next !== child) {
3612
+ replacements.push([child, next]);
3613
+ }
3614
+ }
3615
+ for (const [child, next] of replacements) {
3616
+ unwrapped.delete(child);
3617
+ unwrapped.add(next);
3618
+ }
3619
+ return unwrapped;
3620
+ }
3621
+ if (isPlainObject(unwrapped)) {
3622
+ for (const key of Object.keys(unwrapped)) {
3623
+ const child = unwrapDeep(unwrapped[key], seen);
3624
+ if (child !== unwrapped[key]) {
3625
+ unwrapped[key] = child;
3626
+ }
3627
+ }
3628
+ }
3629
+ return unwrapped;
3630
+ }
3631
+ function unwrapWriteThroughProxy(value) {
3632
+ return unwrapDeep(value, /* @__PURE__ */ new Set());
3633
+ }
2429
3634
 
2430
3635
  // src/registry/native.ts
2431
3636
  var textEncoder = new TextEncoder();
@@ -2474,10 +3679,28 @@ async function loadAutoRuntime(config, loaders = defaultRuntimeLoaders) {
2474
3679
  if (loaders.detectHost() === "edge-like") {
2475
3680
  return (await loaders.loadWasm(config.wasm)).runtime;
2476
3681
  }
3682
+ let nativeError;
2477
3683
  try {
2478
3684
  return (await loaders.loadNative()).runtime;
2479
- } catch {
3685
+ } catch (error) {
3686
+ nativeError = error;
3687
+ logger2().warn({
3688
+ msg: "native runtime failed to load; falling back to wasm",
3689
+ error: stringifyError(error)
3690
+ });
3691
+ }
3692
+ try {
2480
3693
  return (await loaders.loadWasm(config.wasm)).runtime;
3694
+ } catch (wasmError) {
3695
+ throw new RivetError(
3696
+ "config",
3697
+ "runtime_unavailable",
3698
+ `RivetKit could not load a core runtime. Native runtime: ${stringifyError(nativeError)} Wasm runtime: ${stringifyError(wasmError)}`,
3699
+ {
3700
+ public: true,
3701
+ statusCode: 500
3702
+ }
3703
+ );
2481
3704
  }
2482
3705
  }
2483
3706
  async function loadConfiguredRuntime(config, loaders = defaultRuntimeLoaders) {
@@ -2528,9 +3751,10 @@ function normalizeRuntimeConfig(config, runtime) {
2528
3751
  return normalizeRuntimeConfigForKind(config, loadedRuntimeKind(runtime));
2529
3752
  }
2530
3753
  function getNativeRuntimeState(runtime, ctx) {
2531
- const runtimeState = callNativeSync(
2532
- () => runtime.actorRuntimeState(ctx)
2533
- );
3754
+ const runtimeState = readNativeRuntimeStateBag(runtime, ctx);
3755
+ if (runtimeState.cleared) {
3756
+ throw actorStopping(callNativeSync(() => runtime.actorId(ctx)));
3757
+ }
2534
3758
  if (!runtimeState.destroyGate) {
2535
3759
  runtimeState.destroyGate = {};
2536
3760
  }
@@ -2543,6 +3767,14 @@ function getNativeRuntimeState(runtime, ctx) {
2543
3767
  }
2544
3768
  return runtimeState;
2545
3769
  }
3770
+ function readNativeRuntimeStateBag(runtime, ctx) {
3771
+ return callNativeSync(
3772
+ () => runtime.actorRuntimeState(ctx)
3773
+ );
3774
+ }
3775
+ function isNativeRuntimeStateCleared(runtime, ctx) {
3776
+ return readNativeRuntimeStateBag(runtime, ctx).cleared === true;
3777
+ }
2546
3778
  function getNativePersistState(runtime, ctx) {
2547
3779
  const persistState = getNativeRuntimeState(runtime, ctx).persistState;
2548
3780
  if (!persistState) {
@@ -2572,6 +3804,14 @@ function stateMutationReentrantError() {
2572
3804
  "State mutations are not allowed inside onStateChange."
2573
3805
  );
2574
3806
  }
3807
+ function stateTransactionConflictError() {
3808
+ return new RivetError(
3809
+ "actor",
3810
+ "state_transaction_conflict",
3811
+ "State cannot be mutated by another action while an experimental state-aware database transaction is active.",
3812
+ { public: true, statusCode: 409 }
3813
+ );
3814
+ }
2575
3815
  function databaseNotConfiguredError() {
2576
3816
  return new RivetError(
2577
3817
  "actor",
@@ -2588,6 +3828,14 @@ function databaseClientNotReadyError() {
2588
3828
  { public: true }
2589
3829
  );
2590
3830
  }
3831
+ function runHandlerNotConfiguredError() {
3832
+ return new RivetError(
3833
+ "actor",
3834
+ "run_handler_unavailable",
3835
+ "Cannot schedule a run wake because this actor does not define a run handler.",
3836
+ { public: true, statusCode: 409 }
3837
+ );
3838
+ }
2591
3839
  function stateNotEnabledError() {
2592
3840
  return new RivetError(
2593
3841
  "actor",
@@ -2637,13 +3885,18 @@ function resolveNativeDestroy(runtime, ctx) {
2637
3885
  gate.destroyCompletion = void 0;
2638
3886
  }
2639
3887
  function clearNativeRuntimeState(runtime, ctx) {
3888
+ var _a;
3889
+ const pendingSaveHandle = (_a = readNativeRuntimeStateBag(runtime, ctx).persistState) == null ? void 0 : _a.pendingSaveHandle;
3890
+ if (pendingSaveHandle !== void 0) {
3891
+ clearImmediate(pendingSaveHandle);
3892
+ }
2640
3893
  callNativeSync(() => runtime.actorClearRuntimeState(ctx));
3894
+ readNativeRuntimeStateBag(runtime, ctx).cleared = true;
2641
3895
  }
2642
3896
  async function cleanupNativeSleepRuntimeState(runtime, ctx, afterTrackedWorkDrained) {
2643
3897
  const drained = await runtime.actorWaitForTrackedShutdownWork(ctx);
2644
3898
  if (!drained) {
2645
- await closeNativeDatabaseClient(runtime, ctx);
2646
- await closeNativeSqlDatabase(runtime, ctx);
3899
+ await detachNativeDatabaseForShutdown(runtime, ctx);
2647
3900
  void runtime.actorWaitForTrackedShutdownWorkUnbounded(ctx).then(async () => {
2648
3901
  await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
2649
3902
  clearNativeRuntimeState(runtime, ctx);
@@ -2656,10 +3909,19 @@ async function cleanupNativeSleepRuntimeState(runtime, ctx, afterTrackedWorkDrai
2656
3909
  return;
2657
3910
  }
2658
3911
  await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
2659
- await closeNativeDatabaseClient(runtime, ctx);
2660
- await closeNativeSqlDatabase(runtime, ctx);
3912
+ await detachNativeDatabaseForShutdown(runtime, ctx);
2661
3913
  clearNativeRuntimeState(runtime, ctx);
2662
3914
  }
3915
+ async function detachNativeDatabaseForShutdown(runtime, ctx) {
3916
+ var _a;
3917
+ const runtimeState = getNativeRuntimeState(runtime, ctx);
3918
+ await ((_a = runtimeState.sql) == null ? void 0 : _a.detachForShutdown());
3919
+ try {
3920
+ await closeNativeDatabaseClient(runtime, ctx);
3921
+ } finally {
3922
+ runtimeState.sql = void 0;
3923
+ }
3924
+ }
2663
3925
  function closeNativeSqlDatabase(runtime, ctx) {
2664
3926
  const runtimeState = getNativeRuntimeState(runtime, ctx);
2665
3927
  const database = runtimeState.sql;
@@ -2680,21 +3942,89 @@ async function closeNativeDatabaseClient(runtime, ctx) {
2680
3942
  await entry.client.close();
2681
3943
  }
2682
3944
  }
3945
+ function createNativeSqlTransaction(runtime, transaction) {
3946
+ return {
3947
+ exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
3948
+ execSync: (sql) => runtime.actorSqlTransactionExecSync(transaction, sql),
3949
+ execute: (sql, params) => runtime.actorSqlTransactionExecute(transaction, sql, params),
3950
+ executeSync: (sql, params) => runtime.actorSqlTransactionExecuteSync(transaction, sql, params),
3951
+ commit: () => runtime.actorSqlTransactionCommit(transaction),
3952
+ commitSync: () => runtime.actorSqlTransactionCommitSync(transaction),
3953
+ rollback: () => runtime.actorSqlTransactionRollback(transaction),
3954
+ rollbackSync: () => runtime.actorSqlTransactionRollbackSync(transaction)
3955
+ };
3956
+ }
2683
3957
  function getOrCreateNativeSqlDatabase(runtime, ctx) {
2684
3958
  const runtimeState = getNativeRuntimeState(runtime, ctx);
2685
3959
  const cachedDatabase = runtimeState.sql;
2686
3960
  if (cachedDatabase) {
2687
3961
  return cachedDatabase;
2688
3962
  }
2689
- const database = wrapJsNativeDatabase({
3963
+ const bindings = {
2690
3964
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
3965
+ execSync: (sql) => runtime.actorSqlExecSync(ctx, sql),
2691
3966
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
3967
+ executeSync: (sql, params) => runtime.actorSqlExecuteSync(ctx, sql, params),
3968
+ executeBatch: (statements) => runtime.actorSqlExecuteBatch(ctx, statements),
3969
+ beginTransaction: async (timeoutMs, name) => {
3970
+ const transaction = await runtime.actorSqlBeginTransaction(
3971
+ ctx,
3972
+ timeoutMs,
3973
+ name
3974
+ );
3975
+ return createNativeSqlTransaction(runtime, transaction);
3976
+ },
3977
+ beginTransactionSync: (timeoutMs, name) => {
3978
+ const transaction = runtime.actorSqlBeginTransactionSync(
3979
+ ctx,
3980
+ timeoutMs,
3981
+ name
3982
+ );
3983
+ return createNativeSqlTransaction(runtime, transaction);
3984
+ },
3985
+ beginStateTransaction: async (timeoutMs, context) => {
3986
+ const scope = context;
3987
+ if (!scope) {
3988
+ throw new Error(
3989
+ "actor state transaction context is not configured"
3990
+ );
3991
+ }
3992
+ const transaction = await runtime.actorBeginStateTransaction(
3993
+ ctx,
3994
+ timeoutMs
3995
+ );
3996
+ return {
3997
+ exec: async () => {
3998
+ throw new Error(
3999
+ "actor state transactions only support single-statement execute calls"
4000
+ );
4001
+ },
4002
+ execute: (sql, params) => runtime.actorStateTransactionExecute(
4003
+ transaction,
4004
+ sql,
4005
+ params
4006
+ ),
4007
+ commit: async () => {
4008
+ await runtime.actorStateTransactionCommit(
4009
+ transaction,
4010
+ scope.actorContext.serializeForTick("save")
4011
+ );
4012
+ scope.committed = true;
4013
+ },
4014
+ rollback: () => runtime.actorStateTransactionRollback(transaction)
4015
+ };
4016
+ },
2692
4017
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
2693
4018
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
2694
4019
  metrics: () => runtime.actorSqlMetrics(ctx),
2695
4020
  takeLastKvError: () => runtime.actorSqlTakeLastKvError(ctx),
4021
+ open: () => runtime.actorSqlOpen(ctx),
4022
+ commitTicket: () => runtime.actorSqlCommitTicket(ctx),
4023
+ whenDurable: (ticket) => runtime.actorSqlWhenDurable(ctx, ticket),
4024
+ abortGeneration: (reason) => runtime.actorSqlAbortGeneration(ctx, reason),
2696
4025
  close: () => runtime.actorSqlClose(ctx)
2697
- });
4026
+ };
4027
+ const database = wrapJsNativeDatabase(bindings);
2698
4028
  runtimeState.sql = database;
2699
4029
  return database;
2700
4030
  }
@@ -2710,7 +4040,7 @@ function toRuntimeBytes(value) {
2710
4040
  function arrayBufferViewToRuntimeBytes(value) {
2711
4041
  return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
2712
4042
  }
2713
- function runtimeBytesToArrayBuffer(value) {
4043
+ function runtimeBytesToArrayBuffer2(value) {
2714
4044
  return value.buffer.slice(
2715
4045
  value.byteOffset,
2716
4046
  value.byteOffset + value.byteLength
@@ -2756,6 +4086,9 @@ function decodeNativeKvValue(value, options) {
2756
4086
  async function loadEngineCli() {
2757
4087
  return import(["@rivetkit", "engine-cli"].join("/"));
2758
4088
  }
4089
+ async function loadServices() {
4090
+ return import(["@rivet-dev", "services"].join("/"));
4091
+ }
2759
4092
  function decodeValue(value) {
2760
4093
  if (!value || value.length === 0) {
2761
4094
  return void 0;
@@ -2800,13 +4133,25 @@ function isStructuredBridgeError(error) {
2800
4133
  }
2801
4134
  function encodeNativeCallbackError(error) {
2802
4135
  const structuredError = isStructuredBridgeError(error) ? error : deconstructError(error, true);
2803
- const bridgeError = new Error(encodeBridgeRivetError(structuredError), {
4136
+ const { encoded, droppedMetadataCause } = encodeBridgeRivetError(structuredError);
4137
+ if (droppedMetadataCause !== void 0) {
4138
+ logger2().warn(
4139
+ {
4140
+ group: structuredError.group,
4141
+ code: structuredError.code,
4142
+ error: String(droppedMetadataCause)
4143
+ },
4144
+ "dropped error metadata that JSON cannot encode"
4145
+ );
4146
+ }
4147
+ const bridgeError = new Error(encoded, {
2804
4148
  cause: error instanceof Error ? error : void 0
2805
4149
  });
2806
4150
  return Object.assign(bridgeError, {
2807
4151
  group: structuredError.group,
2808
4152
  code: structuredError.code,
2809
- metadata: structuredError.metadata
4153
+ metadata: structuredError.metadata,
4154
+ rayId: structuredError.rayId
2810
4155
  });
2811
4156
  }
2812
4157
  async function callNative(invoke) {
@@ -2948,6 +4293,14 @@ function serializeWorkflowEntryKind(kind) {
2948
4293
  originalName: kind.val.originalName
2949
4294
  }
2950
4295
  };
4296
+ case "WorkflowVersionCheckEntry":
4297
+ return {
4298
+ tag: kind.tag,
4299
+ val: {
4300
+ resolved: kind.val.resolved,
4301
+ latest: kind.val.latest
4302
+ }
4303
+ };
2951
4304
  }
2952
4305
  }
2953
4306
  function serializeWorkflowHistoryForJson(data) {
@@ -3032,24 +4385,6 @@ function decodeArgs(value) {
3032
4385
  const decoded = decodeValue(value);
3033
4386
  return normalizeArgs(decoded);
3034
4387
  }
3035
- function buildRequest(init) {
3036
- const url = init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString();
3037
- const body = init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
3038
- return new Request(url, {
3039
- method: init.method,
3040
- headers: init.headers,
3041
- body
3042
- });
3043
- }
3044
- async function toRuntimeHttpResponse(response) {
3045
- const headers = Object.fromEntries(response.headers.entries());
3046
- const body = new Uint8Array(await response.arrayBuffer());
3047
- return {
3048
- status: response.status,
3049
- headers,
3050
- body
3051
- };
3052
- }
3053
4388
  function toActorKey(segments) {
3054
4389
  return segments.map(
3055
4390
  (segment) => segment.kind === "number" ? String(segment.numberValue ?? 0) : segment.stringValue ?? ""
@@ -3061,12 +4396,16 @@ var NativeConnAdapter = class {
3061
4396
  #schemas;
3062
4397
  #ctx;
3063
4398
  #queueHibernationRemoval;
3064
- constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval) {
4399
+ #assertCanMutateState;
4400
+ #stateProxy;
4401
+ #stateProxyTarget;
4402
+ constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval, assertCanMutateState) {
3065
4403
  this.#runtime = runtime;
3066
4404
  this.#conn = conn;
3067
4405
  this.#schemas = schemas;
3068
4406
  this.#ctx = ctx;
3069
4407
  this.#queueHibernationRemoval = queueHibernationRemoval;
4408
+ this.#assertCanMutateState = assertCanMutateState;
3070
4409
  this[CONN_STATE_MANAGER_SYMBOL] = {
3071
4410
  stateEnabled: true,
3072
4411
  get state() {
@@ -3089,22 +4428,46 @@ var NativeConnAdapter = class {
3089
4428
  }
3090
4429
  get state() {
3091
4430
  const nextState = this.#readState();
4431
+ if (!this.#ctx) {
4432
+ return this.#createStateProxy(nextState);
4433
+ }
4434
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
4435
+ this.#stateProxyTarget = nextState;
4436
+ this.#stateProxy = this.#createStateProxy(nextState);
4437
+ }
4438
+ return this.#stateProxy;
4439
+ }
4440
+ #createStateProxy(state) {
4441
+ const assertCurrentState = () => {
4442
+ var _a;
4443
+ (_a = this.#assertCanMutateState) == null ? void 0 : _a.call(this);
4444
+ if (this.#ctx && this.#readState() !== state) {
4445
+ throw stateTransactionConflictError();
4446
+ }
4447
+ };
3092
4448
  return createWriteThroughProxy(
3093
- nextState,
4449
+ state,
3094
4450
  (nextValue) => {
4451
+ assertCurrentState();
3095
4452
  this.#writeState(nextValue, { writeNative: true });
3096
4453
  },
3097
4454
  (newValue) => {
4455
+ assertCurrentState();
3098
4456
  assertJsonCompatValue(newValue);
3099
4457
  }
3100
4458
  );
3101
4459
  }
3102
4460
  set state(value) {
3103
- assertJsonCompatValue(value);
3104
- this.#writeState(value, { writeNative: true });
4461
+ var _a;
4462
+ (_a = this.#assertCanMutateState) == null ? void 0 : _a.call(this);
4463
+ const nextValue = unwrapWriteThroughProxy(value);
4464
+ assertJsonCompatValue(nextValue);
4465
+ this.#writeState(nextValue, { writeNative: true });
3105
4466
  }
3106
4467
  initializeState(value) {
3107
- this.#writeState(value, { writeNative: false });
4468
+ this.#writeState(unwrapWriteThroughProxy(value), {
4469
+ writeNative: false
4470
+ });
3108
4471
  }
3109
4472
  get isHibernatable() {
3110
4473
  return callNativeSync(
@@ -3174,26 +4537,116 @@ var NativeScheduleAdapter = class {
3174
4537
  this.#ctx = ctx;
3175
4538
  }
3176
4539
  async after(duration, action, ...args) {
3177
- callNativeSync(
3178
- () => this.#runtime.actorScheduleAfter(
3179
- this.#ctx,
3180
- duration,
3181
- action,
3182
- encodeValue(args)
3183
- )
4540
+ return await this.#runtime.actorScheduleAfter(
4541
+ this.#ctx,
4542
+ duration,
4543
+ action,
4544
+ encodeValue(args)
3184
4545
  );
3185
4546
  }
3186
4547
  async at(timestamp, action, ...args) {
3187
- callNativeSync(
3188
- () => this.#runtime.actorScheduleAt(
3189
- this.#ctx,
3190
- timestamp,
3191
- action,
3192
- encodeValue(args)
3193
- )
4548
+ return await this.#runtime.actorScheduleAt(
4549
+ this.#ctx,
4550
+ timestamp,
4551
+ action,
4552
+ encodeValue(args)
4553
+ );
4554
+ }
4555
+ async cancel(id) {
4556
+ return await this.#runtime.actorScheduleCancel(this.#ctx, id);
4557
+ }
4558
+ async get(id) {
4559
+ const event2 = await this.#runtime.actorScheduleGet(this.#ctx, id);
4560
+ return event2 ? decodeScheduledEventInfo(event2) : void 0;
4561
+ }
4562
+ async list() {
4563
+ return (await this.#runtime.actorScheduleList(this.#ctx)).map(
4564
+ decodeScheduledEventInfo
4565
+ );
4566
+ }
4567
+ };
4568
+ var NativeCronAdapter = class {
4569
+ #runtime;
4570
+ #ctx;
4571
+ constructor(runtime, ctx) {
4572
+ this.#runtime = runtime;
4573
+ this.#ctx = ctx;
4574
+ }
4575
+ async set(options) {
4576
+ await this.#runtime.actorCronSet(
4577
+ this.#ctx,
4578
+ options.name,
4579
+ options.expression,
4580
+ options.timezone,
4581
+ options.action,
4582
+ encodeValue(options.args ?? []),
4583
+ options.maxHistory
4584
+ );
4585
+ }
4586
+ async every(options) {
4587
+ await this.#runtime.actorCronEvery(
4588
+ this.#ctx,
4589
+ options.name,
4590
+ options.interval,
4591
+ options.action,
4592
+ encodeValue(options.args ?? []),
4593
+ options.maxHistory
4594
+ );
4595
+ }
4596
+ async get(name) {
4597
+ const job = await this.#runtime.actorCronGet(this.#ctx, name);
4598
+ return job ? decodeCronJobInfo(job) : void 0;
4599
+ }
4600
+ async list() {
4601
+ return (await this.#runtime.actorCronList(this.#ctx)).map(
4602
+ decodeCronJobInfo
3194
4603
  );
3195
4604
  }
4605
+ async delete(name) {
4606
+ return await this.#runtime.actorCronDelete(this.#ctx, name);
4607
+ }
4608
+ async history(name, options) {
4609
+ return (await this.#runtime.actorCronHistory(
4610
+ this.#ctx,
4611
+ name,
4612
+ options == null ? void 0 : options.limit
4613
+ )).map(decodeCronFire);
4614
+ }
3196
4615
  };
4616
+ function decodeScheduledEventInfo(event2) {
4617
+ return {
4618
+ id: event2.id,
4619
+ action: event2.action,
4620
+ args: decodeArgs(event2.args),
4621
+ runAt: event2.runAt
4622
+ };
4623
+ }
4624
+ function decodeCronJobInfo(job) {
4625
+ const base = {
4626
+ name: job.name,
4627
+ action: job.action,
4628
+ args: decodeArgs(job.args),
4629
+ nextRunAt: job.nextRunAt,
4630
+ lastRunAt: job.lastRunAt,
4631
+ maxHistory: job.maxHistory
4632
+ };
4633
+ if (job.kind === "cron") {
4634
+ return {
4635
+ ...base,
4636
+ kind: "cron",
4637
+ expression: job.expression,
4638
+ timezone: job.timezone
4639
+ };
4640
+ }
4641
+ return {
4642
+ ...base,
4643
+ kind: "every",
4644
+ interval: job.intervalMs
4645
+ };
4646
+ }
4647
+ function decodeCronFire(fire) {
4648
+ return { ...fire };
4649
+ }
3197
4650
  var NativeKvAdapter = class {
3198
4651
  #runtime;
3199
4652
  #ctx;
@@ -3332,8 +4785,9 @@ var NativeKvAdapter = class {
3332
4785
  };
3333
4786
  function wrapQueueMessage(message, schemas) {
3334
4787
  const name = callNativeSync(() => message.name());
4788
+ const id = callNativeSync(() => message.id());
3335
4789
  return {
3336
- id: Number(callNativeSync(() => message.id())),
4790
+ id: id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : id,
3337
4791
  name,
3338
4792
  body: validateQueueBody(
3339
4793
  schemas,
@@ -3471,6 +4925,25 @@ var NativeQueueAdapter = class {
3471
4925
  cleanup == null ? void 0 : cleanup();
3472
4926
  }
3473
4927
  }
4928
+ async waitForAvailable(names, options) {
4929
+ await this.waitForNamesAvailable(names ?? [], options);
4930
+ }
4931
+ async complete(message, response) {
4932
+ const validatedResponse = validateQueueComplete(
4933
+ this.#schemas,
4934
+ message.name,
4935
+ response
4936
+ );
4937
+ await callNative(
4938
+ () => this.#runtime.actorQueueCompletePersisted(
4939
+ this.#ctx,
4940
+ BigInt(message.id),
4941
+ message.name,
4942
+ encodeValue(validatedResponse)
4943
+ )
4944
+ );
4945
+ this.#pendingCompletableMessageIds.delete(message.id.toString());
4946
+ }
3474
4947
  async enqueueAndWait(name, body, options) {
3475
4948
  const validatedBody = validateQueueBody(this.#schemas, name, body);
3476
4949
  const { token, cleanup } = await createCancellationTokenHandle(
@@ -3624,7 +5097,7 @@ var NativeWebSocketAdapter = class {
3624
5097
  this.#runtime.webSocketSetEventCallback(this.#ws, (event2) => {
3625
5098
  if (event2.kind === "message") {
3626
5099
  this.#virtual.triggerMessage(
3627
- event2.binary ? runtimeBytesToArrayBuffer(event2.data) : event2.data,
5100
+ event2.binary ? runtimeBytesToArrayBuffer2(event2.data) : event2.data,
3628
5101
  event2.messageIndex
3629
5102
  );
3630
5103
  return;
@@ -3907,10 +5380,12 @@ var NativeConnectionMap = class {
3907
5380
  #runtime;
3908
5381
  #ctx;
3909
5382
  #schemas;
3910
- constructor(runtime, ctx, schemas) {
5383
+ #assertCanMutateState;
5384
+ constructor(runtime, ctx, schemas, assertCanMutateState) {
3911
5385
  this.#runtime = runtime;
3912
5386
  this.#ctx = ctx;
3913
5387
  this.#schemas = schemas;
5388
+ this.#assertCanMutateState = assertCanMutateState;
3914
5389
  }
3915
5390
  #connToAdapter(conn) {
3916
5391
  return new NativeConnAdapter(
@@ -3923,7 +5398,8 @@ var NativeConnectionMap = class {
3923
5398
  this.#ctx,
3924
5399
  connId
3925
5400
  )
3926
- )
5401
+ ),
5402
+ this.#assertCanMutateState
3927
5403
  );
3928
5404
  }
3929
5405
  get size() {
@@ -3965,6 +5441,7 @@ var NativeConnectionMap = class {
3965
5441
  }
3966
5442
  [Symbol.toStringTag] = "NativeConnectionMap";
3967
5443
  };
5444
+ var NO_INVOCATION_SCOPE = {};
3968
5445
  var ActorContextHandleAdapter = class {
3969
5446
  #runtime;
3970
5447
  #ctx;
@@ -3974,24 +5451,29 @@ var ActorContextHandleAdapter = class {
3974
5451
  #client;
3975
5452
  #clientFactory;
3976
5453
  #connMap;
5454
+ #cron;
3977
5455
  #databaseProvider;
3978
5456
  #db;
3979
5457
  #dispatchCancelToken;
3980
5458
  #kv;
5459
+ #logByInvocationScope = /* @__PURE__ */ new WeakMap();
3981
5460
  #queue;
3982
5461
  #request;
3983
5462
  #schedule;
3984
- #sql;
3985
- #runHandlerActiveProvider;
5463
+ #run;
5464
+ #runHandlerConfigured;
3986
5465
  #onStateChange;
3987
5466
  #stateEnabled;
3988
- constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, runHandlerActiveProvider, onStateChange, dispatchCancelToken) {
5467
+ #stateProxy;
5468
+ #stateProxyTarget;
5469
+ #stateTransactionOwner = /* @__PURE__ */ Symbol("actor-state-transaction-owner");
5470
+ constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
3989
5471
  this.#runtime = runtime;
3990
5472
  this.#ctx = ctx;
3991
5473
  this.#clientFactory = clientFactory;
3992
5474
  this.#schemas = schemas;
3993
5475
  this.#dispatchCancelToken = dispatchCancelToken;
3994
- this.#runHandlerActiveProvider = runHandlerActiveProvider;
5476
+ this.#runHandlerConfigured = runHandlerConfigured;
3995
5477
  this.#onStateChange = onStateChange;
3996
5478
  this.#stateEnabled = stateEnabled;
3997
5479
  if (databaseProvider) {
@@ -3999,7 +5481,10 @@ var ActorContextHandleAdapter = class {
3999
5481
  }
4000
5482
  this.#request = request;
4001
5483
  this[ACTOR_CONTEXT_INTERNAL_SYMBOL] = new NativeWorkflowRuntimeAdapter(
4002
- this
5484
+ this,
5485
+ () => this.#logByInvocationScope.delete(
5486
+ this.#runtime.currentInvocationScope() ?? NO_INVOCATION_SCOPE
5487
+ )
4003
5488
  );
4004
5489
  }
4005
5490
  get kv() {
@@ -4008,11 +5493,10 @@ var ActorContextHandleAdapter = class {
4008
5493
  }
4009
5494
  return this.#kv;
4010
5495
  }
4011
- get sql() {
4012
- if (!this.#sql) {
4013
- this.#sql = getOrCreateNativeSqlDatabase(this.#runtime, this.#ctx);
4014
- }
4015
- return this.#sql;
5496
+ async actorRuntimeSocket() {
5497
+ return await callNative(
5498
+ () => this.#runtime.actorRuntimeSocketProvision(this.#ctx)
5499
+ );
4016
5500
  }
4017
5501
  get db() {
4018
5502
  if (!this.#databaseProvider) {
@@ -4024,7 +5508,7 @@ var ActorContextHandleAdapter = class {
4024
5508
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4025
5509
  const cachedClient = runtimeState.databaseClient;
4026
5510
  if (cachedClient) {
4027
- this.#db = cachedClient.client;
5511
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
4028
5512
  return this.#db;
4029
5513
  }
4030
5514
  throw databaseClientNotReadyError();
@@ -4039,36 +5523,45 @@ var ActorContextHandleAdapter = class {
4039
5523
  if (!this.#stateEnabled) {
4040
5524
  throw stateNotEnabledError();
4041
5525
  }
4042
- const actorState = getNativePersistState(this.#runtime, this.#ctx);
4043
5526
  const nextState = this.#readState();
4044
- if (actorState.stateProxy === void 0 || actorState.stateProxyTarget !== nextState) {
4045
- actorState.stateProxyTarget = nextState;
4046
- actorState.stateProxy = createWriteThroughProxy(
5527
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
5528
+ const assertCurrentState = () => {
5529
+ this.#assertCanMutateState();
5530
+ if (this.#readState() !== nextState) {
5531
+ throw stateTransactionConflictError();
5532
+ }
5533
+ };
5534
+ this.#stateProxyTarget = nextState;
5535
+ this.#stateProxy = createWriteThroughProxy(
4047
5536
  nextState,
4048
5537
  (nextValue) => {
5538
+ assertCurrentState();
4049
5539
  this.#writeState(nextValue, { scheduleSave: true });
4050
5540
  },
4051
5541
  (newValue) => {
4052
- this.#assertCanMutateState();
5542
+ assertCurrentState();
4053
5543
  assertJsonCompatValue(newValue);
4054
5544
  }
4055
5545
  );
4056
5546
  }
4057
- return actorState.stateProxy;
5547
+ return this.#stateProxy;
4058
5548
  }
4059
5549
  set state(value) {
4060
5550
  if (!this.#stateEnabled) {
4061
5551
  throw stateNotEnabledError();
4062
5552
  }
4063
5553
  this.#assertCanMutateState();
4064
- assertJsonCompatValue(value);
4065
- this.#writeState(value, { scheduleSave: true });
5554
+ const nextValue = unwrapWriteThroughProxy(value);
5555
+ assertJsonCompatValue(nextValue);
5556
+ this.#writeState(nextValue, { scheduleSave: true });
4066
5557
  }
4067
5558
  initializeState(value) {
4068
5559
  if (!this.#stateEnabled) {
4069
5560
  return;
4070
5561
  }
4071
- this.#writeState(value, { scheduleSave: false });
5562
+ this.#writeState(unwrapWriteThroughProxy(value), {
5563
+ scheduleSave: false
5564
+ });
4072
5565
  }
4073
5566
  get vars() {
4074
5567
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
@@ -4094,6 +5587,30 @@ var ActorContextHandleAdapter = class {
4094
5587
  }
4095
5588
  return this.#queue;
4096
5589
  }
5590
+ get run() {
5591
+ if (!this.#run) {
5592
+ this.#run = {
5593
+ setWakeAt: async (timestamp) => {
5594
+ if (timestamp !== null && !this.#runHandlerConfigured) {
5595
+ throw runHandlerNotConfiguredError();
5596
+ }
5597
+ if (timestamp !== null && (!Number.isSafeInteger(timestamp) || timestamp < 0)) {
5598
+ throw new TypeError(
5599
+ "Run wake timestamp must be a non-negative safe integer or null"
5600
+ );
5601
+ }
5602
+ await callNative(
5603
+ () => this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp)
5604
+ );
5605
+ },
5606
+ startWorkflowSpan: () => callNative(
5607
+ () => this.#runtime.startWorkflowSpan(this.#ctx)
5608
+ ),
5609
+ runOutsideWorkflowSpan: (body) => this.#runtime.runOutsideActorInvocationContext(body)
5610
+ };
5611
+ }
5612
+ return this.#run;
5613
+ }
4097
5614
  get schedule() {
4098
5615
  if (!this.#schedule) {
4099
5616
  this.#schedule = new NativeScheduleAdapter(
@@ -4103,6 +5620,12 @@ var ActorContextHandleAdapter = class {
4103
5620
  }
4104
5621
  return this.#schedule;
4105
5622
  }
5623
+ get cron() {
5624
+ if (!this.#cron) {
5625
+ this.#cron = new NativeCronAdapter(this.#runtime, this.#ctx);
5626
+ }
5627
+ return this.#cron;
5628
+ }
4106
5629
  get actorId() {
4107
5630
  return callNativeSync(() => this.#runtime.actorId(this.#ctx));
4108
5631
  }
@@ -4122,22 +5645,49 @@ var ActorContextHandleAdapter = class {
4122
5645
  this.#connMap = new NativeConnectionMap(
4123
5646
  this.#runtime,
4124
5647
  this.#ctx,
4125
- this.#schemas
5648
+ this.#schemas,
5649
+ () => this.#assertCanMutateState()
4126
5650
  );
4127
5651
  }
4128
5652
  return this.#connMap;
4129
5653
  }
5654
+ #invocationTraceContext() {
5655
+ return callNativeSync(
5656
+ () => this.#runtime.actorInvocationTraceContext(this.#ctx)
5657
+ );
5658
+ }
5659
+ /**
5660
+ * Cached per invocation, because the `run` context outlives workflow runs and steps.
5661
+ * A workflow queue receive clears the entry, because the run's ray becomes the message's ray.
5662
+ */
4130
5663
  get log() {
4131
- return logger2();
5664
+ const scope = this.#runtime.currentInvocationScope() ?? NO_INVOCATION_SCOPE;
5665
+ const cached = this.#logByInvocationScope.get(scope);
5666
+ if (cached) return cached;
5667
+ const invocation = this.#invocationTraceContext();
5668
+ const log = logger2().child({
5669
+ actorId: this.actorId,
5670
+ actorName: this.name,
5671
+ actorKey: this.key,
5672
+ ...(invocation == null ? void 0 : invocation.rayId) && { rayId: invocation.rayId },
5673
+ ...(invocation == null ? void 0 : invocation.span) && {
5674
+ traceId: invocation.span.traceId,
5675
+ spanId: invocation.span.spanId
5676
+ }
5677
+ });
5678
+ this.#logByInvocationScope.set(scope, log);
5679
+ return log;
4132
5680
  }
4133
5681
  get abortSignal() {
4134
5682
  if (!this.#abortSignal) {
4135
- const actorSignal = this.#createActorAbortSignal();
5683
+ const actorAbort = this.#actorAbort();
5684
+ const actorSignal = actorAbort.signal;
4136
5685
  if (this.#dispatchCancelToken === void 0) {
4137
5686
  this.#abortSignal = actorSignal;
4138
5687
  } else {
4139
5688
  const controller = new AbortController();
4140
5689
  let cleanedUp = false;
5690
+ let releaseDispatchListener;
4141
5691
  const onActorAbort = () => {
4142
5692
  cleanup();
4143
5693
  controller.abort();
@@ -4147,7 +5697,9 @@ var ActorContextHandleAdapter = class {
4147
5697
  return;
4148
5698
  }
4149
5699
  cleanedUp = true;
4150
- actorSignal.removeEventListener("abort", onActorAbort);
5700
+ actorAbort.listeners.delete(onActorAbort);
5701
+ releaseDispatchListener == null ? void 0 : releaseDispatchListener();
5702
+ releaseDispatchListener = void 0;
4151
5703
  this.#abortSignalCleanup = void 0;
4152
5704
  };
4153
5705
  if (actorSignal.aborted || this.#runtime.cancellationTokenAborted(
@@ -4157,10 +5709,8 @@ var ActorContextHandleAdapter = class {
4157
5709
  } else {
4158
5710
  const dispatchCancelToken = this.#dispatchCancelToken;
4159
5711
  this.#abortSignalCleanup = cleanup;
4160
- actorSignal.addEventListener("abort", onActorAbort, {
4161
- once: true
4162
- });
4163
- callNativeSync(
5712
+ actorAbort.listeners.add(onActorAbort);
5713
+ releaseDispatchListener = callNativeSync(
4164
5714
  () => this.#runtime.onCancellationTokenCancelled(
4165
5715
  dispatchCancelToken,
4166
5716
  () => {
@@ -4191,11 +5741,11 @@ var ActorContextHandleAdapter = class {
4191
5741
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4192
5742
  const cachedClient = runtimeState.databaseClient;
4193
5743
  if (cachedClient) {
4194
- this.#db = cachedClient.client;
5744
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
4195
5745
  return this.#db;
4196
5746
  }
4197
5747
  const actorId = this.actorId;
4198
- const client = await this.#databaseProvider.createClient({
5748
+ const createdClient = await this.#databaseProvider.createClient({
4199
5749
  actorId,
4200
5750
  kv: {
4201
5751
  batchPut: async (entries) => {
@@ -4216,21 +5766,128 @@ var ActorContextHandleAdapter = class {
4216
5766
  log: {
4217
5767
  debug: (obj) => logger2().debug(obj)
4218
5768
  },
4219
- nativeDatabaseProvider: {
4220
- open: async (requestedActorId) => {
4221
- void requestedActorId;
4222
- return getOrCreateNativeSqlDatabase(
4223
- this.#runtime,
4224
- this.#ctx
4225
- );
4226
- }
5769
+ nativeDatabaseProvider: registerNativeStateTransactionOpener(
5770
+ {
5771
+ open: async (requestedActorId) => {
5772
+ void requestedActorId;
5773
+ const database = getOrCreateNativeSqlDatabase(
5774
+ this.#runtime,
5775
+ this.#ctx
5776
+ );
5777
+ await database.open();
5778
+ return database;
5779
+ }
5780
+ },
5781
+ async (timeoutMs, context) => await getOrCreateNativeSqlDatabase(
5782
+ this.#runtime,
5783
+ this.#ctx
5784
+ ).beginStateTransaction(timeoutMs, context)
5785
+ )
5786
+ });
5787
+ runtimeState.databaseClient = {
5788
+ client: createdClient
5789
+ };
5790
+ this.#db = this.#bindDatabaseClient(createdClient);
5791
+ return this.#db;
5792
+ }
5793
+ #bindDatabaseClient(client) {
5794
+ return bindNativeStateTransactionContext(client, {
5795
+ enter: async () => await this.#enterStateTransaction(),
5796
+ exit: (scope) => this.#exitStateTransaction(
5797
+ scope
5798
+ )
5799
+ });
5800
+ }
5801
+ async #enterStateTransaction() {
5802
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5803
+ let pendingOwners = actorState.pendingStateTransactionOwners;
5804
+ if (!pendingOwners) {
5805
+ pendingOwners = /* @__PURE__ */ new Set();
5806
+ actorState.pendingStateTransactionOwners = pendingOwners;
5807
+ }
5808
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner || pendingOwners.has(this.#stateTransactionOwner)) {
5809
+ throw stateTransactionConflictError();
5810
+ }
5811
+ pendingOwners.add(this.#stateTransactionOwner);
5812
+ const predecessor = actorState.stateTransactionTail ?? Promise.resolve();
5813
+ let release;
5814
+ const hold = new Promise((resolve) => {
5815
+ release = resolve;
5816
+ });
5817
+ actorState.stateTransactionTail = predecessor.then(
5818
+ async () => await hold
5819
+ );
5820
+ try {
5821
+ await predecessor;
5822
+ pendingOwners.delete(this.#stateTransactionOwner);
5823
+ actorState.activeStateTransactionOwner = this.#stateTransactionOwner;
5824
+ return {
5825
+ actorContext: this,
5826
+ actorStateBaseline: this.#stateEnabled ? structuredClone(this.#readState()) : void 0,
5827
+ connectionStateBaselines: new Map(
5828
+ callNativeSync(
5829
+ () => this.#runtime.actorConns(this.#ctx)
5830
+ ).map((conn) => [
5831
+ callNativeSync(() => this.#runtime.connId(conn)),
5832
+ new Uint8Array(
5833
+ callNativeSync(() => this.#runtime.connState(conn))
5834
+ )
5835
+ ])
5836
+ ),
5837
+ committed: false,
5838
+ release
5839
+ };
5840
+ } catch (error) {
5841
+ pendingOwners.delete(this.#stateTransactionOwner);
5842
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5843
+ actorState.activeStateTransactionOwner = void 0;
5844
+ }
5845
+ release();
5846
+ throw error;
5847
+ }
5848
+ }
5849
+ #exitStateTransaction(scope) {
5850
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5851
+ try {
5852
+ if (!scope.committed) {
5853
+ this.#restoreStateTransactionBaseline(scope);
5854
+ }
5855
+ } finally {
5856
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5857
+ actorState.activeStateTransactionOwner = void 0;
5858
+ }
5859
+ if (actorState.stateTransactionSaveDeferred) {
5860
+ actorState.stateTransactionSaveDeferred = false;
5861
+ this.#scheduleSave();
5862
+ }
5863
+ scope.release();
5864
+ }
5865
+ }
5866
+ #restoreStateTransactionBaseline(scope) {
5867
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5868
+ if (actorState.pendingSaveHandle !== void 0) {
5869
+ clearImmediate(actorState.pendingSaveHandle);
5870
+ }
5871
+ actorState.pendingSaveHandle = void 0;
5872
+ actorState.saveScheduled = false;
5873
+ if (this.#stateEnabled) {
5874
+ actorState.state = structuredClone(scope.actorStateBaseline);
5875
+ }
5876
+ for (const conn of callNativeSync(
5877
+ () => this.#runtime.actorConns(this.#ctx)
5878
+ )) {
5879
+ const connId = callNativeSync(() => this.#runtime.connId(conn));
5880
+ const baseline = scope.connectionStateBaselines.get(connId);
5881
+ if (baseline === void 0) {
5882
+ continue;
4227
5883
  }
4228
- });
4229
- runtimeState.databaseClient = {
4230
- client
4231
- };
4232
- this.#db = client;
4233
- return client;
5884
+ callNativeSync(() => this.#runtime.connSetState(conn, baseline));
5885
+ const cached = actorState.connStates.get(connId);
5886
+ if (cached) {
5887
+ cached.state = decodeValue(baseline);
5888
+ }
5889
+ }
5890
+ this.#scheduleSave();
4234
5891
  }
4235
5892
  async prepare() {
4236
5893
  if (!this.#databaseProvider) {
@@ -4248,7 +5905,6 @@ var ActorContextHandleAdapter = class {
4248
5905
  }
4249
5906
  async closeDatabase() {
4250
5907
  this.#db = void 0;
4251
- this.#sql = void 0;
4252
5908
  await closeNativeDatabaseClient(this.#runtime, this.#ctx);
4253
5909
  await closeNativeSqlDatabase(this.#runtime, this.#ctx);
4254
5910
  }
@@ -4268,6 +5924,7 @@ var ActorContextHandleAdapter = class {
4268
5924
  }
4269
5925
  async saveState(opts) {
4270
5926
  if (opts == null ? void 0 : opts.immediate) {
5927
+ this.#assertCanAwaitStateSave();
4271
5928
  await callNative(
4272
5929
  () => this.#runtime.actorRequestSaveAndWait(this.#ctx, {
4273
5930
  immediate: true
@@ -4287,6 +5944,18 @@ var ActorContextHandleAdapter = class {
4287
5944
  () => this.#runtime.actorRequestSave(this.#ctx, { immediate: false })
4288
5945
  );
4289
5946
  }
5947
+ async saveStateAndWorkflowBatch(writes) {
5948
+ this.#assertCanAwaitStateSave();
5949
+ await callNative(
5950
+ () => this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes)
5951
+ );
5952
+ }
5953
+ #assertCanAwaitStateSave() {
5954
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5955
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5956
+ throw stateTransactionConflictError();
5957
+ }
5958
+ }
4290
5959
  serializeForTick(reason) {
4291
5960
  void reason;
4292
5961
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -4340,10 +6009,6 @@ var ActorContextHandleAdapter = class {
4340
6009
  }
4341
6010
  return promise;
4342
6011
  }
4343
- runHandlerActive() {
4344
- var _a;
4345
- return ((_a = this.#runHandlerActiveProvider) == null ? void 0 : _a.call(this)) ?? false;
4346
- }
4347
6012
  internalKeepAwake(run) {
4348
6013
  const promise = typeof run === "function" ? run() : run;
4349
6014
  const trackedPromise = promise.then(
@@ -4423,23 +6088,42 @@ var ActorContextHandleAdapter = class {
4423
6088
  }
4424
6089
  async dispose() {
4425
6090
  var _a;
4426
- this.#flushStateChange();
6091
+ if (!isNativeRuntimeStateCleared(this.#runtime, this.#ctx)) {
6092
+ this.#flushStateChange();
6093
+ }
4427
6094
  (_a = this.#abortSignalCleanup) == null ? void 0 : _a.call(this);
4428
- this.#sql = void 0;
4429
6095
  }
4430
- #createActorAbortSignal() {
6096
+ #actorAbort() {
6097
+ const runtimeState = readNativeRuntimeStateBag(
6098
+ this.#runtime,
6099
+ this.#ctx
6100
+ );
6101
+ const cached = runtimeState.actorAbort;
6102
+ if (cached && !cached.signal.aborted) {
6103
+ return cached;
6104
+ }
4431
6105
  const nativeSignal = callNativeSync(
4432
6106
  () => this.#runtime.actorAbortSignal(this.#ctx)
4433
6107
  );
4434
6108
  const controller = new AbortController();
4435
- if (nativeSignal.aborted) {
6109
+ const actorAbort = {
6110
+ signal: controller.signal,
6111
+ listeners: /* @__PURE__ */ new Set()
6112
+ };
6113
+ const abort = () => {
4436
6114
  controller.abort();
6115
+ for (const listener of actorAbort.listeners) {
6116
+ listener();
6117
+ }
6118
+ actorAbort.listeners.clear();
6119
+ };
6120
+ if (nativeSignal.aborted) {
6121
+ abort();
4437
6122
  } else {
4438
- nativeSignal.addEventListener("abort", () => controller.abort(), {
4439
- once: true
4440
- });
6123
+ nativeSignal.addEventListener("abort", abort, { once: true });
4441
6124
  }
4442
- return controller.signal;
6125
+ runtimeState.actorAbort = actorAbort;
6126
+ return actorAbort;
4443
6127
  }
4444
6128
  #readState() {
4445
6129
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -4459,10 +6143,18 @@ var ActorContextHandleAdapter = class {
4459
6143
  this.#scheduleSave();
4460
6144
  }
4461
6145
  #assertCanMutateState() {
6146
+ var _a;
4462
6147
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4463
6148
  if (actorState.isInOnStateChange) {
4464
6149
  throw stateMutationReentrantError();
4465
6150
  }
6151
+ if (actorState.activeStateTransactionOwner !== this.#stateTransactionOwner && (actorState.activeStateTransactionOwner !== void 0 || (((_a = actorState.pendingStateTransactionOwners) == null ? void 0 : _a.size) ?? 0) > 0)) {
6152
+ throw stateTransactionConflictError();
6153
+ }
6154
+ }
6155
+ /** @internal */
6156
+ assertCanMutateState() {
6157
+ this.#assertCanMutateState();
4466
6158
  }
4467
6159
  // Coalesce the request-save and onStateChange work to once per event loop
4468
6160
  // tick. A synchronous burst of mutations (for example
@@ -4484,6 +6176,15 @@ var ActorContextHandleAdapter = class {
4484
6176
  if (!actorState.saveScheduled) {
4485
6177
  return;
4486
6178
  }
6179
+ if (actorState.activeStateTransactionOwner !== void 0) {
6180
+ actorState.saveScheduled = false;
6181
+ if (actorState.pendingSaveHandle !== void 0) {
6182
+ clearImmediate(actorState.pendingSaveHandle);
6183
+ actorState.pendingSaveHandle = void 0;
6184
+ }
6185
+ actorState.stateTransactionSaveDeferred = true;
6186
+ return;
6187
+ }
4487
6188
  actorState.saveScheduled = false;
4488
6189
  if (actorState.pendingSaveHandle !== void 0) {
4489
6190
  clearImmediate(actorState.pendingSaveHandle);
@@ -4529,13 +6230,15 @@ var ActorContextHandleAdapter = class {
4529
6230
  };
4530
6231
  var NativeWorkflowRuntimeAdapter = class {
4531
6232
  #ctx;
6233
+ #onMessagesReceived;
4532
6234
  #completions = /* @__PURE__ */ new Map();
4533
6235
  id;
4534
6236
  driver;
4535
6237
  queueManager;
4536
6238
  stateManager;
4537
- constructor(ctx) {
6239
+ constructor(ctx, onMessagesReceived) {
4538
6240
  this.#ctx = ctx;
6241
+ this.#onMessagesReceived = onMessagesReceived;
4539
6242
  this.id = ctx.actorId;
4540
6243
  this.driver = {
4541
6244
  kvBatchGet: async (actorId, keys) => {
@@ -4575,6 +6278,9 @@ var NativeWorkflowRuntimeAdapter = class {
4575
6278
  timeout: timeout ?? 0,
4576
6279
  completable
4577
6280
  });
6281
+ if (messages.length > 0) {
6282
+ this.#onMessagesReceived();
6283
+ }
4578
6284
  return messages.map(
4579
6285
  (message) => this.#wrapQueueMessage(message)
4580
6286
  );
@@ -4601,12 +6307,12 @@ var NativeWorkflowRuntimeAdapter = class {
4601
6307
  this.stateManager = {
4602
6308
  saveState: async (opts) => {
4603
6309
  await this.#ctx.saveState(opts);
6310
+ },
6311
+ saveStateAndWorkflowBatch: async (writes) => {
6312
+ await this.#ctx.saveStateAndWorkflowBatch(writes);
4604
6313
  }
4605
6314
  };
4606
6315
  }
4607
- isRunHandlerActive() {
4608
- return this.#ctx.runHandlerActive();
4609
- }
4610
6316
  async restartRunHandler() {
4611
6317
  await this.#ctx.restartRunHandler();
4612
6318
  }
@@ -4639,45 +6345,60 @@ var NativeWorkflowRuntimeAdapter = class {
4639
6345
  };
4640
6346
  }
4641
6347
  };
4642
- function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken) {
4643
- return Object.assign(
4644
- new ActorContextHandleAdapter(
6348
+ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
6349
+ const actorContext = new ActorContextHandleAdapter(
6350
+ runtime,
6351
+ ctx,
6352
+ clientFactory,
6353
+ schemas,
6354
+ databaseProvider,
6355
+ request,
6356
+ stateEnabled,
6357
+ onStateChange,
6358
+ dispatchCancelToken,
6359
+ runHandlerConfigured
6360
+ );
6361
+ return Object.assign(actorContext, {
6362
+ conn: new NativeConnAdapter(
4645
6363
  runtime,
4646
- ctx,
4647
- clientFactory,
6364
+ conn,
4648
6365
  schemas,
4649
- databaseProvider,
4650
- request,
4651
- stateEnabled,
4652
- void 0,
4653
- onStateChange,
4654
- dispatchCancelToken
4655
- ),
4656
- {
4657
- conn: new NativeConnAdapter(
4658
- runtime,
4659
- conn,
4660
- schemas,
4661
- ctx,
4662
- (connId) => callNativeSync(
4663
- () => runtime.actorQueueHibernationRemoval(ctx, connId)
4664
- )
4665
- )
4666
- }
4667
- );
6366
+ ctx,
6367
+ (connId) => callNativeSync(
6368
+ () => runtime.actorQueueHibernationRemoval(ctx, connId)
6369
+ ),
6370
+ () => actorContext.assertCanMutateState()
6371
+ )
6372
+ });
6373
+ }
6374
+ function buildActorTracingConfig(actions, tracing) {
6375
+ if (tracing === void 0) return void 0;
6376
+ return {
6377
+ sampler: tracing.sampler,
6378
+ actions: flattenActionTraceSamplers(actions, tracing.actions)
6379
+ };
4668
6380
  }
6381
+ var SQLITE_DEFERRED_COMMITS = /* @__PURE__ */ Symbol.for("rivetkit.sqlite.deferredCommits");
4669
6382
  function buildActorConfig(definition, registryConfig, runtimeKind) {
4670
- var _a;
6383
+ var _a, _b;
4671
6384
  const config = definition.config;
4672
6385
  const options = config.options ?? {};
4673
6386
  const canHibernate = options.canHibernateWebSocket;
6387
+ const usesRemoteSqlite = sqliteBackendForConfig(registryConfig) === "remote";
4674
6388
  const sqliteProfiling = (_a = config.db) == null ? void 0 : _a.sqliteProfiling;
6389
+ const sqliteDeferredCommits = ((_b = config.db) == null ? void 0 : _b[SQLITE_DEFERRED_COMMITS]) === true;
4675
6390
  return {
4676
6391
  name: options.name,
4677
6392
  icon: options.icon,
4678
- hasDatabase: config.db !== void 0,
6393
+ hasDatabase: true,
6394
+ remoteSqlite: usesRemoteSqlite,
6395
+ sqliteDeferredCommits: sqliteDeferredCommits || void 0,
4679
6396
  sqliteProfiling,
4680
- remoteSqlite: config.db !== void 0 && sqliteBackendForConfig(registryConfig) === "remote",
6397
+ tracing: buildActorTracingConfig(
6398
+ definition.config.actions,
6399
+ definition.config.tracing
6400
+ ),
6401
+ enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
4681
6402
  hasState: config.state !== void 0 || typeof config.createState === "function",
4682
6403
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
4683
6404
  stateSaveIntervalMs: options.stateSaveInterval,
@@ -4693,12 +6414,13 @@ function buildActorConfig(definition, registryConfig, runtimeKind) {
4693
6414
  connectionLivenessTimeoutMs: options.connectionLivenessTimeout,
4694
6415
  connectionLivenessIntervalMs: options.connectionLivenessInterval,
4695
6416
  maxQueueSize: options.maxQueueSize,
6417
+ maxSchedules: options.maxSchedules,
4696
6418
  maxQueueMessageSize: options.maxQueueMessageSize,
4697
6419
  maxIncomingMessageSize: registryConfig.maxIncomingMessageSize,
4698
6420
  maxOutgoingMessageSize: registryConfig.maxOutgoingMessageSize,
4699
6421
  preloadMaxWorkflowBytes: options.preloadMaxWorkflowBytes,
4700
6422
  preloadMaxConnectionsBytes: options.preloadMaxConnectionsBytes,
4701
- actions: Object.keys(config.actions ?? {}).sort().map((name) => ({ name })),
6423
+ actions: Object.keys(flattenActionHandlers(config.actions)).sort().map((name) => ({ name })),
4702
6424
  inspectorTabs: buildInspectorTabs(config.inspector, runtimeKind)
4703
6425
  };
4704
6426
  }
@@ -4774,32 +6496,38 @@ function validateInspectorTabSource(tabId, resolved) {
4774
6496
  function buildNativeFactory(runtime, registryConfig, definition) {
4775
6497
  var _a;
4776
6498
  const config = definition.config;
4777
- const databaseProvider = config.db;
6499
+ const databaseProvider = config.db ?? db();
6500
+ const actionHandlers = flattenActionHandlers(config.actions);
4778
6501
  const schemaConfig = {
4779
- actionInputSchemas: config.actionInputSchemas,
6502
+ actionInputSchemas: flattenActionInputSchemas(
6503
+ config.actions,
6504
+ config.actionInputSchemas
6505
+ ),
4780
6506
  connParamsSchema: config.connParamsSchema,
4781
6507
  events: config.events,
4782
6508
  queues: config.queues
4783
6509
  };
4784
- const actionHandlers = Object.fromEntries(
4785
- Object.entries(config.actions ?? {}).map(([name, handler]) => [name, handler])
4786
- );
4787
- const createClient = () => createClientWithDriver(
6510
+ const createClient = (ctx) => createClientWithDriver(
4788
6511
  new RemoteEngineControlClient(
4789
6512
  convertRegistryConfigToClientConfig(registryConfig)
4790
6513
  ),
4791
- { encoding: "bare" }
6514
+ {
6515
+ encoding: "bare",
6516
+ currentActorInvocation: () => callNativeSync(
6517
+ () => runtime.actorInvocationTraceContext(ctx)
6518
+ ),
6519
+ startCallSpan: (actorName, actionName) => callNativeSync(
6520
+ () => runtime.startCallSpan(ctx, actorName, actionName)
6521
+ )
6522
+ }
4792
6523
  );
4793
- const nativeRunHandlerActiveByActorId = /* @__PURE__ */ new Map();
4794
- const isNativeRunHandlerActive = (ctx) => nativeRunHandlerActiveByActorId.get(
4795
- callNativeSync(() => runtime.actorId(ctx))
4796
- ) ?? false;
6524
+ const run = getRunFunction(config.run);
6525
+ const runHandlerCoordinator = getRunInspectorKind(config.run) === "workflow" ? new RunHandlerCoordinator(config.run) : void 0;
4797
6526
  const getNativeWorkflowInspector = (ctx) => {
4798
- var _a2;
4799
- return (_a2 = getRunInspectorConfig(
4800
- config.run,
4801
- callNativeSync(() => runtime.actorId(ctx))
4802
- )) == null ? void 0 : _a2.workflow;
6527
+ var _a2, _b;
6528
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
6529
+ const restart = () => callNativeSync(() => runtime.actorRestartRunHandler(ctx));
6530
+ return ((_a2 = runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.getInspector(actorId, restart)) == null ? void 0 : _a2.workflow) ?? ((_b = getRunInspectorConfig(config.run, actorId)) == null ? void 0 : _b.workflow);
4803
6531
  };
4804
6532
  const onStateChange = typeof config.onStateChange === "function" ? (actorCtx, nextState) => {
4805
6533
  config.onStateChange(actorCtx, nextState);
@@ -4814,33 +6542,36 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4814
6542
  const makeActorCtx = (ctx, request, cancelToken) => new ActorContextHandleAdapter(
4815
6543
  runtime,
4816
6544
  ctx,
4817
- createClient,
6545
+ () => createClient(ctx),
4818
6546
  schemaConfig,
4819
6547
  databaseProvider,
4820
6548
  request,
4821
6549
  stateEnabled,
4822
- () => isNativeRunHandlerActive(ctx),
4823
6550
  onStateChange,
4824
- cancelToken
6551
+ cancelToken,
6552
+ run !== void 0
4825
6553
  );
4826
6554
  const makeConnCtx = (ctx, conn, request, cancelToken) => withConnContext(
4827
6555
  runtime,
4828
6556
  ctx,
4829
6557
  conn,
4830
- createClient,
6558
+ () => createClient(ctx),
4831
6559
  schemaConfig,
4832
6560
  databaseProvider,
4833
6561
  request,
4834
6562
  stateEnabled,
4835
6563
  onStateChange,
4836
- cancelToken
6564
+ cancelToken,
6565
+ run !== void 0
4837
6566
  );
4838
- const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
6567
+ const maybeHandleNativeInspectorRequest = async (ctx, rawRequest) => {
4839
6568
  var _a2, _b, _c, _d;
4840
- const url = new URL(jsRequest.url);
6569
+ const rawUrl = rawRequest.uri.startsWith("http") ? rawRequest.uri : new URL(rawRequest.uri, "http://127.0.0.1").toString();
6570
+ const url = new URL(rawUrl);
4841
6571
  if (!url.pathname.startsWith("/inspector/")) {
4842
6572
  return void 0;
4843
6573
  }
6574
+ const jsRequest = buildNativeHttpRequest(rawRequest);
4844
6575
  const jsonResponse = (body, init) => new Response(JSON.stringify(body), {
4845
6576
  status: (init == null ? void 0 : init.status) ?? 200,
4846
6577
  headers: {
@@ -4862,7 +6593,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4862
6593
  }
4863
6594
  );
4864
6595
  };
4865
- const isPublicPerActorPath = jsRequest.method === "GET" && (url.pathname === "/inspector/tab-config" || url.pathname.startsWith("/inspector/custom-tabs/"));
6596
+ const isPublicPerActorPath = jsRequest.method === "GET" && url.pathname.startsWith("/inspector/custom-tabs/");
4866
6597
  if (!isPublicPerActorPath) {
4867
6598
  try {
4868
6599
  await runtime.actorVerifyInspectorAuth(
@@ -4884,6 +6615,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4884
6615
  return await ((_b2 = (_a3 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a3.getState) == null ? void 0 : _b2.call(_a3)) ?? null;
4885
6616
  };
4886
6617
  const actorCtx = makeActorCtx(ctx, jsRequest);
6618
+ const sql = getOrCreateNativeSqlDatabase(runtime, ctx);
4887
6619
  try {
4888
6620
  if (url.pathname === "/inspector/state" && jsRequest.method === "GET") {
4889
6621
  return jsonResponse({
@@ -4938,6 +6670,47 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4938
6670
  messages
4939
6671
  });
4940
6672
  }
6673
+ if (url.pathname === "/inspector/queue" && jsRequest.method === "DELETE") {
6674
+ await runtime.actorQueueReset(ctx);
6675
+ return jsonResponse({});
6676
+ }
6677
+ if (url.pathname === "/inspector/queue" && jsRequest.method === "POST") {
6678
+ let body;
6679
+ try {
6680
+ body = await jsRequest.json();
6681
+ } catch {
6682
+ return errorResponse(
6683
+ new RivetError(
6684
+ "actor",
6685
+ "invalid_request",
6686
+ "Invalid inspector JSON body",
6687
+ { public: true }
6688
+ ),
6689
+ 400
6690
+ );
6691
+ }
6692
+ const name = body.name ?? "";
6693
+ if (name === "") {
6694
+ return errorResponse(
6695
+ new RivetError(
6696
+ "actor",
6697
+ "invalid_request",
6698
+ "Queue message name must not be empty",
6699
+ { public: true }
6700
+ ),
6701
+ 400
6702
+ );
6703
+ }
6704
+ const cbor = encodeCborCompat(
6705
+ body.body ?? null
6706
+ );
6707
+ const message = await runtime.actorQueueSend(ctx, name, cbor);
6708
+ return jsonResponse({
6709
+ id: message.id().toString(),
6710
+ name: message.name(),
6711
+ createdAtMs: message.createdAt()
6712
+ });
6713
+ }
4941
6714
  if (url.pathname === "/inspector/traces" && jsRequest.method === "GET") {
4942
6715
  return jsonResponse({ otlp: [], clamped: false });
4943
6716
  }
@@ -4970,9 +6743,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4970
6743
  }
4971
6744
  }
4972
6745
  if (url.pathname === "/inspector/database/schema" && jsRequest.method === "GET") {
4973
- const db = actorCtx.sql;
6746
+ const db2 = sql;
4974
6747
  const tables = queryRows(
4975
- await db.query(
6748
+ await db2.query(
4976
6749
  "SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle_%' ORDER BY name"
4977
6750
  )
4978
6751
  );
@@ -4980,13 +6753,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4980
6753
  for (const table of tables) {
4981
6754
  const quoted = `"${table.name.replace(/"/g, '""')}"`;
4982
6755
  const columns = queryRows(
4983
- await db.query(`PRAGMA table_info(${quoted})`)
6756
+ await db2.query(`PRAGMA table_info(${quoted})`)
4984
6757
  );
4985
6758
  const foreignKeys = queryRows(
4986
- await db.query(`PRAGMA foreign_key_list(${quoted})`)
6759
+ await db2.query(`PRAGMA foreign_key_list(${quoted})`)
4987
6760
  );
4988
6761
  const countResult = queryRows(
4989
- await db.query(
6762
+ await db2.query(
4990
6763
  `SELECT COUNT(*) as count FROM ${quoted}`
4991
6764
  )
4992
6765
  );
@@ -5021,7 +6794,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5021
6794
  );
5022
6795
  const quoted = `"${table.replace(/"/g, '""')}"`;
5023
6796
  const rows = queryRows(
5024
- await actorCtx.sql.query(
6797
+ await sql.query(
5025
6798
  `SELECT * FROM ${quoted} LIMIT ? OFFSET ?`,
5026
6799
  [
5027
6800
  Math.max(0, Math.min(limit, 500)),
@@ -5049,15 +6822,11 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5049
6822
  const bindings = normalizeSqlitePropertyBindings(
5050
6823
  body.properties
5051
6824
  );
5052
- const rows2 = queryRows(
5053
- await actorCtx.sql.query(body.sql, bindings)
5054
- );
6825
+ const rows2 = queryRows(await sql.query(body.sql, bindings));
5055
6826
  return jsonResponse({ rows: jsonSafe(rows2) });
5056
6827
  }
5057
6828
  const args = Array.isArray(body.args) ? body.args : [];
5058
- const rows = queryRows(
5059
- await actorCtx.sql.query(body.sql, args)
5060
- );
6829
+ const rows = queryRows(await sql.query(body.sql, args));
5061
6830
  return jsonResponse({ rows: jsonSafe(rows) });
5062
6831
  }
5063
6832
  if (url.pathname === "/inspector/summary" && jsRequest.method === "GET") {
@@ -5083,7 +6852,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5083
6852
  rpcs: Object.keys(actionHandlers).sort(),
5084
6853
  queueSize: inspectorSnapshot.queueSize,
5085
6854
  isStateEnabled: stateEnabled,
5086
- isDatabaseEnabled: databaseProvider !== void 0,
6855
+ isDatabaseEnabled: true,
5087
6856
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0,
5088
6857
  workflowState: await workflowState(),
5089
6858
  workflowHistory: workflowHistory()
@@ -5273,6 +7042,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5273
7042
  async (error, payload) => {
5274
7043
  const { ctx } = unwrapTsfnPayload(error, payload);
5275
7044
  const actorCtx = makeActorCtx(ctx);
7045
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
5276
7046
  const saveActorState = async () => {
5277
7047
  if (runtime.kind === "wasm") {
5278
7048
  await runtime.actorSaveState(
@@ -5298,6 +7068,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5298
7068
  saveActorState
5299
7069
  );
5300
7070
  } finally {
7071
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
7072
+ disposeRunInspector(config.run, actorId);
5301
7073
  await actorCtx.dispose();
5302
7074
  }
5303
7075
  }
@@ -5307,16 +7079,16 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5307
7079
  async (error, payload) => {
5308
7080
  const { ctx } = unwrapTsfnPayload(error, payload);
5309
7081
  const actorCtx = makeActorCtx(ctx);
7082
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
7083
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
7084
+ disposeRunInspector(config.run, actorId);
5310
7085
  try {
5311
7086
  if (typeof config.onDestroy === "function") {
5312
7087
  await config.onDestroy(actorCtx);
5313
7088
  }
5314
7089
  } finally {
5315
- const actorId = callNativeSync(() => runtime.actorId(ctx));
5316
- nativeRunHandlerActiveByActorId.delete(actorId);
5317
- disposeRunInspector(config.run, actorId);
5318
7090
  resolveNativeDestroy(runtime, ctx);
5319
- await actorCtx.closeDatabase();
7091
+ await detachNativeDatabaseForShutdown(runtime, ctx);
5320
7092
  clearNativeRuntimeState(runtime, ctx);
5321
7093
  await actorCtx.dispose();
5322
7094
  }
@@ -5330,7 +7102,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5330
7102
  );
5331
7103
  const actorCtx = makeActorCtx(
5332
7104
  ctx,
5333
- request ? buildRequest(request) : void 0
7105
+ request ? buildNativeHttpRequest(request) : void 0
5334
7106
  );
5335
7107
  try {
5336
7108
  await config.onBeforeConnect(
@@ -5350,7 +7122,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5350
7122
  const { ctx, conn, params, request } = unwrapTsfnPayload(error, payload);
5351
7123
  const actorCtx = makeActorCtx(
5352
7124
  ctx,
5353
- request ? buildRequest(request) : void 0
7125
+ request ? buildNativeHttpRequest(request) : void 0
5354
7126
  );
5355
7127
  const connAdapter = new NativeConnAdapter(
5356
7128
  runtime,
@@ -5362,7 +7134,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5362
7134
  ctx,
5363
7135
  connId
5364
7136
  )
5365
- )
7137
+ ),
7138
+ () => actorCtx.assertCanMutateState()
5366
7139
  );
5367
7140
  try {
5368
7141
  const nextConnState = hasStaticConnState ? structuredClone(config.connState) : await config.createConnState(
@@ -5387,7 +7160,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5387
7160
  );
5388
7161
  const actorCtx = makeActorCtx(
5389
7162
  ctx,
5390
- request ? buildRequest(request) : void 0
7163
+ request ? buildNativeHttpRequest(request) : void 0
5391
7164
  );
5392
7165
  const connAdapter = new NativeConnAdapter(
5393
7166
  runtime,
@@ -5399,7 +7172,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5399
7172
  ctx,
5400
7173
  connId
5401
7174
  )
5402
- )
7175
+ ),
7176
+ () => actorCtx.assertCanMutateState()
5403
7177
  );
5404
7178
  try {
5405
7179
  await config.onConnect(
@@ -5431,7 +7205,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5431
7205
  ctx,
5432
7206
  connId
5433
7207
  )
5434
- )
7208
+ ),
7209
+ () => actorCtx.assertCanMutateState()
5435
7210
  )
5436
7211
  );
5437
7212
  }
@@ -5492,61 +7267,126 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5492
7267
  onRequest: wrapNativeCallback(
5493
7268
  async (error, payload) => {
5494
7269
  try {
5495
- const { ctx, request, cancelToken } = unwrapTsfnPayload(
5496
- error,
5497
- payload
5498
- );
5499
- const jsRequest = buildRequest(request);
5500
- const inspectorResponse = await maybeHandleNativeInspectorRequest(
7270
+ const { ctx, request, cancelToken, responseBodyStream } = unwrapTsfnPayload(error, payload);
7271
+ return await runtime.runWithActorInvocationContext(
5501
7272
  ctx,
5502
- request,
5503
- jsRequest
5504
- );
5505
- if (inspectorResponse) {
5506
- return await toRuntimeHttpResponse(inspectorResponse);
5507
- }
5508
- if (typeof config.onRequest !== "function") {
5509
- return await toRuntimeHttpResponse(
5510
- new Response(null, { status: 404 })
5511
- );
5512
- }
5513
- const rawConnParams = jsRequest.headers.get(HEADER_CONN_PARAMS);
5514
- let requestCtx;
5515
- let conn;
5516
- try {
5517
- const connParams = validateConnParams(
5518
- schemaConfig.connParamsSchema,
5519
- rawConnParams ? JSON.parse(rawConnParams) : void 0
5520
- );
5521
- conn = await callNative(
5522
- () => runtime.actorConnectConn(
7273
+ async () => {
7274
+ const inspectorResponse = await maybeHandleNativeInspectorRequest(
5523
7275
  ctx,
5524
- encodeValue(connParams),
5525
7276
  request
5526
- )
5527
- );
5528
- requestCtx = makeConnCtx(
5529
- ctx,
5530
- conn,
5531
- jsRequest,
5532
- cancelToken
5533
- );
5534
- const response = await config.onRequest(
5535
- requestCtx,
5536
- jsRequest
5537
- );
5538
- if (!(response instanceof Response)) {
5539
- throw new Error(
5540
- "onRequest handler must return a Response"
5541
7277
  );
7278
+ if (inspectorResponse) {
7279
+ await cancelNativeHttpRequestBody(
7280
+ request.bodyStream
7281
+ );
7282
+ return (await convertNativeHttpResponse(
7283
+ inspectorResponse,
7284
+ responseBodyStream
7285
+ )).response;
7286
+ }
7287
+ if (typeof config.onRequest !== "function") {
7288
+ await cancelNativeHttpRequestBody(
7289
+ request.bodyStream
7290
+ );
7291
+ return (await convertNativeHttpResponse(
7292
+ new Response(null, { status: 404 }),
7293
+ responseBodyStream
7294
+ )).response;
7295
+ }
7296
+ const requestAbortController = new AbortController();
7297
+ const handlerRequest = buildNativeHttpRequest({
7298
+ ...request,
7299
+ abortController: requestAbortController
7300
+ });
7301
+ const rawConnParams = handlerRequest.headers.get(HEADER_CONN_PARAMS);
7302
+ let requestCtx;
7303
+ let conn;
7304
+ let removeRequestAbortListener;
7305
+ let cleanupDeferredToBody = false;
7306
+ let cleanedUp = false;
7307
+ const cleanupRequest = async () => {
7308
+ if (cleanedUp) return;
7309
+ cleanedUp = true;
7310
+ removeRequestAbortListener == null ? void 0 : removeRequestAbortListener();
7311
+ try {
7312
+ await (requestCtx == null ? void 0 : requestCtx.dispose());
7313
+ } finally {
7314
+ if (conn) {
7315
+ await runtime.connDisconnect(conn);
7316
+ }
7317
+ }
7318
+ };
7319
+ try {
7320
+ const connParams = validateConnParams(
7321
+ schemaConfig.connParamsSchema,
7322
+ rawConnParams ? JSON.parse(rawConnParams) : void 0
7323
+ );
7324
+ conn = await callNative(
7325
+ () => runtime.actorConnectConn(
7326
+ ctx,
7327
+ encodeValue(connParams),
7328
+ request
7329
+ )
7330
+ );
7331
+ requestCtx = makeConnCtx(
7332
+ ctx,
7333
+ conn,
7334
+ handlerRequest,
7335
+ cancelToken
7336
+ );
7337
+ const ctxAbortSignal = requestCtx.abortSignal;
7338
+ const abortRequest = () => requestAbortController.abort(
7339
+ ctxAbortSignal.reason
7340
+ );
7341
+ if (ctxAbortSignal.aborted) {
7342
+ abortRequest();
7343
+ } else {
7344
+ ctxAbortSignal.addEventListener(
7345
+ "abort",
7346
+ abortRequest,
7347
+ { once: true }
7348
+ );
7349
+ removeRequestAbortListener = () => ctxAbortSignal.removeEventListener(
7350
+ "abort",
7351
+ abortRequest
7352
+ );
7353
+ }
7354
+ const response = await config.onRequest(
7355
+ requestCtx,
7356
+ handlerRequest
7357
+ );
7358
+ if (!isResponseLike(response)) {
7359
+ throw new Error(
7360
+ "onRequest handler must return a Response"
7361
+ );
7362
+ }
7363
+ const conversion = await convertNativeHttpResponse(
7364
+ response,
7365
+ responseBodyStream
7366
+ );
7367
+ if (conversion.bodyCompletion) {
7368
+ cleanupDeferredToBody = true;
7369
+ void conversion.bodyCompletion.then(cleanupRequest).catch((cleanupError) => {
7370
+ logger2().error({
7371
+ msg: "failed to clean up native streaming http request",
7372
+ error: cleanupError
7373
+ });
7374
+ });
7375
+ }
7376
+ return conversion.response;
7377
+ } finally {
7378
+ try {
7379
+ await cancelNativeHttpRequestBody(
7380
+ request.bodyStream
7381
+ );
7382
+ } finally {
7383
+ if (!cleanupDeferredToBody) {
7384
+ await cleanupRequest();
7385
+ }
7386
+ }
7387
+ }
5542
7388
  }
5543
- return await toRuntimeHttpResponse(response);
5544
- } finally {
5545
- await (requestCtx == null ? void 0 : requestCtx.dispose());
5546
- if (conn) {
5547
- await runtime.connDisconnect(conn);
5548
- }
5549
- }
7389
+ );
5550
7390
  } catch (error2) {
5551
7391
  logger2().error({
5552
7392
  msg: "native onRequest failed",
@@ -5559,7 +7399,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5559
7399
  onWebSocket: typeof config.onWebSocket === "function" ? wrapNativeCallback(
5560
7400
  async (error, payload) => {
5561
7401
  const { ctx, conn, ws, request } = unwrapTsfnPayload(error, payload);
5562
- const jsRequest = request ? buildRequest(request) : void 0;
7402
+ const jsRequest = request ? buildNativeHttpRequest(request) : void 0;
5563
7403
  const actorCtx = makeConnCtx(ctx, conn, jsRequest);
5564
7404
  try {
5565
7405
  await config.onWebSocket(
@@ -5575,7 +7415,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5575
7415
  }
5576
7416
  ) : void 0,
5577
7417
  run: (() => {
5578
- const run = getRunFunction(config.run);
5579
7418
  if (!run) {
5580
7419
  return void 0;
5581
7420
  }
@@ -5583,26 +7422,38 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5583
7422
  async (error, payload) => {
5584
7423
  const { ctx } = unwrapTsfnPayload(error, payload);
5585
7424
  const actorId = callNativeSync(() => runtime.actorId(ctx));
5586
- const actorCtx = makeActorCtx(ctx);
5587
- nativeRunHandlerActiveByActorId.set(actorId, true);
5588
- try {
5589
- await run(actorCtx);
5590
- } finally {
5591
- nativeRunHandlerActiveByActorId.delete(actorId);
5592
- await actorCtx.dispose();
7425
+ const executeRun = async () => {
7426
+ const actorCtx = makeActorCtx(ctx);
7427
+ try {
7428
+ await run(actorCtx);
7429
+ } finally {
7430
+ await actorCtx.dispose();
7431
+ }
7432
+ };
7433
+ if (runHandlerCoordinator) {
7434
+ const outcome = await runHandlerCoordinator.run(
7435
+ actorId,
7436
+ () => callNativeSync(
7437
+ () => runtime.actorRestartRunHandler(ctx)
7438
+ ),
7439
+ executeRun
7440
+ );
7441
+ return outcome !== "suppressed";
5593
7442
  }
7443
+ await executeRun();
7444
+ return true;
5594
7445
  }
5595
7446
  );
5596
7447
  })(),
5597
- getWorkflowHistory: getRunInspectorConfig(config.run) !== void 0 ? wrapNativeCallback(
7448
+ getWorkflowHistory: hasRunInspectorConfig(config.run) ? wrapNativeCallback(
5598
7449
  async (error, payload) => {
5599
7450
  var _a2;
5600
7451
  const { ctx } = unwrapTsfnPayload(error, payload);
5601
7452
  const history = (_a2 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a2.getHistory();
5602
- return history == null ? void 0 : encodeValue(history);
7453
+ return history == null ? void 0 : toUint8Array(history);
5603
7454
  }
5604
7455
  ) : void 0,
5605
- replayWorkflow: getRunInspectorConfig(config.run) !== void 0 ? wrapNativeCallback(
7456
+ replayWorkflow: hasRunInspectorConfig(config.run) ? wrapNativeCallback(
5606
7457
  async (error, payload) => {
5607
7458
  const { ctx, entryId } = unwrapTsfnPayload(
5608
7459
  error,
@@ -5612,10 +7463,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5612
7463
  if (!(workflowInspector == null ? void 0 : workflowInspector.replayFromStep)) {
5613
7464
  return void 0;
5614
7465
  }
5615
- const history = await workflowInspector.replayFromStep(
5616
- entryId
5617
- ) ?? null;
5618
- return history == null ? void 0 : encodeValue(history);
7466
+ const history = await workflowInspector.replayFromStep(entryId) ?? null;
7467
+ return history == null ? void 0 : toUint8Array(history);
5619
7468
  }
5620
7469
  ) : void 0,
5621
7470
  actions: Object.fromEntries(
@@ -5623,22 +7472,29 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5623
7472
  name,
5624
7473
  wrapNativeCallback(
5625
7474
  async (error, payload) => {
5626
- const { ctx, conn, args, cancelToken } = unwrapTsfnPayload(error, payload);
7475
+ const { ctx, conn, args, scheduledFire, cancelToken } = unwrapTsfnPayload(error, payload);
5627
7476
  const actorCtx = conn != null ? makeConnCtx(ctx, conn, void 0, cancelToken) : makeActorCtx(ctx, void 0, cancelToken);
5628
- try {
5629
- return encodeValue(
5630
- await handler(
5631
- actorCtx,
5632
- ...validateActionArgs(
5633
- schemaConfig.actionInputSchemas,
5634
- name,
5635
- decodeArgs(args)
7477
+ const runAction = async () => {
7478
+ try {
7479
+ return encodeValue(
7480
+ await handler(
7481
+ actorCtx,
7482
+ ...validateActionArgs(
7483
+ schemaConfig.actionInputSchemas,
7484
+ name,
7485
+ decodeArgs(args)
7486
+ ),
7487
+ ...scheduledFire ? [scheduledFire] : []
5636
7488
  )
5637
- )
5638
- );
5639
- } finally {
5640
- await actorCtx.dispose();
5641
- }
7489
+ );
7490
+ } finally {
7491
+ await actorCtx.dispose();
7492
+ }
7493
+ };
7494
+ return await runtime.runWithActorInvocationContext(
7495
+ ctx,
7496
+ runAction
7497
+ );
5642
7498
  }
5643
7499
  )
5644
7500
  ])
@@ -5655,56 +7511,62 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5655
7511
  timeoutMs,
5656
7512
  cancelToken
5657
7513
  } = unwrapTsfnPayload(error, payload);
5658
- const jsRequest = buildRequest(request);
7514
+ const jsRequest = buildNativeHttpRequest(request);
5659
7515
  const actorCtx = withConnContext(
5660
7516
  runtime,
5661
7517
  ctx,
5662
7518
  conn,
5663
- createClient,
7519
+ () => createClient(ctx),
5664
7520
  schemaConfig,
5665
7521
  databaseProvider,
5666
7522
  jsRequest,
5667
7523
  stateEnabled,
5668
7524
  onStateChange,
5669
- cancelToken
7525
+ cancelToken,
7526
+ run !== void 0
5670
7527
  );
5671
- try {
5672
- if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
5673
- return { status: "completed" };
5674
- }
5675
- const canPublish = getQueueCanPublish(
5676
- schemaConfig.queues,
5677
- name
5678
- );
5679
- if (canPublish && !await canPublish(actorCtx)) {
5680
- throw forbiddenError();
5681
- }
5682
- const decodedBody = decodeValue(body);
5683
- if (wait) {
7528
+ return await runtime.runWithActorInvocationContext(
7529
+ ctx,
7530
+ async () => {
5684
7531
  try {
5685
- const response = await actorCtx.queue.enqueueAndWait(
5686
- name,
5687
- decodedBody,
5688
- {
5689
- timeout: timeoutMs === void 0 || timeoutMs === null ? void 0 : Number(timeoutMs)
5690
- }
7532
+ if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
7533
+ return { status: "completed" };
7534
+ }
7535
+ const canPublish = getQueueCanPublish(
7536
+ schemaConfig.queues,
7537
+ name
5691
7538
  );
5692
- return {
5693
- status: "completed",
5694
- response: response === void 0 ? void 0 : encodeValue(response)
5695
- };
5696
- } catch (error2) {
5697
- if (error2.group === "queue" && error2.code === "timed_out") {
5698
- return { status: "timedOut" };
7539
+ if (canPublish && !await canPublish(actorCtx)) {
7540
+ throw forbiddenError();
7541
+ }
7542
+ const decodedBody = decodeValue(body);
7543
+ if (wait) {
7544
+ try {
7545
+ const response = await actorCtx.queue.enqueueAndWait(
7546
+ name,
7547
+ decodedBody,
7548
+ {
7549
+ timeout: timeoutMs === void 0 || timeoutMs === null ? void 0 : Number(timeoutMs)
7550
+ }
7551
+ );
7552
+ return {
7553
+ status: "completed",
7554
+ response: response === void 0 ? void 0 : encodeValue(response)
7555
+ };
7556
+ } catch (error2) {
7557
+ if (error2.group === "queue" && error2.code === "timed_out") {
7558
+ return { status: "timedOut" };
7559
+ }
7560
+ throw error2;
7561
+ }
5699
7562
  }
5700
- throw error2;
7563
+ await actorCtx.queue.send(name, decodedBody);
7564
+ return { status: "completed" };
7565
+ } finally {
7566
+ await actorCtx.dispose();
5701
7567
  }
5702
7568
  }
5703
- await actorCtx.queue.send(name, decodedBody);
5704
- return { status: "completed" };
5705
- } finally {
5706
- await actorCtx.dispose();
5707
- }
7569
+ );
5708
7570
  }
5709
7571
  ),
5710
7572
  serializeState: wrapNativeCallback(
@@ -5724,17 +7586,19 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5724
7586
  buildActorConfig(definition, registryConfig, runtime.kind)
5725
7587
  );
5726
7588
  }
5727
- async function buildServeConfig(config) {
7589
+ async function buildServeConfig(config, resolveServicesBinary = true) {
5728
7590
  var _a;
5729
7591
  if (!config.endpoint) {
5730
7592
  throw nativeEndpointNotConfiguredError();
5731
7593
  }
5732
7594
  const serveConfig = {
5733
- version: config.envoy.version,
7595
+ version: config.node.version,
5734
7596
  endpoint: config.endpoint,
7597
+ engineSpawn: config.engineSpawn,
5735
7598
  token: config.token,
5736
7599
  namespace: config.namespace,
5737
- poolName: config.envoy.poolName,
7600
+ poolName: config.node.poolName,
7601
+ startServices: resolveServicesBinary && config.startServices,
5738
7602
  handleInspectorHttpInRuntime: true,
5739
7603
  serverlessBasePath: config.serverless.basePath,
5740
7604
  serverlessPackageVersion: VERSION,
@@ -5753,6 +7617,19 @@ async function buildServeConfig(config) {
5753
7617
  error: stringifyError(error)
5754
7618
  });
5755
7619
  }
7620
+ if (resolveServicesBinary && config.startServices) {
7621
+ const servicesBinary = getEnvUniversal("RIVET_SERVICES_BINARY");
7622
+ if (servicesBinary) {
7623
+ serveConfig.servicesBinaryPath = servicesBinary;
7624
+ } else {
7625
+ try {
7626
+ const { getServicesPath } = await loadServices();
7627
+ serveConfig.servicesBinaryPath = getServicesPath();
7628
+ } catch (error) {
7629
+ throw servicesBinaryUnavailable(error);
7630
+ }
7631
+ }
7632
+ }
5756
7633
  serveConfig.engineHost = config.engineHost;
5757
7634
  serveConfig.enginePort = config.enginePort;
5758
7635
  if ((_a = config.test) == null ? void 0 : _a.enabled) {
@@ -5779,7 +7656,7 @@ async function buildRegistryWithRuntime(config, runtime) {
5779
7656
  return {
5780
7657
  runtime,
5781
7658
  registry,
5782
- serveConfig: await buildServeConfig(config)
7659
+ serveConfig: await buildServeConfig(config, runtime.kind === "napi")
5783
7660
  };
5784
7661
  }
5785
7662
  async function buildConfiguredRegistry(config) {
@@ -5791,6 +7668,10 @@ async function buildConfiguredRegistry(config) {
5791
7668
  }
5792
7669
 
5793
7670
  // src/registry/index.ts
7671
+ var REGISTRY_READY_TIMEOUT_MS = 3e4;
7672
+ function rejectServerless() {
7673
+ throw new Error("serverless is disabled in this version");
7674
+ }
5794
7675
  function signalExitCode(signal) {
5795
7676
  switch (signal) {
5796
7677
  case "SIGINT":
@@ -5805,6 +7686,54 @@ function finishShutdownSignal(signal) {
5805
7686
  }
5806
7687
  process.kill(process.pid, signal);
5807
7688
  }
7689
+ function createApplicationFetch(application, runtime) {
7690
+ return async (request, responseBodyStream) => {
7691
+ const method2 = request.method.toUpperCase();
7692
+ const body = method2 === "GET" || method2 === "HEAD" || request.body.length === 0 ? void 0 : Uint8Array.from(request.body).buffer;
7693
+ const abortController = new AbortController();
7694
+ if (request.cancelToken) {
7695
+ if (runtime.cancellationTokenAborted(request.cancelToken)) {
7696
+ abortController.abort();
7697
+ } else {
7698
+ runtime.onCancellationTokenCancelled(
7699
+ request.cancelToken,
7700
+ () => abortController.abort()
7701
+ );
7702
+ }
7703
+ }
7704
+ const response = await application.fetch(
7705
+ new Request(request.url, {
7706
+ method: method2,
7707
+ headers: request.headers,
7708
+ body,
7709
+ signal: abortController.signal
7710
+ })
7711
+ );
7712
+ if (!isResponseLike(response)) {
7713
+ throw new TypeError(
7714
+ "registry.listen() application fetch must return a Response"
7715
+ );
7716
+ }
7717
+ const conversion = await convertNativeHttpResponse(
7718
+ response,
7719
+ responseBodyStream
7720
+ );
7721
+ if (conversion.bodyCompletion) {
7722
+ void conversion.bodyCompletion.catch((error) => {
7723
+ logger2().error({
7724
+ msg: "application response stream failed",
7725
+ error
7726
+ });
7727
+ });
7728
+ }
7729
+ return {
7730
+ status: conversion.response.status ?? response.status,
7731
+ headers: conversion.response.headers ?? Object.fromEntries(response.headers.entries()),
7732
+ body: conversion.response.body,
7733
+ stream: conversion.response.stream
7734
+ };
7735
+ };
7736
+ }
5808
7737
  var Registry = class {
5809
7738
  #config;
5810
7739
  #buildConfiguredRegistry;
@@ -5816,15 +7745,22 @@ var Registry = class {
5816
7745
  return RegistryConfigSchema.parse(this.#config);
5817
7746
  }
5818
7747
  #runtimeServePromise;
7748
+ #runtimeServeLifecyclePromise;
7749
+ #runtimeReadyPromise;
5819
7750
  #runtimeServeConfiguredPromise;
5820
7751
  #runtimeServerlessPromise;
7752
+ #applicationListenerPromise;
5821
7753
  #configureServerlessPoolPromise;
5822
7754
  #welcomePrinted = false;
5823
7755
  #shutdownInstalled = false;
5824
7756
  #shutdownInFlight = null;
5825
7757
  #signalHandlers = {};
5826
7758
  constructor(config, deps) {
7759
+ var _a;
5827
7760
  this.#config = config;
7761
+ if ((_a = config.logging) == null ? void 0 : _a.baseLogger) {
7762
+ configureBaseLogger(config.logging.baseLogger);
7763
+ }
5828
7764
  this.#buildConfiguredRegistry = (deps == null ? void 0 : deps.buildConfiguredRegistry) ?? buildConfiguredRegistry;
5829
7765
  this.routes = {
5830
7766
  health: () => this.#healthRoute(),
@@ -5840,6 +7776,7 @@ var Registry = class {
5840
7776
  */
5841
7777
  #ensureServerlessPoolConfigured(config) {
5842
7778
  if (!config.configurePool) return void 0;
7779
+ rejectServerless();
5843
7780
  if (!this.#configureServerlessPoolPromise) {
5844
7781
  this.#configureServerlessPoolPromise = configureServerlessPool(
5845
7782
  config
@@ -5864,6 +7801,7 @@ var Registry = class {
5864
7801
  */
5865
7802
  async handler(request) {
5866
7803
  var _a;
7804
+ rejectServerless();
5867
7805
  const config = this.parseConfig();
5868
7806
  this.#printWelcome(config, "serverless");
5869
7807
  if (!this.#runtimeServerlessPromise) {
@@ -6025,6 +7963,7 @@ var Registry = class {
6025
7963
  * ```
6026
7964
  */
6027
7965
  serve() {
7966
+ rejectServerless();
6028
7967
  return {
6029
7968
  fetch: (request) => this.handler(request)
6030
7969
  };
@@ -6039,18 +7978,67 @@ var Registry = class {
6039
7978
  * @param opts.host Address to bind. Defaults to `0.0.0.0`.
6040
7979
  * @param opts.publicDir If set, serves static files from this directory
6041
7980
  * as a fallback below the framework routes.
7981
+ * @param opts.application If set, handles requests that do not match a
7982
+ * framework route.
6042
7983
  *
6043
7984
  * @example
6044
7985
  * ```ts
6045
7986
  * await registry.listen();
6046
- * await registry.listen({ port: 8080, publicDir: "./public" });
7987
+ * await registry.listen({ application: app });
6047
7988
  * ```
6048
7989
  */
6049
7990
  async listen(opts = {}) {
7991
+ if (!opts.application) {
7992
+ rejectServerless();
7993
+ }
6050
7994
  const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3e3;
6051
7995
  const publicDir = opts.publicDir ?? getRivetkitPublicDir();
6052
7996
  const config = this.parseConfig();
6053
- const configuredRegistryPromise = buildConfiguredRegistry(config);
7997
+ if (opts.application && getRivetkitRuntimeMode() !== "serverless") {
7998
+ if (config.runtime === "wasm") {
7999
+ throw new Error(
8000
+ "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly"
8001
+ );
8002
+ }
8003
+ this.#installSignalHandlers(config);
8004
+ this.#printWelcome(config, "serverful", {
8005
+ port,
8006
+ host: opts.host,
8007
+ publicDir
8008
+ });
8009
+ this.#startEnvoy(config, true);
8010
+ const readyPromise = this.startAndWait();
8011
+ const configuredRegistryPromise2 = this.#runtimeServeConfiguredPromise;
8012
+ if (!configuredRegistryPromise2) {
8013
+ throw new Error("registry envoy startup did not initialize");
8014
+ }
8015
+ const { runtime: runtime2, registry: registry2, serveConfig: serveConfig2 } = await configuredRegistryPromise2;
8016
+ const application2 = createApplicationFetch(
8017
+ opts.application,
8018
+ runtime2
8019
+ );
8020
+ await readyPromise;
8021
+ const listenerPromise = runtime2.serveApplicationListener(
8022
+ registry2,
8023
+ {
8024
+ port,
8025
+ host: opts.host,
8026
+ publicDir,
8027
+ application: application2
8028
+ },
8029
+ serveConfig2
8030
+ );
8031
+ this.#applicationListenerPromise = listenerPromise;
8032
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
8033
+ if (!serveLifecyclePromise) {
8034
+ throw new Error(
8035
+ "registry envoy serve lifecycle did not initialize"
8036
+ );
8037
+ }
8038
+ await Promise.all([listenerPromise, serveLifecyclePromise]);
8039
+ return;
8040
+ }
8041
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config);
6054
8042
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
6055
8043
  this.#runtimeServerlessPromise = configuredRegistryPromise;
6056
8044
  this.#installSignalHandlers(config);
@@ -6061,9 +8049,15 @@ var Registry = class {
6061
8049
  });
6062
8050
  this.#ensureServerlessPoolConfigured(config);
6063
8051
  const { runtime, registry, serveConfig } = await configuredRegistryPromise;
8052
+ const application = opts.application ? createApplicationFetch(opts.application, runtime) : void 0;
6064
8053
  await runtime.serveListener(
6065
8054
  registry,
6066
- { port, host: opts.host, publicDir },
8055
+ {
8056
+ port,
8057
+ host: opts.host,
8058
+ publicDir,
8059
+ application
8060
+ },
6067
8061
  serveConfig
6068
8062
  );
6069
8063
  }
@@ -6097,6 +8091,7 @@ var Registry = class {
6097
8091
  * Returns serverless metadata suitable for mounting in a user-owned router.
6098
8092
  */
6099
8093
  async #metadataRoute() {
8094
+ rejectServerless();
6100
8095
  const configured = await this.#activeConfiguredRegistry();
6101
8096
  if (!configured) {
6102
8097
  return new Response("registry not started\n", {
@@ -6155,13 +8150,35 @@ var Registry = class {
6155
8150
  * Starts an actor envoy for standalone server deployments.
6156
8151
  */
6157
8152
  #startEnvoy(config, printWelcome) {
8153
+ var _a;
6158
8154
  if (!this.#runtimeServePromise) {
8155
+ const configuredEnvoyVersion = (_a = this.#config.node) == null ? void 0 : _a.version;
8156
+ const envoyVersionSource = configuredEnvoyVersion !== void 0 ? "config" : getRivetEnvoyVersion() !== void 0 ? "environment" : "default";
8157
+ logger2().info({
8158
+ msg: "starting rivetkit envoy",
8159
+ rivetkitVersion: VERSION,
8160
+ envoyVersion: config.node.version,
8161
+ envoyVersionSource
8162
+ });
8163
+ if (envoyVersionSource === "default" && getNodeEnv() === "production") {
8164
+ logger2().error({
8165
+ msg: "node version defaulted because neither config.node.version nor RIVET_NODE_VERSION is set; actors will not drain automatically across deploys. See https://rivet.dev/docs/actors/versions",
8166
+ envoyVersion: config.node.version,
8167
+ envoyVersionSource
8168
+ });
8169
+ }
6159
8170
  const configuredRegistryPromise = this.#buildConfiguredRegistry(config);
6160
8171
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
6161
- this.#runtimeServePromise = configuredRegistryPromise.then(async ({ runtime, registry, serveConfig }) => {
6162
- await runtime.serveRegistry(registry, serveConfig);
6163
- }).catch((error) => {
6164
- logger2().warn({ error }, "runtime registry serve errored");
8172
+ this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(
8173
+ async ({ runtime, registry, serveConfig }) => {
8174
+ await runtime.serveRegistry(registry, serveConfig);
8175
+ }
8176
+ );
8177
+ this.#runtimeServePromise = this.#runtimeServeLifecyclePromise.catch((error) => {
8178
+ logger2().error({ error }, "runtime registry serve errored");
8179
+ if (typeof process !== "undefined" && typeof process.exit === "function") {
8180
+ process.exit(1);
8181
+ }
6165
8182
  });
6166
8183
  this.#installSignalHandlers(config);
6167
8184
  }
@@ -6191,7 +8208,7 @@ var Registry = class {
6191
8208
  finishShutdownSignal(signal);
6192
8209
  return;
6193
8210
  }
6194
- this.#shutdownInFlight = this.#drain(config).catch((err) => {
8211
+ this.#shutdownInFlight = this.#drain(config, true).catch((err) => {
6195
8212
  logger2().warn({ err }, "shutdown error");
6196
8213
  }).then(() => {
6197
8214
  this.#removeSignalHandlers();
@@ -6227,11 +8244,18 @@ var Registry = class {
6227
8244
  });
6228
8245
  return this.#shutdownInFlight;
6229
8246
  }
6230
- async #drain(config) {
8247
+ async #drain(config, signalDriven = false) {
6231
8248
  var _a;
6232
8249
  const modeAPromise = this.#runtimeServeConfiguredPromise;
6233
8250
  const modeBPromise = this.#runtimeServerlessPromise;
6234
- const gracePeriodMs = ((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs) ?? await this.#actorStopThresholdMs(modeAPromise ?? modeBPromise) ?? 30 * 60 * 1e3;
8251
+ const runtimes = /* @__PURE__ */ new Set();
8252
+ const localDevSignal = signalDriven && getNodeEnv() !== "production" && config.engineSpawn && config.endpoint !== void 0 && isLocalEngineEndpoint(config.endpoint);
8253
+ let gracePeriodMs = (_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs;
8254
+ if (gracePeriodMs === void 0) {
8255
+ gracePeriodMs = localDevSignal ? 1e3 : await this.#actorStopThresholdMs(
8256
+ modeAPromise ?? modeBPromise
8257
+ ) ?? 30 * 60 * 1e3;
8258
+ }
6235
8259
  const drain = async () => {
6236
8260
  const registries = [];
6237
8261
  if (modeAPromise !== void 0) {
@@ -6239,6 +8263,7 @@ var Registry = class {
6239
8263
  (async () => {
6240
8264
  try {
6241
8265
  const { runtime, registry } = await modeAPromise;
8266
+ runtimes.add(runtime);
6242
8267
  await runtime.shutdownRegistry(registry);
6243
8268
  } catch (err) {
6244
8269
  logger2().warn(
@@ -6254,6 +8279,7 @@ var Registry = class {
6254
8279
  (async () => {
6255
8280
  try {
6256
8281
  const { runtime, registry } = await modeBPromise;
8282
+ runtimes.add(runtime);
6257
8283
  await runtime.shutdownRegistry(registry);
6258
8284
  } catch (err) {
6259
8285
  logger2().warn(
@@ -6269,6 +8295,9 @@ var Registry = class {
6269
8295
  if (runtimeServePromise !== void 0) {
6270
8296
  await runtimeServePromise.catch(() => void 0);
6271
8297
  }
8298
+ if (this.#applicationListenerPromise !== void 0) {
8299
+ await this.#applicationListenerPromise.catch(() => void 0);
8300
+ }
6272
8301
  };
6273
8302
  await Promise.race([
6274
8303
  drain(),
@@ -6279,6 +8308,12 @@ var Registry = class {
6279
8308
  }
6280
8309
  )
6281
8310
  ]);
8311
+ await Promise.all(
8312
+ [...runtimes].map((runtime) => {
8313
+ var _a2;
8314
+ return (_a2 = runtime.shutdownTelemetry) == null ? void 0 : _a2.call(runtime);
8315
+ })
8316
+ );
6282
8317
  }
6283
8318
  async #actorStopThresholdMs(configuredRegistryPromise) {
6284
8319
  var _a;
@@ -6308,6 +8343,83 @@ var Registry = class {
6308
8343
  startEnvoy() {
6309
8344
  this.#startEnvoy(this.parseConfig(), true);
6310
8345
  }
8346
+ /**
8347
+ * Starts the serverful registry if needed and waits until its envoy has
8348
+ * registered with the Engine. Repeated and concurrent calls share one
8349
+ * startup lifecycle and readiness promise.
8350
+ *
8351
+ * Unlike {@link start}, this reports startup failures and does not resolve
8352
+ * merely because an HTTP health endpoint is listening.
8353
+ */
8354
+ startAndWait() {
8355
+ if (this.#shutdownInFlight !== null) {
8356
+ return Promise.reject(
8357
+ new Error(
8358
+ "registry.startAndWait() cannot run after shutdown has begun"
8359
+ )
8360
+ );
8361
+ }
8362
+ if (this.#runtimeReadyPromise) return this.#runtimeReadyPromise;
8363
+ try {
8364
+ if (getRivetkitRuntimeMode() === "serverless") {
8365
+ return Promise.reject(
8366
+ new Error(
8367
+ "registry.startAndWait() requires envoy runtime mode; serverless registries become ready per request"
8368
+ )
8369
+ );
8370
+ }
8371
+ } catch (error) {
8372
+ return Promise.reject(error);
8373
+ }
8374
+ const config = this.parseConfig();
8375
+ if (config.runtime === "wasm") {
8376
+ return Promise.reject(
8377
+ new Error(
8378
+ "registry.startAndWait() requires the native runtime; WebAssembly registries do not host an envoy"
8379
+ )
8380
+ );
8381
+ }
8382
+ this.#startEnvoy(config, true);
8383
+ const configuredRegistryPromise = this.#runtimeServeConfiguredPromise;
8384
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
8385
+ if (!configuredRegistryPromise || !serveLifecyclePromise) {
8386
+ throw new Error("registry envoy startup did not initialize");
8387
+ }
8388
+ let timeout;
8389
+ const timeoutPromise = new Promise((_resolve, reject) => {
8390
+ var _a;
8391
+ timeout = setTimeout(
8392
+ () => reject(
8393
+ new Error(
8394
+ `RivetKit registry did not register with the Engine within ${REGISTRY_READY_TIMEOUT_MS}ms`
8395
+ )
8396
+ ),
8397
+ REGISTRY_READY_TIMEOUT_MS
8398
+ );
8399
+ (_a = timeout.unref) == null ? void 0 : _a.call(timeout);
8400
+ });
8401
+ const readinessPromise = (async () => {
8402
+ const { runtime, registry } = await configuredRegistryPromise;
8403
+ const stoppedBeforeReady = serveLifecyclePromise.then(() => {
8404
+ throw new Error(
8405
+ "RivetKit registry stopped before becoming ready"
8406
+ );
8407
+ });
8408
+ await Promise.race([
8409
+ runtime.waitRegistryReady(registry),
8410
+ stoppedBeforeReady
8411
+ ]);
8412
+ })();
8413
+ this.#runtimeReadyPromise = Promise.race([
8414
+ readinessPromise,
8415
+ timeoutPromise
8416
+ ]).finally(() => {
8417
+ if (timeout !== void 0) clearTimeout(timeout);
8418
+ });
8419
+ this.#runtimeReadyPromise.catch(() => {
8420
+ });
8421
+ return this.#runtimeReadyPromise;
8422
+ }
6311
8423
  /**
6312
8424
  * Starts the actor envoy for standalone server deployments.
6313
8425
  *
@@ -6411,6 +8523,7 @@ export {
6411
8523
  actor,
6412
8524
  buildActorNames,
6413
8525
  createClientWithDriver,
8526
+ defineRunHandler,
6414
8527
  event,
6415
8528
  isStaticActorDefinition,
6416
8529
  isStaticActorInstance,