rivetkit 2.3.11-rc.8 → 2.3.11

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 (153) hide show
  1. package/dist/browser/client.d.ts +96 -14
  2. package/dist/browser/client.js +12 -2
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +139 -139
  5. package/dist/browser/inspector/client.js +12 -2
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/agent-os/index.cjs +146 -76
  8. package/dist/tsup/agent-os/index.cjs.map +1 -1
  9. package/dist/tsup/agent-os/index.d.cts +83 -9
  10. package/dist/tsup/agent-os/index.d.ts +83 -9
  11. package/dist/tsup/agent-os/index.js +146 -76
  12. package/dist/tsup/agent-os/index.js.map +1 -1
  13. package/dist/tsup/{chunk-JBQ63WSM.js → chunk-3ZR542SK.js} +4 -4
  14. package/dist/tsup/chunk-3ZR542SK.js.map +1 -0
  15. package/dist/tsup/{chunk-HNHLBM3Y.cjs → chunk-4KGXFC6M.cjs} +42 -5
  16. package/dist/tsup/chunk-4KGXFC6M.cjs.map +1 -0
  17. package/dist/tsup/chunk-5UYWLCRO.js +14 -0
  18. package/dist/tsup/chunk-5UYWLCRO.js.map +1 -0
  19. package/dist/tsup/{chunk-QWLJCP3X.js → chunk-6W5VGLFT.js} +42 -5
  20. package/dist/tsup/chunk-6W5VGLFT.js.map +1 -0
  21. package/dist/tsup/chunk-6WYATRS4.js +243 -0
  22. package/dist/tsup/chunk-6WYATRS4.js.map +1 -0
  23. package/dist/tsup/chunk-B3W74FBB.cjs +14 -0
  24. package/dist/tsup/chunk-B3W74FBB.cjs.map +1 -0
  25. package/dist/tsup/{chunk-V6ANE6JM.js → chunk-FWROC5LA.js} +2 -2
  26. package/dist/tsup/{chunk-ZVM35ICH.cjs → chunk-GLIPKKEC.cjs} +7 -7
  27. package/dist/tsup/{chunk-ZVM35ICH.cjs.map → chunk-GLIPKKEC.cjs.map} +1 -1
  28. package/dist/tsup/{chunk-CCUO5OKD.cjs → chunk-GN2EUMEW.cjs} +3 -3
  29. package/dist/tsup/{chunk-CCUO5OKD.cjs.map → chunk-GN2EUMEW.cjs.map} +1 -1
  30. package/dist/tsup/{chunk-2ROUKH7W.cjs → chunk-GU7ML3KE.cjs} +13 -3
  31. package/dist/tsup/chunk-GU7ML3KE.cjs.map +1 -0
  32. package/dist/tsup/{chunk-WRRB24UY.js → chunk-JQ2AZ5FN.js} +3 -3
  33. package/dist/tsup/{chunk-7AFZMFPQ.js → chunk-JTHHCZCZ.js} +10 -1
  34. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  35. package/dist/tsup/{chunk-UEULFXUI.cjs → chunk-KVFIONKQ.cjs} +11 -2
  36. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  37. package/dist/tsup/chunk-LWQFXGKS.cjs +243 -0
  38. package/dist/tsup/chunk-LWQFXGKS.cjs.map +1 -0
  39. package/dist/tsup/{chunk-KVD6ZWNM.js → chunk-MO2SSUOR.js} +8 -7
  40. package/dist/tsup/chunk-MO2SSUOR.js.map +1 -0
  41. package/dist/tsup/{chunk-AGNBLCNJ.js → chunk-OUENKQHB.js} +13 -3
  42. package/dist/tsup/chunk-OUENKQHB.js.map +1 -0
  43. package/dist/tsup/{chunk-E6WB2BLO.cjs → chunk-PUZY2XCD.cjs} +10 -9
  44. package/dist/tsup/chunk-PUZY2XCD.cjs.map +1 -0
  45. package/dist/tsup/{chunk-4EDGOGCB.js → chunk-QFJ24MBU.js} +27 -2
  46. package/dist/tsup/{chunk-4EDGOGCB.js.map → chunk-QFJ24MBU.js.map} +1 -1
  47. package/dist/tsup/{chunk-A55CGZIV.cjs → chunk-RXXDNJXB.cjs} +140 -140
  48. package/dist/tsup/{chunk-A55CGZIV.cjs.map → chunk-RXXDNJXB.cjs.map} +1 -1
  49. package/dist/tsup/{chunk-N6MBTYGX.cjs → chunk-VBJQIBXI.cjs} +30 -5
  50. package/dist/tsup/chunk-VBJQIBXI.cjs.map +1 -0
  51. package/dist/tsup/client/mod.cjs +6 -6
  52. package/dist/tsup/client/mod.d.cts +4 -3
  53. package/dist/tsup/client/mod.d.ts +4 -3
  54. package/dist/tsup/client/mod.js +5 -5
  55. package/dist/tsup/common/log.cjs +2 -2
  56. package/dist/tsup/common/log.js +1 -1
  57. package/dist/tsup/common/websocket.cjs +3 -3
  58. package/dist/tsup/common/websocket.js +2 -2
  59. package/dist/tsup/{config-CZcjyT5B.d.ts → config-C4OSv0QP.d.ts} +92 -7
  60. package/dist/tsup/{config-rGWrumlO.d.cts → config-DTGoWdkG.d.cts} +92 -7
  61. package/dist/tsup/{config-BxOimoGX.d.cts → config-ey2I2zz5.d.cts} +46 -6
  62. package/dist/tsup/{config-BxOimoGX.d.ts → config-ey2I2zz5.d.ts} +46 -6
  63. package/dist/tsup/{context-B8W8E8nW.d.cts → context-C6cvDNyk.d.cts} +2 -2
  64. package/dist/tsup/{context-_UrDZhEh.d.ts → context-CMygeBxS.d.ts} +2 -2
  65. package/dist/tsup/db/drizzle.cjs +18 -10
  66. package/dist/tsup/db/drizzle.cjs.map +1 -1
  67. package/dist/tsup/db/drizzle.d.cts +5 -6
  68. package/dist/tsup/db/drizzle.d.ts +5 -6
  69. package/dist/tsup/db/drizzle.js +13 -5
  70. package/dist/tsup/db/drizzle.js.map +1 -1
  71. package/dist/tsup/db/mod.cjs +5 -175
  72. package/dist/tsup/db/mod.cjs.map +1 -1
  73. package/dist/tsup/db/mod.d.cts +11 -4
  74. package/dist/tsup/db/mod.d.ts +11 -4
  75. package/dist/tsup/db/mod.js +4 -174
  76. package/dist/tsup/db/mod.js.map +1 -1
  77. package/dist/tsup/dynamic/mod.cjs +2 -2
  78. package/dist/tsup/dynamic/mod.d.cts +3 -2
  79. package/dist/tsup/dynamic/mod.d.ts +3 -2
  80. package/dist/tsup/dynamic/mod.js +1 -1
  81. package/dist/tsup/inspector/mod.cjs +5 -4
  82. package/dist/tsup/inspector/mod.cjs.map +1 -1
  83. package/dist/tsup/inspector/mod.d.cts +12 -146
  84. package/dist/tsup/inspector/mod.d.ts +12 -146
  85. package/dist/tsup/inspector/mod.js +4 -3
  86. package/dist/tsup/inspector/mod.js.map +1 -1
  87. package/dist/tsup/inspector/workflow.cjs +21 -0
  88. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  89. package/dist/tsup/inspector/workflow.d.cts +144 -0
  90. package/dist/tsup/inspector/workflow.d.ts +144 -0
  91. package/dist/tsup/inspector/workflow.js +21 -0
  92. package/dist/tsup/inspector/workflow.js.map +1 -0
  93. package/dist/tsup/inspector-tab/mod.cjs +2 -2
  94. package/dist/tsup/inspector-tab/mod.d.cts +4 -3
  95. package/dist/tsup/inspector-tab/mod.d.ts +4 -3
  96. package/dist/tsup/inspector-tab/mod.js +1 -1
  97. package/dist/tsup/mod.cjs +837 -243
  98. package/dist/tsup/mod.cjs.map +1 -1
  99. package/dist/tsup/mod.d.cts +6 -5
  100. package/dist/tsup/mod.d.ts +6 -5
  101. package/dist/tsup/mod.js +766 -172
  102. package/dist/tsup/mod.js.map +1 -1
  103. package/dist/tsup/test/mod.cjs +7 -7
  104. package/dist/tsup/test/mod.d.cts +3 -2
  105. package/dist/tsup/test/mod.d.ts +3 -2
  106. package/dist/tsup/test/mod.js +5 -5
  107. package/dist/tsup/unstable/migrations.d.cts +1 -1
  108. package/dist/tsup/unstable/migrations.d.ts +1 -1
  109. package/dist/tsup/utils.cjs +2 -2
  110. package/dist/tsup/utils.js +1 -1
  111. package/dist/tsup/workflow/mod.cjs +89 -95
  112. package/dist/tsup/workflow/mod.cjs.map +1 -1
  113. package/dist/tsup/workflow/mod.d.cts +5 -4
  114. package/dist/tsup/workflow/mod.d.ts +5 -4
  115. package/dist/tsup/workflow/mod.js +86 -92
  116. package/dist/tsup/workflow/mod.js.map +1 -1
  117. package/package.json +19 -9
  118. package/src/actor/config.test.ts +65 -1
  119. package/src/actor/config.ts +169 -5
  120. package/src/actor/mod.ts +10 -1
  121. package/src/client/actor-common.ts +5 -14
  122. package/src/common/database/config.ts +50 -3
  123. package/src/common/database/mod.test.ts +142 -4
  124. package/src/common/database/mod.ts +210 -98
  125. package/src/common/database/native-database.ts +42 -3
  126. package/src/common/database/shared.ts +9 -0
  127. package/src/db/drizzle.test.ts +8 -1
  128. package/src/db/drizzle.ts +15 -4
  129. package/src/db/mod.ts +3 -0
  130. package/src/inspector/workflow.ts +61 -0
  131. package/src/registry/napi-runtime.ts +69 -1
  132. package/src/registry/native.ts +505 -155
  133. package/src/registry/run-handler-coordinator.test.ts +252 -0
  134. package/src/registry/run-handler-coordinator.ts +219 -0
  135. package/src/registry/runtime.ts +34 -1
  136. package/src/registry/wasm-runtime.ts +122 -17
  137. package/src/registry/write-through-proxy.ts +101 -0
  138. package/src/utils/node.ts +44 -28
  139. package/src/workflow/driver.ts +56 -58
  140. package/src/workflow/inspector.ts +10 -15
  141. package/src/workflow/mod.ts +48 -70
  142. package/dist/tsup/chunk-2ROUKH7W.cjs.map +0 -1
  143. package/dist/tsup/chunk-7AFZMFPQ.js.map +0 -1
  144. package/dist/tsup/chunk-AGNBLCNJ.js.map +0 -1
  145. package/dist/tsup/chunk-E6WB2BLO.cjs.map +0 -1
  146. package/dist/tsup/chunk-HNHLBM3Y.cjs.map +0 -1
  147. package/dist/tsup/chunk-JBQ63WSM.js.map +0 -1
  148. package/dist/tsup/chunk-KVD6ZWNM.js.map +0 -1
  149. package/dist/tsup/chunk-N6MBTYGX.cjs.map +0 -1
  150. package/dist/tsup/chunk-QWLJCP3X.js.map +0 -1
  151. package/dist/tsup/chunk-UEULFXUI.cjs.map +0 -1
  152. /package/dist/tsup/{chunk-V6ANE6JM.js.map → chunk-FWROC5LA.js.map} +0 -0
  153. /package/dist/tsup/{chunk-WRRB24UY.js.map → chunk-JQ2AZ5FN.js.map} +0 -0
package/dist/tsup/mod.js CHANGED
@@ -1,18 +1,22 @@
1
1
  import {
2
2
  decodeWorkflowHistoryTransport
3
- } from "./chunk-4EDGOGCB.js";
3
+ } from "./chunk-QFJ24MBU.js";
4
4
  import {
5
5
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
6
6
  ActorConfigSchema,
7
7
  CONN_STATE_MANAGER_SYMBOL,
8
8
  RAW_STATE_SYMBOL,
9
+ createRunInspector,
10
+ defineRunHandler,
9
11
  disposeRunInspector,
10
12
  flattenActionHandlers,
11
13
  flattenActionInputSchemas,
12
14
  getRunFunction,
13
15
  getRunInspectorConfig,
14
- getRunMetadata
15
- } from "./chunk-QWLJCP3X.js";
16
+ getRunInspectorKind,
17
+ getRunMetadata,
18
+ hasRunInspectorConfig
19
+ } from "./chunk-6W5VGLFT.js";
16
20
  import {
17
21
  ALLOWED_PUBLIC_HEADERS,
18
22
  HEADER_CONN_PARAMS,
@@ -23,13 +27,18 @@ import {
23
27
  isResponseLike,
24
28
  tryParseEndpoint,
25
29
  updateRunnerConfig
26
- } from "./chunk-JBQ63WSM.js";
30
+ } from "./chunk-3ZR542SK.js";
27
31
  import {
28
32
  makePrefixedKey,
29
33
  removePrefixFromKey
30
34
  } from "./chunk-JI6GZ2C2.js";
31
- import "./chunk-7AFZMFPQ.js";
32
- import "./chunk-V6ANE6JM.js";
35
+ import {
36
+ bindNativeStateTransactionContext,
37
+ db,
38
+ registerNativeStateTransactionOpener
39
+ } from "./chunk-6WYATRS4.js";
40
+ import "./chunk-JTHHCZCZ.js";
41
+ import "./chunk-FWROC5LA.js";
33
42
  import {
34
43
  LogLevelSchema,
35
44
  VERSION,
@@ -62,7 +71,7 @@ import {
62
71
  parsePortEnv,
63
72
  stringifyError,
64
73
  toUint8Array
65
- } from "./chunk-AGNBLCNJ.js";
74
+ } from "./chunk-OUENKQHB.js";
66
75
  import {
67
76
  INTERNAL_ERROR_CODE,
68
77
  RivetError,
@@ -1193,11 +1202,33 @@ function wrapJsNativeDatabase(database) {
1193
1202
  release();
1194
1203
  }
1195
1204
  },
1196
- async beginTransaction(timeoutMs) {
1205
+ async beginTransaction(timeoutMs, name) {
1206
+ const release = gate.enter();
1207
+ let transaction;
1208
+ try {
1209
+ transaction = await database.beginTransaction(timeoutMs, name);
1210
+ } catch (error) {
1211
+ enrichNativeDatabaseError(database, error);
1212
+ } finally {
1213
+ release();
1214
+ }
1215
+ return wrapTransaction(database, transaction, gate, (result) => {
1216
+ if (result.lastInsertRowId !== void 0) {
1217
+ lastInsertRowId = result.lastInsertRowId;
1218
+ }
1219
+ });
1220
+ },
1221
+ async beginStateTransaction(timeoutMs, context) {
1222
+ if (!database.beginStateTransaction) {
1223
+ throw new Error("actor state transactions are not configured");
1224
+ }
1197
1225
  const release = gate.enter();
1198
1226
  let transaction;
1199
1227
  try {
1200
- transaction = await database.beginTransaction(timeoutMs);
1228
+ transaction = await database.beginStateTransaction(
1229
+ timeoutMs,
1230
+ context
1231
+ );
1201
1232
  } catch (error) {
1202
1233
  enrichNativeDatabaseError(database, error);
1203
1234
  } finally {
@@ -1307,45 +1338,37 @@ var nodeChildProcess;
1307
1338
  var nodeStream;
1308
1339
  var nodeUrl;
1309
1340
  var hasImportedDependencies = false;
1310
- function getRequireFn() {
1311
- return createRequire(import.meta.url);
1341
+ var fallbackRequire;
1342
+ function loadNodeBuiltin(id) {
1343
+ var _a;
1344
+ const nodeProcess = globalThis.process;
1345
+ const builtin = (_a = nodeProcess == null ? void 0 : nodeProcess.getBuiltinModule) == null ? void 0 : _a.call(nodeProcess, id);
1346
+ if (builtin !== void 0) {
1347
+ return builtin;
1348
+ }
1349
+ if (!(nodeProcess == null ? void 0 : nodeProcess.execPath)) {
1350
+ throw new Error("Node.js built-ins are not available");
1351
+ }
1352
+ fallbackRequire ??= createRequire(nodeProcess.execPath);
1353
+ return fallbackRequire(id);
1312
1354
  }
1313
1355
  function importNodeDependencies() {
1314
1356
  if (hasImportedDependencies) return;
1315
1357
  try {
1316
- const requireFn = getRequireFn();
1317
- nodeCrypto = requireFn(
1318
- /* webpackIgnore: true */
1319
- "node:crypto"
1320
- );
1321
- nodeFsSync = requireFn(
1322
- /* webpackIgnore: true */
1323
- "node:fs"
1324
- );
1325
- nodeFs = requireFn(
1326
- /* webpackIgnore: true */
1358
+ nodeCrypto = loadNodeBuiltin("node:crypto");
1359
+ nodeFsSync = loadNodeBuiltin("node:fs");
1360
+ nodeFs = loadNodeBuiltin(
1327
1361
  "node:fs/promises"
1328
1362
  );
1329
- nodePath = requireFn(
1330
- /* webpackIgnore: true */
1331
- "node:path"
1332
- );
1333
- nodeOs = requireFn(
1334
- /* webpackIgnore: true */
1335
- "node:os"
1336
- );
1337
- nodeChildProcess = requireFn(
1338
- /* webpackIgnore: true */
1363
+ nodePath = loadNodeBuiltin("node:path");
1364
+ nodeOs = loadNodeBuiltin("node:os");
1365
+ nodeChildProcess = loadNodeBuiltin(
1339
1366
  "node:child_process"
1340
1367
  );
1341
- nodeStream = requireFn(
1342
- /* webpackIgnore: true */
1368
+ nodeStream = loadNodeBuiltin(
1343
1369
  "node:stream/promises"
1344
1370
  );
1345
- nodeUrl = requireFn(
1346
- /* webpackIgnore: true */
1347
- "node:url"
1348
- );
1371
+ nodeUrl = loadNodeBuiltin("node:url");
1349
1372
  hasImportedDependencies = true;
1350
1373
  } catch (err) {
1351
1374
  console.warn(
@@ -1396,6 +1419,9 @@ function asNativeWebSocket(handle) {
1396
1419
  function asNativeSqlTransaction(handle) {
1397
1420
  return handle;
1398
1421
  }
1422
+ function asNativeActorStateTransaction(handle) {
1423
+ return handle;
1424
+ }
1399
1425
  function asNativeCancellationToken(handle) {
1400
1426
  return handle;
1401
1427
  }
@@ -1619,6 +1645,9 @@ var NapiCoreRuntime = class {
1619
1645
  actorSetAlarm(ctx, timestampMs) {
1620
1646
  asNativeActorContext(ctx).setAlarm(timestampMs);
1621
1647
  }
1648
+ async actorSetRunWakeAt(ctx, timestampMs) {
1649
+ await asNativeActorContext(ctx).setRunWakeAt(timestampMs);
1650
+ }
1622
1651
  actorRequestSave(ctx, opts) {
1623
1652
  asNativeActorContext(ctx).requestSave(opts);
1624
1653
  }
@@ -1779,9 +1808,10 @@ var NapiCoreRuntime = class {
1779
1808
  );
1780
1809
  return results.map(normalizeRuntimeSqlExecuteResult);
1781
1810
  }
1782
- async actorSqlBeginTransaction(ctx, timeoutMs) {
1811
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
1783
1812
  return await this.#actorSql(ctx).beginTransaction(
1784
- timeoutMs
1813
+ timeoutMs,
1814
+ name
1785
1815
  );
1786
1816
  }
1787
1817
  async actorSqlTransactionExec(transaction, sql) {
@@ -1800,6 +1830,26 @@ var NapiCoreRuntime = class {
1800
1830
  async actorSqlTransactionRollback(transaction) {
1801
1831
  await asNativeSqlTransaction(transaction).rollback();
1802
1832
  }
1833
+ async actorBeginStateTransaction(ctx, timeoutMs) {
1834
+ return await asNativeActorContext(ctx).beginStateTransaction(
1835
+ timeoutMs
1836
+ );
1837
+ }
1838
+ async actorStateTransactionExecute(transaction, sql, params) {
1839
+ const result = await asNativeActorStateTransaction(transaction).execute(
1840
+ sql,
1841
+ toNapiSqlBindParams(params)
1842
+ );
1843
+ return normalizeRuntimeSqlExecuteResult(result);
1844
+ }
1845
+ async actorStateTransactionCommit(transaction, payload) {
1846
+ await asNativeActorStateTransaction(transaction).commit(
1847
+ toNapiStateDeltaPayload(payload)
1848
+ );
1849
+ }
1850
+ async actorStateTransactionRollback(transaction) {
1851
+ await asNativeActorStateTransaction(transaction).rollback();
1852
+ }
1803
1853
  async actorSqlQuery(ctx, sql, params) {
1804
1854
  return await this.#actorSql(ctx).query(
1805
1855
  sql,
@@ -1857,6 +1907,13 @@ var NapiCoreRuntime = class {
1857
1907
  signal ? asNativeCancellationToken(signal) : signal
1858
1908
  );
1859
1909
  }
1910
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
1911
+ return await asNativeActorContext(ctx).queue().completePersisted(
1912
+ messageId,
1913
+ expectedName,
1914
+ response == null ? response : toNapiBuffer(response)
1915
+ );
1916
+ }
1860
1917
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
1861
1918
  return await asNativeActorContext(ctx).queue().enqueueAndWait(
1862
1919
  name,
@@ -2046,7 +2103,167 @@ function validationError(target, issues) {
2046
2103
  });
2047
2104
  }
2048
2105
 
2106
+ // src/registry/run-handler-coordinator.ts
2107
+ function runUnavailable(actorId, reason) {
2108
+ return new RivetError(
2109
+ "actor",
2110
+ "run_handler_unavailable",
2111
+ `Run handler control is unavailable for actor ${actorId}: ${reason}.`,
2112
+ {
2113
+ public: true,
2114
+ statusCode: 409,
2115
+ metadata: { actorId, reason }
2116
+ }
2117
+ );
2118
+ }
2119
+ function notifyStateChanged(state) {
2120
+ const waiters = [...state.waiters];
2121
+ state.waiters.clear();
2122
+ for (const waiter of waiters) {
2123
+ waiter();
2124
+ }
2125
+ }
2126
+ function waitForStateChange(state) {
2127
+ return new Promise((resolve) => {
2128
+ state.waiters.add(resolve);
2129
+ });
2130
+ }
2131
+ var RunHandlerCoordinator = class {
2132
+ #run;
2133
+ #states = /* @__PURE__ */ new Map();
2134
+ constructor(run) {
2135
+ this.#run = run;
2136
+ }
2137
+ get inspectorKind() {
2138
+ return getRunInspectorKind(this.#run);
2139
+ }
2140
+ async run(actorId, restart, callback) {
2141
+ const state = this.#getOrCreate(actorId);
2142
+ state.restart = restart;
2143
+ this.#initializeInspector(actorId, state);
2144
+ state.queued += 1;
2145
+ const blockedGeneration = state.exclusive ? state.exclusiveGeneration : void 0;
2146
+ try {
2147
+ while (!state.closed && (state.exclusive || state.active)) {
2148
+ await waitForStateChange(state);
2149
+ }
2150
+ } finally {
2151
+ state.queued -= 1;
2152
+ }
2153
+ if (state.closed) {
2154
+ return "closed";
2155
+ }
2156
+ if (blockedGeneration !== void 0 && state.exclusiveGeneration === blockedGeneration && state.exclusiveOutcome === "failure") {
2157
+ return "suppressed";
2158
+ }
2159
+ state.active = true;
2160
+ try {
2161
+ await callback();
2162
+ return "ran";
2163
+ } finally {
2164
+ state.active = false;
2165
+ notifyStateChanged(state);
2166
+ }
2167
+ }
2168
+ getInspector(actorId, restart) {
2169
+ var _a;
2170
+ const state = this.#getOrCreate(actorId);
2171
+ state.restart = restart;
2172
+ this.#initializeInspector(actorId, state);
2173
+ return (_a = state.inspector) == null ? void 0 : _a.inspector;
2174
+ }
2175
+ destroy(actorId) {
2176
+ var _a, _b;
2177
+ const state = this.#states.get(actorId);
2178
+ if (!state) return;
2179
+ state.closed = true;
2180
+ (_b = (_a = state.inspector) == null ? void 0 : _a.dispose) == null ? void 0 : _b.call(_a);
2181
+ state.inspector = void 0;
2182
+ notifyStateChanged(state);
2183
+ this.#states.delete(actorId);
2184
+ }
2185
+ #control(actorId, state) {
2186
+ return {
2187
+ run: {
2188
+ withInactive: async (options, callback) => {
2189
+ if (state.closed) {
2190
+ throw runUnavailable(actorId, "actor is destroyed");
2191
+ }
2192
+ if (state.active || state.queued > 0 || state.exclusive) {
2193
+ throw runUnavailable(
2194
+ actorId,
2195
+ "the run handler is active or waiting to start"
2196
+ );
2197
+ }
2198
+ state.exclusive = true;
2199
+ state.exclusiveGeneration += 1;
2200
+ state.exclusiveOutcome = void 0;
2201
+ try {
2202
+ const result = await callback();
2203
+ if (state.closed) {
2204
+ throw runUnavailable(actorId, "actor is destroyed");
2205
+ }
2206
+ state.exclusiveOutcome = "success";
2207
+ if (options.restartOnSuccess && state.queued === 0) {
2208
+ if (!state.restart) {
2209
+ throw runUnavailable(
2210
+ actorId,
2211
+ "the runtime restart callback is not available"
2212
+ );
2213
+ }
2214
+ await state.restart();
2215
+ }
2216
+ return result;
2217
+ } catch (error) {
2218
+ state.exclusiveOutcome = "failure";
2219
+ throw error;
2220
+ } finally {
2221
+ state.exclusive = false;
2222
+ notifyStateChanged(state);
2223
+ }
2224
+ }
2225
+ }
2226
+ };
2227
+ }
2228
+ #getOrCreate(actorId) {
2229
+ let state = this.#states.get(actorId);
2230
+ if (!state) {
2231
+ state = {
2232
+ active: false,
2233
+ closed: false,
2234
+ exclusive: false,
2235
+ exclusiveGeneration: 0,
2236
+ inspectorInitialized: false,
2237
+ queued: 0,
2238
+ waiters: /* @__PURE__ */ new Set()
2239
+ };
2240
+ this.#states.set(actorId, state);
2241
+ }
2242
+ return state;
2243
+ }
2244
+ #initializeInspector(actorId, state) {
2245
+ if (state.inspectorInitialized) return;
2246
+ const inspector = createRunInspector(this.#run, {
2247
+ actorId,
2248
+ control: this.#control(actorId, state)
2249
+ });
2250
+ if (this.inspectorKind === "workflow") {
2251
+ const workflow = inspector === void 0 ? void 0 : inspector.inspector.workflow;
2252
+ if (!workflow || typeof workflow.getHistory !== "function" || typeof workflow.getState !== "function" || typeof workflow.onHistoryUpdated !== "function" || typeof workflow.replayFromStep !== "function") {
2253
+ throw new TypeError(
2254
+ `defineRunHandler createInspector returned an invalid workflow adapter for actor ${actorId}`
2255
+ );
2256
+ }
2257
+ }
2258
+ state.inspector = inspector;
2259
+ state.inspectorInitialized = true;
2260
+ }
2261
+ };
2262
+
2049
2263
  // src/registry/wasm-runtime.ts
2264
+ function asWasmConstructors(bindings) {
2265
+ return bindings;
2266
+ }
2050
2267
  function asWasmRegistry(handle) {
2051
2268
  return handle;
2052
2269
  }
@@ -2171,10 +2388,10 @@ function childHandle(handle, name) {
2171
2388
  }
2172
2389
  var WasmCoreRuntime = class {
2173
2390
  kind = "wasm";
2174
- #bindings;
2391
+ #constructors;
2175
2392
  #sql = /* @__PURE__ */ new WeakMap();
2176
2393
  constructor(bindings) {
2177
- this.#bindings = bindings;
2394
+ this.#constructors = asWasmConstructors(bindings);
2178
2395
  }
2179
2396
  #actorSql(ctx) {
2180
2397
  const wasmCtx = asWasmActorContext(ctx);
@@ -2187,7 +2404,7 @@ var WasmCoreRuntime = class {
2187
2404
  }
2188
2405
  createRegistry() {
2189
2406
  return callWasmSync(
2190
- () => asRegistryHandle2(new this.#bindings.CoreRegistry())
2407
+ () => asRegistryHandle2(new this.#constructors.CoreRegistry())
2191
2408
  );
2192
2409
  }
2193
2410
  registerActor(registry, name, factory) {
@@ -2242,13 +2459,13 @@ var WasmCoreRuntime = class {
2242
2459
  createActorFactory(callbacks, config) {
2243
2460
  return callWasmSync(
2244
2461
  () => asActorFactoryHandle2(
2245
- new this.#bindings.ActorFactory(callbacks, config)
2462
+ new this.#constructors.ActorFactory(callbacks, config)
2246
2463
  )
2247
2464
  );
2248
2465
  }
2249
2466
  createCancellationToken() {
2250
2467
  return callWasmSync(
2251
- () => new this.#bindings.CancellationToken()
2468
+ () => new this.#constructors.CancellationToken()
2252
2469
  );
2253
2470
  }
2254
2471
  cancellationTokenAborted(token) {
@@ -2283,6 +2500,13 @@ var WasmCoreRuntime = class {
2283
2500
  optionalWasmNumber(timestampMs)
2284
2501
  );
2285
2502
  }
2503
+ async actorSetRunWakeAt(ctx, timestampMs) {
2504
+ await callHandleAsync(
2505
+ asWasmActorContext(ctx),
2506
+ "setRunWakeAt",
2507
+ optionalWasmNumber(timestampMs)
2508
+ );
2509
+ }
2286
2510
  actorRequestSave(ctx, opts) {
2287
2511
  callHandle(asWasmActorContext(ctx), "requestSave", opts);
2288
2512
  }
@@ -2497,9 +2721,9 @@ var WasmCoreRuntime = class {
2497
2721
  );
2498
2722
  return results.map(normalizeRuntimeSqlExecuteResult);
2499
2723
  }
2500
- async actorSqlBeginTransaction(ctx, timeoutMs) {
2724
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
2501
2725
  return await callWasm(
2502
- () => this.#actorSql(ctx).beginTransaction(timeoutMs)
2726
+ () => this.#actorSql(ctx).beginTransaction(timeoutMs, name)
2503
2727
  );
2504
2728
  }
2505
2729
  async actorSqlTransactionExec(transaction, sql) {
@@ -2523,6 +2747,27 @@ var WasmCoreRuntime = class {
2523
2747
  () => transaction.rollback()
2524
2748
  );
2525
2749
  }
2750
+ async actorBeginStateTransaction(ctx, timeoutMs) {
2751
+ return await callWasm(
2752
+ () => asWasmActorContext(ctx).beginStateTransaction(timeoutMs)
2753
+ );
2754
+ }
2755
+ async actorStateTransactionExecute(transaction, sql, params) {
2756
+ const result = await callWasm(
2757
+ () => transaction.execute(sql, params)
2758
+ );
2759
+ return normalizeRuntimeSqlExecuteResult(result);
2760
+ }
2761
+ async actorStateTransactionCommit(transaction, payload) {
2762
+ await callWasm(
2763
+ () => transaction.commit(payload)
2764
+ );
2765
+ }
2766
+ async actorStateTransactionRollback(transaction) {
2767
+ await callWasm(
2768
+ () => transaction.rollback()
2769
+ );
2770
+ }
2526
2771
  async actorSqlQuery(ctx, sql, params) {
2527
2772
  return await callWasm(() => this.#actorSql(ctx).query(sql, params));
2528
2773
  }
@@ -2595,6 +2840,16 @@ var WasmCoreRuntime = class {
2595
2840
  signal
2596
2841
  );
2597
2842
  }
2843
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
2844
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2845
+ return await callHandleAsync(
2846
+ queue2,
2847
+ "completePersisted",
2848
+ messageId,
2849
+ expectedName,
2850
+ response
2851
+ );
2852
+ }
2598
2853
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
2599
2854
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2600
2855
  return optionalBytes(
@@ -2795,6 +3050,83 @@ function createWriteThroughProxy(value, commit, beforeChange) {
2795
3050
  }
2796
3051
  );
2797
3052
  }
3053
+ function unwrapProxy(value) {
3054
+ let current = value;
3055
+ while (current !== null && typeof current === "object") {
3056
+ const target = onChange.target(current);
3057
+ if (target === current) {
3058
+ break;
3059
+ }
3060
+ current = target;
3061
+ }
3062
+ return current;
3063
+ }
3064
+ function isPlainObject(value) {
3065
+ const proto = Object.getPrototypeOf(value);
3066
+ return proto === Object.prototype || proto === null;
3067
+ }
3068
+ function unwrapDeep(value, seen) {
3069
+ const unwrapped = unwrapProxy(value);
3070
+ if (!unwrapped || typeof unwrapped !== "object") {
3071
+ return unwrapped;
3072
+ }
3073
+ if (seen.has(unwrapped)) {
3074
+ return unwrapped;
3075
+ }
3076
+ seen.add(unwrapped);
3077
+ if (Array.isArray(unwrapped)) {
3078
+ for (let i = 0; i < unwrapped.length; i++) {
3079
+ const child = unwrapDeep(unwrapped[i], seen);
3080
+ if (child !== unwrapped[i]) {
3081
+ unwrapped[i] = child;
3082
+ }
3083
+ }
3084
+ return unwrapped;
3085
+ }
3086
+ if (unwrapped instanceof Map) {
3087
+ const replacements = [];
3088
+ for (const [key, child] of unwrapped.entries()) {
3089
+ const nextKey = unwrapDeep(key, seen);
3090
+ const nextChild = unwrapDeep(child, seen);
3091
+ if (nextKey !== key || nextChild !== child) {
3092
+ replacements.push([key, nextKey, nextChild]);
3093
+ }
3094
+ }
3095
+ for (const [key, nextKey, nextChild] of replacements) {
3096
+ if (nextKey !== key) {
3097
+ unwrapped.delete(key);
3098
+ }
3099
+ unwrapped.set(nextKey, nextChild);
3100
+ }
3101
+ return unwrapped;
3102
+ }
3103
+ if (unwrapped instanceof Set) {
3104
+ const replacements = [];
3105
+ for (const child of unwrapped.values()) {
3106
+ const next = unwrapDeep(child, seen);
3107
+ if (next !== child) {
3108
+ replacements.push([child, next]);
3109
+ }
3110
+ }
3111
+ for (const [child, next] of replacements) {
3112
+ unwrapped.delete(child);
3113
+ unwrapped.add(next);
3114
+ }
3115
+ return unwrapped;
3116
+ }
3117
+ if (isPlainObject(unwrapped)) {
3118
+ for (const key of Object.keys(unwrapped)) {
3119
+ const child = unwrapDeep(unwrapped[key], seen);
3120
+ if (child !== unwrapped[key]) {
3121
+ unwrapped[key] = child;
3122
+ }
3123
+ }
3124
+ }
3125
+ return unwrapped;
3126
+ }
3127
+ function unwrapWriteThroughProxy(value) {
3128
+ return unwrapDeep(value, /* @__PURE__ */ new Set());
3129
+ }
2798
3130
 
2799
3131
  // src/registry/native.ts
2800
3132
  var textEncoder = new TextEncoder();
@@ -2941,6 +3273,14 @@ function stateMutationReentrantError() {
2941
3273
  "State mutations are not allowed inside onStateChange."
2942
3274
  );
2943
3275
  }
3276
+ function stateTransactionConflictError() {
3277
+ return new RivetError(
3278
+ "actor",
3279
+ "state_transaction_conflict",
3280
+ "State cannot be mutated by another action while an experimental state-aware database transaction is active.",
3281
+ { public: true, statusCode: 409 }
3282
+ );
3283
+ }
2944
3284
  function databaseNotConfiguredError() {
2945
3285
  return new RivetError(
2946
3286
  "actor",
@@ -2957,6 +3297,14 @@ function databaseClientNotReadyError() {
2957
3297
  { public: true }
2958
3298
  );
2959
3299
  }
3300
+ function runHandlerNotConfiguredError() {
3301
+ return new RivetError(
3302
+ "actor",
3303
+ "run_handler_unavailable",
3304
+ "Cannot schedule a run wake because this actor does not define a run handler.",
3305
+ { public: true, statusCode: 409 }
3306
+ );
3307
+ }
2960
3308
  function stateNotEnabledError() {
2961
3309
  return new RivetError(
2962
3310
  "actor",
@@ -3059,10 +3407,11 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
3059
3407
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
3060
3408
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
3061
3409
  executeBatch: (statements) => runtime.actorSqlExecuteBatch(ctx, statements),
3062
- beginTransaction: async (timeoutMs) => {
3410
+ beginTransaction: async (timeoutMs, name) => {
3063
3411
  const transaction = await runtime.actorSqlBeginTransaction(
3064
3412
  ctx,
3065
- timeoutMs
3413
+ timeoutMs,
3414
+ name
3066
3415
  );
3067
3416
  return {
3068
3417
  exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
@@ -3075,6 +3424,38 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
3075
3424
  rollback: () => runtime.actorSqlTransactionRollback(transaction)
3076
3425
  };
3077
3426
  },
3427
+ beginStateTransaction: async (timeoutMs, context) => {
3428
+ const scope = context;
3429
+ if (!scope) {
3430
+ throw new Error(
3431
+ "actor state transaction context is not configured"
3432
+ );
3433
+ }
3434
+ const transaction = await runtime.actorBeginStateTransaction(
3435
+ ctx,
3436
+ timeoutMs
3437
+ );
3438
+ return {
3439
+ exec: async () => {
3440
+ throw new Error(
3441
+ "actor state transactions only support single-statement execute calls"
3442
+ );
3443
+ },
3444
+ execute: (sql, params) => runtime.actorStateTransactionExecute(
3445
+ transaction,
3446
+ sql,
3447
+ params
3448
+ ),
3449
+ commit: async () => {
3450
+ await runtime.actorStateTransactionCommit(
3451
+ transaction,
3452
+ scope.actorContext.serializeForTick("save")
3453
+ );
3454
+ scope.committed = true;
3455
+ },
3456
+ rollback: () => runtime.actorStateTransactionRollback(transaction)
3457
+ };
3458
+ },
3078
3459
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
3079
3460
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
3080
3461
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -3455,12 +3836,16 @@ var NativeConnAdapter = class {
3455
3836
  #schemas;
3456
3837
  #ctx;
3457
3838
  #queueHibernationRemoval;
3458
- constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval) {
3839
+ #assertCanMutateState;
3840
+ #stateProxy;
3841
+ #stateProxyTarget;
3842
+ constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval, assertCanMutateState) {
3459
3843
  this.#runtime = runtime;
3460
3844
  this.#conn = conn;
3461
3845
  this.#schemas = schemas;
3462
3846
  this.#ctx = ctx;
3463
3847
  this.#queueHibernationRemoval = queueHibernationRemoval;
3848
+ this.#assertCanMutateState = assertCanMutateState;
3464
3849
  this[CONN_STATE_MANAGER_SYMBOL] = {
3465
3850
  stateEnabled: true,
3466
3851
  get state() {
@@ -3483,22 +3868,46 @@ var NativeConnAdapter = class {
3483
3868
  }
3484
3869
  get state() {
3485
3870
  const nextState = this.#readState();
3871
+ if (!this.#ctx) {
3872
+ return this.#createStateProxy(nextState);
3873
+ }
3874
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
3875
+ this.#stateProxyTarget = nextState;
3876
+ this.#stateProxy = this.#createStateProxy(nextState);
3877
+ }
3878
+ return this.#stateProxy;
3879
+ }
3880
+ #createStateProxy(state) {
3881
+ const assertCurrentState = () => {
3882
+ var _a;
3883
+ (_a = this.#assertCanMutateState) == null ? void 0 : _a.call(this);
3884
+ if (this.#ctx && this.#readState() !== state) {
3885
+ throw stateTransactionConflictError();
3886
+ }
3887
+ };
3486
3888
  return createWriteThroughProxy(
3487
- nextState,
3889
+ state,
3488
3890
  (nextValue) => {
3891
+ assertCurrentState();
3489
3892
  this.#writeState(nextValue, { writeNative: true });
3490
3893
  },
3491
3894
  (newValue) => {
3895
+ assertCurrentState();
3492
3896
  assertJsonCompatValue(newValue);
3493
3897
  }
3494
3898
  );
3495
3899
  }
3496
3900
  set state(value) {
3497
- assertJsonCompatValue(value);
3498
- this.#writeState(value, { writeNative: true });
3901
+ var _a;
3902
+ (_a = this.#assertCanMutateState) == null ? void 0 : _a.call(this);
3903
+ const nextValue = unwrapWriteThroughProxy(value);
3904
+ assertJsonCompatValue(nextValue);
3905
+ this.#writeState(nextValue, { writeNative: true });
3499
3906
  }
3500
3907
  initializeState(value) {
3501
- this.#writeState(value, { writeNative: false });
3908
+ this.#writeState(unwrapWriteThroughProxy(value), {
3909
+ writeNative: false
3910
+ });
3502
3911
  }
3503
3912
  get isHibernatable() {
3504
3913
  return callNativeSync(
@@ -3816,8 +4225,9 @@ var NativeKvAdapter = class {
3816
4225
  };
3817
4226
  function wrapQueueMessage(message, schemas) {
3818
4227
  const name = callNativeSync(() => message.name());
4228
+ const id = callNativeSync(() => message.id());
3819
4229
  return {
3820
- id: Number(callNativeSync(() => message.id())),
4230
+ id: id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : id,
3821
4231
  name,
3822
4232
  body: validateQueueBody(
3823
4233
  schemas,
@@ -3955,6 +4365,25 @@ var NativeQueueAdapter = class {
3955
4365
  cleanup == null ? void 0 : cleanup();
3956
4366
  }
3957
4367
  }
4368
+ async waitForAvailable(names, options) {
4369
+ await this.waitForNamesAvailable(names ?? [], options);
4370
+ }
4371
+ async complete(message, response) {
4372
+ const validatedResponse = validateQueueComplete(
4373
+ this.#schemas,
4374
+ message.name,
4375
+ response
4376
+ );
4377
+ await callNative(
4378
+ () => this.#runtime.actorQueueCompletePersisted(
4379
+ this.#ctx,
4380
+ BigInt(message.id),
4381
+ message.name,
4382
+ encodeValue(validatedResponse)
4383
+ )
4384
+ );
4385
+ this.#pendingCompletableMessageIds.delete(message.id.toString());
4386
+ }
3958
4387
  async enqueueAndWait(name, body, options) {
3959
4388
  const validatedBody = validateQueueBody(this.#schemas, name, body);
3960
4389
  const { token, cleanup } = await createCancellationTokenHandle(
@@ -4391,10 +4820,12 @@ var NativeConnectionMap = class {
4391
4820
  #runtime;
4392
4821
  #ctx;
4393
4822
  #schemas;
4394
- constructor(runtime, ctx, schemas) {
4823
+ #assertCanMutateState;
4824
+ constructor(runtime, ctx, schemas, assertCanMutateState) {
4395
4825
  this.#runtime = runtime;
4396
4826
  this.#ctx = ctx;
4397
4827
  this.#schemas = schemas;
4828
+ this.#assertCanMutateState = assertCanMutateState;
4398
4829
  }
4399
4830
  #connToAdapter(conn) {
4400
4831
  return new NativeConnAdapter(
@@ -4407,7 +4838,8 @@ var NativeConnectionMap = class {
4407
4838
  this.#ctx,
4408
4839
  connId
4409
4840
  )
4410
- )
4841
+ ),
4842
+ this.#assertCanMutateState
4411
4843
  );
4412
4844
  }
4413
4845
  get size() {
@@ -4466,17 +4898,20 @@ var ActorContextHandleAdapter = class {
4466
4898
  #queue;
4467
4899
  #request;
4468
4900
  #schedule;
4469
- #sql;
4470
- #runHandlerActiveProvider;
4901
+ #run;
4902
+ #runHandlerConfigured;
4471
4903
  #onStateChange;
4472
4904
  #stateEnabled;
4473
- constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, runHandlerActiveProvider, onStateChange, dispatchCancelToken) {
4905
+ #stateProxy;
4906
+ #stateProxyTarget;
4907
+ #stateTransactionOwner = /* @__PURE__ */ Symbol("actor-state-transaction-owner");
4908
+ constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
4474
4909
  this.#runtime = runtime;
4475
4910
  this.#ctx = ctx;
4476
4911
  this.#clientFactory = clientFactory;
4477
4912
  this.#schemas = schemas;
4478
4913
  this.#dispatchCancelToken = dispatchCancelToken;
4479
- this.#runHandlerActiveProvider = runHandlerActiveProvider;
4914
+ this.#runHandlerConfigured = runHandlerConfigured;
4480
4915
  this.#onStateChange = onStateChange;
4481
4916
  this.#stateEnabled = stateEnabled;
4482
4917
  if (databaseProvider) {
@@ -4493,12 +4928,6 @@ var ActorContextHandleAdapter = class {
4493
4928
  }
4494
4929
  return this.#kv;
4495
4930
  }
4496
- get sql() {
4497
- if (!this.#sql) {
4498
- this.#sql = getOrCreateNativeSqlDatabase(this.#runtime, this.#ctx);
4499
- }
4500
- return this.#sql;
4501
- }
4502
4931
  async actorRuntimeSocket() {
4503
4932
  return await callNative(
4504
4933
  () => this.#runtime.actorRuntimeSocketProvision(this.#ctx)
@@ -4514,7 +4943,7 @@ var ActorContextHandleAdapter = class {
4514
4943
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4515
4944
  const cachedClient = runtimeState.databaseClient;
4516
4945
  if (cachedClient) {
4517
- this.#db = cachedClient.client;
4946
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
4518
4947
  return this.#db;
4519
4948
  }
4520
4949
  throw databaseClientNotReadyError();
@@ -4529,36 +4958,45 @@ var ActorContextHandleAdapter = class {
4529
4958
  if (!this.#stateEnabled) {
4530
4959
  throw stateNotEnabledError();
4531
4960
  }
4532
- const actorState = getNativePersistState(this.#runtime, this.#ctx);
4533
4961
  const nextState = this.#readState();
4534
- if (actorState.stateProxy === void 0 || actorState.stateProxyTarget !== nextState) {
4535
- actorState.stateProxyTarget = nextState;
4536
- actorState.stateProxy = createWriteThroughProxy(
4962
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
4963
+ const assertCurrentState = () => {
4964
+ this.#assertCanMutateState();
4965
+ if (this.#readState() !== nextState) {
4966
+ throw stateTransactionConflictError();
4967
+ }
4968
+ };
4969
+ this.#stateProxyTarget = nextState;
4970
+ this.#stateProxy = createWriteThroughProxy(
4537
4971
  nextState,
4538
4972
  (nextValue) => {
4973
+ assertCurrentState();
4539
4974
  this.#writeState(nextValue, { scheduleSave: true });
4540
4975
  },
4541
4976
  (newValue) => {
4542
- this.#assertCanMutateState();
4977
+ assertCurrentState();
4543
4978
  assertJsonCompatValue(newValue);
4544
4979
  }
4545
4980
  );
4546
4981
  }
4547
- return actorState.stateProxy;
4982
+ return this.#stateProxy;
4548
4983
  }
4549
4984
  set state(value) {
4550
4985
  if (!this.#stateEnabled) {
4551
4986
  throw stateNotEnabledError();
4552
4987
  }
4553
4988
  this.#assertCanMutateState();
4554
- assertJsonCompatValue(value);
4555
- this.#writeState(value, { scheduleSave: true });
4989
+ const nextValue = unwrapWriteThroughProxy(value);
4990
+ assertJsonCompatValue(nextValue);
4991
+ this.#writeState(nextValue, { scheduleSave: true });
4556
4992
  }
4557
4993
  initializeState(value) {
4558
4994
  if (!this.#stateEnabled) {
4559
4995
  return;
4560
4996
  }
4561
- this.#writeState(value, { scheduleSave: false });
4997
+ this.#writeState(unwrapWriteThroughProxy(value), {
4998
+ scheduleSave: false
4999
+ });
4562
5000
  }
4563
5001
  get vars() {
4564
5002
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
@@ -4584,6 +5022,26 @@ var ActorContextHandleAdapter = class {
4584
5022
  }
4585
5023
  return this.#queue;
4586
5024
  }
5025
+ get run() {
5026
+ if (!this.#run) {
5027
+ this.#run = {
5028
+ setWakeAt: async (timestamp) => {
5029
+ if (timestamp !== null && !this.#runHandlerConfigured) {
5030
+ throw runHandlerNotConfiguredError();
5031
+ }
5032
+ if (timestamp !== null && (!Number.isSafeInteger(timestamp) || timestamp < 0)) {
5033
+ throw new TypeError(
5034
+ "Run wake timestamp must be a non-negative safe integer or null"
5035
+ );
5036
+ }
5037
+ await callNative(
5038
+ () => this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp)
5039
+ );
5040
+ }
5041
+ };
5042
+ }
5043
+ return this.#run;
5044
+ }
4587
5045
  get schedule() {
4588
5046
  if (!this.#schedule) {
4589
5047
  this.#schedule = new NativeScheduleAdapter(
@@ -4618,7 +5076,8 @@ var ActorContextHandleAdapter = class {
4618
5076
  this.#connMap = new NativeConnectionMap(
4619
5077
  this.#runtime,
4620
5078
  this.#ctx,
4621
- this.#schemas
5079
+ this.#schemas,
5080
+ () => this.#assertCanMutateState()
4622
5081
  );
4623
5082
  }
4624
5083
  return this.#connMap;
@@ -4687,11 +5146,11 @@ var ActorContextHandleAdapter = class {
4687
5146
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4688
5147
  const cachedClient = runtimeState.databaseClient;
4689
5148
  if (cachedClient) {
4690
- this.#db = cachedClient.client;
5149
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
4691
5150
  return this.#db;
4692
5151
  }
4693
5152
  const actorId = this.actorId;
4694
- const client = await this.#databaseProvider.createClient({
5153
+ const createdClient = await this.#databaseProvider.createClient({
4695
5154
  actorId,
4696
5155
  kv: {
4697
5156
  batchPut: async (entries) => {
@@ -4712,21 +5171,126 @@ var ActorContextHandleAdapter = class {
4712
5171
  log: {
4713
5172
  debug: (obj) => logger2().debug(obj)
4714
5173
  },
4715
- nativeDatabaseProvider: {
4716
- open: async (requestedActorId) => {
4717
- void requestedActorId;
4718
- return getOrCreateNativeSqlDatabase(
4719
- this.#runtime,
4720
- this.#ctx
4721
- );
4722
- }
4723
- }
5174
+ nativeDatabaseProvider: registerNativeStateTransactionOpener(
5175
+ {
5176
+ open: async (requestedActorId) => {
5177
+ void requestedActorId;
5178
+ return getOrCreateNativeSqlDatabase(
5179
+ this.#runtime,
5180
+ this.#ctx
5181
+ );
5182
+ }
5183
+ },
5184
+ async (timeoutMs, context) => await getOrCreateNativeSqlDatabase(
5185
+ this.#runtime,
5186
+ this.#ctx
5187
+ ).beginStateTransaction(timeoutMs, context)
5188
+ )
4724
5189
  });
4725
5190
  runtimeState.databaseClient = {
4726
- client
5191
+ client: createdClient
4727
5192
  };
4728
- this.#db = client;
4729
- return client;
5193
+ this.#db = this.#bindDatabaseClient(createdClient);
5194
+ return this.#db;
5195
+ }
5196
+ #bindDatabaseClient(client) {
5197
+ return bindNativeStateTransactionContext(client, {
5198
+ enter: async () => await this.#enterStateTransaction(),
5199
+ exit: (scope) => this.#exitStateTransaction(
5200
+ scope
5201
+ )
5202
+ });
5203
+ }
5204
+ async #enterStateTransaction() {
5205
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5206
+ let pendingOwners = actorState.pendingStateTransactionOwners;
5207
+ if (!pendingOwners) {
5208
+ pendingOwners = /* @__PURE__ */ new Set();
5209
+ actorState.pendingStateTransactionOwners = pendingOwners;
5210
+ }
5211
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner || pendingOwners.has(this.#stateTransactionOwner)) {
5212
+ throw stateTransactionConflictError();
5213
+ }
5214
+ pendingOwners.add(this.#stateTransactionOwner);
5215
+ const predecessor = actorState.stateTransactionTail ?? Promise.resolve();
5216
+ let release;
5217
+ const hold = new Promise((resolve) => {
5218
+ release = resolve;
5219
+ });
5220
+ actorState.stateTransactionTail = predecessor.then(
5221
+ async () => await hold
5222
+ );
5223
+ try {
5224
+ await predecessor;
5225
+ pendingOwners.delete(this.#stateTransactionOwner);
5226
+ actorState.activeStateTransactionOwner = this.#stateTransactionOwner;
5227
+ return {
5228
+ actorContext: this,
5229
+ actorStateBaseline: this.#stateEnabled ? structuredClone(this.#readState()) : void 0,
5230
+ connectionStateBaselines: new Map(
5231
+ callNativeSync(
5232
+ () => this.#runtime.actorConns(this.#ctx)
5233
+ ).map((conn) => [
5234
+ callNativeSync(() => this.#runtime.connId(conn)),
5235
+ new Uint8Array(
5236
+ callNativeSync(() => this.#runtime.connState(conn))
5237
+ )
5238
+ ])
5239
+ ),
5240
+ committed: false,
5241
+ release
5242
+ };
5243
+ } catch (error) {
5244
+ pendingOwners.delete(this.#stateTransactionOwner);
5245
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5246
+ actorState.activeStateTransactionOwner = void 0;
5247
+ }
5248
+ release();
5249
+ throw error;
5250
+ }
5251
+ }
5252
+ #exitStateTransaction(scope) {
5253
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5254
+ try {
5255
+ if (!scope.committed) {
5256
+ this.#restoreStateTransactionBaseline(scope);
5257
+ }
5258
+ } finally {
5259
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5260
+ actorState.activeStateTransactionOwner = void 0;
5261
+ }
5262
+ if (actorState.stateTransactionSaveDeferred) {
5263
+ actorState.stateTransactionSaveDeferred = false;
5264
+ this.#scheduleSave();
5265
+ }
5266
+ scope.release();
5267
+ }
5268
+ }
5269
+ #restoreStateTransactionBaseline(scope) {
5270
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5271
+ if (actorState.pendingSaveHandle !== void 0) {
5272
+ clearImmediate(actorState.pendingSaveHandle);
5273
+ }
5274
+ actorState.pendingSaveHandle = void 0;
5275
+ actorState.saveScheduled = false;
5276
+ if (this.#stateEnabled) {
5277
+ actorState.state = structuredClone(scope.actorStateBaseline);
5278
+ }
5279
+ for (const conn of callNativeSync(
5280
+ () => this.#runtime.actorConns(this.#ctx)
5281
+ )) {
5282
+ const connId = callNativeSync(() => this.#runtime.connId(conn));
5283
+ const baseline = scope.connectionStateBaselines.get(connId);
5284
+ if (baseline === void 0) {
5285
+ continue;
5286
+ }
5287
+ callNativeSync(() => this.#runtime.connSetState(conn, baseline));
5288
+ const cached = actorState.connStates.get(connId);
5289
+ if (cached) {
5290
+ cached.state = decodeValue(baseline);
5291
+ }
5292
+ }
5293
+ this.#scheduleSave();
4730
5294
  }
4731
5295
  async prepare() {
4732
5296
  if (!this.#databaseProvider) {
@@ -4744,7 +5308,6 @@ var ActorContextHandleAdapter = class {
4744
5308
  }
4745
5309
  async closeDatabase() {
4746
5310
  this.#db = void 0;
4747
- this.#sql = void 0;
4748
5311
  await closeNativeDatabaseClient(this.#runtime, this.#ctx);
4749
5312
  await closeNativeSqlDatabase(this.#runtime, this.#ctx);
4750
5313
  }
@@ -4764,6 +5327,7 @@ var ActorContextHandleAdapter = class {
4764
5327
  }
4765
5328
  async saveState(opts) {
4766
5329
  if (opts == null ? void 0 : opts.immediate) {
5330
+ this.#assertCanAwaitStateSave();
4767
5331
  await callNative(
4768
5332
  () => this.#runtime.actorRequestSaveAndWait(this.#ctx, {
4769
5333
  immediate: true
@@ -4784,10 +5348,17 @@ var ActorContextHandleAdapter = class {
4784
5348
  );
4785
5349
  }
4786
5350
  async saveStateAndWorkflowBatch(writes) {
5351
+ this.#assertCanAwaitStateSave();
4787
5352
  await callNative(
4788
5353
  () => this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes)
4789
5354
  );
4790
5355
  }
5356
+ #assertCanAwaitStateSave() {
5357
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5358
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5359
+ throw stateTransactionConflictError();
5360
+ }
5361
+ }
4791
5362
  serializeForTick(reason) {
4792
5363
  void reason;
4793
5364
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -4841,10 +5412,6 @@ var ActorContextHandleAdapter = class {
4841
5412
  }
4842
5413
  return promise;
4843
5414
  }
4844
- runHandlerActive() {
4845
- var _a;
4846
- return ((_a = this.#runHandlerActiveProvider) == null ? void 0 : _a.call(this)) ?? false;
4847
- }
4848
5415
  internalKeepAwake(run) {
4849
5416
  const promise = typeof run === "function" ? run() : run;
4850
5417
  const trackedPromise = promise.then(
@@ -4926,7 +5493,6 @@ var ActorContextHandleAdapter = class {
4926
5493
  var _a;
4927
5494
  this.#flushStateChange();
4928
5495
  (_a = this.#abortSignalCleanup) == null ? void 0 : _a.call(this);
4929
- this.#sql = void 0;
4930
5496
  }
4931
5497
  #createActorAbortSignal() {
4932
5498
  const nativeSignal = callNativeSync(
@@ -4960,10 +5526,18 @@ var ActorContextHandleAdapter = class {
4960
5526
  this.#scheduleSave();
4961
5527
  }
4962
5528
  #assertCanMutateState() {
5529
+ var _a;
4963
5530
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4964
5531
  if (actorState.isInOnStateChange) {
4965
5532
  throw stateMutationReentrantError();
4966
5533
  }
5534
+ if (actorState.activeStateTransactionOwner !== this.#stateTransactionOwner && (actorState.activeStateTransactionOwner !== void 0 || (((_a = actorState.pendingStateTransactionOwners) == null ? void 0 : _a.size) ?? 0) > 0)) {
5535
+ throw stateTransactionConflictError();
5536
+ }
5537
+ }
5538
+ /** @internal */
5539
+ assertCanMutateState() {
5540
+ this.#assertCanMutateState();
4967
5541
  }
4968
5542
  // Coalesce the request-save and onStateChange work to once per event loop
4969
5543
  // tick. A synchronous burst of mutations (for example
@@ -4985,6 +5559,15 @@ var ActorContextHandleAdapter = class {
4985
5559
  if (!actorState.saveScheduled) {
4986
5560
  return;
4987
5561
  }
5562
+ if (actorState.activeStateTransactionOwner !== void 0) {
5563
+ actorState.saveScheduled = false;
5564
+ if (actorState.pendingSaveHandle !== void 0) {
5565
+ clearImmediate(actorState.pendingSaveHandle);
5566
+ actorState.pendingSaveHandle = void 0;
5567
+ }
5568
+ actorState.stateTransactionSaveDeferred = true;
5569
+ return;
5570
+ }
4988
5571
  actorState.saveScheduled = false;
4989
5572
  if (actorState.pendingSaveHandle !== void 0) {
4990
5573
  clearImmediate(actorState.pendingSaveHandle);
@@ -5108,9 +5691,6 @@ var NativeWorkflowRuntimeAdapter = class {
5108
5691
  }
5109
5692
  };
5110
5693
  }
5111
- isRunHandlerActive() {
5112
- return this.#ctx.runHandlerActive();
5113
- }
5114
5694
  async restartRunHandler() {
5115
5695
  await this.#ctx.restartRunHandler();
5116
5696
  }
@@ -5143,43 +5723,45 @@ var NativeWorkflowRuntimeAdapter = class {
5143
5723
  };
5144
5724
  }
5145
5725
  };
5146
- function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken) {
5147
- return Object.assign(
5148
- new ActorContextHandleAdapter(
5726
+ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
5727
+ const actorContext = new ActorContextHandleAdapter(
5728
+ runtime,
5729
+ ctx,
5730
+ clientFactory,
5731
+ schemas,
5732
+ databaseProvider,
5733
+ request,
5734
+ stateEnabled,
5735
+ onStateChange,
5736
+ dispatchCancelToken,
5737
+ runHandlerConfigured
5738
+ );
5739
+ return Object.assign(actorContext, {
5740
+ conn: new NativeConnAdapter(
5149
5741
  runtime,
5150
- ctx,
5151
- clientFactory,
5742
+ conn,
5152
5743
  schemas,
5153
- databaseProvider,
5154
- request,
5155
- stateEnabled,
5156
- void 0,
5157
- onStateChange,
5158
- dispatchCancelToken
5159
- ),
5160
- {
5161
- conn: new NativeConnAdapter(
5162
- runtime,
5163
- conn,
5164
- schemas,
5165
- ctx,
5166
- (connId) => callNativeSync(
5167
- () => runtime.actorQueueHibernationRemoval(ctx, connId)
5168
- )
5169
- )
5170
- }
5171
- );
5744
+ ctx,
5745
+ (connId) => callNativeSync(
5746
+ () => runtime.actorQueueHibernationRemoval(ctx, connId)
5747
+ ),
5748
+ () => actorContext.assertCanMutateState()
5749
+ )
5750
+ });
5172
5751
  }
5173
5752
  function buildActorConfig(definition, registryConfig, runtimeKind) {
5753
+ var _a;
5174
5754
  const config = definition.config;
5175
5755
  const options = config.options ?? {};
5176
5756
  const canHibernate = options.canHibernateWebSocket;
5177
5757
  const usesRemoteSqlite = sqliteBackendForConfig(registryConfig) === "remote";
5758
+ const sqliteProfiling = (_a = config.db) == null ? void 0 : _a.sqliteProfiling;
5178
5759
  return {
5179
5760
  name: options.name,
5180
5761
  icon: options.icon,
5181
- hasDatabase: config.db !== void 0 || usesRemoteSqlite,
5762
+ hasDatabase: true,
5182
5763
  remoteSqlite: usesRemoteSqlite,
5764
+ sqliteProfiling,
5183
5765
  enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
5184
5766
  hasState: config.state !== void 0 || typeof config.createState === "function",
5185
5767
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
@@ -5278,7 +5860,7 @@ function validateInspectorTabSource(tabId, resolved) {
5278
5860
  function buildNativeFactory(runtime, registryConfig, definition) {
5279
5861
  var _a;
5280
5862
  const config = definition.config;
5281
- const databaseProvider = config.db;
5863
+ const databaseProvider = config.db ?? db();
5282
5864
  const actionHandlers = flattenActionHandlers(config.actions);
5283
5865
  const schemaConfig = {
5284
5866
  actionInputSchemas: flattenActionInputSchemas(
@@ -5295,16 +5877,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5295
5877
  ),
5296
5878
  { encoding: "bare" }
5297
5879
  );
5298
- const nativeRunHandlerActiveByActorId = /* @__PURE__ */ new Map();
5299
- const isNativeRunHandlerActive = (ctx) => nativeRunHandlerActiveByActorId.get(
5300
- callNativeSync(() => runtime.actorId(ctx))
5301
- ) ?? false;
5880
+ const run = getRunFunction(config.run);
5881
+ const runHandlerCoordinator = getRunInspectorKind(config.run) === "workflow" ? new RunHandlerCoordinator(config.run) : void 0;
5302
5882
  const getNativeWorkflowInspector = (ctx) => {
5303
- var _a2;
5304
- return (_a2 = getRunInspectorConfig(
5305
- config.run,
5306
- callNativeSync(() => runtime.actorId(ctx))
5307
- )) == null ? void 0 : _a2.workflow;
5883
+ var _a2, _b;
5884
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
5885
+ const restart = () => callNativeSync(() => runtime.actorRestartRunHandler(ctx));
5886
+ 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);
5308
5887
  };
5309
5888
  const onStateChange = typeof config.onStateChange === "function" ? (actorCtx, nextState) => {
5310
5889
  config.onStateChange(actorCtx, nextState);
@@ -5324,9 +5903,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5324
5903
  databaseProvider,
5325
5904
  request,
5326
5905
  stateEnabled,
5327
- () => isNativeRunHandlerActive(ctx),
5328
5906
  onStateChange,
5329
- cancelToken
5907
+ cancelToken,
5908
+ run !== void 0
5330
5909
  );
5331
5910
  const makeConnCtx = (ctx, conn, request, cancelToken) => withConnContext(
5332
5911
  runtime,
@@ -5338,7 +5917,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5338
5917
  request,
5339
5918
  stateEnabled,
5340
5919
  onStateChange,
5341
- cancelToken
5920
+ cancelToken,
5921
+ run !== void 0
5342
5922
  );
5343
5923
  const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
5344
5924
  var _a2, _b, _c, _d;
@@ -5389,6 +5969,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5389
5969
  return await ((_b2 = (_a3 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a3.getState) == null ? void 0 : _b2.call(_a3)) ?? null;
5390
5970
  };
5391
5971
  const actorCtx = makeActorCtx(ctx, jsRequest);
5972
+ const sql = getOrCreateNativeSqlDatabase(runtime, ctx);
5392
5973
  try {
5393
5974
  if (url.pathname === "/inspector/state" && jsRequest.method === "GET") {
5394
5975
  return jsonResponse({
@@ -5516,9 +6097,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5516
6097
  }
5517
6098
  }
5518
6099
  if (url.pathname === "/inspector/database/schema" && jsRequest.method === "GET") {
5519
- const db = actorCtx.sql;
6100
+ const db2 = sql;
5520
6101
  const tables = queryRows(
5521
- await db.query(
6102
+ await db2.query(
5522
6103
  "SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle_%' ORDER BY name"
5523
6104
  )
5524
6105
  );
@@ -5526,13 +6107,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5526
6107
  for (const table of tables) {
5527
6108
  const quoted = `"${table.name.replace(/"/g, '""')}"`;
5528
6109
  const columns = queryRows(
5529
- await db.query(`PRAGMA table_info(${quoted})`)
6110
+ await db2.query(`PRAGMA table_info(${quoted})`)
5530
6111
  );
5531
6112
  const foreignKeys = queryRows(
5532
- await db.query(`PRAGMA foreign_key_list(${quoted})`)
6113
+ await db2.query(`PRAGMA foreign_key_list(${quoted})`)
5533
6114
  );
5534
6115
  const countResult = queryRows(
5535
- await db.query(
6116
+ await db2.query(
5536
6117
  `SELECT COUNT(*) as count FROM ${quoted}`
5537
6118
  )
5538
6119
  );
@@ -5567,7 +6148,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5567
6148
  );
5568
6149
  const quoted = `"${table.replace(/"/g, '""')}"`;
5569
6150
  const rows = queryRows(
5570
- await actorCtx.sql.query(
6151
+ await sql.query(
5571
6152
  `SELECT * FROM ${quoted} LIMIT ? OFFSET ?`,
5572
6153
  [
5573
6154
  Math.max(0, Math.min(limit, 500)),
@@ -5595,15 +6176,11 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5595
6176
  const bindings = normalizeSqlitePropertyBindings(
5596
6177
  body.properties
5597
6178
  );
5598
- const rows2 = queryRows(
5599
- await actorCtx.sql.query(body.sql, bindings)
5600
- );
6179
+ const rows2 = queryRows(await sql.query(body.sql, bindings));
5601
6180
  return jsonResponse({ rows: jsonSafe(rows2) });
5602
6181
  }
5603
6182
  const args = Array.isArray(body.args) ? body.args : [];
5604
- const rows = queryRows(
5605
- await actorCtx.sql.query(body.sql, args)
5606
- );
6183
+ const rows = queryRows(await sql.query(body.sql, args));
5607
6184
  return jsonResponse({ rows: jsonSafe(rows) });
5608
6185
  }
5609
6186
  if (url.pathname === "/inspector/summary" && jsRequest.method === "GET") {
@@ -5629,7 +6206,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5629
6206
  rpcs: Object.keys(actionHandlers).sort(),
5630
6207
  queueSize: inspectorSnapshot.queueSize,
5631
6208
  isStateEnabled: stateEnabled,
5632
- isDatabaseEnabled: databaseProvider !== void 0,
6209
+ isDatabaseEnabled: true,
5633
6210
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0,
5634
6211
  workflowState: await workflowState(),
5635
6212
  workflowHistory: workflowHistory()
@@ -5819,6 +6396,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5819
6396
  async (error, payload) => {
5820
6397
  const { ctx } = unwrapTsfnPayload(error, payload);
5821
6398
  const actorCtx = makeActorCtx(ctx);
6399
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
5822
6400
  const saveActorState = async () => {
5823
6401
  if (runtime.kind === "wasm") {
5824
6402
  await runtime.actorSaveState(
@@ -5844,6 +6422,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5844
6422
  saveActorState
5845
6423
  );
5846
6424
  } finally {
6425
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
6426
+ disposeRunInspector(config.run, actorId);
5847
6427
  await actorCtx.dispose();
5848
6428
  }
5849
6429
  }
@@ -5853,14 +6433,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5853
6433
  async (error, payload) => {
5854
6434
  const { ctx } = unwrapTsfnPayload(error, payload);
5855
6435
  const actorCtx = makeActorCtx(ctx);
6436
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
6437
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
6438
+ disposeRunInspector(config.run, actorId);
5856
6439
  try {
5857
6440
  if (typeof config.onDestroy === "function") {
5858
6441
  await config.onDestroy(actorCtx);
5859
6442
  }
5860
6443
  } finally {
5861
- const actorId = callNativeSync(() => runtime.actorId(ctx));
5862
- nativeRunHandlerActiveByActorId.delete(actorId);
5863
- disposeRunInspector(config.run, actorId);
5864
6444
  resolveNativeDestroy(runtime, ctx);
5865
6445
  await actorCtx.closeDatabase();
5866
6446
  clearNativeRuntimeState(runtime, ctx);
@@ -5908,7 +6488,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5908
6488
  ctx,
5909
6489
  connId
5910
6490
  )
5911
- )
6491
+ ),
6492
+ () => actorCtx.assertCanMutateState()
5912
6493
  );
5913
6494
  try {
5914
6495
  const nextConnState = hasStaticConnState ? structuredClone(config.connState) : await config.createConnState(
@@ -5945,7 +6526,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5945
6526
  ctx,
5946
6527
  connId
5947
6528
  )
5948
- )
6529
+ ),
6530
+ () => actorCtx.assertCanMutateState()
5949
6531
  );
5950
6532
  try {
5951
6533
  await config.onConnect(
@@ -5977,7 +6559,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5977
6559
  ctx,
5978
6560
  connId
5979
6561
  )
5980
- )
6562
+ ),
6563
+ () => actorCtx.assertCanMutateState()
5981
6564
  )
5982
6565
  );
5983
6566
  }
@@ -6121,7 +6704,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6121
6704
  }
6122
6705
  ) : void 0,
6123
6706
  run: (() => {
6124
- const run = getRunFunction(config.run);
6125
6707
  if (!run) {
6126
6708
  return void 0;
6127
6709
  }
@@ -6129,18 +6711,30 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6129
6711
  async (error, payload) => {
6130
6712
  const { ctx } = unwrapTsfnPayload(error, payload);
6131
6713
  const actorId = callNativeSync(() => runtime.actorId(ctx));
6132
- const actorCtx = makeActorCtx(ctx);
6133
- nativeRunHandlerActiveByActorId.set(actorId, true);
6134
- try {
6135
- await run(actorCtx);
6136
- } finally {
6137
- nativeRunHandlerActiveByActorId.delete(actorId);
6138
- await actorCtx.dispose();
6714
+ const executeRun = async () => {
6715
+ const actorCtx = makeActorCtx(ctx);
6716
+ try {
6717
+ await run(actorCtx);
6718
+ } finally {
6719
+ await actorCtx.dispose();
6720
+ }
6721
+ };
6722
+ if (runHandlerCoordinator) {
6723
+ const outcome = await runHandlerCoordinator.run(
6724
+ actorId,
6725
+ () => callNativeSync(
6726
+ () => runtime.actorRestartRunHandler(ctx)
6727
+ ),
6728
+ executeRun
6729
+ );
6730
+ return outcome !== "suppressed";
6139
6731
  }
6732
+ await executeRun();
6733
+ return true;
6140
6734
  }
6141
6735
  );
6142
6736
  })(),
6143
- getWorkflowHistory: getRunInspectorConfig(config.run) !== void 0 ? wrapNativeCallback(
6737
+ getWorkflowHistory: hasRunInspectorConfig(config.run) ? wrapNativeCallback(
6144
6738
  async (error, payload) => {
6145
6739
  var _a2;
6146
6740
  const { ctx } = unwrapTsfnPayload(error, payload);
@@ -6148,7 +6742,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6148
6742
  return history == null ? void 0 : toUint8Array(history);
6149
6743
  }
6150
6744
  ) : void 0,
6151
- replayWorkflow: getRunInspectorConfig(config.run) !== void 0 ? wrapNativeCallback(
6745
+ replayWorkflow: hasRunInspectorConfig(config.run) ? wrapNativeCallback(
6152
6746
  async (error, payload) => {
6153
6747
  const { ctx, entryId } = unwrapTsfnPayload(
6154
6748
  error,
@@ -6158,9 +6752,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6158
6752
  if (!(workflowInspector == null ? void 0 : workflowInspector.replayFromStep)) {
6159
6753
  return void 0;
6160
6754
  }
6161
- const history = await workflowInspector.replayFromStep(
6162
- entryId
6163
- ) ?? null;
6755
+ const history = await workflowInspector.replayFromStep(entryId) ?? null;
6164
6756
  return history == null ? void 0 : toUint8Array(history);
6165
6757
  }
6166
6758
  ) : void 0,
@@ -6213,7 +6805,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6213
6805
  jsRequest,
6214
6806
  stateEnabled,
6215
6807
  onStateChange,
6216
- cancelToken
6808
+ cancelToken,
6809
+ run !== void 0
6217
6810
  );
6218
6811
  try {
6219
6812
  if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
@@ -7119,6 +7712,7 @@ export {
7119
7712
  actor,
7120
7713
  buildActorNames,
7121
7714
  createClientWithDriver,
7715
+ defineRunHandler,
7122
7716
  event,
7123
7717
  isStaticActorDefinition,
7124
7718
  isStaticActorInstance,