rivetkit 0.0.0-sqlite-profiling-compat.4a9a623 → 0.0.0-sqlite-sync-3-0-0-release.14341d0

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