rivetkit 0.0.0-main.41efcce → 0.0.0-main.49693dc

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 (299) hide show
  1. package/dist/browser/client.d.ts +939 -104
  2. package/dist/browser/client.js +1867 -900
  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 +2079 -233
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/actor/errors.cjs +6 -2
  8. package/dist/tsup/actor/errors.cjs.map +1 -1
  9. package/dist/tsup/actor/errors.d.cts +1 -74
  10. package/dist/tsup/actor/errors.d.ts +1 -74
  11. package/dist/tsup/actor/errors.js +5 -1
  12. package/dist/tsup/agent-os/index.cjs +2408 -2029
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +932 -114
  15. package/dist/tsup/agent-os/index.d.ts +932 -114
  16. package/dist/tsup/agent-os/index.js +2412 -2033
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-J27CEW6F.js → chunk-2OBVQZX6.js} +6 -6
  19. package/dist/tsup/chunk-2OBVQZX6.js.map +1 -0
  20. package/dist/tsup/chunk-3ZWHWMFJ.js +14 -0
  21. package/dist/tsup/chunk-3ZWHWMFJ.js.map +1 -0
  22. package/dist/tsup/{chunk-AK57AL7S.cjs → chunk-4KGXFC6M.cjs} +238 -22
  23. package/dist/tsup/chunk-4KGXFC6M.cjs.map +1 -0
  24. package/dist/tsup/{chunk-CVHUXINE.js → chunk-5IU3MI7X.js} +594 -72
  25. package/dist/tsup/chunk-5IU3MI7X.js.map +1 -0
  26. package/dist/tsup/{chunk-VD7AZIBR.js → chunk-6CXQMHZR.js} +1161 -361
  27. package/dist/tsup/chunk-6CXQMHZR.js.map +1 -0
  28. package/dist/tsup/{chunk-SBEFJ4IQ.js → chunk-6W2UIH3X.js} +70 -8
  29. package/dist/tsup/chunk-6W2UIH3X.js.map +1 -0
  30. package/dist/tsup/{chunk-7MRGNVSR.js → chunk-6W5VGLFT.js} +237 -21
  31. package/dist/tsup/chunk-6W5VGLFT.js.map +1 -0
  32. package/dist/tsup/{chunk-RF3MEJV6.cjs → chunk-B73TBMMG.cjs} +18 -11
  33. package/dist/tsup/chunk-B73TBMMG.cjs.map +1 -0
  34. package/dist/tsup/chunk-D6TORRA4.js +243 -0
  35. package/dist/tsup/chunk-D6TORRA4.js.map +1 -0
  36. package/dist/tsup/{chunk-PXLJOMJD.js → chunk-FXT3HN32.js} +2 -2
  37. package/dist/tsup/{chunk-ZGWSH7YV.js → chunk-IXBD7BXC.js} +48 -72
  38. package/dist/tsup/chunk-IXBD7BXC.js.map +1 -0
  39. package/dist/tsup/{chunk-3BFYSYRU.js → chunk-JI6GZ2C2.js} +4 -12
  40. package/dist/tsup/chunk-JI6GZ2C2.js.map +1 -0
  41. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-JTHHCZCZ.js} +24 -1
  42. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  43. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-KVFIONKQ.cjs} +25 -2
  44. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  45. package/dist/tsup/{chunk-SPMMF6TR.cjs → chunk-LGOWPZJ5.cjs} +3 -3
  46. package/dist/tsup/chunk-LGOWPZJ5.cjs.map +1 -0
  47. package/dist/tsup/chunk-LYNWTX6R.cjs +14 -0
  48. package/dist/tsup/chunk-LYNWTX6R.cjs.map +1 -0
  49. package/dist/tsup/{chunk-LLD2D5LO.cjs → chunk-MYWZCDML.cjs} +4 -12
  50. package/dist/tsup/chunk-MYWZCDML.cjs.map +1 -0
  51. package/dist/tsup/{chunk-XSC2WWXD.js → chunk-NYDZLWHZ.js} +16 -9
  52. package/dist/tsup/chunk-NYDZLWHZ.js.map +1 -0
  53. package/dist/tsup/{chunk-AV54CVAG.cjs → chunk-RB7WUDX6.cjs} +1290 -490
  54. package/dist/tsup/chunk-RB7WUDX6.cjs.map +1 -0
  55. package/dist/tsup/{chunk-JTL6Y2UN.cjs → chunk-SPJORZMM.cjs} +49 -73
  56. package/dist/tsup/chunk-SPJORZMM.cjs.map +1 -0
  57. package/dist/tsup/chunk-SSMKIYEX.cjs +243 -0
  58. package/dist/tsup/chunk-SSMKIYEX.cjs.map +1 -0
  59. package/dist/tsup/{chunk-TQSL4NJ3.cjs → chunk-TQ4HSX2U.cjs} +72 -10
  60. package/dist/tsup/chunk-TQ4HSX2U.cjs.map +1 -0
  61. package/dist/tsup/{chunk-EVADNK6Z.cjs → chunk-U6ZQELGJ.cjs} +10 -10
  62. package/dist/tsup/chunk-U6ZQELGJ.cjs.map +1 -0
  63. package/dist/tsup/chunk-XLBMKZD3.cjs +1257 -0
  64. package/dist/tsup/chunk-XLBMKZD3.cjs.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 +18 -7
  68. package/dist/tsup/client/mod.d.ts +18 -7
  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-B3RIidaJ.d.ts → config-BXSV17G7.d.cts} +987 -72
  79. package/dist/tsup/{config-D6WxBYjV.d.cts → config-Bi1r6gI7.d.ts} +987 -72
  80. package/dist/tsup/{config-B9qUIHX4.d.ts → config-ey2I2zz5.d.cts} +82 -15
  81. package/dist/tsup/{config-B9qUIHX4.d.cts → config-ey2I2zz5.d.ts} +82 -15
  82. package/dist/tsup/context-4fJemY0D.d.cts +129 -0
  83. package/dist/tsup/context-D4sNYboo.d.ts +129 -0
  84. package/dist/tsup/db/drizzle.cjs +168 -103
  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 +170 -105
  89. package/dist/tsup/db/drizzle.js.map +1 -1
  90. package/dist/tsup/db/mod.cjs +6 -163
  91. package/dist/tsup/db/mod.cjs.map +1 -1
  92. package/dist/tsup/db/mod.d.cts +12 -4
  93. package/dist/tsup/db/mod.d.ts +12 -4
  94. package/dist/tsup/db/mod.js +5 -162
  95. package/dist/tsup/db/mod.js.map +1 -1
  96. package/dist/tsup/dynamic/mod.cjs +24 -0
  97. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  98. package/dist/tsup/dynamic/mod.d.cts +38 -0
  99. package/dist/tsup/dynamic/mod.d.ts +38 -0
  100. package/dist/tsup/dynamic/mod.js +24 -0
  101. package/dist/tsup/dynamic/mod.js.map +1 -0
  102. package/dist/tsup/inspector/mod.cjs +47 -12
  103. package/dist/tsup/inspector/mod.cjs.map +1 -1
  104. package/dist/tsup/inspector/mod.d.cts +26 -136
  105. package/dist/tsup/inspector/mod.d.ts +26 -136
  106. package/dist/tsup/inspector/mod.js +46 -11
  107. package/dist/tsup/inspector/mod.js.map +1 -1
  108. package/dist/tsup/inspector/workflow.cjs +21 -0
  109. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  110. package/dist/tsup/inspector/workflow.d.cts +144 -0
  111. package/dist/tsup/inspector/workflow.d.ts +144 -0
  112. package/dist/tsup/inspector/workflow.js +21 -0
  113. package/dist/tsup/inspector/workflow.js.map +1 -0
  114. package/dist/tsup/inspector-tab/mod.cjs +162 -0
  115. package/dist/tsup/inspector-tab/mod.cjs.map +1 -0
  116. package/dist/tsup/inspector-tab/mod.d.cts +241 -0
  117. package/dist/tsup/inspector-tab/mod.d.ts +241 -0
  118. package/dist/tsup/inspector-tab/mod.js +162 -0
  119. package/dist/tsup/inspector-tab/mod.js.map +1 -0
  120. package/dist/tsup/mod.cjs +4268 -944
  121. package/dist/tsup/mod.cjs.map +1 -1
  122. package/dist/tsup/mod.d.cts +9 -8
  123. package/dist/tsup/mod.d.ts +9 -8
  124. package/dist/tsup/mod.js +4229 -905
  125. package/dist/tsup/mod.js.map +1 -1
  126. package/dist/tsup/test/mod.cjs +26 -21
  127. package/dist/tsup/test/mod.cjs.map +1 -1
  128. package/dist/tsup/test/mod.d.cts +7 -6
  129. package/dist/tsup/test/mod.d.ts +7 -6
  130. package/dist/tsup/test/mod.js +25 -20
  131. package/dist/tsup/test/mod.js.map +1 -1
  132. package/dist/tsup/unstable/migrations.cjs +101 -0
  133. package/dist/tsup/unstable/migrations.cjs.map +1 -0
  134. package/dist/tsup/unstable/migrations.d.cts +29 -0
  135. package/dist/tsup/unstable/migrations.d.ts +29 -0
  136. package/dist/tsup/unstable/migrations.js +101 -0
  137. package/dist/tsup/unstable/migrations.js.map +1 -0
  138. package/dist/tsup/utils-Bbz-3411.d.cts +162 -0
  139. package/dist/tsup/utils-BqdWVlzm.d.ts +162 -0
  140. package/dist/tsup/utils-vvJQyygr.d.cts +109 -0
  141. package/dist/tsup/utils-vvJQyygr.d.ts +109 -0
  142. package/dist/tsup/utils.cjs +7 -3
  143. package/dist/tsup/utils.cjs.map +1 -1
  144. package/dist/tsup/utils.d.cts +4 -147
  145. package/dist/tsup/utils.d.ts +4 -147
  146. package/dist/tsup/utils.js +6 -2
  147. package/dist/tsup/workflow/mod.cjs +517 -412
  148. package/dist/tsup/workflow/mod.cjs.map +1 -1
  149. package/dist/tsup/workflow/mod.d.cts +11 -10
  150. package/dist/tsup/workflow/mod.d.ts +11 -10
  151. package/dist/tsup/workflow/mod.js +511 -406
  152. package/dist/tsup/workflow/mod.js.map +1 -1
  153. package/package.json +62 -14
  154. package/src/actor/actions.ts +119 -0
  155. package/src/actor/config.test.ts +78 -0
  156. package/src/actor/config.ts +518 -96
  157. package/src/actor/contexts/index.ts +7 -2
  158. package/src/actor/definition.ts +38 -26
  159. package/src/actor/errors.ts +101 -89
  160. package/src/actor/keys.ts +2 -1
  161. package/src/actor/mod.ts +32 -21
  162. package/src/actor/schema.ts +2 -2
  163. package/src/agent-os/actor/cron.ts +37 -2
  164. package/src/agent-os/actor/index.ts +39 -19
  165. package/src/agent-os/actor/preview.ts +1 -2
  166. package/src/agent-os/actor/session.ts +2 -2
  167. package/src/agent-os/config.ts +1 -1
  168. package/src/agent-os/fs/database-vfs.ts +1 -1
  169. package/src/agent-os/index.ts +16 -15
  170. package/src/agent-os/types.ts +11 -0
  171. package/src/client/actor-common.ts +106 -53
  172. package/src/client/actor-conn.ts +94 -45
  173. package/src/client/actor-handle.ts +198 -79
  174. package/src/client/actor-query.ts +13 -6
  175. package/src/client/client.ts +43 -15
  176. package/src/client/config.ts +8 -0
  177. package/src/client/errors.ts +4 -2
  178. package/src/client/lifecycle-errors.ts +28 -4
  179. package/src/client/mod.ts +9 -4
  180. package/src/client/query.ts +3 -1
  181. package/src/client/queue.ts +8 -3
  182. package/src/client/raw-utils.ts +24 -16
  183. package/src/client/resolve-gateway-target.ts +3 -1
  184. package/src/client/utils.ts +36 -10
  185. package/src/common/actor-router-consts.ts +7 -0
  186. package/src/common/actor-websocket.ts +3 -1
  187. package/src/common/bare/actor-persist/v1.ts +205 -163
  188. package/src/common/bare/actor-persist/v2.ts +265 -213
  189. package/src/common/bare/actor-persist/v3.ts +176 -172
  190. package/src/common/bare/actor-persist/v4.ts +254 -253
  191. package/src/common/bare/generated/actor-runtime-socket-protocol/v1.ts +848 -0
  192. package/src/common/bare/generated/client-protocol/v4.ts +599 -0
  193. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  194. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  195. package/src/common/bare/transport/v1.ts +694 -542
  196. package/src/common/client-protocol-versioned.ts +176 -67
  197. package/src/common/client-protocol-zod.ts +7 -0
  198. package/src/common/client-protocol.ts +1 -1
  199. package/src/common/database/config.ts +103 -10
  200. package/src/common/database/mod.test.ts +364 -0
  201. package/src/common/database/mod.ts +278 -149
  202. package/src/common/database/native-database.test.ts +220 -0
  203. package/src/common/database/native-database.ts +394 -58
  204. package/src/common/database/shared.ts +25 -0
  205. package/src/common/encoding.ts +302 -38
  206. package/src/common/engine.ts +28 -1
  207. package/src/common/eventsource.ts +1 -1
  208. package/src/common/fetch-like.ts +49 -0
  209. package/src/common/inline-websocket-adapter.ts +14 -13
  210. package/src/common/inspector-transport.ts +12 -2
  211. package/src/common/log.ts +117 -14
  212. package/src/common/router.ts +49 -23
  213. package/src/common/utils.ts +23 -203
  214. package/src/common/websocket-interface.ts +1 -1
  215. package/src/db/drizzle.test.ts +164 -0
  216. package/src/db/drizzle.ts +207 -121
  217. package/src/db/mod.ts +6 -1
  218. package/src/devtools-loader/index.ts +4 -7
  219. package/src/devtools-loader/serve-devtools.ts +26 -0
  220. package/src/dynamic/instance.ts +32 -0
  221. package/src/dynamic/internal.ts +50 -0
  222. package/src/dynamic/isolate-runtime.ts +64 -0
  223. package/src/dynamic/mod.ts +32 -0
  224. package/src/engine-client/actor-http-client.ts +23 -4
  225. package/src/engine-client/actor-websocket-client.ts +32 -5
  226. package/src/engine-client/api-endpoints.ts +52 -2
  227. package/src/engine-client/api-utils.ts +2 -2
  228. package/src/engine-client/driver.ts +21 -17
  229. package/src/engine-client/mod.ts +116 -64
  230. package/src/engine-client/ws-proxy.ts +9 -4
  231. package/src/globals.d.ts +4 -0
  232. package/src/inspector/client.browser.ts +127 -15
  233. package/src/inspector/mod.ts +2 -4
  234. package/src/inspector/workflow.ts +61 -0
  235. package/src/inspector-tab/mod.ts +301 -0
  236. package/src/registry/config/envoy.ts +1 -2
  237. package/src/registry/config/index.ts +160 -53
  238. package/src/registry/config/serverless.ts +7 -1
  239. package/src/registry/index.ts +659 -96
  240. package/src/registry/napi-runtime.ts +1154 -0
  241. package/src/registry/native-validation.ts +10 -12
  242. package/src/registry/native.ts +2005 -955
  243. package/src/registry/process-metrics.ts +250 -0
  244. package/src/registry/run-handler-coordinator.test.ts +252 -0
  245. package/src/registry/run-handler-coordinator.ts +219 -0
  246. package/src/registry/runtime.test.ts +50 -0
  247. package/src/registry/runtime.ts +839 -0
  248. package/src/registry/wasm-runtime.ts +1283 -0
  249. package/src/registry/write-through-proxy.ts +141 -0
  250. package/src/serde.ts +8 -2
  251. package/src/serverless/configure.ts +102 -49
  252. package/src/test/mod.ts +2 -17
  253. package/src/test/ready.ts +22 -0
  254. package/src/unstable/migrations.test.ts +170 -0
  255. package/src/unstable/migrations.ts +141 -0
  256. package/src/utils/crypto.ts +14 -0
  257. package/src/utils/endpoint-parser.ts +1 -1
  258. package/src/utils/env-vars.ts +39 -0
  259. package/src/utils/node.ts +44 -28
  260. package/src/utils/router.ts +1 -1
  261. package/src/utils.ts +4 -2
  262. package/src/workflow/context.ts +683 -242
  263. package/src/workflow/driver.test.ts +62 -0
  264. package/src/workflow/driver.ts +246 -119
  265. package/src/workflow/inspector.ts +24 -24
  266. package/src/workflow/mod.ts +76 -84
  267. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  268. package/dist/tsup/chunk-3BFYSYRU.js.map +0 -1
  269. package/dist/tsup/chunk-6AVUJ52Q.cjs +0 -253
  270. package/dist/tsup/chunk-6AVUJ52Q.cjs.map +0 -1
  271. package/dist/tsup/chunk-7MRGNVSR.js.map +0 -1
  272. package/dist/tsup/chunk-7X7RVTFF.cjs +0 -735
  273. package/dist/tsup/chunk-7X7RVTFF.cjs.map +0 -1
  274. package/dist/tsup/chunk-AK57AL7S.cjs.map +0 -1
  275. package/dist/tsup/chunk-AV54CVAG.cjs.map +0 -1
  276. package/dist/tsup/chunk-CVHUXINE.js.map +0 -1
  277. package/dist/tsup/chunk-EVADNK6Z.cjs.map +0 -1
  278. package/dist/tsup/chunk-J27CEW6F.js.map +0 -1
  279. package/dist/tsup/chunk-JTL6Y2UN.cjs.map +0 -1
  280. package/dist/tsup/chunk-LLD2D5LO.cjs.map +0 -1
  281. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  282. package/dist/tsup/chunk-RF3MEJV6.cjs.map +0 -1
  283. package/dist/tsup/chunk-SB4MXRN2.js +0 -253
  284. package/dist/tsup/chunk-SB4MXRN2.js.map +0 -1
  285. package/dist/tsup/chunk-SBEFJ4IQ.js.map +0 -1
  286. package/dist/tsup/chunk-SPMMF6TR.cjs.map +0 -1
  287. package/dist/tsup/chunk-TQSL4NJ3.cjs.map +0 -1
  288. package/dist/tsup/chunk-VD7AZIBR.js.map +0 -1
  289. package/dist/tsup/chunk-XSC2WWXD.js.map +0 -1
  290. package/dist/tsup/chunk-ZGWSH7YV.js.map +0 -1
  291. package/dist/tsup/context-BxvHh9wi.d.cts +0 -92
  292. package/dist/tsup/context-CNIZBIKl.d.ts +0 -92
  293. package/dist/tsup/utils-fwx3o3K9.d.cts +0 -18
  294. package/dist/tsup/utils-fwx3o3K9.d.ts +0 -18
  295. package/src/actor/driver.ts +0 -141
  296. package/src/actor/instance/mod.ts +0 -2501
  297. package/src/drivers/engine/actor-driver.ts +0 -2470
  298. package/src/utils/serve.ts +0 -217
  299. /package/dist/tsup/{chunk-PXLJOMJD.js.map → chunk-FXT3HN32.js.map} +0 -0
@@ -1,22 +1,23 @@
1
1
  import {
2
2
  createWorkflowInspectorAdapter
3
- } from "../chunk-XSC2WWXD.js";
3
+ } from "../chunk-NYDZLWHZ.js";
4
+ import "../chunk-3ZWHWMFJ.js";
5
+ import "../chunk-6W2UIH3X.js";
4
6
  import {
5
7
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
6
- RUN_FUNCTION_CONFIG_SYMBOL
7
- } from "../chunk-7MRGNVSR.js";
8
- import "../chunk-SBEFJ4IQ.js";
8
+ defineRunHandler
9
+ } from "../chunk-6W5VGLFT.js";
9
10
  import {
10
11
  makeWorkflowKey,
11
12
  workflowStoragePrefix
12
- } from "../chunk-3BFYSYRU.js";
13
- import "../chunk-SB4MXRN2.js";
13
+ } from "../chunk-JI6GZ2C2.js";
14
14
  import {
15
15
  stringifyError
16
- } from "../chunk-CVHUXINE.js";
16
+ } from "../chunk-5IU3MI7X.js";
17
17
  import {
18
- RivetError
19
- } from "../chunk-ZGWSH7YV.js";
18
+ RivetError,
19
+ isActorAbortedError
20
+ } from "../chunk-IXBD7BXC.js";
20
21
 
21
22
  // src/workflow/mod.ts
22
23
  import {
@@ -25,287 +26,109 @@ import {
25
26
  HistoryDivergedError,
26
27
  JoinError,
27
28
  RaceError,
28
- replayWorkflowFromStep,
29
29
  RollbackCheckpointError,
30
30
  RollbackError,
31
+ replayWorkflowFromStep,
31
32
  runWorkflow,
32
33
  StepExhaustedError
33
34
  } from "@rivetkit/workflow-engine";
34
35
  import invariant from "invariant";
35
36
 
36
- // src/workflow/driver.ts
37
- var WORKFLOW_STORAGE_PREFIX = workflowStoragePrefix();
38
- function stripWorkflowKey(prefixed) {
39
- return prefixed.slice(WORKFLOW_STORAGE_PREFIX.length);
40
- }
41
- function computeUpperBound(prefix) {
42
- const upperBound = prefix.slice();
43
- for (let i = upperBound.length - 1; i >= 0; i--) {
44
- if (upperBound[i] !== 255) {
45
- upperBound[i]++;
46
- return upperBound.slice(0, i + 1);
47
- }
48
- }
49
- return null;
50
- }
51
- var ActorWorkflowMessageDriver = class {
52
- #actor;
53
- #runCtx;
54
- constructor(actor, runCtx) {
55
- this.#actor = actor;
56
- this.#runCtx = runCtx;
57
- }
58
- async addMessage(message) {
59
- await this.#runCtx.internalKeepAwake(
60
- this.#actor.queueManager.enqueue(message.name, message.data)
61
- );
62
- }
63
- async receiveMessages(opts) {
64
- const messages = await this.#runCtx.internalKeepAwake(
65
- this.#actor.queueManager.receive(
66
- opts.names && opts.names.length > 0 ? [...opts.names] : void 0,
67
- opts.count,
68
- 0,
69
- void 0,
70
- opts.completable
71
- )
72
- );
73
- return messages.map((message) => ({
74
- id: message.id.toString(),
75
- name: message.name,
76
- data: message.body,
77
- sentAt: message.createdAt,
78
- ...opts.completable ? {
79
- complete: async (response) => {
80
- await this.#runCtx.internalKeepAwake(
81
- this.#actor.queueManager.completeMessage(
82
- message,
83
- response
84
- )
85
- );
86
- }
87
- } : {}
88
- }));
89
- }
90
- async completeMessage(messageId, response) {
91
- let parsedId;
92
- try {
93
- parsedId = BigInt(messageId);
94
- } catch {
95
- return;
96
- }
97
- await this.#runCtx.internalKeepAwake(
98
- this.#actor.queueManager.completeMessageById(parsedId, response)
99
- );
100
- }
101
- };
102
- var ActorWorkflowDriver = class {
103
- workerPollInterval = 100;
104
- messageDriver;
105
- #actor;
37
+ // src/workflow/constants.ts
38
+ var WORKFLOW_GUARD_KV_KEY = "__rivet_actor_workflow_guard_triggered";
39
+
40
+ // src/workflow/context.ts
41
+ var DEACTIVATE_STEP = /* @__PURE__ */ Symbol("workflow.step.deactivate");
42
+ var WorkflowStepContext = class {
106
43
  #runCtx;
107
- constructor(actor, runCtx) {
108
- this.#actor = actor;
44
+ #active = true;
45
+ #onGuardViolation;
46
+ constructor(runCtx, onGuardViolation) {
109
47
  this.#runCtx = runCtx;
110
- this.messageDriver = new ActorWorkflowMessageDriver(actor, runCtx);
111
- }
112
- async get(key) {
113
- const [value] = await this.#runCtx.internalKeepAwake(
114
- this.#actor.driver.kvBatchGet(this.#actor.id, [
115
- makeWorkflowKey(key)
116
- ])
117
- );
118
- return value ?? null;
119
- }
120
- async set(key, value) {
121
- await this.#runCtx.internalKeepAwake(
122
- this.#actor.driver.kvBatchPut(this.#actor.id, [
123
- [makeWorkflowKey(key), value]
124
- ])
125
- );
48
+ this.#onGuardViolation = onGuardViolation;
126
49
  }
127
- async delete(key) {
128
- await this.#runCtx.internalKeepAwake(
129
- this.#actor.driver.kvBatchDelete(this.#actor.id, [
130
- makeWorkflowKey(key)
131
- ])
132
- );
50
+ [DEACTIVATE_STEP]() {
51
+ this.#active = false;
133
52
  }
134
- async deletePrefix(prefix) {
135
- const start = makeWorkflowKey(prefix);
136
- const end = computeUpperBound(start);
137
- if (end) {
138
- await this.#runCtx.internalKeepAwake(
139
- this.#actor.driver.kvDeleteRange(this.#actor.id, start, end)
140
- );
141
- } else {
142
- const entries = await this.#runCtx.internalKeepAwake(
143
- this.#actor.driver.kvListPrefix(this.#actor.id, start)
144
- );
145
- if (entries.length === 0) {
146
- return;
147
- }
148
- await this.#runCtx.internalKeepAwake(
149
- this.#actor.driver.kvBatchDelete(
150
- this.#actor.id,
151
- entries.map(([key]) => key)
152
- )
53
+ #ensureActive(feature) {
54
+ if (!this.#active) {
55
+ this.#onGuardViolation();
56
+ throw new Error(
57
+ `${feature} is only available inside workflow steps`
153
58
  );
154
59
  }
155
60
  }
156
- async deleteRange(start, end) {
157
- await this.#runCtx.internalKeepAwake(
158
- this.#actor.driver.kvDeleteRange(
159
- this.#actor.id,
160
- makeWorkflowKey(start),
161
- makeWorkflowKey(end)
162
- )
163
- );
164
- }
165
- async list(prefix) {
166
- const entries = await this.#runCtx.internalKeepAwake(
167
- this.#actor.driver.kvListPrefix(
168
- this.#actor.id,
169
- makeWorkflowKey(prefix)
170
- )
171
- );
172
- return entries.map(([key, value]) => ({
173
- key: stripWorkflowKey(key),
174
- value
175
- }));
176
- }
177
- async batch(writes) {
178
- if (writes.length === 0) return;
179
- await this.#runCtx.internalKeepAwake(
180
- Promise.all([
181
- this.#actor.driver.kvBatchPut(
182
- this.#actor.id,
183
- writes.map(({ key, value }) => [
184
- makeWorkflowKey(key),
185
- value
186
- ])
187
- ),
188
- this.#actor.stateManager.saveState({
189
- immediate: true
190
- })
191
- ])
192
- );
193
- }
194
- async setAlarm(_workflowId, wakeAt) {
195
- await this.#runCtx.internalKeepAwake(
196
- this.#actor.driver.setAlarm(this.#actor, wakeAt)
197
- );
198
- }
199
- async clearAlarm(_workflowId) {
200
- return;
201
- }
202
- waitForMessages(messageNames, abortSignal) {
203
- return this.#actor.queueManager.waitForNames(
204
- messageNames.length > 0 ? messageNames : void 0,
205
- abortSignal
206
- );
207
- }
208
- };
209
- var NoopWorkflowMessageDriver = class {
210
- async addMessage(_message) {
211
- throw new Error("Workflow control driver does not support messages");
61
+ get actorId() {
62
+ return this.#runCtx.actorId;
212
63
  }
213
- async receiveMessages(_opts) {
214
- throw new Error("Workflow control driver does not support messages");
64
+ get name() {
65
+ return this.#runCtx.name;
215
66
  }
216
- async completeMessage(_messageId, _response) {
217
- throw new Error("Workflow control driver does not support messages");
67
+ get key() {
68
+ return this.#runCtx.key;
218
69
  }
219
- };
220
- var ActorWorkflowControlDriver = class {
221
- workerPollInterval = 100;
222
- messageDriver = new NoopWorkflowMessageDriver();
223
- #actor;
224
- constructor(actor) {
225
- this.#actor = actor;
70
+ get log() {
71
+ return this.#runCtx.log;
226
72
  }
227
- async get(key) {
228
- const [value] = await this.#actor.driver.kvBatchGet(this.#actor.id, [
229
- makeWorkflowKey(key)
230
- ]);
231
- return value ?? null;
73
+ get abortSignal() {
74
+ return this.#runCtx.abortSignal;
232
75
  }
233
- async set(key, value) {
234
- await this.#actor.driver.kvBatchPut(this.#actor.id, [
235
- [makeWorkflowKey(key), value]
236
- ]);
76
+ get state() {
77
+ this.#ensureActive("state");
78
+ return this.#runCtx.state;
237
79
  }
238
- async delete(key) {
239
- await this.#actor.driver.kvBatchDelete(this.#actor.id, [
240
- makeWorkflowKey(key)
241
- ]);
80
+ get vars() {
81
+ this.#ensureActive("vars");
82
+ return this.#runCtx.vars;
242
83
  }
243
- async deletePrefix(prefix) {
244
- const start = makeWorkflowKey(prefix);
245
- const end = computeUpperBound(start);
246
- if (end) {
247
- await this.#actor.driver.kvDeleteRange(this.#actor.id, start, end);
248
- return;
249
- }
250
- const entries = await this.#actor.driver.kvListPrefix(
251
- this.#actor.id,
252
- start
253
- );
254
- if (entries.length === 0) {
255
- return;
256
- }
257
- await this.#actor.driver.kvBatchDelete(
258
- this.#actor.id,
259
- entries.map(([key]) => key)
260
- );
84
+ get db() {
85
+ this.#ensureActive("db");
86
+ return this.#runCtx.db;
261
87
  }
262
- async deleteRange(start, end) {
263
- await this.#actor.driver.kvDeleteRange(
264
- this.#actor.id,
265
- makeWorkflowKey(start),
266
- makeWorkflowKey(end)
267
- );
88
+ client() {
89
+ this.#ensureActive("client");
90
+ return this.#runCtx.client();
268
91
  }
269
- async list(prefix) {
270
- const entries = await this.#actor.driver.kvListPrefix(
271
- this.#actor.id,
272
- makeWorkflowKey(prefix)
92
+ broadcast(name, ...args) {
93
+ this.#ensureActive("broadcast");
94
+ this.#runCtx.broadcast(
95
+ name,
96
+ ...args
273
97
  );
274
- return entries.map(([key, value]) => ({
275
- key: stripWorkflowKey(key),
276
- value
277
- }));
278
98
  }
279
- async batch(writes) {
280
- if (writes.length === 0) {
281
- return;
99
+ get queue() {
100
+ const self = this;
101
+ async function send(name, body) {
102
+ self.#ensureActive("queue.send");
103
+ await self.#runCtx.queue.send(name, body);
282
104
  }
283
- await this.#actor.driver.kvBatchPut(
284
- this.#actor.id,
285
- writes.map(({ key, value }) => [makeWorkflowKey(key), value])
286
- );
105
+ return { send };
287
106
  }
288
- async setAlarm(_workflowId, wakeAt) {
289
- await this.#actor.driver.setAlarm(this.#actor, wakeAt);
107
+ /**
108
+ * Holds the actor awake for the duration of the provided promise. The actor
109
+ * cannot idle-sleep or finalize the sleep grace period until the promise
110
+ * settles.
111
+ */
112
+ keepAwake(promise) {
113
+ this.#ensureActive("keepAwake");
114
+ return this.#runCtx.keepAwake(promise);
290
115
  }
291
- async clearAlarm(_workflowId) {
292
- return;
116
+ /**
117
+ * Registers a promise that the sleep grace period will wait on. Use this for
118
+ * best-effort flush/cleanup work that may complete inside the grace window.
119
+ */
120
+ waitUntil(promise) {
121
+ this.#ensureActive("waitUntil");
122
+ this.#runCtx.waitUntil(promise);
293
123
  }
294
- waitForMessages(_messageNames, _abortSignal) {
295
- throw new Error("Workflow control driver does not support messages");
124
+ destroy() {
125
+ this.#ensureActive("destroy");
126
+ this.#runCtx.destroy();
296
127
  }
297
128
  };
298
-
299
- // src/workflow/constants.ts
300
- var WORKFLOW_GUARD_KV_KEY = "__rivet_actor_workflow_guard_triggered";
301
-
302
- // src/workflow/context.ts
303
- var ActorWorkflowContext = class _ActorWorkflowContext {
129
+ var WorkflowContext = class _WorkflowContext {
304
130
  #inner;
305
131
  #runCtx;
306
- #actorAccessDepth = 0;
307
- #allowActorAccess = false;
308
- #guardViolation = false;
309
132
  constructor(inner, runCtx) {
310
133
  this.#inner = inner;
311
134
  this.#runCtx = runCtx;
@@ -316,6 +139,18 @@ var ActorWorkflowContext = class _ActorWorkflowContext {
316
139
  get abortSignal() {
317
140
  return this.#inner.abortSignal;
318
141
  }
142
+ get actorId() {
143
+ return this.#runCtx.actorId;
144
+ }
145
+ get name() {
146
+ return this.#runCtx.name;
147
+ }
148
+ get key() {
149
+ return this.#runCtx.key;
150
+ }
151
+ get log() {
152
+ return this.#runCtx.log;
153
+ }
319
154
  get queue() {
320
155
  const self = this;
321
156
  async function next(name, opts) {
@@ -328,14 +163,9 @@ var ActorWorkflowContext = class _ActorWorkflowContext {
328
163
  (message) => self.#toActorQueueMessage(message)
329
164
  );
330
165
  }
331
- async function send(name, body) {
332
- self.#ensureActorAccess("queue.send");
333
- await self.#runCtx.queue.send(name, body);
334
- }
335
166
  return {
336
167
  next,
337
- nextBatch,
338
- send
168
+ nextBatch
339
169
  };
340
170
  }
341
171
  async step(nameOrConfig, run) {
@@ -343,17 +173,17 @@ var ActorWorkflowContext = class _ActorWorkflowContext {
343
173
  if (!run) {
344
174
  throw new Error("Step run function missing");
345
175
  }
176
+ const stepRun = run;
346
177
  return await this.#wrapActive(
347
- () => this.#inner.step(
348
- nameOrConfig,
349
- () => this.#withActorAccess(run)
350
- )
178
+ () => this.#inner.step(nameOrConfig, () => this.#runStep(stepRun))
351
179
  );
352
180
  }
353
181
  const stepConfig = nameOrConfig;
182
+ const rollback = stepConfig.rollback;
354
183
  const config = {
355
184
  ...stepConfig,
356
- run: () => this.#withActorAccess(stepConfig.run)
185
+ run: () => this.#runStep(stepConfig.run),
186
+ rollback: rollback ? (_ctx, output) => this.#runRollback(rollback, output) : void 0
357
187
  };
358
188
  return await this.#wrapActive(() => this.#inner.step(config));
359
189
  }
@@ -362,17 +192,17 @@ var ActorWorkflowContext = class _ActorWorkflowContext {
362
192
  if (!run) {
363
193
  throw new Error("Step run function missing");
364
194
  }
195
+ const stepRun = run;
365
196
  return await this.#wrapActive(
366
- () => this.#inner.tryStep(
367
- nameOrConfig,
368
- () => this.#withActorAccess(run)
369
- )
197
+ () => this.#inner.tryStep(nameOrConfig, () => this.#runStep(stepRun))
370
198
  );
371
199
  }
372
200
  const stepConfig = nameOrConfig;
201
+ const rollback = stepConfig.rollback;
373
202
  const config = {
374
203
  ...stepConfig,
375
- run: () => this.#withActorAccess(stepConfig.run)
204
+ run: () => this.#runStep(stepConfig.run),
205
+ rollback: rollback ? (_ctx, output) => this.#runRollback(rollback, output) : void 0
376
206
  };
377
207
  return await this.#wrapActive(() => this.#inner.tryStep(config));
378
208
  }
@@ -381,10 +211,11 @@ var ActorWorkflowContext = class _ActorWorkflowContext {
381
211
  if (!run) {
382
212
  throw new Error("Try run function missing");
383
213
  }
214
+ const tryRun = run;
384
215
  return await this.#wrapActive(
385
216
  () => this.#inner.try(
386
217
  nameOrConfig,
387
- async (ctx) => run(this.#createChildContext(ctx))
218
+ async (ctx) => tryRun(this.#createChildContext(ctx))
388
219
  )
389
220
  );
390
221
  }
@@ -400,16 +231,20 @@ var ActorWorkflowContext = class _ActorWorkflowContext {
400
231
  if (!run) {
401
232
  throw new Error("Loop run function missing");
402
233
  }
234
+ const loopRun = run;
403
235
  return await this.#wrapActive(
404
236
  () => this.#inner.loop(
405
237
  nameOrConfig,
406
- async (ctx) => run(this.#createChildContext(ctx))
238
+ // A void return (no explicit Loop result) is undefined at
239
+ // runtime, which the engine treats as continue.
240
+ async (ctx) => await loopRun(this.#createChildContext(ctx)) ?? void 0
407
241
  )
408
242
  );
409
243
  }
244
+ const loopConfig = nameOrConfig;
410
245
  const wrapped = {
411
- ...nameOrConfig,
412
- run: async (ctx, state) => nameOrConfig.run(this.#createChildContext(ctx), state)
246
+ ...loopConfig,
247
+ run: (async (ctx, state) => await loopConfig.run(this.#createChildContext(ctx), state) ?? void 0)
413
248
  };
414
249
  return await this.#wrapActive(() => this.#inner.loop(wrapped));
415
250
  }
@@ -419,10 +254,6 @@ var ActorWorkflowContext = class _ActorWorkflowContext {
419
254
  sleepUntil(name, timestampMs) {
420
255
  return this.#inner.sleepUntil(name, timestampMs);
421
256
  }
422
- destroy() {
423
- this.#ensureActorAccess("destroy");
424
- this.#runCtx.destroy();
425
- }
426
257
  async rollbackCheckpoint(name) {
427
258
  await this.#wrapActive(() => this.#inner.rollbackCheckpoint(name));
428
259
  }
@@ -451,65 +282,22 @@ var ActorWorkflowContext = class _ActorWorkflowContext {
451
282
  async removed(name, originalType) {
452
283
  await this.#wrapActive(() => this.#inner.removed(name, originalType));
453
284
  }
285
+ getVersion(name, latest) {
286
+ return this.#wrapActive(() => this.#inner.getVersion(name, latest));
287
+ }
454
288
  isEvicted() {
455
289
  return this.#inner.isEvicted();
456
290
  }
457
- get state() {
458
- this.#ensureActorAccess("state");
459
- return this.#runCtx.state;
460
- }
461
- get vars() {
462
- this.#ensureActorAccess("vars");
463
- return this.#runCtx.vars;
464
- }
465
- client() {
466
- this.#ensureActorAccess("client");
467
- return this.#runCtx.client();
468
- }
469
- get db() {
470
- this.#ensureActorAccess("db");
471
- return this.#runCtx.db;
472
- }
473
- get log() {
474
- return this.#runCtx.log;
475
- }
476
- /** @deprecated No-op. Use `keepAwake(promise)` or `waitUntil(promise)` instead. */
477
- setPreventSleep(_prevent) {
478
- this.#ensureActorAccess("setPreventSleep");
479
- }
480
- /** @deprecated No-op. Always returns `false`. */
481
- get preventSleep() {
482
- this.#ensureActorAccess("preventSleep");
483
- return false;
484
- }
485
- /**
486
- * Holds the actor awake for the duration of the provided promise. The
487
- * actor cannot idle-sleep or finalize the sleep grace period until the
488
- * promise settles.
489
- */
490
- keepAwake(promise) {
491
- this.#ensureActorAccess("keepAwake");
492
- return this.#runCtx.keepAwake(promise);
493
- }
494
- /**
495
- * Registers a promise that the sleep grace period will wait on. Use this
496
- * for best-effort flush/cleanup work that may complete inside the grace
497
- * window. For work the actor must stay running through, prefer
498
- * `c.keepAwake(promise)` which also blocks idle sleep.
499
- */
500
- waitUntil(promise) {
501
- this.#ensureActorAccess("waitUntil");
502
- this.#runCtx.waitUntil(promise);
503
- }
504
- get actorId() {
505
- return this.#runCtx.actorId;
506
- }
507
- broadcast(name, ...args) {
508
- this.#ensureActorAccess("broadcast");
509
- this.#runCtx.broadcast(
510
- name,
511
- ...args
512
- );
291
+ // Runs a user step body inside a fresh step context and deactivates the step
292
+ // context once the body settles. Workflows are roll-forward only, so state and
293
+ // vars mutations made before a failure always remain visible.
294
+ async #runStep(run) {
295
+ const stepCtx = new WorkflowStepContext(this.#runCtx, () => this.#markGuardTriggered());
296
+ try {
297
+ return await run(stepCtx);
298
+ } finally {
299
+ stepCtx[DEACTIVATE_STEP]();
300
+ }
513
301
  }
514
302
  #toActorQueueMessage(message) {
515
303
  let id;
@@ -526,37 +314,20 @@ var ActorWorkflowContext = class _ActorWorkflowContext {
526
314
  ...message.complete ? { complete: message.complete } : {}
527
315
  };
528
316
  }
529
- async #wrapActive(run) {
530
- return await this.#runCtx.internalKeepAwake(run);
531
- }
532
- async #withActorAccess(run) {
533
- this.#actorAccessDepth++;
534
- if (this.#actorAccessDepth === 1) {
535
- this.#allowActorAccess = true;
536
- }
317
+ // Runs a step rollback compensation with an active step context.
318
+ async #runRollback(rollback, output) {
319
+ const stepCtx = new WorkflowStepContext(this.#runCtx, () => this.#markGuardTriggered());
537
320
  try {
538
- return await run();
321
+ await rollback(stepCtx, output);
539
322
  } finally {
540
- this.#actorAccessDepth--;
541
- if (this.#actorAccessDepth === 0) {
542
- this.#allowActorAccess = false;
543
- }
544
- }
545
- }
546
- #ensureActorAccess(feature) {
547
- if (!this.#allowActorAccess) {
548
- this.#guardViolation = true;
549
- this.#markGuardTriggered();
550
- throw new Error(
551
- `${feature} is only available inside workflow steps`
552
- );
323
+ stepCtx[DEACTIVATE_STEP]();
553
324
  }
554
325
  }
555
- consumeGuardViolation() {
556
- const violated = this.#guardViolation;
557
- this.#guardViolation = false;
558
- return violated;
326
+ async #wrapActive(run) {
327
+ return await this.#runCtx.internalKeepAwake(run);
559
328
  }
329
+ // Records that a step context was used outside its step. Mirrors the value
330
+ // onto actor state and a KV flag so callers can observe the violation.
560
331
  #markGuardTriggered() {
561
332
  try {
562
333
  const state = this.#runCtx.state;
@@ -579,7 +350,346 @@ var ActorWorkflowContext = class _ActorWorkflowContext {
579
350
  );
580
351
  }
581
352
  #createChildContext(ctx) {
582
- return new _ActorWorkflowContext(ctx, this.#runCtx);
353
+ return new _WorkflowContext(ctx, this.#runCtx);
354
+ }
355
+ };
356
+
357
+ // src/workflow/driver.ts
358
+ var WORKFLOW_STORAGE_PREFIX = workflowStoragePrefix();
359
+ var WORKFLOW_SQLITE_MAX_BATCH_ROWS = 128;
360
+ var WORKFLOW_SQLITE_MAX_BATCH_BYTES = 512 * 1024;
361
+ function stripWorkflowKey(prefixed) {
362
+ return prefixed.slice(WORKFLOW_STORAGE_PREFIX.length);
363
+ }
364
+ function computeUpperBound(prefix) {
365
+ const upperBound = prefix.slice();
366
+ for (let i = upperBound.length - 1; i >= 0; i--) {
367
+ if (upperBound[i] !== 255) {
368
+ upperBound[i]++;
369
+ return upperBound.slice(0, i + 1);
370
+ }
371
+ }
372
+ return null;
373
+ }
374
+ function normalizeSqlBlob(value) {
375
+ if (value instanceof Uint8Array) {
376
+ return value;
377
+ }
378
+ if (value instanceof ArrayBuffer) {
379
+ return new Uint8Array(value);
380
+ }
381
+ if (ArrayBuffer.isView(value)) {
382
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
383
+ }
384
+ if (Array.isArray(value)) {
385
+ const bytes = new Uint8Array(value.length);
386
+ for (const [i, item] of value.entries()) {
387
+ if (!Number.isInteger(item) || item < 0 || item > 255) {
388
+ throw new Error("workflow sqlite value was not a byte array");
389
+ }
390
+ bytes[i] = item;
391
+ }
392
+ return bytes;
393
+ }
394
+ throw new Error("workflow sqlite value was not a blob");
395
+ }
396
+ function runtimeDbFromContext(runCtx) {
397
+ const db = runCtx == null ? void 0 : runCtx.db;
398
+ if (db && typeof db === "object" && "execute" in db && "transaction" in db) {
399
+ return db;
400
+ }
401
+ return void 0;
402
+ }
403
+ var WorkflowStorage = class {
404
+ #db;
405
+ constructor(db) {
406
+ if (!db) {
407
+ throw new Error(
408
+ "workflow storage requires embedded SQLite; actor KV workflow storage is no longer supported"
409
+ );
410
+ }
411
+ this.#db = db;
412
+ }
413
+ async get(key) {
414
+ var _a;
415
+ const prefixed = makeWorkflowKey(key);
416
+ const rows = await this.#db.execute(
417
+ "SELECT value FROM _rivet_wf_kv WHERE key = ?",
418
+ prefixed
419
+ );
420
+ return ((_a = rows[0]) == null ? void 0 : _a.value) == null ? null : normalizeSqlBlob(rows[0].value);
421
+ }
422
+ async set(key, value) {
423
+ await this.batch([{ key, value }]);
424
+ }
425
+ async delete(key) {
426
+ const prefixed = makeWorkflowKey(key);
427
+ await this.#db.execute(
428
+ "DELETE FROM _rivet_wf_kv WHERE key = ?",
429
+ prefixed
430
+ );
431
+ }
432
+ async deletePrefix(prefix) {
433
+ const start = makeWorkflowKey(prefix);
434
+ const end = computeUpperBound(start);
435
+ if (end) {
436
+ await this.#db.execute(
437
+ "DELETE FROM _rivet_wf_kv WHERE key >= ? AND key < ?",
438
+ start,
439
+ end
440
+ );
441
+ return;
442
+ }
443
+ const entries = await this.listRaw(start);
444
+ await this.deleteRawKeys(
445
+ entries.filter(([key]) => keyStartsWith(key, start)).map(([key]) => key)
446
+ );
447
+ }
448
+ async deleteRange(start, end) {
449
+ const prefixedStart = makeWorkflowKey(start);
450
+ const prefixedEnd = makeWorkflowKey(end);
451
+ await this.#db.execute(
452
+ "DELETE FROM _rivet_wf_kv WHERE key >= ? AND key < ?",
453
+ prefixedStart,
454
+ prefixedEnd
455
+ );
456
+ }
457
+ async list(prefix) {
458
+ const prefixed = makeWorkflowKey(prefix);
459
+ const entries = await this.listRaw(prefixed);
460
+ return entries.filter(([key]) => keyStartsWith(key, prefixed)).map(([key, value]) => ({
461
+ key: stripWorkflowKey(key),
462
+ value
463
+ }));
464
+ }
465
+ async batch(writes) {
466
+ if (writes.length === 0) return;
467
+ for (const chunk of chunkWorkflowWrites(writes)) {
468
+ await this.#db.transaction(async (tx) => {
469
+ for (const { key, value } of chunk) {
470
+ await tx.execute(
471
+ "INSERT INTO _rivet_wf_kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
472
+ makeWorkflowKey(key),
473
+ value
474
+ );
475
+ }
476
+ });
477
+ }
478
+ }
479
+ async listRaw(prefix) {
480
+ const end = computeUpperBound(prefix);
481
+ const rows = end ? await this.#db.execute(
482
+ "SELECT key, value FROM _rivet_wf_kv WHERE key >= ? AND key < ? ORDER BY key ASC",
483
+ prefix,
484
+ end
485
+ ) : await this.#db.execute(
486
+ "SELECT key, value FROM _rivet_wf_kv WHERE key >= ? ORDER BY key ASC",
487
+ prefix
488
+ );
489
+ return rows.map((row) => [
490
+ normalizeSqlBlob(row.key),
491
+ normalizeSqlBlob(row.value)
492
+ ]);
493
+ }
494
+ async deleteRawKeys(keys) {
495
+ for (let start = 0; start < keys.length; start += WORKFLOW_SQLITE_MAX_BATCH_ROWS) {
496
+ await this.#db.transaction(async (tx) => {
497
+ for (const key of keys.slice(
498
+ start,
499
+ start + WORKFLOW_SQLITE_MAX_BATCH_ROWS
500
+ )) {
501
+ await tx.execute(
502
+ "DELETE FROM _rivet_wf_kv WHERE key = ?",
503
+ key
504
+ );
505
+ }
506
+ });
507
+ }
508
+ }
509
+ };
510
+ function chunkWorkflowWrites(writes) {
511
+ const chunks = [];
512
+ let chunk = [];
513
+ let chunkBytes = 0;
514
+ for (const write of writes) {
515
+ const writeBytes = WORKFLOW_STORAGE_PREFIX.length + write.key.length + write.value.length;
516
+ if (chunk.length > 0 && (chunk.length >= WORKFLOW_SQLITE_MAX_BATCH_ROWS || chunkBytes + writeBytes > WORKFLOW_SQLITE_MAX_BATCH_BYTES)) {
517
+ chunks.push(chunk);
518
+ chunk = [];
519
+ chunkBytes = 0;
520
+ }
521
+ chunk.push(write);
522
+ chunkBytes += writeBytes;
523
+ }
524
+ if (chunk.length > 0) chunks.push(chunk);
525
+ return chunks;
526
+ }
527
+ function keyStartsWith(key, prefix) {
528
+ if (key.length < prefix.length) return false;
529
+ for (let i = 0; i < prefix.length; i++) {
530
+ if (key[i] !== prefix[i]) return false;
531
+ }
532
+ return true;
533
+ }
534
+ var ActorWorkflowMessageDriver = class {
535
+ #actor;
536
+ #runCtx;
537
+ constructor(actor, runCtx) {
538
+ this.#actor = actor;
539
+ this.#runCtx = runCtx;
540
+ }
541
+ async addMessage(message) {
542
+ await this.#runCtx.internalKeepAwake(
543
+ this.#actor.queueManager.enqueue(message.name, message.data)
544
+ );
545
+ }
546
+ async receiveMessages(opts) {
547
+ const messages = await this.#runCtx.internalKeepAwake(
548
+ this.#actor.queueManager.receive(
549
+ opts.names && opts.names.length > 0 ? [...opts.names] : void 0,
550
+ opts.count,
551
+ 0,
552
+ void 0,
553
+ opts.completable
554
+ )
555
+ );
556
+ return messages.map((message) => ({
557
+ id: message.id.toString(),
558
+ name: message.name,
559
+ data: message.body,
560
+ sentAt: message.createdAt,
561
+ ...opts.completable ? {
562
+ complete: async (response) => {
563
+ await this.#runCtx.internalKeepAwake(
564
+ this.#actor.queueManager.completeMessage(
565
+ message,
566
+ response
567
+ )
568
+ );
569
+ }
570
+ } : {}
571
+ }));
572
+ }
573
+ async completeMessage(messageId, response) {
574
+ let parsedId;
575
+ try {
576
+ parsedId = BigInt(messageId);
577
+ } catch {
578
+ return;
579
+ }
580
+ await this.#runCtx.internalKeepAwake(
581
+ this.#actor.queueManager.completeMessageById(parsedId, response)
582
+ );
583
+ }
584
+ };
585
+ var ActorWorkflowDriver = class {
586
+ atomicBatch = true;
587
+ workerPollInterval = 100;
588
+ messageDriver;
589
+ #actor;
590
+ #runCtx;
591
+ #storage;
592
+ constructor(actor, runCtx) {
593
+ this.#actor = actor;
594
+ this.#runCtx = runCtx;
595
+ this.messageDriver = new ActorWorkflowMessageDriver(actor, runCtx);
596
+ this.#storage = new WorkflowStorage(runtimeDbFromContext(runCtx));
597
+ }
598
+ async get(key) {
599
+ return await this.#runCtx.internalKeepAwake(this.#storage.get(key));
600
+ }
601
+ async set(key, value) {
602
+ await this.#runCtx.internalKeepAwake(this.#storage.set(key, value));
603
+ }
604
+ async delete(key) {
605
+ await this.#runCtx.internalKeepAwake(this.#storage.delete(key));
606
+ }
607
+ async deletePrefix(prefix) {
608
+ await this.#runCtx.internalKeepAwake(
609
+ this.#storage.deletePrefix(prefix)
610
+ );
611
+ }
612
+ async deleteRange(start, end) {
613
+ await this.#runCtx.internalKeepAwake(
614
+ this.#storage.deleteRange(start, end)
615
+ );
616
+ }
617
+ async list(prefix) {
618
+ return await this.#runCtx.internalKeepAwake(this.#storage.list(prefix));
619
+ }
620
+ async batch(writes) {
621
+ if (writes.length === 0) return;
622
+ await this.#runCtx.internalKeepAwake(
623
+ this.#actor.stateManager.saveStateAndWorkflowBatch(writes)
624
+ );
625
+ }
626
+ async setAlarm(_workflowId, wakeAt) {
627
+ await this.#runCtx.internalKeepAwake(
628
+ this.#actor.driver.setAlarm(this.#actor, wakeAt)
629
+ );
630
+ }
631
+ async clearAlarm(_workflowId) {
632
+ return;
633
+ }
634
+ waitForMessages(messageNames, abortSignal) {
635
+ return this.#actor.queueManager.waitForNames(
636
+ messageNames.length > 0 ? messageNames : void 0,
637
+ abortSignal
638
+ );
639
+ }
640
+ };
641
+ var NoopWorkflowMessageDriver = class {
642
+ async addMessage(_message) {
643
+ throw new Error("Workflow control driver does not support messages");
644
+ }
645
+ async receiveMessages(_opts) {
646
+ throw new Error("Workflow control driver does not support messages");
647
+ }
648
+ async completeMessage(_messageId, _response) {
649
+ throw new Error("Workflow control driver does not support messages");
650
+ }
651
+ };
652
+ var ActorWorkflowControlDriver = class {
653
+ workerPollInterval = 100;
654
+ messageDriver = new NoopWorkflowMessageDriver();
655
+ #actor;
656
+ #storage;
657
+ constructor(actor, runCtx) {
658
+ this.#actor = actor;
659
+ this.#storage = new WorkflowStorage(runtimeDbFromContext(runCtx));
660
+ }
661
+ async get(key) {
662
+ return await this.#storage.get(key);
663
+ }
664
+ async set(key, value) {
665
+ await this.#storage.set(key, value);
666
+ }
667
+ async delete(key) {
668
+ await this.#storage.delete(key);
669
+ }
670
+ async deletePrefix(prefix) {
671
+ await this.#storage.deletePrefix(prefix);
672
+ }
673
+ async deleteRange(start, end) {
674
+ await this.#storage.deleteRange(start, end);
675
+ }
676
+ async list(prefix) {
677
+ return await this.#storage.list(prefix);
678
+ }
679
+ async batch(writes) {
680
+ if (writes.length === 0) {
681
+ return;
682
+ }
683
+ await this.#storage.batch(writes);
684
+ }
685
+ async setAlarm(_workflowId, wakeAt) {
686
+ await this.#actor.driver.setAlarm(this.#actor, wakeAt);
687
+ }
688
+ async clearAlarm(_workflowId) {
689
+ return;
690
+ }
691
+ waitForMessages(_messageNames, _abortSignal) {
692
+ throw new Error("Workflow control driver does not support messages");
583
693
  }
584
694
  };
585
695
 
@@ -608,6 +718,9 @@ function workflowReplayInFlightError() {
608
718
  function isWorkflowReplayBlockedByRunningEntry(error) {
609
719
  return error instanceof Error && error.message === "Cannot replay a workflow while a step is currently running";
610
720
  }
721
+ function isRunHandlerUnavailable(error) {
722
+ return error instanceof RivetError && error.group === "actor" && error.code === "run_handler_unavailable";
723
+ }
611
724
  function workflow(fn, options = {}) {
612
725
  const onError = options.onError;
613
726
  const workflowInspectors = /* @__PURE__ */ new Map();
@@ -624,37 +737,44 @@ function workflow(fn, options = {}) {
624
737
  invariant(actor, "workflow() requires an actor instance");
625
738
  const workflowInspector = getWorkflowInspector(actor.id);
626
739
  const driver = new ActorWorkflowDriver(actor, runCtx);
627
- const controlDriver = new ActorWorkflowControlDriver(actor);
740
+ const controlDriver = new ActorWorkflowControlDriver(actor, runCtx);
628
741
  workflowInspector.setReplayFromStep(async (entryId) => {
629
742
  const workflowState = await workflowInspector.adapter.getState();
630
- if (actor.isRunHandlerActive() || workflowState === "pending" || workflowState === "running") {
743
+ if (workflowState === "pending" || workflowState === "running") {
631
744
  throw workflowReplayInFlightError();
632
745
  }
633
- let snapshot;
746
+ const control = workflowInspector.control;
747
+ invariant(control, "workflow Inspector control is not initialized");
634
748
  try {
635
- snapshot = await replayWorkflowFromStep(
636
- actor.id,
637
- controlDriver,
638
- entryId,
639
- { scheduleAlarm: false }
749
+ return await control.run.withInactive(
750
+ { restartOnSuccess: true },
751
+ async () => {
752
+ const snapshot = await replayWorkflowFromStep(
753
+ actor.id,
754
+ controlDriver,
755
+ entryId,
756
+ { scheduleAlarm: false }
757
+ );
758
+ workflowInspector.update(snapshot);
759
+ return workflowInspector.adapter.getHistory();
760
+ }
640
761
  );
641
762
  } catch (error) {
642
- if (isWorkflowReplayBlockedByRunningEntry(error)) {
763
+ if (isWorkflowReplayBlockedByRunningEntry(error) || isRunHandlerUnavailable(error)) {
643
764
  throw workflowReplayInFlightError();
644
765
  }
645
766
  throw error;
646
767
  }
647
- workflowInspector.update(snapshot);
648
- await actor.restartRunHandler();
649
- return workflowInspector.adapter.getHistory();
650
768
  });
651
769
  const handle = runWorkflow(
652
770
  actor.id,
653
- async (ctx) => await fn(new ActorWorkflowContext(ctx, runCtx)),
771
+ async (ctx) => await fn(new WorkflowContext(ctx, runCtx)),
654
772
  void 0,
655
773
  driver,
656
774
  {
657
775
  mode: "live",
776
+ // The actor logger and the engine's pino logger are runtime
777
+ // compatible but not structurally assignable.
658
778
  logger: runCtx.log,
659
779
  onHistoryUpdated: workflowInspector.update,
660
780
  onError: onError ? async (event) => await onError(runCtx, event) : void 0
@@ -674,7 +794,7 @@ function workflow(fn, options = {}) {
674
794
  try {
675
795
  await handle.result;
676
796
  } catch (error) {
677
- if (runCtx.abortSignal.aborted) {
797
+ if (runCtx.abortSignal.aborted || isActorAbortedError(error)) {
678
798
  return;
679
799
  }
680
800
  if (shouldRethrowWorkflowError(error)) {
@@ -692,42 +812,27 @@ function workflow(fn, options = {}) {
692
812
  runCtx.abortSignal.removeEventListener("abort", onAbort);
693
813
  }
694
814
  }
695
- const runWithConfig = run;
696
- runWithConfig[RUN_FUNCTION_CONFIG_SYMBOL] = {
815
+ return defineRunHandler(run, {
697
816
  icon: "diagram-project",
698
- inspectorFactory: (actor) => {
699
- const actorId = resolveWorkflowInspectorActorId(actor);
817
+ inspectorKind: "workflow",
818
+ createInspector: ({ actorId, control }) => {
819
+ const workflowInspector = getWorkflowInspector(actorId);
820
+ workflowInspector.control = control;
700
821
  return {
701
- workflow: actorId ? getWorkflowInspector(actorId).adapter : {
702
- getHistory: () => null,
703
- onHistoryUpdated: () => () => {
704
- },
705
- replayFromStep: async () => null
822
+ inspector: { workflow: workflowInspector.adapter },
823
+ dispose: () => {
824
+ if (workflowInspectors.get(actorId) === workflowInspector) {
825
+ workflowInspectors.delete(actorId);
826
+ }
706
827
  }
707
828
  };
708
829
  }
709
- };
710
- return runWithConfig;
711
- }
712
- function resolveWorkflowInspectorActorId(actor) {
713
- if (typeof actor === "string" && actor.length > 0) {
714
- return actor;
715
- }
716
- if (!actor || typeof actor !== "object") {
717
- return void 0;
718
- }
719
- const candidate = actor;
720
- if (typeof candidate.id === "string" && candidate.id.length > 0) {
721
- return candidate.id;
722
- }
723
- if (typeof candidate.actorId === "string" && candidate.actorId.length > 0) {
724
- return candidate.actorId;
725
- }
726
- return void 0;
830
+ });
727
831
  }
728
832
  export {
729
- ActorWorkflowContext,
730
833
  Loop,
834
+ WorkflowContext,
835
+ WorkflowStepContext,
731
836
  workflow
732
837
  };
733
838
  //# sourceMappingURL=mod.js.map