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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/dist/browser/client.d.ts +1317 -765
  2. package/dist/browser/client.js +1457 -737
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +252 -129
  5. package/dist/browser/inspector/client.js +2042 -228
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/actor/errors.cjs +6 -2
  8. package/dist/tsup/actor/errors.cjs.map +1 -1
  9. package/dist/tsup/actor/errors.d.cts +1 -1
  10. package/dist/tsup/actor/errors.d.ts +1 -1
  11. package/dist/tsup/actor/errors.js +5 -1
  12. package/dist/tsup/agent-os/index.cjs +3 -2367
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +1 -2277
  15. package/dist/tsup/agent-os/index.d.ts +1 -2277
  16. package/dist/tsup/agent-os/index.js +3 -2367
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-7QKCGUTJ.cjs → chunk-2MOLY6AM.cjs} +444 -29
  19. package/dist/tsup/chunk-2MOLY6AM.cjs.map +1 -0
  20. package/dist/tsup/{chunk-IICIOTML.js → chunk-3DONDAMG.js} +2 -2
  21. package/dist/tsup/{chunk-XIX5DOZN.js → chunk-6FEYCVZC.js} +196 -20
  22. package/dist/tsup/chunk-6FEYCVZC.js.map +1 -0
  23. package/dist/tsup/chunk-6KXVLIXL.cjs +14 -0
  24. package/dist/tsup/chunk-6KXVLIXL.cjs.map +1 -0
  25. package/dist/tsup/chunk-73RNTXHB.cjs +243 -0
  26. package/dist/tsup/chunk-73RNTXHB.cjs.map +1 -0
  27. package/dist/tsup/{chunk-HXUEHHJF.js → chunk-A2CF6PFH.js} +19 -11
  28. package/dist/tsup/chunk-A2CF6PFH.js.map +1 -0
  29. package/dist/tsup/{chunk-75UE45DE.js → chunk-BRH4PQS5.js} +436 -21
  30. package/dist/tsup/chunk-BRH4PQS5.js.map +1 -0
  31. package/dist/tsup/{chunk-2WMYYG4R.cjs → chunk-BTSDFFDC.cjs} +18 -11
  32. package/dist/tsup/chunk-BTSDFFDC.cjs.map +1 -0
  33. package/dist/tsup/{chunk-RIT7N3TX.js → chunk-D5WUPE47.js} +50 -3
  34. package/dist/tsup/chunk-D5WUPE47.js.map +1 -0
  35. package/dist/tsup/{chunk-4PX3ZKJR.js → chunk-DJUBJQEQ.js} +3 -3
  36. package/dist/tsup/chunk-DJUBJQEQ.js.map +1 -0
  37. package/dist/tsup/{chunk-3MHDOUD7.cjs → chunk-HDVZ6YZG.cjs} +197 -21
  38. package/dist/tsup/chunk-HDVZ6YZG.cjs.map +1 -0
  39. package/dist/tsup/{chunk-JZ7TWV65.js → chunk-JTHHCZCZ.js} +24 -1
  40. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  41. package/dist/tsup/{chunk-ND567FR5.cjs → chunk-JUHXV3HF.cjs} +3 -3
  42. package/dist/tsup/chunk-JUHXV3HF.cjs.map +1 -0
  43. package/dist/tsup/chunk-JUWMP5O3.js +14 -0
  44. package/dist/tsup/chunk-JUWMP5O3.js.map +1 -0
  45. package/dist/tsup/{chunk-ZA7FLHKH.cjs → chunk-KVFIONKQ.cjs} +25 -2
  46. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  47. package/dist/tsup/{chunk-4FC7TVS6.cjs → chunk-MGI2VVF6.cjs} +39 -7
  48. package/dist/tsup/chunk-MGI2VVF6.cjs.map +1 -0
  49. package/dist/tsup/{chunk-NHUTYWKU.cjs → chunk-OTVJYZ2L.cjs} +1139 -470
  50. package/dist/tsup/chunk-OTVJYZ2L.cjs.map +1 -0
  51. package/dist/tsup/{chunk-VE2X4KMG.cjs → chunk-RTWH3AX3.cjs} +18 -10
  52. package/dist/tsup/chunk-RTWH3AX3.cjs.map +1 -0
  53. package/dist/tsup/{chunk-QAVN4QNO.cjs → chunk-TM76Z7XT.cjs} +7 -7
  54. package/dist/tsup/chunk-TM76Z7XT.cjs.map +1 -0
  55. package/dist/tsup/{chunk-AGDY6TKH.js → chunk-TRUHDXOU.js} +1023 -354
  56. package/dist/tsup/chunk-TRUHDXOU.js.map +1 -0
  57. package/dist/tsup/{chunk-XFYEVYHG.js → chunk-TSQTI6H6.js} +16 -9
  58. package/dist/tsup/chunk-TSQTI6H6.js.map +1 -0
  59. package/dist/tsup/{chunk-2CICCOBL.cjs → chunk-Z7E2G3JZ.cjs} +52 -5
  60. package/dist/tsup/chunk-Z7E2G3JZ.cjs.map +1 -0
  61. package/dist/tsup/{chunk-ZZ3WBRPD.js → chunk-ZOVJDAOW.js} +38 -6
  62. package/dist/tsup/chunk-ZOVJDAOW.js.map +1 -0
  63. package/dist/tsup/chunk-ZYK4B5WV.js +243 -0
  64. package/dist/tsup/chunk-ZYK4B5WV.js.map +1 -0
  65. package/dist/tsup/client/mod.cjs +8 -9
  66. package/dist/tsup/client/mod.cjs.map +1 -1
  67. package/dist/tsup/client/mod.d.cts +32 -6
  68. package/dist/tsup/client/mod.d.ts +32 -6
  69. package/dist/tsup/client/mod.js +7 -8
  70. package/dist/tsup/common/log.cjs +5 -3
  71. package/dist/tsup/common/log.cjs.map +1 -1
  72. package/dist/tsup/common/log.d.cts +5 -1
  73. package/dist/tsup/common/log.d.ts +5 -1
  74. package/dist/tsup/common/log.js +6 -4
  75. package/dist/tsup/common/websocket.cjs +4 -4
  76. package/dist/tsup/common/websocket.cjs.map +1 -1
  77. package/dist/tsup/common/websocket.js +3 -3
  78. package/dist/tsup/{config-BR1Nn0QQ.d.ts → config-B4erdavw.d.ts} +571 -65
  79. package/dist/tsup/{config-B0LNDrLY.d.ts → config-BfG1qpYz.d.cts} +80 -14
  80. package/dist/tsup/{config-B0LNDrLY.d.cts → config-BfG1qpYz.d.ts} +80 -14
  81. package/dist/tsup/{config-tCvkwzyN.d.cts → config-DK144OAw.d.cts} +571 -65
  82. package/dist/tsup/{context-oc9zhA3x.d.ts → context-Cvnf3BRe.d.cts} +3 -2
  83. package/dist/tsup/{context-D4WDwf9m.d.cts → context-Oxi6YWcG.d.ts} +3 -2
  84. package/dist/tsup/db/drizzle.cjs +127 -67
  85. package/dist/tsup/db/drizzle.cjs.map +1 -1
  86. package/dist/tsup/db/drizzle.d.cts +8 -4
  87. package/dist/tsup/db/drizzle.d.ts +8 -4
  88. package/dist/tsup/db/drizzle.js +127 -67
  89. package/dist/tsup/db/drizzle.js.map +1 -1
  90. package/dist/tsup/db/mod.cjs +6 -126
  91. package/dist/tsup/db/mod.cjs.map +1 -1
  92. package/dist/tsup/db/mod.d.cts +8 -4
  93. package/dist/tsup/db/mod.d.ts +8 -4
  94. package/dist/tsup/db/mod.js +5 -125
  95. package/dist/tsup/db/mod.js.map +1 -1
  96. package/dist/tsup/dynamic/mod.cjs +2 -2
  97. package/dist/tsup/dynamic/mod.cjs.map +1 -1
  98. package/dist/tsup/dynamic/mod.d.cts +6 -4
  99. package/dist/tsup/dynamic/mod.d.ts +6 -4
  100. package/dist/tsup/dynamic/mod.js +1 -1
  101. package/dist/tsup/inspector/mod.cjs +47 -12
  102. package/dist/tsup/inspector/mod.cjs.map +1 -1
  103. package/dist/tsup/inspector/mod.d.cts +26 -136
  104. package/dist/tsup/inspector/mod.d.ts +26 -136
  105. package/dist/tsup/inspector/mod.js +46 -11
  106. package/dist/tsup/inspector/mod.js.map +1 -1
  107. package/dist/tsup/inspector/workflow.cjs +21 -0
  108. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  109. package/dist/tsup/inspector/workflow.d.cts +144 -0
  110. package/dist/tsup/inspector/workflow.d.ts +144 -0
  111. package/dist/tsup/inspector/workflow.js +21 -0
  112. package/dist/tsup/inspector/workflow.js.map +1 -0
  113. package/dist/tsup/inspector-tab/mod.cjs +2 -13
  114. package/dist/tsup/inspector-tab/mod.cjs.map +1 -1
  115. package/dist/tsup/inspector-tab/mod.d.cts +9 -17
  116. package/dist/tsup/inspector-tab/mod.d.ts +9 -17
  117. package/dist/tsup/inspector-tab/mod.js +1 -12
  118. package/dist/tsup/inspector-tab/mod.js.map +1 -1
  119. package/dist/tsup/mod.cjs +2724 -611
  120. package/dist/tsup/mod.cjs.map +1 -1
  121. package/dist/tsup/mod.d.cts +9 -7
  122. package/dist/tsup/mod.d.ts +9 -7
  123. package/dist/tsup/mod.js +2641 -528
  124. package/dist/tsup/mod.js.map +1 -1
  125. package/dist/tsup/test/mod.cjs +19 -17
  126. package/dist/tsup/test/mod.cjs.map +1 -1
  127. package/dist/tsup/test/mod.d.cts +6 -4
  128. package/dist/tsup/test/mod.d.ts +6 -4
  129. package/dist/tsup/test/mod.js +18 -16
  130. package/dist/tsup/test/mod.js.map +1 -1
  131. package/dist/tsup/unstable/migrations.cjs +101 -0
  132. package/dist/tsup/unstable/migrations.cjs.map +1 -0
  133. package/dist/tsup/unstable/migrations.d.cts +29 -0
  134. package/dist/tsup/unstable/migrations.d.ts +29 -0
  135. package/dist/tsup/unstable/migrations.js +101 -0
  136. package/dist/tsup/unstable/migrations.js.map +1 -0
  137. package/dist/tsup/{utils-CqDnC_PS.d.cts → utils-3rsE0JvI.d.cts} +25 -2
  138. package/dist/tsup/{utils-CqDnC_PS.d.ts → utils-3rsE0JvI.d.ts} +25 -2
  139. package/dist/tsup/utils-C1O-SklO.d.ts +162 -0
  140. package/dist/tsup/utils-C6b0aYUM.d.cts +162 -0
  141. package/dist/tsup/utils.cjs +7 -3
  142. package/dist/tsup/utils.cjs.map +1 -1
  143. package/dist/tsup/utils.d.cts +4 -147
  144. package/dist/tsup/utils.d.ts +4 -147
  145. package/dist/tsup/utils.js +6 -2
  146. package/dist/tsup/workflow/mod.cjs +260 -200
  147. package/dist/tsup/workflow/mod.cjs.map +1 -1
  148. package/dist/tsup/workflow/mod.d.cts +8 -6
  149. package/dist/tsup/workflow/mod.d.ts +8 -6
  150. package/dist/tsup/workflow/mod.js +249 -189
  151. package/dist/tsup/workflow/mod.js.map +1 -1
  152. package/package.json +34 -14
  153. package/src/actor/actions.ts +155 -0
  154. package/src/actor/config.ts +403 -43
  155. package/src/actor/definition.ts +26 -7
  156. package/src/actor/errors.ts +87 -5
  157. package/src/actor/keys.ts +86 -0
  158. package/src/actor/mod.ts +15 -1
  159. package/src/actor/tracing.ts +28 -0
  160. package/src/agent-os/index.ts +5 -65
  161. package/src/client/actor-common.ts +8 -15
  162. package/src/client/actor-conn.ts +135 -8
  163. package/src/client/actor-handle.ts +180 -42
  164. package/src/client/actor-query.ts +8 -1
  165. package/src/client/auth.ts +37 -0
  166. package/src/client/client.ts +89 -21
  167. package/src/client/config.ts +27 -2
  168. package/src/client/errors.ts +2 -1
  169. package/src/client/lifecycle-errors.ts +16 -1
  170. package/src/client/mod.ts +9 -0
  171. package/src/client/outbound-telemetry.ts +66 -0
  172. package/src/client/query.ts +2 -0
  173. package/src/client/queue.ts +3 -0
  174. package/src/client/raw-utils.ts +37 -8
  175. package/src/client/resolve-gateway-target.ts +2 -0
  176. package/src/client/retry-budget.ts +78 -0
  177. package/src/client/token-provider.ts +93 -0
  178. package/src/client/utils.ts +16 -2
  179. package/src/common/actor-router-consts.ts +5 -0
  180. package/src/common/actor-telemetry-context.ts +19 -0
  181. package/src/common/bare/generated/actor-runtime-socket-protocol/v1.ts +848 -0
  182. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  183. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  184. package/src/common/bare/transport/v1.ts +36 -0
  185. package/src/common/database/config.ts +108 -15
  186. package/src/common/database/mod.ts +247 -76
  187. package/src/common/database/native-database.ts +433 -23
  188. package/src/common/database/shared.ts +24 -0
  189. package/src/common/encoding.ts +31 -21
  190. package/src/common/fetch-like.ts +63 -0
  191. package/src/common/inspector-transport.ts +12 -2
  192. package/src/common/log.ts +14 -8
  193. package/src/common/otel-context.ts +99 -0
  194. package/src/common/router.ts +1 -1
  195. package/src/common/utils.ts +7 -19
  196. package/src/db/drizzle.ts +182 -80
  197. package/src/db/mod.ts +2 -0
  198. package/src/dynamic/isolate-runtime.ts +0 -2
  199. package/src/engine-api/actors.ts +3 -3
  200. package/src/engine-client/actor-http-client.ts +29 -20
  201. package/src/engine-client/actor-websocket-client.ts +6 -3
  202. package/src/engine-client/api-endpoints.ts +72 -14
  203. package/src/engine-client/driver.ts +8 -15
  204. package/src/engine-client/mod.ts +248 -112
  205. package/src/inspector/client.browser.ts +134 -16
  206. package/src/inspector/mod.ts +1 -1
  207. package/src/inspector/workflow.ts +61 -0
  208. package/src/inspector-tab/mod.ts +1 -15
  209. package/src/registry/config/envoy.ts +2 -18
  210. package/src/registry/config/index.ts +53 -61
  211. package/src/registry/index.ts +311 -21
  212. package/src/registry/napi-runtime.ts +583 -39
  213. package/src/registry/native-http.ts +225 -0
  214. package/src/registry/native.ts +1365 -414
  215. package/src/registry/run-handler-coordinator.ts +219 -0
  216. package/src/registry/runtime.ts +372 -7
  217. package/src/registry/wasm-runtime.ts +490 -21
  218. package/src/registry/write-through-proxy.ts +101 -0
  219. package/src/test/mod.ts +1 -19
  220. package/src/test/ready.ts +22 -0
  221. package/src/unstable/migrations.ts +141 -0
  222. package/src/utils/env-vars.ts +15 -6
  223. package/src/utils/node.ts +44 -28
  224. package/src/utils.ts +3 -0
  225. package/src/workflow/context.ts +9 -27
  226. package/src/workflow/driver.ts +253 -116
  227. package/src/workflow/inspector.ts +23 -24
  228. package/src/workflow/mod.ts +50 -72
  229. package/dist/tsup/chunk-2CICCOBL.cjs.map +0 -1
  230. package/dist/tsup/chunk-2WMYYG4R.cjs.map +0 -1
  231. package/dist/tsup/chunk-3MHDOUD7.cjs.map +0 -1
  232. package/dist/tsup/chunk-4FC7TVS6.cjs.map +0 -1
  233. package/dist/tsup/chunk-4PX3ZKJR.js.map +0 -1
  234. package/dist/tsup/chunk-75UE45DE.js.map +0 -1
  235. package/dist/tsup/chunk-7QKCGUTJ.cjs.map +0 -1
  236. package/dist/tsup/chunk-AGDY6TKH.js.map +0 -1
  237. package/dist/tsup/chunk-HXUEHHJF.js.map +0 -1
  238. package/dist/tsup/chunk-JZ7TWV65.js.map +0 -1
  239. package/dist/tsup/chunk-ND567FR5.cjs.map +0 -1
  240. package/dist/tsup/chunk-NHUTYWKU.cjs.map +0 -1
  241. package/dist/tsup/chunk-QAVN4QNO.cjs.map +0 -1
  242. package/dist/tsup/chunk-RIT7N3TX.js.map +0 -1
  243. package/dist/tsup/chunk-RV5MAFDT.cjs +0 -382
  244. package/dist/tsup/chunk-RV5MAFDT.cjs.map +0 -1
  245. package/dist/tsup/chunk-VE2X4KMG.cjs.map +0 -1
  246. package/dist/tsup/chunk-XFYEVYHG.js.map +0 -1
  247. package/dist/tsup/chunk-XHGDS3DZ.js +0 -382
  248. package/dist/tsup/chunk-XHGDS3DZ.js.map +0 -1
  249. package/dist/tsup/chunk-XIX5DOZN.js.map +0 -1
  250. package/dist/tsup/chunk-ZA7FLHKH.cjs.map +0 -1
  251. package/dist/tsup/chunk-ZZ3WBRPD.js.map +0 -1
  252. package/src/actor/driver.ts +0 -141
  253. package/src/actor/instance/mod.ts +0 -2484
  254. package/src/actor/keys.test.ts +0 -275
  255. package/src/actor/utils.test.ts +0 -48
  256. package/src/agent-os/actor/cron.ts +0 -84
  257. package/src/agent-os/actor/db.ts +0 -54
  258. package/src/agent-os/actor/filesystem.ts +0 -131
  259. package/src/agent-os/actor/index.ts +0 -285
  260. package/src/agent-os/actor/network.ts +0 -58
  261. package/src/agent-os/actor/preview.ts +0 -190
  262. package/src/agent-os/actor/process.ts +0 -177
  263. package/src/agent-os/actor/session.ts +0 -518
  264. package/src/agent-os/actor/shell.ts +0 -60
  265. package/src/agent-os/config.ts +0 -79
  266. package/src/agent-os/fs/database-vfs.ts +0 -624
  267. package/src/agent-os/types.ts +0 -148
  268. package/src/client/test.ts +0 -44
  269. package/src/common/database/mod.test.ts +0 -137
  270. package/src/common/database/native-database.test.ts +0 -211
  271. package/src/common/inline-websocket-adapter.test.ts +0 -51
  272. package/src/drivers/engine/actor-driver.ts +0 -2473
  273. package/src/registry/process-metrics.ts +0 -250
  274. package/src/registry/runtime.test.ts +0 -50
  275. package/src/utils/endpoint-parser.test.ts +0 -206
  276. package/src/utils.test.ts +0 -34
  277. /package/dist/tsup/{chunk-IICIOTML.js.map → chunk-3DONDAMG.js.map} +0 -0
@@ -1,25 +1,24 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } var _class; var _class2;
2
2
 
3
3
 
4
- var _chunkVE2X4KMGcjs = require('./chunk-VE2X4KMG.cjs');
5
4
 
5
+ var _chunkRTWH3AX3cjs = require('./chunk-RTWH3AX3.cjs');
6
6
 
7
7
 
8
8
 
9
+ var _chunkJUHXV3HFcjs = require('./chunk-JUHXV3HF.cjs');
9
10
 
10
11
 
12
+ var _chunkKVFIONKQcjs = require('./chunk-KVFIONKQ.cjs');
11
13
 
12
14
 
13
15
 
14
16
 
15
- var _chunkRV5MAFDTcjs = require('./chunk-RV5MAFDT.cjs');
16
17
 
17
18
 
18
- var _chunkZA7FLHKHcjs = require('./chunk-ZA7FLHKH.cjs');
19
19
 
20
20
 
21
21
 
22
- var _chunkND567FR5cjs = require('./chunk-ND567FR5.cjs');
23
22
 
24
23
 
25
24
 
@@ -37,13 +36,14 @@ var _chunkND567FR5cjs = require('./chunk-ND567FR5.cjs');
37
36
 
38
37
 
39
38
 
40
- var _chunk7QKCGUTJcjs = require('./chunk-7QKCGUTJ.cjs');
39
+ var _chunk2MOLY6AMcjs = require('./chunk-2MOLY6AM.cjs');
41
40
 
42
41
 
43
42
 
44
43
 
45
44
 
46
- var _chunk4FC7TVS6cjs = require('./chunk-4FC7TVS6.cjs');
45
+
46
+ var _chunkMGI2VVF6cjs = require('./chunk-MGI2VVF6.cjs');
47
47
 
48
48
  // src/common/actor-router-consts.ts
49
49
  var PATH_CONNECT = "/connect";
@@ -52,10 +52,14 @@ var PATH_WEBSOCKET_PREFIX = "/websocket/";
52
52
  var HEADER_ACTOR_QUERY = "x-rivet-query";
53
53
  var HEADER_ENCODING = "x-rivet-encoding";
54
54
  var HEADER_CONN_PARAMS = "x-rivet-conn-params";
55
+ var HEADER_ORIGINAL_REQUEST_URL = "x-rivet-internal-original-request-url";
55
56
  var HEADER_ACTOR_ID = "x-rivet-actor";
56
57
  var HEADER_ACTOR_GENERATION = "x-rivet-actor-generation";
57
58
  var HEADER_ACTOR_KEY = "x-rivet-actor-key";
58
59
  var HEADER_RIVET_TOKEN = "x-rivet-token";
60
+ var HEADER_RIVET_RAY_ID = "x-rivet-ray-id";
61
+ var HEADER_TRACEPARENT = "traceparent";
62
+ var HEADER_TRACESTATE = "tracestate";
59
63
  var HEADER_RIVET_TARGET = "x-rivet-target";
60
64
  var HEADER_RIVET_ACTOR = "x-rivet-actor";
61
65
  var HEADER_RIVET_NAMESPACE = "x-rivet-namespace";
@@ -110,16 +114,16 @@ var ActorConnDisposed = class extends ActorClientError {
110
114
  function isSchedulingError(group, code) {
111
115
  return group === "guard" && (code === "actor_ready_timeout" || code === "actor_runner_failed");
112
116
  }
113
- function actorSchedulingError(group, code, actorId, details) {
114
- return new (0, _chunk4FC7TVS6cjs.RivetError)(
117
+ function actorSchedulingError(group, code, actorId, details, rayId) {
118
+ return new (0, _chunkMGI2VVF6cjs.RivetError)(
115
119
  group,
116
120
  code,
117
121
  `Actor failed to start (${actorId}): ${JSON.stringify(details)}`,
118
- { metadata: { actorId, details } }
122
+ { metadata: { actorId, details }, rayId }
119
123
  );
120
124
  }
121
125
  function internalClientError(message, opts) {
122
- return new (0, _chunk4FC7TVS6cjs.RivetError)("rivetkit", _chunk4FC7TVS6cjs.INTERNAL_ERROR_CODE, message, {
126
+ return new (0, _chunkMGI2VVF6cjs.RivetError)("rivetkit", _chunkMGI2VVF6cjs.INTERNAL_ERROR_CODE, message, {
123
127
  cause: opts == null ? void 0 : opts.cause
124
128
  });
125
129
  }
@@ -2104,7 +2108,7 @@ function getActorNameFromQuery(query) {
2104
2108
  if ("getForKey" in query) return query.getForKey.name;
2105
2109
  if ("getOrCreateForKey" in query) return query.getOrCreateForKey.name;
2106
2110
  if ("create" in query) return query.create.name;
2107
- throw _chunk4FC7TVS6cjs.invalidRequest.call(void 0, "Invalid query format");
2111
+ throw _chunkMGI2VVF6cjs.invalidRequest.call(void 0, "Invalid query format");
2108
2112
  }
2109
2113
  function isDynamicActorQuery(actorQuery) {
2110
2114
  return "getForKey" in actorQuery || "getOrCreateForKey" in actorQuery;
@@ -2114,7 +2118,7 @@ function getGatewayTarget(state) {
2114
2118
  return { directId: state.getForId.actorId };
2115
2119
  }
2116
2120
  if ("create" in state) {
2117
- throw _chunk4FC7TVS6cjs.invalidRequest.call(void 0,
2121
+ throw _chunkMGI2VVF6cjs.invalidRequest.call(void 0,
2118
2122
  "create queries cannot be used as gateway targets. Resolve to an actor ID first."
2119
2123
  );
2120
2124
  }
@@ -2123,28 +2127,106 @@ function getGatewayTarget(state) {
2123
2127
  function isStaleResolvedActorError(group, code) {
2124
2128
  return group === "actor" && (code === "not_found" || code === "starting" || code === "stopping" || code === "not_configured" || code === "dropped_reply" || code.startsWith("destroyed_"));
2125
2129
  }
2126
- async function checkForSchedulingError(group, code, actorId, query, driver) {
2130
+ async function checkForSchedulingError(group, code, actorId, query, driver, rayId) {
2127
2131
  const name = getActorNameFromQuery(query);
2128
2132
  try {
2129
2133
  const actor = await driver.getForId({ name, actorId });
2130
2134
  if (actor == null ? void 0 : actor.error) {
2131
- _chunkND567FR5cjs.logger.call(void 0, ).info({
2135
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).info({
2132
2136
  msg: "found actor scheduling error",
2133
2137
  actorId,
2134
2138
  error: actor.error
2135
2139
  });
2136
- return actorSchedulingError(group, code, actorId, actor.error);
2140
+ return actorSchedulingError(
2141
+ group,
2142
+ code,
2143
+ actorId,
2144
+ actor.error,
2145
+ rayId
2146
+ );
2137
2147
  }
2138
2148
  } catch (err) {
2139
- _chunkND567FR5cjs.logger.call(void 0, ).warn({
2149
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({
2140
2150
  msg: "failed to fetch actor details for scheduling error check",
2141
2151
  actorId,
2142
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, err)
2152
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, err)
2143
2153
  });
2144
2154
  }
2145
2155
  return null;
2146
2156
  }
2147
2157
 
2158
+ // src/common/fetch-like.ts
2159
+ function isUrlLike(value) {
2160
+ return typeof value === "object" && value !== null && typeof value.href === "string" && typeof value.pathname === "string" && typeof value.search === "string";
2161
+ }
2162
+ function isRequestLike(value) {
2163
+ return typeof value === "object" && value !== null && typeof value.url === "string" && typeof value.method === "string" && isHeadersLike(value.headers);
2164
+ }
2165
+ function isResponseLike(value) {
2166
+ return typeof value === "object" && value !== null && typeof value.status === "number" && isHeadersLike(value.headers) && typeof value.arrayBuffer === "function";
2167
+ }
2168
+ function isHeadersLike(value) {
2169
+ return typeof value === "object" && value !== null && typeof value.entries === "function";
2170
+ }
2171
+ function readRequestBody(request) {
2172
+ if (!request.body) return request.arrayBuffer();
2173
+ return new Response(
2174
+ request.body.pipeThrough(new TransformStream(), {
2175
+ signal: request.signal
2176
+ })
2177
+ ).arrayBuffer();
2178
+ }
2179
+
2180
+ // src/client/retry-budget.ts
2181
+ var DEFAULT_PERCENT = 10;
2182
+ var DEFAULT_MAX_TOKENS = 100;
2183
+ var RetryBudget = class {
2184
+ #tokens;
2185
+ #maxTokens;
2186
+ #deposit;
2187
+ constructor(options = {}) {
2188
+ const percent = _nullishCoalesce(options.percent, () => ( DEFAULT_PERCENT));
2189
+ const maxTokens = _nullishCoalesce(options.maxTokens, () => ( DEFAULT_MAX_TOKENS));
2190
+ if (!(percent >= 0 && percent <= 100)) {
2191
+ throw new Error("retryBudget.percent must be in 0..=100");
2192
+ }
2193
+ if (!(maxTokens >= 0)) {
2194
+ throw new Error("retryBudget.maxTokens must be at least 0");
2195
+ }
2196
+ this.#maxTokens = maxTokens;
2197
+ this.#tokens = maxTokens;
2198
+ this.#deposit = percent / 100;
2199
+ }
2200
+ /** Credits one request sent. */
2201
+ deposit() {
2202
+ this.#tokens = Math.min(this.#maxTokens, this.#tokens + this.#deposit);
2203
+ }
2204
+ /** Spends one token. Returns `false` when the budget is spent. */
2205
+ tryWithdraw() {
2206
+ if (this.#tokens + 1e-9 < 1) {
2207
+ return false;
2208
+ }
2209
+ this.#tokens = Math.max(0, this.#tokens - 1);
2210
+ return true;
2211
+ }
2212
+ };
2213
+ function retryAfterMs(error) {
2214
+ if (!(error instanceof _chunkMGI2VVF6cjs.RivetError)) {
2215
+ return void 0;
2216
+ }
2217
+ const metadata = error.metadata;
2218
+ if (metadata === null || typeof metadata !== "object") {
2219
+ return void 0;
2220
+ }
2221
+ const hint = metadata.retry_after_ms;
2222
+ return typeof hint === "number" && hint >= 0 ? hint : void 0;
2223
+ }
2224
+ function retryDelayMs(attempt, opts) {
2225
+ const backoff = Math.min(opts.initialDelayMs * 2 ** attempt, opts.maxDelayMs);
2226
+ const jittered = backoff / 2 + Math.random() * (backoff / 2);
2227
+ return Math.max(jittered, _nullishCoalesce(opts.hintMs, () => ( 0)));
2228
+ }
2229
+
2148
2230
  // src/client/lifecycle-errors.ts
2149
2231
  function* walkErrorChain(error, maxDepth = 8) {
2150
2232
  let current = error;
@@ -2272,7 +2354,7 @@ function classifyTransportError(error) {
2272
2354
  }
2273
2355
  function classifyLifecycleBoundaryError(error) {
2274
2356
  for (const current of walkErrorChain(error)) {
2275
- if (current instanceof _chunk4FC7TVS6cjs.RivetError) {
2357
+ if (current instanceof _chunkMGI2VVF6cjs.RivetError) {
2276
2358
  const classified = classifyActorError(current);
2277
2359
  if (classified) {
2278
2360
  return classified;
@@ -2320,9 +2402,11 @@ async function waitWithSignal(ms, signal) {
2320
2402
  });
2321
2403
  }
2322
2404
  async function retryOnLifecycleBoundary(run, opts) {
2405
+ var _a;
2323
2406
  const maxAttempts = _nullishCoalesce((opts == null ? void 0 : opts.maxAttempts), () => ( 5));
2324
2407
  const initialDelayMs = _nullishCoalesce((opts == null ? void 0 : opts.initialDelayMs), () => ( 25));
2325
2408
  const maxDelayMs = _nullishCoalesce((opts == null ? void 0 : opts.maxDelayMs), () => ( 200));
2409
+ (_a = opts == null ? void 0 : opts.budget) == null ? void 0 : _a.deposit();
2326
2410
  let lastError;
2327
2411
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
2328
2412
  throwIfAborted(opts == null ? void 0 : opts.signal);
@@ -2336,26 +2420,122 @@ async function retryOnLifecycleBoundary(run, opts) {
2336
2420
  if (attempt === maxAttempts - 1) {
2337
2421
  break;
2338
2422
  }
2339
- const delayMs = Math.min(initialDelayMs * 2 ** attempt, maxDelayMs);
2423
+ if ((opts == null ? void 0 : opts.budget) && !opts.budget.tryWithdraw()) {
2424
+ break;
2425
+ }
2426
+ const delayMs = retryDelayMs(attempt, {
2427
+ initialDelayMs,
2428
+ maxDelayMs,
2429
+ hintMs: retryAfterMs(error)
2430
+ });
2340
2431
  await waitWithSignal(delayMs, opts == null ? void 0 : opts.signal);
2341
2432
  }
2342
2433
  }
2343
2434
  throw lastError;
2344
2435
  }
2345
2436
 
2437
+ // src/common/otel-context.ts
2438
+
2439
+
2440
+
2441
+
2442
+
2443
+
2444
+ var _api = require('@opentelemetry/api');
2445
+ function readActiveTraceHeaders() {
2446
+ return traceHeaders(_api.trace.getSpanContext(_api.context.active()));
2447
+ }
2448
+ var RAY_BAGGAGE_KEY = "rivet.ray.id";
2449
+ function readActiveRayId() {
2450
+ var _a, _b;
2451
+ const value = (_b = (_a = _api.propagation.getBaggage(_api.context.active())) == null ? void 0 : _a.getEntry(RAY_BAGGAGE_KEY)) == null ? void 0 : _b.value;
2452
+ if (value && value.length <= 30 && /^[A-Za-z0-9_-]+$/.test(value)) {
2453
+ return value;
2454
+ }
2455
+ return void 0;
2456
+ }
2457
+ function actorInvocationTraceHeaders(invocation) {
2458
+ const spanContext = invocationSpanContext(invocation);
2459
+ if (!spanContext) return void 0;
2460
+ return traceHeaders(spanContext);
2461
+ }
2462
+ function traceHeaders(spanContext) {
2463
+ var _a;
2464
+ if (!spanContext || !_api.isSpanContextValid.call(void 0, spanContext)) return void 0;
2465
+ const tracestate = (_a = spanContext.traceState) == null ? void 0 : _a.serialize();
2466
+ return {
2467
+ traceparent: `00-${spanContext.traceId}-${spanContext.spanId}-${spanContext.traceFlags.toString(16).padStart(2, "0")}`,
2468
+ ...tracestate ? { tracestate } : {}
2469
+ };
2470
+ }
2471
+ function runWithActorInvocationSpan(invocation, run) {
2472
+ if (!invocation) return run();
2473
+ const spanContext = invocationSpanContext(invocation);
2474
+ if (!spanContext) return run();
2475
+ const parent = _api.trace.setSpanContext(_api.context.active(), spanContext);
2476
+ return _api.context.with(parent, run);
2477
+ }
2478
+ function invocationSpanContext(invocation) {
2479
+ if (!invocation) return void 0;
2480
+ try {
2481
+ const spanContext = {
2482
+ traceId: invocation.traceId,
2483
+ spanId: invocation.spanId,
2484
+ traceFlags: invocation.traceFlags,
2485
+ traceState: invocation.tracestate ? _api.createTraceState.call(void 0, invocation.tracestate) : void 0,
2486
+ isRemote: false
2487
+ };
2488
+ return _api.isSpanContextValid.call(void 0, spanContext) ? spanContext : void 0;
2489
+ } catch (e) {
2490
+ return void 0;
2491
+ }
2492
+ }
2493
+
2494
+ // src/client/outbound-telemetry.ts
2495
+ function outboundTelemetryHeaders(invocation, callSpan) {
2496
+ const headers = {};
2497
+ const rayId = _nullishCoalesce((invocation == null ? void 0 : invocation.rayId), () => ( readActiveRayId()));
2498
+ if (rayId) {
2499
+ headers[HEADER_RIVET_RAY_ID] = rayId;
2500
+ }
2501
+ const traceHeaders2 = _nullishCoalesce(_nullishCoalesce(actorInvocationTraceHeaders(callSpan), () => ( readActiveTraceHeaders())), () => ( actorInvocationTraceHeaders(invocation == null ? void 0 : invocation.span)));
2502
+ if (traceHeaders2) {
2503
+ headers[HEADER_TRACEPARENT] = traceHeaders2.traceparent;
2504
+ if (traceHeaders2.tracestate) {
2505
+ headers[HEADER_TRACESTATE] = traceHeaders2.tracestate;
2506
+ }
2507
+ }
2508
+ return headers;
2509
+ }
2510
+ function addOutboundTelemetryHeaders(headers, telemetry) {
2511
+ const callerSetTraceContext = headers.has(HEADER_TRACEPARENT) || headers.has(HEADER_TRACESTATE);
2512
+ for (const [name, value] of Object.entries(telemetry)) {
2513
+ const isTraceContext = name === HEADER_TRACEPARENT || name === HEADER_TRACESTATE;
2514
+ if (isTraceContext ? callerSetTraceContext : headers.has(name)) {
2515
+ continue;
2516
+ }
2517
+ headers.set(name, value);
2518
+ }
2519
+ }
2520
+
2346
2521
  // src/client/utils.ts
2347
2522
 
2523
+ var RETRY_AFTER_SUFFIX = /^retry_after_ms=(\d+)$/;
2348
2524
  function parseWebSocketCloseReason(reason) {
2349
- const [mainPart, rayId] = reason.split("#");
2525
+ const [mainPart, suffix] = reason.split("#");
2350
2526
  const [group, code] = mainPart.split(".");
2351
2527
  if (!group || !code) {
2352
- _chunkND567FR5cjs.logger.call(void 0, ).warn({ msg: "failed to parse close reason", reason });
2528
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({ msg: "failed to parse close reason", reason });
2353
2529
  return void 0;
2354
2530
  }
2531
+ const retryAfter = suffix == null ? void 0 : suffix.match(RETRY_AFTER_SUFFIX);
2532
+ if (retryAfter) {
2533
+ return { group, code, retryAfterMs: Number(retryAfter[1]) };
2534
+ }
2355
2535
  return {
2356
2536
  group,
2357
2537
  code,
2358
- rayId
2538
+ rayId: suffix
2359
2539
  };
2360
2540
  }
2361
2541
  function messageLength(message) {
@@ -2371,11 +2551,11 @@ function messageLength(message) {
2371
2551
  if (typeof message === "string") {
2372
2552
  return message.length;
2373
2553
  }
2374
- _chunk7QKCGUTJcjs.assertUnreachable.call(void 0, message);
2554
+ _chunk2MOLY6AMcjs.assertUnreachable.call(void 0, message);
2375
2555
  }
2376
2556
  async function sendHttpRequest(opts) {
2377
2557
  var _a, _b, _c;
2378
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
2558
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
2379
2559
  msg: "sending http request",
2380
2560
  url: opts.url,
2381
2561
  encoding: opts.encoding
@@ -2384,8 +2564,8 @@ async function sendHttpRequest(opts) {
2384
2564
  let bodyData;
2385
2565
  if (opts.method === "POST" || opts.method === "PUT") {
2386
2566
  _invariant2.default.call(void 0, opts.body !== void 0, "missing body");
2387
- contentType = _chunkRV5MAFDTcjs.contentTypeForEncoding.call(void 0, opts.encoding);
2388
- bodyData = _chunkRV5MAFDTcjs.serializeWithEncoding.call(void 0,
2567
+ contentType = _chunk2MOLY6AMcjs.contentTypeForEncoding.call(void 0, opts.encoding);
2568
+ bodyData = _chunk2MOLY6AMcjs.serializeWithEncoding.call(void 0,
2389
2569
  opts.encoding,
2390
2570
  opts.body,
2391
2571
  opts.requestVersionedDataHandler,
@@ -2405,7 +2585,7 @@ async function sendHttpRequest(opts) {
2405
2585
  ...contentType ? {
2406
2586
  "Content-Type": contentType
2407
2587
  } : {},
2408
- "User-Agent": _chunk7QKCGUTJcjs.httpUserAgent.call(void 0, )
2588
+ "User-Agent": _chunk2MOLY6AMcjs.httpUserAgent.call(void 0, )
2409
2589
  },
2410
2590
  body: bodyData,
2411
2591
  credentials: "include",
@@ -2423,7 +2603,7 @@ async function sendHttpRequest(opts) {
2423
2603
  const rayId = response.headers.get("x-rivet-ray-id");
2424
2604
  const encoding = (contentType2 == null ? void 0 : contentType2.includes("application/json")) ? "json" : opts.encoding;
2425
2605
  try {
2426
- const responseData = _chunkRV5MAFDTcjs.deserializeWithEncoding.call(void 0,
2606
+ const responseData = _chunk2MOLY6AMcjs.deserializeWithEncoding.call(void 0,
2427
2607
  encoding,
2428
2608
  new Uint8Array(bufferResponse),
2429
2609
  HTTP_RESPONSE_ERROR_VERSIONED,
@@ -2441,7 +2621,7 @@ async function sendHttpRequest(opts) {
2441
2621
  group: bare5.group,
2442
2622
  code: bare5.code,
2443
2623
  message: bare5.message,
2444
- metadata: bare5.metadata ? _chunkRV5MAFDTcjs.decodeCborCompat.call(void 0, new Uint8Array(bare5.metadata)) : void 0,
2624
+ metadata: bare5.metadata ? _chunk2MOLY6AMcjs.decodeCborCompat.call(void 0, new Uint8Array(bare5.metadata)) : void 0,
2445
2625
  actor: bare5.actor ? {
2446
2626
  actorId: bare5.actor.actorId,
2447
2627
  generation: Number(bare5.actor.generation),
@@ -2449,27 +2629,30 @@ async function sendHttpRequest(opts) {
2449
2629
  } : void 0
2450
2630
  })
2451
2631
  );
2452
- _chunkND567FR5cjs.logger.call(void 0, ).warn({
2632
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({
2453
2633
  msg: "http error response",
2454
2634
  group: responseData.group,
2455
2635
  code: responseData.code,
2456
2636
  message: responseData.message,
2457
2637
  metadata: responseData.metadata,
2638
+ rayId,
2458
2639
  actorId: (_a = responseData.actor) == null ? void 0 : _a.actorId,
2459
2640
  generation: (_b = responseData.actor) == null ? void 0 : _b.generation,
2460
2641
  actorKey: (_c = responseData.actor) == null ? void 0 : _c.key
2461
2642
  });
2462
- throw new (0, _chunk4FC7TVS6cjs.RivetError)(
2643
+ throw new (0, _chunkMGI2VVF6cjs.RivetError)(
2463
2644
  responseData.group,
2464
2645
  responseData.code,
2465
2646
  responseData.message,
2466
2647
  {
2467
2648
  metadata: responseData.metadata,
2468
- actor: responseData.actor
2649
+ rayId: _nullishCoalesce(rayId, () => ( void 0)),
2650
+ actor: responseData.actor,
2651
+ statusCode: response.status
2469
2652
  }
2470
2653
  );
2471
2654
  } catch (error) {
2472
- if (error instanceof _chunk4FC7TVS6cjs.RivetError) {
2655
+ if (error instanceof _chunkMGI2VVF6cjs.RivetError) {
2473
2656
  throw error;
2474
2657
  }
2475
2658
  const textResponse = new TextDecoder("utf-8", {
@@ -2493,7 +2676,7 @@ ${textResponse}`
2493
2676
  }
2494
2677
  try {
2495
2678
  const buffer = new Uint8Array(await response.arrayBuffer());
2496
- return _chunkRV5MAFDTcjs.deserializeWithEncoding.call(void 0,
2679
+ return _chunk2MOLY6AMcjs.deserializeWithEncoding.call(void 0,
2497
2680
  opts.encoding,
2498
2681
  buffer,
2499
2682
  opts.responseVersionedDataHandler,
@@ -2518,6 +2701,7 @@ function createQueueSender(senderOptions) {
2518
2701
  method: "POST",
2519
2702
  headers: {
2520
2703
  [HEADER_ENCODING]: senderOptions.encoding,
2704
+ ...senderOptions.telemetryHeaders(),
2521
2705
  ...senderOptions.params !== void 0 ? {
2522
2706
  [HEADER_CONN_PARAMS]: JSON.stringify(
2523
2707
  senderOptions.params
@@ -2540,8 +2724,8 @@ function createQueueSender(senderOptions) {
2540
2724
  }),
2541
2725
  requestToBare: (value) => ({
2542
2726
  name: _nullishCoalesce(value.name, () => ( name)),
2543
- body: _chunk7QKCGUTJcjs.bufferToArrayBuffer.call(void 0,
2544
- _chunkRV5MAFDTcjs.encodeCborCompat.call(void 0, value.body)
2727
+ body: _chunk2MOLY6AMcjs.bufferToArrayBuffer.call(void 0,
2728
+ _chunk2MOLY6AMcjs.encodeCborCompat.call(void 0, value.body)
2545
2729
  ),
2546
2730
  wait: _nullishCoalesce(value.wait, () => ( false)),
2547
2731
  timeout: value.timeout !== void 0 ? BigInt(value.timeout) : null
@@ -2561,7 +2745,7 @@ function createQueueSender(senderOptions) {
2561
2745
  }
2562
2746
  return {
2563
2747
  status: bare5.status,
2564
- response: _chunkRV5MAFDTcjs.decodeCborCompat.call(void 0, new Uint8Array(bare5.response))
2748
+ response: _chunk2MOLY6AMcjs.decodeCborCompat.call(void 0, new Uint8Array(bare5.response))
2565
2749
  };
2566
2750
  }
2567
2751
  });
@@ -2576,25 +2760,38 @@ function createQueueSender(senderOptions) {
2576
2760
  }
2577
2761
 
2578
2762
  // src/client/raw-utils.ts
2579
- async function rawHttpFetch(driver, target, params, input, init, options = {}) {
2763
+ async function prepareRetryableInit(init) {
2764
+ if (init.body instanceof ReadableStream) {
2765
+ return {
2766
+ ...init,
2767
+ body: new Uint8Array(await new Response(init.body).arrayBuffer())
2768
+ };
2769
+ }
2770
+ return init;
2771
+ }
2772
+ async function rawHttpFetch(driver, target, params, input, init, options = {}, telemetryHeaders = {}) {
2580
2773
  let path;
2774
+ let originalUrl;
2581
2775
  let mergedInit = init || {};
2582
2776
  if (typeof input === "string") {
2583
2777
  path = input;
2584
- } else if (input instanceof URL) {
2778
+ } else if (isUrlLike(input)) {
2585
2779
  path = input.pathname + input.search;
2586
- } else if (input instanceof Request) {
2780
+ originalUrl = input.toString();
2781
+ } else if (isRequestLike(input)) {
2587
2782
  const url = new URL(input.url);
2588
2783
  path = url.pathname + url.search;
2784
+ originalUrl = url.toString();
2589
2785
  const requestHeaders = new Headers(input.headers);
2590
2786
  const initHeaders = new Headers((init == null ? void 0 : init.headers) || {});
2591
2787
  const mergedHeaders = new Headers(requestHeaders);
2592
2788
  initHeaders.forEach((value, key) => {
2593
2789
  mergedHeaders.set(key, value);
2594
2790
  });
2791
+ const readsInputBody = (init == null ? void 0 : init.body) === void 0 && input.method !== "GET" && input.method !== "HEAD";
2595
2792
  mergedInit = {
2596
2793
  method: input.method,
2597
- body: input.body,
2794
+ body: readsInputBody ? await readRequestBody(input) : void 0,
2598
2795
  mode: input.mode,
2599
2796
  credentials: input.credentials,
2600
2797
  redirect: input.redirect,
@@ -2615,7 +2812,7 @@ async function rawHttpFetch(driver, target, params, input, init, options = {}) {
2615
2812
  throw new TypeError("Invalid input type for fetch");
2616
2813
  }
2617
2814
  try {
2618
- _chunkND567FR5cjs.logger.call(void 0, ).debug(
2815
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug(
2619
2816
  "directId" in target ? {
2620
2817
  msg: "sending raw http request to actor",
2621
2818
  actorId: target.directId
@@ -2627,20 +2824,22 @@ async function rawHttpFetch(driver, target, params, input, init, options = {}) {
2627
2824
  const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
2628
2825
  const url = new URL(`http://actor/request/${normalizedPath}`);
2629
2826
  const proxyRequestHeaders = new Headers(mergedInit.headers);
2827
+ proxyRequestHeaders.delete(HEADER_ORIGINAL_REQUEST_URL);
2828
+ if (originalUrl) {
2829
+ proxyRequestHeaders.set(HEADER_ORIGINAL_REQUEST_URL, originalUrl);
2830
+ }
2630
2831
  if (params) {
2631
2832
  proxyRequestHeaders.set(HEADER_CONN_PARAMS, JSON.stringify(params));
2632
2833
  }
2834
+ addOutboundTelemetryHeaders(proxyRequestHeaders, telemetryHeaders);
2633
2835
  const proxyRequest = new Request(url, {
2634
2836
  ...mergedInit,
2635
2837
  headers: proxyRequestHeaders
2636
2838
  });
2637
2839
  return driver.sendRequest(target, proxyRequest, options);
2638
2840
  } catch (err) {
2639
- const { group, code, message, metadata, actor } = _chunk7QKCGUTJcjs.deconstructError.call(void 0,
2640
- err,
2641
- true
2642
- );
2643
- throw new (0, _chunk4FC7TVS6cjs.RivetError)(group, code, message, { metadata, actor });
2841
+ const { group, code, message, metadata, rayId, actor } = _chunk2MOLY6AMcjs.deconstructError.call(void 0, err, true);
2842
+ throw new (0, _chunkMGI2VVF6cjs.RivetError)(group, code, message, { metadata, rayId, actor });
2644
2843
  }
2645
2844
  }
2646
2845
  async function rawWebSocket(driver, target, params, path, _protocols, options = {}) {
@@ -2660,7 +2859,7 @@ async function rawWebSocket(driver, target, params, path, _protocols, options =
2660
2859
  }
2661
2860
  }
2662
2861
  const fullPath = `${PATH_WEBSOCKET_PREFIX}${pathPortion}${queryPortion}`;
2663
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
2862
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
2664
2863
  msg: "opening websocket",
2665
2864
  target,
2666
2865
  encoding,
@@ -2690,7 +2889,7 @@ async function resolveGatewayTarget(driver, target) {
2690
2889
  key: target.getForKey.key
2691
2890
  });
2692
2891
  if (!output) {
2693
- throw _chunk4FC7TVS6cjs.actorNotFound.call(void 0,
2892
+ throw _chunkMGI2VVF6cjs.actorNotFound.call(void 0,
2694
2893
  `${target.getForKey.name}:${JSON.stringify(target.getForKey.key)}`
2695
2894
  );
2696
2895
  }
@@ -2701,7 +2900,8 @@ async function resolveGatewayTarget(driver, target) {
2701
2900
  name: target.getOrCreateForKey.name,
2702
2901
  key: target.getOrCreateForKey.key,
2703
2902
  input: target.getOrCreateForKey.input,
2704
- region: target.getOrCreateForKey.region
2903
+ region: target.getOrCreateForKey.region,
2904
+ poolName: target.getOrCreateForKey.poolName
2705
2905
  });
2706
2906
  return output.actorId;
2707
2907
  }
@@ -2710,11 +2910,12 @@ async function resolveGatewayTarget(driver, target) {
2710
2910
  name: target.create.name,
2711
2911
  key: target.create.key,
2712
2912
  input: target.create.input,
2713
- region: target.create.region
2913
+ region: target.create.region,
2914
+ poolName: target.create.poolName
2714
2915
  });
2715
2916
  return output.actorId;
2716
2917
  }
2717
- throw _chunk4FC7TVS6cjs.invalidRequest.call(void 0, "Invalid query format");
2918
+ throw _chunkMGI2VVF6cjs.invalidRequest.call(void 0, "Invalid query format");
2718
2919
  }
2719
2920
 
2720
2921
  // src/client/actor-handle.ts
@@ -2726,9 +2927,13 @@ var ActorHandleRaw = class {
2726
2927
  #gatewayOptions;
2727
2928
  #params;
2728
2929
  #getParams;
2930
+ #signal;
2729
2931
  #resolvedActorId;
2730
2932
  #resolvingActorId;
2731
- #queueSendMutex = new (0, _chunkZA7FLHKHcjs.AsyncMutex)();
2933
+ #queueSendMutex = new (0, _chunkKVFIONKQcjs.AsyncMutex)();
2934
+ #currentActorInvocation;
2935
+ #startCallSpan;
2936
+ #retryBudget;
2732
2937
  /**
2733
2938
  * Do not call this directly.
2734
2939
  *
@@ -2736,7 +2941,7 @@ var ActorHandleRaw = class {
2736
2941
  *
2737
2942
  * @protected
2738
2943
  */
2739
- constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}) {
2944
+ constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}, signal, currentActorInvocation, startCallSpan, retryBudget = new RetryBudget()) {
2740
2945
  this.#client = client;
2741
2946
  this.#driver = driver;
2742
2947
  this.#encoding = encoding;
@@ -2744,6 +2949,10 @@ var ActorHandleRaw = class {
2744
2949
  this.#gatewayOptions = gatewayOptions;
2745
2950
  this.#params = params;
2746
2951
  this.#getParams = getParams;
2952
+ this.#signal = signal;
2953
+ this.#currentActorInvocation = currentActorInvocation;
2954
+ this.#startCallSpan = startCallSpan;
2955
+ this.#retryBudget = retryBudget;
2747
2956
  }
2748
2957
  async #resolveConnectionParams() {
2749
2958
  if (this.#getParams) {
@@ -2757,7 +2966,10 @@ var ActorHandleRaw = class {
2757
2966
  async #sendQueueMessage(name, body, options) {
2758
2967
  return await this.#queueSendMutex.run(async () => {
2759
2968
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
2760
- let useQueryTarget = false;
2969
+ let useQueryTarget = isDynamicActorQuery(
2970
+ this.#actorResolutionState
2971
+ );
2972
+ this.#retryBudget.deposit();
2761
2973
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
2762
2974
  let actorId;
2763
2975
  try {
@@ -2772,6 +2984,12 @@ var ActorHandleRaw = class {
2772
2984
  return await createQueueSender({
2773
2985
  encoding: this.#encoding,
2774
2986
  params: this.#params,
2987
+ telemetryHeaders: () => {
2988
+ var _a;
2989
+ return outboundTelemetryHeaders(
2990
+ (_a = this.#currentActorInvocation) == null ? void 0 : _a.call(this)
2991
+ );
2992
+ },
2775
2993
  customFetch: async (request) => {
2776
2994
  return await this.#driver.sendRequest(
2777
2995
  target,
@@ -2781,15 +2999,24 @@ var ActorHandleRaw = class {
2781
2999
  }
2782
3000
  }).send(name, body, options);
2783
3001
  } catch (err) {
2784
- const { group, code, message, metadata, actor } = _chunk7QKCGUTJcjs.deconstructError.call(void 0, err, true);
3002
+ const { group, code, message, metadata, rayId, actor } = _chunk2MOLY6AMcjs.deconstructError.call(void 0, err, true);
2785
3003
  if (this.#shouldRetryQueueDispatchOverload(
2786
3004
  group,
2787
3005
  code,
2788
3006
  metadata,
2789
3007
  attempt,
2790
3008
  maxAttempts
2791
- )) {
2792
- await this.#waitForRetryWindow();
3009
+ ) && this.#retryBudget.tryWithdraw()) {
3010
+ await new Promise(
3011
+ (resolve) => setTimeout(
3012
+ resolve,
3013
+ retryDelayMs(attempt, {
3014
+ initialDelayMs: 25,
3015
+ maxDelayMs: 1e3,
3016
+ hintMs: retryAfterMs(err)
3017
+ })
3018
+ )
3019
+ );
2793
3020
  continue;
2794
3021
  }
2795
3022
  if (await this.#shouldRetrySchedulingError(
@@ -2797,7 +3024,8 @@ var ActorHandleRaw = class {
2797
3024
  code,
2798
3025
  actorId,
2799
3026
  attempt,
2800
- maxAttempts
3027
+ maxAttempts,
3028
+ rayId
2801
3029
  )) {
2802
3030
  useQueryTarget = true;
2803
3031
  await this.#waitForRetryWindow();
@@ -2819,14 +3047,16 @@ var ActorHandleRaw = class {
2819
3047
  code
2820
3048
  );
2821
3049
  if (invalidated && attempt < maxAttempts - 1) {
2822
- useQueryTarget = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
2823
- if (useQueryTarget) {
3050
+ const waitForReady = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
3051
+ useQueryTarget = useQueryTarget || waitForReady;
3052
+ if (waitForReady) {
2824
3053
  await this.#waitForRetryWindow();
2825
3054
  }
2826
3055
  continue;
2827
3056
  }
2828
- throw new (0, _chunk4FC7TVS6cjs.RivetError)(group, code, message, {
3057
+ throw new (0, _chunkMGI2VVF6cjs.RivetError)(group, code, message, {
2829
3058
  metadata,
3059
+ rayId,
2830
3060
  actor
2831
3061
  });
2832
3062
  }
@@ -2842,20 +3072,48 @@ var ActorHandleRaw = class {
2842
3072
  * @template Response - The type of the response returned by the action function.
2843
3073
  */
2844
3074
  async action(opts) {
3075
+ var _a;
2845
3076
  if (typeof opts === "string" || typeof opts !== "object" || opts === null || !("name" in opts)) {
2846
3077
  throw new Error(
2847
3078
  `Invalid action call: expected an options object { name, args }, got ${typeof opts}. Use handle.actionName(...args) for the shorthand API.`
2848
3079
  );
2849
3080
  }
2850
- const run = async () => await this.#sendActionNow(opts);
2851
- if (opts.name === "destroy") {
2852
- return await run();
3081
+ const signal = _nullishCoalesce(opts.signal, () => ( this.#signal));
3082
+ const optsWithSignal = { ...opts, signal };
3083
+ const call = (_a = this.#startCallSpan) == null ? void 0 : _a.call(
3084
+ this,
3085
+ getActorNameFromQuery(this.#actorResolutionState),
3086
+ opts.name
3087
+ );
3088
+ const run = async () => await this.#sendActionAttempts(
3089
+ optsWithSignal,
3090
+ call == null ? void 0 : call.span
3091
+ );
3092
+ const send = async () => {
3093
+ if (opts.name === "destroy") {
3094
+ return await run();
3095
+ }
3096
+ return await retryOnLifecycleBoundary(run, {
3097
+ signal,
3098
+ budget: this.#retryBudget
3099
+ });
3100
+ };
3101
+ if (!call) {
3102
+ return await send();
3103
+ }
3104
+ try {
3105
+ const output = await send();
3106
+ call.finish();
3107
+ return output;
3108
+ } catch (error) {
3109
+ call.finish(_chunkMGI2VVF6cjs.encodeErrorForBridge.call(void 0, error));
3110
+ throw error;
2853
3111
  }
2854
- return await retryOnLifecycleBoundary(run, { signal: opts.signal });
2855
3112
  }
2856
- async #sendActionNow(opts) {
3113
+ async #sendActionAttempts(opts, callSpan) {
3114
+ var _a;
2857
3115
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
2858
- let useQueryTarget = false;
3116
+ let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
2859
3117
  const gatewayOptions = resolveActorGatewayOptions(
2860
3118
  this.#gatewayOptions,
2861
3119
  opts
@@ -2868,28 +3126,31 @@ var ActorHandleRaw = class {
2868
3126
  gatewayOptions
2869
3127
  );
2870
3128
  actorId = "directId" in target ? target.directId : void 0;
2871
- _chunkND567FR5cjs.logger.call(void 0, ).debug(
3129
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug(
2872
3130
  actorId ? { msg: "using direct actor gateway target", actorId } : {
2873
3131
  msg: "using query gateway target for action",
2874
3132
  query: this.#actorResolutionState
2875
3133
  }
2876
3134
  );
2877
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
3135
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
2878
3136
  msg: "handling action",
2879
3137
  name: opts.name,
2880
3138
  encoding: this.#encoding
2881
3139
  });
3140
+ const headers = {
3141
+ [HEADER_ENCODING]: this.#encoding,
3142
+ ...outboundTelemetryHeaders(
3143
+ (_a = this.#currentActorInvocation) == null ? void 0 : _a.call(this),
3144
+ callSpan
3145
+ )
3146
+ };
3147
+ if (this.#params !== void 0) {
3148
+ headers[HEADER_CONN_PARAMS] = JSON.stringify(this.#params);
3149
+ }
2882
3150
  const output = await sendHttpRequest({
2883
3151
  url: `http://actor/action/${encodeURIComponent(opts.name)}`,
2884
3152
  method: "POST",
2885
- headers: {
2886
- [HEADER_ENCODING]: this.#encoding,
2887
- ...this.#params !== void 0 ? {
2888
- [HEADER_CONN_PARAMS]: JSON.stringify(
2889
- this.#params
2890
- )
2891
- } : {}
2892
- },
3153
+ headers,
2893
3154
  body: opts.args,
2894
3155
  encoding: this.#encoding,
2895
3156
  customFetch: async (request) => await this.#driver.sendRequest(
@@ -2908,25 +3169,26 @@ var ActorHandleRaw = class {
2908
3169
  args
2909
3170
  }),
2910
3171
  requestToBare: (args) => ({
2911
- args: _chunk7QKCGUTJcjs.bufferToArrayBuffer.call(void 0,
2912
- _chunkRV5MAFDTcjs.encodeCborCompat.call(void 0, args)
3172
+ args: _chunk2MOLY6AMcjs.bufferToArrayBuffer.call(void 0,
3173
+ _chunk2MOLY6AMcjs.encodeCborCompat.call(void 0, args)
2913
3174
  )
2914
3175
  }),
2915
3176
  responseFromJson: (json) => json.output,
2916
- responseFromBare: (bare5) => _chunkRV5MAFDTcjs.decodeCborCompat.call(void 0, new Uint8Array(bare5.output))
3177
+ responseFromBare: (bare5) => _chunk2MOLY6AMcjs.decodeCborCompat.call(void 0, new Uint8Array(bare5.output))
2917
3178
  });
2918
3179
  if (opts.name === "destroy" && actorId) {
2919
3180
  await this.#waitForDestroyActionToSettle(actorId);
2920
3181
  }
2921
3182
  return output;
2922
3183
  } catch (err) {
2923
- const { group, code, message, metadata, actor } = _chunk7QKCGUTJcjs.deconstructError.call(void 0, err, true);
3184
+ const { group, code, message, metadata, rayId, actor } = _chunk2MOLY6AMcjs.deconstructError.call(void 0, err, true);
2924
3185
  if (await this.#shouldRetrySchedulingError(
2925
3186
  group,
2926
3187
  code,
2927
3188
  actorId,
2928
3189
  attempt,
2929
- maxAttempts
3190
+ maxAttempts,
3191
+ rayId
2930
3192
  )) {
2931
3193
  useQueryTarget = true;
2932
3194
  await this.#waitForRetryWindow();
@@ -2944,11 +3206,11 @@ var ActorHandleRaw = class {
2944
3206
  continue;
2945
3207
  }
2946
3208
  if (group === "actor" && code === "destroyed_while_waiting_for_ready" && "getForId" in this.#actorResolutionState) {
2947
- throw new (0, _chunk4FC7TVS6cjs.RivetError)(
3209
+ throw new (0, _chunkMGI2VVF6cjs.RivetError)(
2948
3210
  "actor",
2949
3211
  "not_found",
2950
3212
  "The actor does not exist or was destroyed.",
2951
- { metadata, actor }
3213
+ { metadata, rayId, actor }
2952
3214
  );
2953
3215
  }
2954
3216
  const invalidated = this.#invalidateResolvedActorId(
@@ -2964,7 +3226,11 @@ var ActorHandleRaw = class {
2964
3226
  }
2965
3227
  continue;
2966
3228
  }
2967
- throw new (0, _chunk4FC7TVS6cjs.RivetError)(group, code, message, { metadata, actor });
3229
+ throw new (0, _chunkMGI2VVF6cjs.RivetError)(group, code, message, {
3230
+ metadata,
3231
+ rayId,
3232
+ actor
3233
+ });
2968
3234
  }
2969
3235
  }
2970
3236
  throw new Error("unreachable action retry state");
@@ -3006,7 +3272,7 @@ var ActorHandleRaw = class {
3006
3272
  this.#resolvedActorId = void 0;
3007
3273
  this.#resolvingActorId = void 0;
3008
3274
  }
3009
- async #shouldRetrySchedulingError(group, code, actorId, attempt, maxAttempts) {
3275
+ async #shouldRetrySchedulingError(group, code, actorId, attempt, maxAttempts, rayId) {
3010
3276
  if (!isDynamicActorQuery(this.#actorResolutionState) || !isSchedulingError(group, code) || attempt >= maxAttempts - 1) {
3011
3277
  return false;
3012
3278
  }
@@ -3016,7 +3282,8 @@ var ActorHandleRaw = class {
3016
3282
  code,
3017
3283
  actorId,
3018
3284
  this.#actorResolutionState,
3019
- this.#driver
3285
+ this.#driver,
3286
+ rayId
3020
3287
  );
3021
3288
  if (schedulingError) {
3022
3289
  throw schedulingError;
@@ -3070,7 +3337,7 @@ var ActorHandleRaw = class {
3070
3337
  * @returns {ActorConn<AD>} A connection to the actor.
3071
3338
  */
3072
3339
  connect(params, options = {}) {
3073
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
3340
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3074
3341
  msg: "establishing connection from handle",
3075
3342
  query: this.#actorResolutionState
3076
3343
  });
@@ -3083,7 +3350,8 @@ var ActorHandleRaw = class {
3083
3350
  getParams,
3084
3351
  this.#encoding,
3085
3352
  this.#actorResolutionState,
3086
- resolveActorGatewayOptions(this.#gatewayOptions, options)
3353
+ resolveActorGatewayOptions(this.#gatewayOptions, options),
3354
+ this.#currentActorInvocation
3087
3355
  );
3088
3356
  return this.#client[CREATE_ACTOR_CONN_PROXY](
3089
3357
  conn
@@ -3097,15 +3365,21 @@ var ActorHandleRaw = class {
3097
3365
  return this.#fetchWithResolvedActor(input, init);
3098
3366
  }
3099
3367
  async #fetchWithResolvedActor(input, init) {
3368
+ var _a;
3369
+ const { skipReadyWait, ...restInit } = _nullishCoalesce(init, () => ( {}));
3100
3370
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
3101
- let useQueryTarget = false;
3102
- const { skipReadyWait, ...requestInit } = _nullishCoalesce(init, () => ( {}));
3371
+ const requestInit = maxAttempts > 1 ? await prepareRetryableInit(restInit) : restInit;
3372
+ const clonesInputBody = requestInit.body === void 0 && isRequestLike(input) && input.body !== null;
3373
+ let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
3103
3374
  const gatewayOptions = resolveActorGatewayOptions(
3104
3375
  this.#gatewayOptions,
3105
3376
  {
3106
3377
  skipReadyWait
3107
3378
  }
3108
3379
  );
3380
+ const telemetryHeaders = outboundTelemetryHeaders(
3381
+ (_a = this.#currentActorInvocation) == null ? void 0 : _a.call(this)
3382
+ );
3109
3383
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
3110
3384
  let actorId;
3111
3385
  try {
@@ -3118,9 +3392,12 @@ var ActorHandleRaw = class {
3118
3392
  this.#driver,
3119
3393
  target,
3120
3394
  this.#params,
3121
- input,
3395
+ // Clone a body-bearing Request so retries don't reuse a consumed stream.
3396
+ // NOTE: This holds the body in memory until GC (unavoidable).
3397
+ clonesInputBody ? input.clone() : input,
3122
3398
  requestInit,
3123
- gatewayOptions
3399
+ gatewayOptions,
3400
+ telemetryHeaders
3124
3401
  );
3125
3402
  const retry = await this.#shouldRetryRawFetchResponse(
3126
3403
  response,
@@ -3137,13 +3414,14 @@ var ActorHandleRaw = class {
3137
3414
  }
3138
3415
  return response;
3139
3416
  } catch (err) {
3140
- const { group, code, message, metadata, actor } = _chunk7QKCGUTJcjs.deconstructError.call(void 0, err, true);
3417
+ const { group, code, message, metadata, rayId, actor } = _chunk2MOLY6AMcjs.deconstructError.call(void 0, err, true);
3141
3418
  if (await this.#shouldRetrySchedulingError(
3142
3419
  group,
3143
3420
  code,
3144
3421
  actorId,
3145
3422
  attempt,
3146
- maxAttempts
3423
+ maxAttempts,
3424
+ rayId
3147
3425
  )) {
3148
3426
  useQueryTarget = true;
3149
3427
  await this.#waitForRetryWindow();
@@ -3165,13 +3443,18 @@ var ActorHandleRaw = class {
3165
3443
  code
3166
3444
  );
3167
3445
  if (invalidated && attempt < maxAttempts - 1) {
3168
- useQueryTarget = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
3169
- if (useQueryTarget) {
3446
+ const waitForReady = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
3447
+ useQueryTarget = useQueryTarget || waitForReady;
3448
+ if (waitForReady) {
3170
3449
  await this.#waitForRetryWindow();
3171
3450
  }
3172
3451
  continue;
3173
3452
  }
3174
- throw new (0, _chunk4FC7TVS6cjs.RivetError)(group, code, message, { metadata, actor });
3453
+ throw new (0, _chunkMGI2VVF6cjs.RivetError)(group, code, message, {
3454
+ metadata,
3455
+ rayId,
3456
+ actor
3457
+ });
3175
3458
  }
3176
3459
  }
3177
3460
  throw new Error("unreachable fetch retry state");
@@ -3184,13 +3467,14 @@ var ActorHandleRaw = class {
3184
3467
  if (!error) {
3185
3468
  return null;
3186
3469
  }
3187
- const { group, code } = error;
3470
+ const { group, code, rayId } = error;
3188
3471
  if (await this.#shouldRetrySchedulingError(
3189
3472
  group,
3190
3473
  code,
3191
3474
  actorId,
3192
3475
  attempt,
3193
- maxAttempts
3476
+ maxAttempts,
3477
+ rayId
3194
3478
  )) {
3195
3479
  return {
3196
3480
  useQueryTarget: true,
@@ -3211,10 +3495,10 @@ var ActorHandleRaw = class {
3211
3495
  }
3212
3496
  const invalidated = this.#invalidateResolvedActorId(group, code);
3213
3497
  if (invalidated && attempt < maxAttempts - 1) {
3214
- const useQueryTarget = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
3498
+ const waitForReady = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
3215
3499
  return {
3216
- useQueryTarget,
3217
- waitForRetryWindow: useQueryTarget
3500
+ useQueryTarget: true,
3501
+ waitForRetryWindow: waitForReady
3218
3502
  };
3219
3503
  }
3220
3504
  return null;
@@ -3226,7 +3510,7 @@ var ActorHandleRaw = class {
3226
3510
  const contentType = response.headers.get("content-type");
3227
3511
  const encoding = (contentType == null ? void 0 : contentType.includes("application/json")) ? "json" : this.#encoding;
3228
3512
  try {
3229
- return _chunkRV5MAFDTcjs.deserializeWithEncoding.call(void 0,
3513
+ const error = _chunk2MOLY6AMcjs.deserializeWithEncoding.call(void 0,
3230
3514
  encoding,
3231
3515
  new Uint8Array(await response.clone().arrayBuffer()),
3232
3516
  HTTP_RESPONSE_ERROR_VERSIONED,
@@ -3242,7 +3526,7 @@ var ActorHandleRaw = class {
3242
3526
  group: bare5.group,
3243
3527
  code: bare5.code,
3244
3528
  message: bare5.message,
3245
- metadata: bare5.metadata ? _chunkRV5MAFDTcjs.decodeCborCompat.call(void 0, new Uint8Array(bare5.metadata)) : void 0,
3529
+ metadata: bare5.metadata ? _chunk2MOLY6AMcjs.decodeCborCompat.call(void 0, new Uint8Array(bare5.metadata)) : void 0,
3246
3530
  actor: bare5.actor ? {
3247
3531
  actorId: bare5.actor.actorId,
3248
3532
  generation: Number(bare5.actor.generation),
@@ -3250,7 +3534,11 @@ var ActorHandleRaw = class {
3250
3534
  } : void 0
3251
3535
  })
3252
3536
  );
3253
- } catch (e) {
3537
+ return {
3538
+ ...error,
3539
+ rayId: _nullishCoalesce(response.headers.get("x-rivet-ray-id"), () => ( void 0))
3540
+ };
3541
+ } catch (e2) {
3254
3542
  return null;
3255
3543
  }
3256
3544
  }
@@ -3292,6 +3580,22 @@ var ActorHandleRaw = class {
3292
3580
  "dynamic actor resolution did not produce a direct actor id"
3293
3581
  );
3294
3582
  }
3583
+ /** Issue a token scoped to this actor. Defaults to actor gateway read access. */
3584
+ async issueToken(options = {}) {
3585
+ const actorId = await this.resolve();
3586
+ const permissions = _nullishCoalesce(options.permissions, () => ( {
3587
+ actor_gateway: ["read"]
3588
+ }));
3589
+ const grants = Object.keys(permissions).flatMap((resource) => {
3590
+ const operations = permissions[resource];
3591
+ return operations ? [{ resource, target: { id: actorId }, operations }] : [];
3592
+ });
3593
+ return this.#driver.issueToken({
3594
+ subject: options.subject,
3595
+ expiresIn: options.expiresIn,
3596
+ grants
3597
+ });
3598
+ }
3295
3599
  /**
3296
3600
  * Returns the raw URL for routing traffic to the actor.
3297
3601
  */
@@ -3309,11 +3613,13 @@ var ActorHandleRaw = class {
3309
3613
  const response = await this.#driver.sendRequest(target, request);
3310
3614
  if (!response.ok) {
3311
3615
  const body = await response.text().catch(() => "");
3312
- throw new (0, _chunk4FC7TVS6cjs.RivetError)(
3616
+ throw new (0, _chunkMGI2VVF6cjs.RivetError)(
3313
3617
  "actor",
3314
3618
  "reload_failed",
3315
3619
  `reload failed with status ${response.status}: ${body}`,
3316
- {}
3620
+ {
3621
+ rayId: _nullishCoalesce(response.headers.get("x-rivet-ray-id"), () => ( void 0))
3622
+ }
3317
3623
  );
3318
3624
  }
3319
3625
  }
@@ -3324,17 +3630,28 @@ var ACTOR_CONNS_SYMBOL = /* @__PURE__ */ Symbol("actorConns");
3324
3630
  var CREATE_ACTOR_CONN_PROXY = /* @__PURE__ */ Symbol("createActorConnProxy");
3325
3631
  var ClientRaw = (_class = class {
3326
3632
  #disposed = false;
3633
+ /** Issue namespace-scoped tokens with an explicit grant list. */
3634
+
3327
3635
  __init() {this[ACTOR_CONNS_SYMBOL] = /* @__PURE__ */ new Set()}
3328
3636
  #driver;
3329
3637
  #encodingKind;
3330
3638
  #gatewayOptions;
3639
+ #currentActorInvocation;
3640
+ #startCallSpan;
3641
+ #retryBudget;
3331
3642
  /**
3332
3643
  * Creates an instance of Client.
3333
3644
  */
3334
- constructor(driver, encoding, gatewayOptions = {}) {;_class.prototype.__init.call(this);
3645
+ constructor(driver, options = {}) {;_class.prototype.__init.call(this);
3335
3646
  this.#driver = driver;
3336
- this.#encodingKind = _nullishCoalesce(encoding, () => ( "bare"));
3337
- this.#gatewayOptions = gatewayOptions;
3647
+ this.auth = {
3648
+ issueToken: (issueOptions) => this.#driver.issueToken(issueOptions)
3649
+ };
3650
+ this.#encodingKind = _nullishCoalesce(options.encoding, () => ( "bare"));
3651
+ this.#gatewayOptions = _nullishCoalesce(options.gateway, () => ( {}));
3652
+ this.#currentActorInvocation = options.currentActorInvocation;
3653
+ this.#startCallSpan = options.startCallSpan;
3654
+ this.#retryBudget = new RetryBudget(options.retryBudget);
3338
3655
  }
3339
3656
  /**
3340
3657
  * Gets a stateless handle to a actor by its ID.
@@ -3346,7 +3663,7 @@ var ClientRaw = (_class = class {
3346
3663
  * @returns {ActorHandle<AD>} - A handle to the actor.
3347
3664
  */
3348
3665
  getForId(name, actorId, opts) {
3349
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
3666
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3350
3667
  msg: "get handle to actor with id",
3351
3668
  name,
3352
3669
  actorId,
@@ -3361,7 +3678,8 @@ var ClientRaw = (_class = class {
3361
3678
  const handle = this.#createHandle(
3362
3679
  opts == null ? void 0 : opts.params,
3363
3680
  opts == null ? void 0 : opts.getParams,
3364
- actorQuery
3681
+ actorQuery,
3682
+ opts == null ? void 0 : opts.signal
3365
3683
  );
3366
3684
  return createActorProxy(handle);
3367
3685
  }
@@ -3376,7 +3694,7 @@ var ClientRaw = (_class = class {
3376
3694
  */
3377
3695
  get(name, key, opts) {
3378
3696
  const keyArray = typeof key === "string" ? [key] : key || [];
3379
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
3697
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3380
3698
  msg: "get handle to actor",
3381
3699
  name,
3382
3700
  key: keyArray,
@@ -3391,7 +3709,8 @@ var ClientRaw = (_class = class {
3391
3709
  const handle = this.#createHandle(
3392
3710
  opts == null ? void 0 : opts.params,
3393
3711
  opts == null ? void 0 : opts.getParams,
3394
- actorQuery
3712
+ actorQuery,
3713
+ opts == null ? void 0 : opts.signal
3395
3714
  );
3396
3715
  return createActorProxy(handle);
3397
3716
  }
@@ -3406,7 +3725,7 @@ var ClientRaw = (_class = class {
3406
3725
  */
3407
3726
  getOrCreate(name, key, opts) {
3408
3727
  const keyArray = typeof key === "string" ? [key] : key || [];
3409
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
3728
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3410
3729
  msg: "get or create handle to actor",
3411
3730
  name,
3412
3731
  key: keyArray,
@@ -3418,13 +3737,15 @@ var ClientRaw = (_class = class {
3418
3737
  name,
3419
3738
  key: keyArray,
3420
3739
  input: opts == null ? void 0 : opts.createWithInput,
3421
- region: opts == null ? void 0 : opts.createInRegion
3740
+ region: opts == null ? void 0 : opts.createInRegion,
3741
+ poolName: opts == null ? void 0 : opts.poolName
3422
3742
  }
3423
3743
  };
3424
3744
  const handle = this.#createHandle(
3425
3745
  opts == null ? void 0 : opts.params,
3426
3746
  opts == null ? void 0 : opts.getParams,
3427
- actorQuery
3747
+ actorQuery,
3748
+ opts == null ? void 0 : opts.signal
3428
3749
  );
3429
3750
  return createActorProxy(handle);
3430
3751
  }
@@ -3448,7 +3769,7 @@ var ClientRaw = (_class = class {
3448
3769
  key: keyArray
3449
3770
  }
3450
3771
  };
3451
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
3772
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3452
3773
  msg: "create actor handle",
3453
3774
  name,
3454
3775
  key: keyArray,
@@ -3456,7 +3777,7 @@ var ClientRaw = (_class = class {
3456
3777
  create: createQuery.create
3457
3778
  });
3458
3779
  const actorId = await resolveGatewayTarget(this.#driver, createQuery);
3459
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
3780
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3460
3781
  msg: "created actor with ID",
3461
3782
  name,
3462
3783
  key: keyArray,
@@ -3471,12 +3792,13 @@ var ClientRaw = (_class = class {
3471
3792
  const handle = this.#createHandle(
3472
3793
  opts == null ? void 0 : opts.params,
3473
3794
  opts == null ? void 0 : opts.getParams,
3474
- getForIdQuery
3795
+ getForIdQuery,
3796
+ opts == null ? void 0 : opts.signal
3475
3797
  );
3476
3798
  const proxy = createActorProxy(handle);
3477
3799
  return proxy;
3478
3800
  }
3479
- #createHandle(params, getParams, actorQuery) {
3801
+ #createHandle(params, getParams, actorQuery, signal) {
3480
3802
  return new ActorHandleRaw(
3481
3803
  this,
3482
3804
  this.#driver,
@@ -3484,7 +3806,11 @@ var ClientRaw = (_class = class {
3484
3806
  getParams,
3485
3807
  this.#encodingKind,
3486
3808
  actorQuery,
3487
- this.#gatewayOptions
3809
+ this.#gatewayOptions,
3810
+ signal,
3811
+ this.#currentActorInvocation,
3812
+ this.#startCallSpan,
3813
+ this.#retryBudget
3488
3814
  );
3489
3815
  }
3490
3816
  [CREATE_ACTOR_CONN_PROXY](conn) {
@@ -3499,11 +3825,11 @@ var ClientRaw = (_class = class {
3499
3825
  */
3500
3826
  async dispose() {
3501
3827
  if (this.#disposed) {
3502
- _chunkND567FR5cjs.logger.call(void 0, ).warn({ msg: "client already disconnected" });
3828
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({ msg: "client already disconnected" });
3503
3829
  return;
3504
3830
  }
3505
3831
  this.#disposed = true;
3506
- _chunkND567FR5cjs.logger.call(void 0, ).debug({ msg: "disposing client" });
3832
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({ msg: "disposing client" });
3507
3833
  const disposePromises = [];
3508
3834
  for (const conn of this[ACTOR_CONNS_SYMBOL].values()) {
3509
3835
  disposePromises.push(conn.dispose());
@@ -3511,8 +3837,8 @@ var ClientRaw = (_class = class {
3511
3837
  await Promise.all(disposePromises);
3512
3838
  }
3513
3839
  }, _class);
3514
- function createClientWithDriver(driver, config = {}) {
3515
- const client = new ClientRaw(driver, config.encoding, config.gateway);
3840
+ function createClientWithDriver(driver, options = {}) {
3841
+ const client = new ClientRaw(driver, options);
3516
3842
  return new Proxy(client, {
3517
3843
  get: (target, prop, receiver) => {
3518
3844
  if (typeof prop === "symbol" || prop in target) {
@@ -3545,6 +3871,23 @@ function createClientWithDriver(driver, config = {}) {
3545
3871
  }
3546
3872
  function createActorProxy(handle) {
3547
3873
  const methodCache = /* @__PURE__ */ new Map();
3874
+ const actionPath = (name) => {
3875
+ let method = methodCache.get(name);
3876
+ if (method) return method;
3877
+ method = new Proxy(
3878
+ (...args) => handle.action({ name, args }),
3879
+ {
3880
+ get(target, prop) {
3881
+ if (typeof prop === "symbol")
3882
+ return Reflect.get(target, prop);
3883
+ if (prop === "then") return void 0;
3884
+ return actionPath(`${name}.${prop}`);
3885
+ }
3886
+ }
3887
+ );
3888
+ methodCache.set(name, method);
3889
+ return method;
3890
+ };
3548
3891
  return new Proxy(handle, {
3549
3892
  get(target, prop, receiver) {
3550
3893
  if (typeof prop === "symbol") {
@@ -3559,12 +3902,7 @@ function createActorProxy(handle) {
3559
3902
  }
3560
3903
  if (typeof prop === "string") {
3561
3904
  if (prop === "then") return void 0;
3562
- let method = methodCache.get(prop);
3563
- if (!method) {
3564
- method = (...args) => target.action({ name: prop, args });
3565
- methodCache.set(prop, method);
3566
- }
3567
- return method;
3905
+ return actionPath(prop);
3568
3906
  }
3569
3907
  },
3570
3908
  // Support for 'in' operator
@@ -3582,6 +3920,7 @@ function createActorProxy(handle) {
3582
3920
  },
3583
3921
  // Support proper property descriptors
3584
3922
  getOwnPropertyDescriptor(target, prop) {
3923
+ if (prop === "then") return void 0;
3585
3924
  const targetDescriptor = Reflect.getOwnPropertyDescriptor(
3586
3925
  target,
3587
3926
  prop
@@ -3594,7 +3933,7 @@ function createActorProxy(handle) {
3594
3933
  configurable: true,
3595
3934
  enumerable: false,
3596
3935
  writable: false,
3597
- value: (...args) => target.action({ name: prop, args })
3936
+ value: actionPath(prop)
3598
3937
  };
3599
3938
  }
3600
3939
  return void 0;
@@ -3602,7 +3941,79 @@ function createActorProxy(handle) {
3602
3941
  });
3603
3942
  }
3604
3943
 
3944
+ // src/client/token-provider.ts
3945
+ function isInvalidToken(group, code) {
3946
+ return group === "auth" && (code === "invalid_token" || code === "token_expired");
3947
+ }
3948
+ function isInvalidTokenResponse(response) {
3949
+ if (response.status !== 401) return false;
3950
+ const error = response.headers.get("x-rivet-error");
3951
+ if (!error) return false;
3952
+ const separator = error.indexOf(".");
3953
+ return separator > 0 && isInvalidToken(error.slice(0, separator), error.slice(separator + 1));
3954
+ }
3955
+ var TokenProvider = class {
3956
+ constructor(getToken) {
3957
+ this.getToken = getToken;
3958
+ }
3959
+ #cached;
3960
+ #pending;
3961
+ #pendingForce = false;
3962
+ async current() {
3963
+ if (this.#cached && (this.#cached.expiresAt === void 0 || Date.now() < this.#cached.expiresAt - 5e3)) {
3964
+ return this.#cached.token;
3965
+ }
3966
+ return this.#load(false);
3967
+ }
3968
+ /** A late rejection for an older token must never erase a newer credential. */
3969
+ async refreshIfCurrent(failedToken) {
3970
+ var _a;
3971
+ if (this.#pending !== void 0) {
3972
+ const wasForced = this.#pendingForce;
3973
+ const refreshed = await this.#pending;
3974
+ if (wasForced || refreshed !== failedToken) return refreshed;
3975
+ }
3976
+ if (((_a = this.#cached) == null ? void 0 : _a.token) !== failedToken) {
3977
+ return this.current();
3978
+ }
3979
+ return this.#load(true);
3980
+ }
3981
+ #load(forceRefresh) {
3982
+ if (this.#pending !== void 0) return this.#pending;
3983
+ const pending = Promise.resolve().then(() => this.getToken({ forceRefresh })).then((token) => {
3984
+ if (typeof token !== "string" || token.length === 0) {
3985
+ throw new Error(
3986
+ "getToken must resolve to a nonempty string"
3987
+ );
3988
+ }
3989
+ this.#cached = { token, expiresAt: jwtExpiration(token) };
3990
+ return token;
3991
+ }).finally(() => {
3992
+ if (this.#pending === pending) this.#pending = void 0;
3993
+ });
3994
+ this.#pending = pending;
3995
+ this.#pendingForce = forceRefresh;
3996
+ return pending;
3997
+ }
3998
+ };
3999
+ function jwtExpiration(token) {
4000
+ try {
4001
+ const payload = token.split(".")[1];
4002
+ if (!payload) return void 0;
4003
+ const claims = JSON.parse(
4004
+ atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
4005
+ );
4006
+ return typeof claims.exp === "number" && Number.isSafeInteger(claims.exp) ? claims.exp * 1e3 : void 0;
4007
+ } catch (e3) {
4008
+ return void 0;
4009
+ }
4010
+ }
4011
+
3605
4012
  // src/client/actor-conn.ts
4013
+ var CONNECT_TIMEOUT_MS = 2e4;
4014
+ function isConnectionOpenTimeout(error) {
4015
+ return error instanceof _chunkMGI2VVF6cjs.RivetError && error.group === "client" && error.code === "connection_open_timeout";
4016
+ }
3606
4017
  var CONNECT_SYMBOL = /* @__PURE__ */ Symbol("connect");
3607
4018
  var ActorConnRaw = class {
3608
4019
  #disposed = false;
@@ -3630,9 +4041,13 @@ var ActorConnRaw = class {
3630
4041
  #keepNodeAliveInterval;
3631
4042
  /** Promise used to indicate the socket has connected successfully. This will be rejected if the connection fails. */
3632
4043
  #onOpenPromise;
4044
+ /** Sockets given up on by the connect timeout. Their late events are ignored. */
4045
+ #abandonedSockets = /* @__PURE__ */ new WeakSet();
3633
4046
  #websocket;
4047
+ #authRetryAvailable = true;
3634
4048
  #client;
3635
4049
  #driver;
4050
+ #currentActorInvocation;
3636
4051
  #params;
3637
4052
  #getParams;
3638
4053
  #encoding;
@@ -3646,8 +4061,9 @@ var ActorConnRaw = class {
3646
4061
  *
3647
4062
  * @protected
3648
4063
  */
3649
- constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}) {
4064
+ constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}, currentActorInvocation) {
3650
4065
  this.#client = client;
4066
+ this.#currentActorInvocation = currentActorInvocation;
3651
4067
  this.#driver = driver;
3652
4068
  this.#params = params;
3653
4069
  this.#getParams = getParams;
@@ -3657,8 +4073,8 @@ var ActorConnRaw = class {
3657
4073
  if ("getForId" in actorResolutionState) {
3658
4074
  this.#actorId = actorResolutionState.getForId.actorId;
3659
4075
  }
3660
- this.#readyPromise = _chunk7QKCGUTJcjs.promiseWithResolvers.call(void 0,
3661
- (reason) => _chunkND567FR5cjs.logger.call(void 0, ).warn({
4076
+ this.#readyPromise = _chunk2MOLY6AMcjs.promiseWithResolvers.call(void 0,
4077
+ (reason) => _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({
3662
4078
  msg: "unhandled ready promise rejection",
3663
4079
  reason
3664
4080
  })
@@ -3666,6 +4082,10 @@ var ActorConnRaw = class {
3666
4082
  this.#queueSender = createQueueSender({
3667
4083
  encoding: this.#encoding,
3668
4084
  params: this.#params,
4085
+ telemetryHeaders: () => {
4086
+ var _a;
4087
+ return outboundTelemetryHeaders((_a = this.#currentActorInvocation) == null ? void 0 : _a.call(this));
4088
+ },
3669
4089
  customFetch: async (request) => {
3670
4090
  return await this.#driver.sendRequest(
3671
4091
  getGatewayTarget(this.#actorResolutionState),
@@ -3674,7 +4094,8 @@ var ActorConnRaw = class {
3674
4094
  );
3675
4095
  }
3676
4096
  });
3677
- this.#keepNodeAliveInterval = setInterval(() => 6e4);
4097
+ this.#keepNodeAliveInterval = setInterval(() => {
4098
+ }, 6e4);
3678
4099
  }
3679
4100
  #clearResolvedActorIdentity() {
3680
4101
  this.#actorId = void 0;
@@ -3720,11 +4141,11 @@ var ActorConnRaw = class {
3720
4141
  `Invalid action call: expected an options object { name, args }, got ${typeof opts}. Use conn.actionName(...args) for the shorthand API.`
3721
4142
  );
3722
4143
  }
3723
- _chunkND567FR5cjs.logger.call(void 0, ).debug({ msg: "action", name: opts.name, args: opts.args });
4144
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({ msg: "action", name: opts.name, args: opts.args });
3724
4145
  const actionId = this.#actionIdCounter;
3725
4146
  this.#actionIdCounter += 1;
3726
- const { promise, resolve, reject } = _chunk7QKCGUTJcjs.promiseWithResolvers.call(void 0,
3727
- (reason) => _chunkND567FR5cjs.logger.call(void 0, ).warn({
4147
+ const { promise, resolve, reject } = _chunk2MOLY6AMcjs.promiseWithResolvers.call(void 0,
4148
+ (reason) => _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({
3728
4149
  msg: "unhandled action promise rejection",
3729
4150
  reason
3730
4151
  })
@@ -3734,7 +4155,7 @@ var ActorConnRaw = class {
3734
4155
  resolve,
3735
4156
  reject
3736
4157
  });
3737
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4158
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3738
4159
  msg: "added action to in-flight map",
3739
4160
  actionId,
3740
4161
  actionName: opts.name,
@@ -3774,9 +4195,9 @@ var ActorConnRaw = class {
3774
4195
  try {
3775
4196
  handler(status);
3776
4197
  } catch (err) {
3777
- _chunkND567FR5cjs.logger.call(void 0, ).error({
4198
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).error({
3778
4199
  msg: "error in status change handler",
3779
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, err)
4200
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, err)
3780
4201
  });
3781
4202
  }
3782
4203
  }
@@ -3786,9 +4207,9 @@ var ActorConnRaw = class {
3786
4207
  try {
3787
4208
  handler();
3788
4209
  } catch (err) {
3789
- _chunkND567FR5cjs.logger.call(void 0, ).error({
4210
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).error({
3790
4211
  msg: "error in open handler",
3791
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, err)
4212
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, err)
3792
4213
  });
3793
4214
  }
3794
4215
  }
@@ -3798,9 +4219,9 @@ var ActorConnRaw = class {
3798
4219
  try {
3799
4220
  handler();
3800
4221
  } catch (err) {
3801
- _chunkND567FR5cjs.logger.call(void 0, ).error({
4222
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).error({
3802
4223
  msg: "error in close handler",
3803
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, err)
4224
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, err)
3804
4225
  });
3805
4226
  }
3806
4227
  }
@@ -3812,22 +4233,26 @@ var ActorConnRaw = class {
3812
4233
  forever: true,
3813
4234
  minTimeout: 250,
3814
4235
  maxTimeout: 3e4,
3815
- onFailedAttempt: (error) => {
3816
- _chunkND567FR5cjs.logger.call(void 0, ).warn({
4236
+ onFailedAttempt: async (error) => {
4237
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({
3817
4238
  msg: "failed to reconnect",
3818
4239
  attempt: error.attemptNumber,
3819
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, error)
4240
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, error)
3820
4241
  });
4242
+ const hintMs = retryAfterMs(error);
4243
+ if (hintMs !== void 0) {
4244
+ await new Promise((resolve) => setTimeout(resolve, hintMs));
4245
+ }
3821
4246
  },
3822
4247
  // Cancel retry if aborted
3823
4248
  signal: this.#abortController.signal
3824
4249
  }).catch((err) => {
3825
4250
  if (err instanceof _pretry.AbortError || err.name === "AbortError" || !this.#shouldRetryConnectionOpenError(err)) {
3826
- _chunkND567FR5cjs.logger.call(void 0, ).info({ msg: "connection retry aborted" });
4251
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).info({ msg: "connection retry aborted" });
3827
4252
  } else {
3828
- _chunkND567FR5cjs.logger.call(void 0, ).error({
4253
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).error({
3829
4254
  msg: "unexpected error in connection retry",
3830
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, err)
4255
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, err)
3831
4256
  });
3832
4257
  }
3833
4258
  });
@@ -3836,50 +4261,107 @@ var ActorConnRaw = class {
3836
4261
  try {
3837
4262
  if (this.#onOpenPromise)
3838
4263
  throw new Error("#onOpenPromise already defined");
3839
- this.#onOpenPromise = _chunk7QKCGUTJcjs.promiseWithResolvers.call(void 0,
3840
- (reason) => _chunkND567FR5cjs.logger.call(void 0, ).warn({
4264
+ this.#onOpenPromise = _chunk2MOLY6AMcjs.promiseWithResolvers.call(void 0,
4265
+ (reason) => _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({
3841
4266
  msg: "unhandled open promise rejection",
3842
4267
  reason
3843
4268
  })
3844
4269
  );
3845
4270
  await this.#connectWebSocket();
3846
- await this.#onOpenPromise.promise;
4271
+ await this.#waitForOpen(this.#onOpenPromise.promise);
3847
4272
  } catch (error) {
3848
4273
  if (this.#shouldRetryConnectionOpenError(error)) {
3849
4274
  throw error;
3850
4275
  }
3851
- const actorError = error instanceof _chunk4FC7TVS6cjs.RivetError ? error : new (0, _chunk4FC7TVS6cjs.RivetError)(
4276
+ const actorError = error instanceof _chunkMGI2VVF6cjs.RivetError ? error : new (0, _chunkMGI2VVF6cjs.RivetError)(
3852
4277
  "client",
3853
4278
  "connection_open_failed",
3854
- `Failed to open connection: ${_chunk7QKCGUTJcjs.stringifyError.call(void 0, error)}`,
3855
- { error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, error) }
4279
+ `Failed to open connection: ${_chunk2MOLY6AMcjs.stringifyError.call(void 0, error)}`,
4280
+ { error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, error) }
3856
4281
  );
3857
4282
  this.#clearQueuedMessages();
3858
4283
  this.#rejectPendingPromises(actorError, false);
3859
4284
  this.#dispatchActorError(actorError);
3860
4285
  this.#setConnStatus("idle");
3861
4286
  throw new (0, _pretry.AbortError)(
3862
- error instanceof Error ? error : new Error(_chunk7QKCGUTJcjs.stringifyError.call(void 0, error))
4287
+ error instanceof Error ? error : new Error(_chunk2MOLY6AMcjs.stringifyError.call(void 0, error))
3863
4288
  );
3864
4289
  } finally {
3865
4290
  this.#onOpenPromise = void 0;
3866
4291
  }
3867
4292
  }
4293
+ /**
4294
+ * Waits for the actor's Init on the current socket, up to {@link CONNECT_TIMEOUT_MS}. A socket
4295
+ * can stay connecting with no open, error or close event, as when the engine holds the
4296
+ * upgrade or a refused connect reports only an error. On timeout the socket is abandoned
4297
+ * and closed, and the retryable `client.connection_open_timeout` starts the next attempt.
4298
+ */
4299
+ async #waitForOpen(open) {
4300
+ let timer;
4301
+ const timedOut = new Promise((_, reject) => {
4302
+ timer = setTimeout(() => {
4303
+ reject(
4304
+ new (0, _chunkMGI2VVF6cjs.RivetError)(
4305
+ "client",
4306
+ "connection_open_timeout",
4307
+ `Connection did not open within ${CONNECT_TIMEOUT_MS} ms`
4308
+ )
4309
+ );
4310
+ }, CONNECT_TIMEOUT_MS);
4311
+ });
4312
+ try {
4313
+ await Promise.race([open, timedOut]);
4314
+ } catch (error) {
4315
+ if (isConnectionOpenTimeout(error)) {
4316
+ this.#abandonCurrentSocket();
4317
+ }
4318
+ throw error;
4319
+ } finally {
4320
+ clearTimeout(timer);
4321
+ }
4322
+ }
4323
+ #abandonCurrentSocket() {
4324
+ const ws = this.#websocket;
4325
+ if (!ws) return;
4326
+ this.#websocket = void 0;
4327
+ this.#abandonedSockets.add(ws);
4328
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({
4329
+ msg: "connection did not open in time, retrying",
4330
+ connId: this.#connId,
4331
+ readyState: ws.readyState,
4332
+ timeoutMs: CONNECT_TIMEOUT_MS
4333
+ });
4334
+ try {
4335
+ ws.close(1e3, "Connect timeout");
4336
+ } catch (err) {
4337
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
4338
+ msg: "failed to close abandoned websocket",
4339
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, err)
4340
+ });
4341
+ }
4342
+ }
3868
4343
  #shouldRetryConnectionOpenError(error) {
3869
4344
  if (error instanceof ActorConnDisposed) {
3870
4345
  return false;
3871
4346
  }
3872
- if (error instanceof _chunk4FC7TVS6cjs.RivetError && this.#shouldReconnectForStaleActor(error.group, error.code)) {
4347
+ if (isConnectionOpenTimeout(error)) {
3873
4348
  return true;
3874
4349
  }
3875
- if (error instanceof _chunk4FC7TVS6cjs.RivetError && error.group === "client" && error.code === "get_params_failed") {
4350
+ if (error instanceof _chunkMGI2VVF6cjs.RivetError && isInvalidToken(error.group, error.code) && this.#driver.refreshAuthToken && this.#authRetryAvailable) {
4351
+ this.#authRetryAvailable = false;
4352
+ return true;
4353
+ }
4354
+ if (error instanceof _chunkMGI2VVF6cjs.RivetError && this.#shouldReconnectForStaleActor(error.group, error.code)) {
4355
+ return true;
4356
+ }
4357
+ if (error instanceof _chunkMGI2VVF6cjs.RivetError && error.group === "client" && error.code === "get_params_failed") {
3876
4358
  return true;
3877
4359
  }
3878
4360
  return isRetryableLifecycleReconnectSignal(error);
3879
4361
  }
3880
4362
  #clearQueuedMessages() {
3881
4363
  if (this.#messageQueue.length === 0) return;
3882
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4364
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3883
4365
  msg: "clearing queued connection messages",
3884
4366
  queueLength: this.#messageQueue.length
3885
4367
  });
@@ -3892,8 +4374,8 @@ var ActorConnRaw = class {
3892
4374
  try {
3893
4375
  return await this.#getParams();
3894
4376
  } catch (err) {
3895
- const errorMessage = _chunk7QKCGUTJcjs.stringifyError.call(void 0, err);
3896
- const error = new (0, _chunk4FC7TVS6cjs.RivetError)(
4377
+ const errorMessage = _chunk2MOLY6AMcjs.stringifyError.call(void 0, err);
4378
+ const error = new (0, _chunkMGI2VVF6cjs.RivetError)(
3897
4379
  "client",
3898
4380
  "get_params_failed",
3899
4381
  `Failed to resolve connection params: ${errorMessage}`,
@@ -3916,7 +4398,7 @@ var ActorConnRaw = class {
3916
4398
  this.#gatewayOptions
3917
4399
  );
3918
4400
  _invariant2.default.call(void 0, ws, "websocket should have been created");
3919
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4401
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3920
4402
  msg: "opened websocket",
3921
4403
  connId: this.#connId,
3922
4404
  readyState: ws.readyState,
@@ -3924,38 +4406,42 @@ var ActorConnRaw = class {
3924
4406
  });
3925
4407
  this.#websocket = ws;
3926
4408
  ws.addEventListener("open", () => {
3927
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4409
+ if (this.#abandonedSockets.has(ws)) return;
4410
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3928
4411
  msg: "client websocket open",
3929
4412
  connId: this.#connId
3930
4413
  });
3931
4414
  });
3932
4415
  ws.addEventListener("message", async (ev) => {
4416
+ if (this.#abandonedSockets.has(ws)) return;
3933
4417
  try {
3934
4418
  await this.#handleOnMessage(ev.data);
3935
4419
  } catch (err) {
3936
- _chunkND567FR5cjs.logger.call(void 0, ).error({
4420
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).error({
3937
4421
  msg: "error in websocket message handler",
3938
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, err)
4422
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, err)
3939
4423
  });
3940
4424
  }
3941
4425
  });
3942
4426
  ws.addEventListener("close", async (ev) => {
4427
+ if (this.#abandonedSockets.has(ws)) return;
3943
4428
  try {
3944
4429
  await this.#handleOnClose(ev);
3945
4430
  } catch (err) {
3946
- _chunkND567FR5cjs.logger.call(void 0, ).error({
4431
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).error({
3947
4432
  msg: "error in websocket close handler",
3948
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, err)
4433
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, err)
3949
4434
  });
3950
4435
  }
3951
4436
  });
3952
4437
  ws.addEventListener("error", () => {
4438
+ if (this.#abandonedSockets.has(ws)) return;
3953
4439
  try {
3954
4440
  this.#handleOnError();
3955
4441
  } catch (err) {
3956
- _chunkND567FR5cjs.logger.call(void 0, ).error({
4442
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).error({
3957
4443
  msg: "error in websocket error handler",
3958
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, err)
4444
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, err)
3959
4445
  });
3960
4446
  }
3961
4447
  });
@@ -3963,7 +4449,7 @@ var ActorConnRaw = class {
3963
4449
  /** Called by the onopen event from drivers. */
3964
4450
  #handleOnOpen() {
3965
4451
  if (this.#disposed) {
3966
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4452
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3967
4453
  msg: "handleOnOpen called after dispose, closing websocket"
3968
4454
  });
3969
4455
  if (this.#websocket) {
@@ -3979,7 +4465,7 @@ var ActorConnRaw = class {
3979
4465
  queueMicrotask(() => {
3980
4466
  this.#openScheduled = false;
3981
4467
  if (this.#disposed) {
3982
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4468
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3983
4469
  msg: "handleOnOpen scheduled after dispose, closing websocket"
3984
4470
  });
3985
4471
  if (this.#websocket) {
@@ -3988,23 +4474,24 @@ var ActorConnRaw = class {
3988
4474
  }
3989
4475
  return;
3990
4476
  }
3991
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4477
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
3992
4478
  msg: "socket open",
3993
4479
  messageQueueLength: this.#messageQueue.length,
3994
4480
  connId: this.#connId
3995
4481
  });
4482
+ this.#authRetryAvailable = true;
3996
4483
  this.#setConnStatus("connected");
3997
4484
  if (this.#onOpenPromise) {
3998
4485
  this.#onOpenPromise.resolve(void 0);
3999
4486
  } else {
4000
- _chunkND567FR5cjs.logger.call(void 0, ).warn({ msg: "#onOpenPromise is undefined" });
4487
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({ msg: "#onOpenPromise is undefined" });
4001
4488
  }
4002
4489
  for (const eventName of this.#eventSubscriptions.keys()) {
4003
4490
  this.#sendSubscription(eventName, true);
4004
4491
  }
4005
4492
  const queue = this.#messageQueue;
4006
4493
  this.#messageQueue = [];
4007
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4494
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
4008
4495
  msg: "flushing message queue",
4009
4496
  queueLength: queue.length
4010
4497
  });
@@ -4016,23 +4503,23 @@ var ActorConnRaw = class {
4016
4503
  /** Called by the onmessage event from drivers. */
4017
4504
  async #handleOnMessage(data) {
4018
4505
  var _a;
4019
- _chunkND567FR5cjs.logger.call(void 0, ).trace({
4506
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).trace({
4020
4507
  msg: "received message",
4021
4508
  dataType: typeof data,
4022
4509
  isBlob: data instanceof Blob,
4023
4510
  isArrayBuffer: data instanceof ArrayBuffer
4024
4511
  });
4025
4512
  const response = await this.#parseMessage(data);
4026
- _chunkND567FR5cjs.logger.call(void 0, ).trace(
4027
- _chunk7QKCGUTJcjs.getLogMessage.call(void 0, ) ? {
4513
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).trace(
4514
+ _chunk2MOLY6AMcjs.getLogMessage.call(void 0, ) ? {
4028
4515
  msg: "parsed message",
4029
- message: _chunkRV5MAFDTcjs.jsonStringifyCompat.call(void 0, response).substring(0, 100) + "..."
4516
+ message: _chunk2MOLY6AMcjs.jsonStringifyCompat.call(void 0, response).substring(0, 100) + "..."
4030
4517
  } : { msg: "parsed message" }
4031
4518
  );
4032
4519
  if (response.body.tag === "Init") {
4033
4520
  this.#actorId = response.body.val.actorId;
4034
4521
  this.#connId = response.body.val.connectionId;
4035
- _chunkND567FR5cjs.logger.call(void 0, ).trace({
4522
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).trace({
4036
4523
  msg: "received init message",
4037
4524
  actorId: this.#actorId,
4038
4525
  connId: this.#connId
@@ -4043,7 +4530,7 @@ var ActorConnRaw = class {
4043
4530
  if (actionId !== null) {
4044
4531
  const inFlight = this.#takeActionInFlight(Number(actionId));
4045
4532
  this.#invalidateActorIfStale(group, code);
4046
- _chunkND567FR5cjs.logger.call(void 0, ).warn({
4533
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({
4047
4534
  msg: "action error",
4048
4535
  actionId,
4049
4536
  actionName: inFlight == null ? void 0 : inFlight.name,
@@ -4056,13 +4543,13 @@ var ActorConnRaw = class {
4056
4543
  actorKey: actor == null ? void 0 : actor.key
4057
4544
  });
4058
4545
  inFlight.reject(
4059
- new (0, _chunk4FC7TVS6cjs.RivetError)(group, code, message, {
4546
+ new (0, _chunkMGI2VVF6cjs.RivetError)(group, code, message, {
4060
4547
  metadata,
4061
4548
  actor
4062
4549
  })
4063
4550
  );
4064
4551
  } else {
4065
- _chunkND567FR5cjs.logger.call(void 0, ).warn({
4552
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({
4066
4553
  msg: "connection error",
4067
4554
  group,
4068
4555
  code,
@@ -4075,14 +4562,14 @@ var ActorConnRaw = class {
4075
4562
  if (this.#shouldReconnectForStaleActor(group, code)) {
4076
4563
  this.#clearResolvedActorIdentity();
4077
4564
  (_a = this.#onOpenPromise) == null ? void 0 : _a.reject(
4078
- new (0, _chunk4FC7TVS6cjs.RivetError)(group, code, message, {
4565
+ new (0, _chunkMGI2VVF6cjs.RivetError)(group, code, message, {
4079
4566
  metadata,
4080
4567
  actor
4081
4568
  })
4082
4569
  );
4083
4570
  return;
4084
4571
  }
4085
- let errorToThrow = new (0, _chunk4FC7TVS6cjs.RivetError)(group, code, message, {
4572
+ let errorToThrow = new (0, _chunkMGI2VVF6cjs.RivetError)(group, code, message, {
4086
4573
  metadata,
4087
4574
  actor
4088
4575
  });
@@ -4110,36 +4597,37 @@ var ActorConnRaw = class {
4110
4597
  }
4111
4598
  } else if (response.body.tag === "ActionResponse") {
4112
4599
  const { id: actionId } = response.body.val;
4113
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4600
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
4114
4601
  msg: "received action response",
4115
4602
  actionId: Number(actionId),
4116
4603
  inFlightCount: this.#actionsInFlight.size,
4117
4604
  inFlightIds: Array.from(this.#actionsInFlight.keys())
4118
4605
  });
4119
4606
  const inFlight = this.#takeActionInFlight(Number(actionId));
4120
- _chunkND567FR5cjs.logger.call(void 0, ).trace({
4607
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).trace({
4121
4608
  msg: "resolving action promise",
4122
4609
  actionId,
4123
4610
  actionName: inFlight == null ? void 0 : inFlight.name
4124
4611
  });
4125
4612
  inFlight.resolve(response.body.val);
4126
4613
  } else if (response.body.tag === "Event") {
4127
- _chunkND567FR5cjs.logger.call(void 0, ).trace({
4614
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).trace({
4128
4615
  msg: "received event",
4129
4616
  name: response.body.val.name
4130
4617
  });
4131
4618
  this.#dispatchEvent(response.body.val);
4132
4619
  } else {
4133
- _chunk7QKCGUTJcjs.assertUnreachable.call(void 0, response.body);
4620
+ _chunk2MOLY6AMcjs.assertUnreachable.call(void 0, response.body);
4134
4621
  }
4135
4622
  }
4136
4623
  /** Called by the onclose event from drivers. */
4137
4624
  async #handleOnClose(event) {
4138
- var _a;
4625
+ var _a, _b, _c;
4626
+ const failedSocket = this.#websocket;
4139
4627
  const closeEvent = event;
4140
4628
  const wasClean = closeEvent.wasClean;
4141
4629
  const wasConnected = this.#connStatus === "connected";
4142
- _chunkND567FR5cjs.logger.call(void 0, ).info({
4630
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).info({
4143
4631
  msg: "socket closed",
4144
4632
  code: closeEvent.code,
4145
4633
  reason: closeEvent.reason,
@@ -4156,15 +4644,31 @@ var ActorConnRaw = class {
4156
4644
  const reason = closeEvent.reason || "";
4157
4645
  const parsed = parseWebSocketCloseReason(reason);
4158
4646
  if (parsed) {
4159
- const { group, code } = parsed;
4647
+ const { group, code, rayId, retryAfterMs: retryAfterMs2 } = parsed;
4648
+ const closeOptions = retryAfterMs2 === void 0 ? { rayId } : { rayId, metadata: { retry_after_ms: retryAfterMs2 } };
4649
+ if (isInvalidToken(group, code) && closeEvent.code === 1008 && failedSocket) {
4650
+ try {
4651
+ if (!await ((_b = (_a = this.#driver).refreshAuthToken) == null ? void 0 : _b.call(
4652
+ _a,
4653
+ failedSocket
4654
+ ))) {
4655
+ this.#authRetryAvailable = false;
4656
+ }
4657
+ } catch (e4) {
4658
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn("token renewal failed");
4659
+ this.#authRetryAvailable = false;
4660
+ }
4661
+ } else if (isInvalidToken(group, code)) {
4662
+ this.#authRetryAvailable = false;
4663
+ }
4160
4664
  if (this.#shouldReconnectForStaleActor(group, code)) {
4161
4665
  this.#clearResolvedActorIdentity();
4162
- (_a = this.#onOpenPromise) == null ? void 0 : _a.reject(
4163
- new (0, _chunk4FC7TVS6cjs.RivetError)(
4666
+ (_c = this.#onOpenPromise) == null ? void 0 : _c.reject(
4667
+ new (0, _chunkMGI2VVF6cjs.RivetError)(
4164
4668
  group,
4165
4669
  code,
4166
4670
  `Connection closed: ${reason}`,
4167
- void 0
4671
+ closeOptions
4168
4672
  )
4169
4673
  );
4170
4674
  return;
@@ -4175,24 +4679,25 @@ var ActorConnRaw = class {
4175
4679
  code,
4176
4680
  this.#actorId,
4177
4681
  this.#actorResolutionState,
4178
- this.#driver
4682
+ this.#driver,
4683
+ rayId
4179
4684
  );
4180
4685
  if (schedulingError) {
4181
4686
  error = schedulingError;
4182
4687
  } else {
4183
- error = new (0, _chunk4FC7TVS6cjs.RivetError)(
4688
+ error = new (0, _chunkMGI2VVF6cjs.RivetError)(
4184
4689
  group,
4185
4690
  code,
4186
4691
  `Connection closed: ${reason}`,
4187
- void 0
4692
+ closeOptions
4188
4693
  );
4189
4694
  }
4190
4695
  } else {
4191
- error = new (0, _chunk4FC7TVS6cjs.RivetError)(
4696
+ error = new (0, _chunkMGI2VVF6cjs.RivetError)(
4192
4697
  group,
4193
4698
  code,
4194
4699
  `Connection closed: ${reason}`,
4195
- void 0
4700
+ closeOptions
4196
4701
  );
4197
4702
  }
4198
4703
  this.#invalidateActorIfStale(group, code);
@@ -4202,11 +4707,11 @@ var ActorConnRaw = class {
4202
4707
  );
4203
4708
  }
4204
4709
  this.#rejectPendingPromises(error, false);
4205
- if (error instanceof _chunk4FC7TVS6cjs.RivetError) {
4710
+ if (error instanceof _chunkMGI2VVF6cjs.RivetError) {
4206
4711
  this.#dispatchActorError(error);
4207
4712
  }
4208
- if (wasConnected) {
4209
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4713
+ if (wasConnected && this.#authRetryAvailable) {
4714
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
4210
4715
  msg: "triggering reconnect",
4211
4716
  connId: this.#connId
4212
4717
  });
@@ -4230,12 +4735,12 @@ var ActorConnRaw = class {
4230
4735
  /** Called by the onerror event from drivers. */
4231
4736
  #handleOnError() {
4232
4737
  if (this.#disposed) return;
4233
- _chunkND567FR5cjs.logger.call(void 0, ).warn("socket error");
4738
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn("socket error");
4234
4739
  }
4235
4740
  #takeActionInFlight(id) {
4236
4741
  const inFlight = this.#actionsInFlight.get(id);
4237
4742
  if (!inFlight) {
4238
- _chunkND567FR5cjs.logger.call(void 0, ).error({
4743
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).error({
4239
4744
  msg: "action not found in in-flight map",
4240
4745
  lookupId: id,
4241
4746
  inFlightCount: this.#actionsInFlight.size,
@@ -4250,7 +4755,7 @@ var ActorConnRaw = class {
4250
4755
  throw internalClientError(`No in flight response for ${id}`);
4251
4756
  }
4252
4757
  this.#actionsInFlight.delete(id);
4253
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4758
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
4254
4759
  msg: "removed action from in-flight map",
4255
4760
  actionId: id,
4256
4761
  actionName: inFlight.name,
@@ -4277,9 +4782,9 @@ var ActorConnRaw = class {
4277
4782
  try {
4278
4783
  handler(error);
4279
4784
  } catch (err) {
4280
- _chunkND567FR5cjs.logger.call(void 0, ).error({
4785
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).error({
4281
4786
  msg: "error in connection error handler",
4282
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, err)
4787
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, err)
4283
4788
  });
4284
4789
  }
4285
4790
  }
@@ -4384,9 +4889,9 @@ var ActorConnRaw = class {
4384
4889
  try {
4385
4890
  callback();
4386
4891
  } catch (err) {
4387
- _chunkND567FR5cjs.logger.call(void 0, ).error({
4892
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).error({
4388
4893
  msg: "error in open handler",
4389
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, err)
4894
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, err)
4390
4895
  });
4391
4896
  }
4392
4897
  });
@@ -4436,7 +4941,7 @@ var ActorConnRaw = class {
4436
4941
  let queueMessage = false;
4437
4942
  if (this.#websocket) {
4438
4943
  const readyState = this.#websocket.readyState;
4439
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4944
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
4440
4945
  msg: "websocket send attempt",
4441
4946
  readyState,
4442
4947
  readyStateString: readyState === 0 ? "CONNECTING" : readyState === 1 ? "OPEN" : readyState === 2 ? "CLOSING" : "CLOSED",
@@ -4445,7 +4950,7 @@ var ActorConnRaw = class {
4445
4950
  actionName: (_a = message.body.val) == null ? void 0 : _a.name
4446
4951
  });
4447
4952
  if (this.#connStatus !== "connected") {
4448
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
4953
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
4449
4954
  msg: "websocket init pending, queueing message",
4450
4955
  connStatus: this.#connStatus,
4451
4956
  messageType: message.body.tag
@@ -4453,7 +4958,7 @@ var ActorConnRaw = class {
4453
4958
  queueMessage = true;
4454
4959
  } else if (readyState === 1) {
4455
4960
  try {
4456
- const messageSerialized = _chunkRV5MAFDTcjs.serializeWithEncoding.call(void 0,
4961
+ const messageSerialized = _chunk2MOLY6AMcjs.serializeWithEncoding.call(void 0,
4457
4962
  this.#encoding,
4458
4963
  message,
4459
4964
  CLIENT_PROTOCOL_TO_SERVER,
@@ -4470,8 +4975,8 @@ var ActorConnRaw = class {
4470
4975
  val: {
4471
4976
  id: msg.body.val.id,
4472
4977
  name: msg.body.val.name,
4473
- args: _chunk7QKCGUTJcjs.bufferToArrayBuffer.call(void 0,
4474
- _chunkRV5MAFDTcjs.encodeCborCompat.call(void 0,
4978
+ args: _chunk2MOLY6AMcjs.bufferToArrayBuffer.call(void 0,
4979
+ _chunk2MOLY6AMcjs.encodeCborCompat.call(void 0,
4475
4980
  msg.body.val.args
4476
4981
  )
4477
4982
  )
@@ -4485,12 +4990,12 @@ var ActorConnRaw = class {
4485
4990
  );
4486
4991
  this.#websocket.send(messageSerialized);
4487
4992
  const serializedLength = messageLength(messageSerialized);
4488
- _chunkND567FR5cjs.logger.call(void 0, ).trace({
4993
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).trace({
4489
4994
  msg: "sent websocket message",
4490
4995
  len: serializedLength
4491
4996
  });
4492
4997
  } catch (error) {
4493
- _chunkND567FR5cjs.logger.call(void 0, ).warn({
4998
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({
4494
4999
  msg: "failed to send message, added to queue",
4495
5000
  error,
4496
5001
  connId: this.#connId
@@ -4498,19 +5003,19 @@ var ActorConnRaw = class {
4498
5003
  queueMessage = true;
4499
5004
  }
4500
5005
  } else {
4501
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
5006
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
4502
5007
  msg: "websocket not open, queueing message",
4503
5008
  readyState
4504
5009
  });
4505
5010
  queueMessage = true;
4506
5011
  }
4507
5012
  } else {
4508
- _chunkND567FR5cjs.logger.call(void 0, ).debug({ msg: "no websocket, queueing message" });
5013
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({ msg: "no websocket, queueing message" });
4509
5014
  queueMessage = true;
4510
5015
  }
4511
5016
  if (!(opts == null ? void 0 : opts.ephemeral) && queueMessage) {
4512
5017
  this.#messageQueue.push(message);
4513
- _chunkND567FR5cjs.logger.call(void 0, ).debug({
5018
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({
4514
5019
  msg: "queued connection message",
4515
5020
  queueLength: this.#messageQueue.length,
4516
5021
  connId: this.#connId,
@@ -4521,8 +5026,8 @@ var ActorConnRaw = class {
4521
5026
  }
4522
5027
  async #parseMessage(data) {
4523
5028
  _invariant2.default.call(void 0, this.#websocket, "websocket must be defined");
4524
- const buffer = await _chunkRV5MAFDTcjs.inputDataToBuffer.call(void 0, data);
4525
- return _chunkRV5MAFDTcjs.deserializeWithEncoding.call(void 0,
5029
+ const buffer = await _chunk2MOLY6AMcjs.inputDataToBuffer.call(void 0, data);
5030
+ return _chunk2MOLY6AMcjs.deserializeWithEncoding.call(void 0,
4526
5031
  this.#encoding,
4527
5032
  buffer,
4528
5033
  CLIENT_PROTOCOL_TO_CLIENT,
@@ -4557,7 +5062,7 @@ var ActorConnRaw = class {
4557
5062
  group: msg.body.val.group,
4558
5063
  code: msg.body.val.code,
4559
5064
  message: msg.body.val.message,
4560
- metadata: msg.body.val.metadata ? _chunkRV5MAFDTcjs.decodeCborCompat.call(void 0,
5065
+ metadata: msg.body.val.metadata ? _chunk2MOLY6AMcjs.decodeCborCompat.call(void 0,
4561
5066
  new Uint8Array(
4562
5067
  msg.body.val.metadata
4563
5068
  )
@@ -4579,7 +5084,7 @@ var ActorConnRaw = class {
4579
5084
  tag: "ActionResponse",
4580
5085
  val: {
4581
5086
  id: msg.body.val.id,
4582
- output: _chunkRV5MAFDTcjs.decodeCborCompat.call(void 0,
5087
+ output: _chunk2MOLY6AMcjs.decodeCborCompat.call(void 0,
4583
5088
  new Uint8Array(msg.body.val.output)
4584
5089
  )
4585
5090
  }
@@ -4591,7 +5096,7 @@ var ActorConnRaw = class {
4591
5096
  tag: "Event",
4592
5097
  val: {
4593
5098
  name: msg.body.val.name,
4594
- args: _chunkRV5MAFDTcjs.decodeCborCompat.call(void 0,
5099
+ args: _chunk2MOLY6AMcjs.decodeCborCompat.call(void 0,
4595
5100
  new Uint8Array(msg.body.val.args)
4596
5101
  )
4597
5102
  }
@@ -4632,11 +5137,11 @@ var ActorConnRaw = class {
4632
5137
  */
4633
5138
  async dispose() {
4634
5139
  if (this.#disposed) {
4635
- _chunkND567FR5cjs.logger.call(void 0, ).warn({ msg: "connection already disconnected" });
5140
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({ msg: "connection already disconnected" });
4636
5141
  return;
4637
5142
  }
4638
5143
  this.#disposed = true;
4639
- _chunkND567FR5cjs.logger.call(void 0, ).debug({ msg: "disposing actor conn" });
5144
+ _chunkJUHXV3HFcjs.logger.call(void 0, ).debug({ msg: "disposing actor conn" });
4640
5145
  this.#setConnStatus("idle");
4641
5146
  clearInterval(this.#keepNodeAliveInterval);
4642
5147
  this.#abortController.abort();
@@ -4644,8 +5149,8 @@ var ActorConnRaw = class {
4644
5149
  if (this.#websocket) {
4645
5150
  const ws = this.#websocket;
4646
5151
  if (ws.readyState !== 2 && ws.readyState !== 3) {
4647
- const { promise, resolve } = _chunk7QKCGUTJcjs.promiseWithResolvers.call(void 0,
4648
- (reason) => _chunkND567FR5cjs.logger.call(void 0, ).warn({
5152
+ const { promise, resolve } = _chunk2MOLY6AMcjs.promiseWithResolvers.call(void 0,
5153
+ (reason) => _chunkJUHXV3HFcjs.logger.call(void 0, ).warn({
4649
5154
  msg: "unhandled websocket close promise rejection",
4650
5155
  reason
4651
5156
  })
@@ -4678,6 +5183,25 @@ var ActorConnRaw = class {
4678
5183
  // src/client/config.ts
4679
5184
 
4680
5185
 
5186
+ // src/common/engine.ts
5187
+ var ENGINE_HOST = "127.0.0.1";
5188
+ var ENGINE_PORT = 6420;
5189
+ var ENGINE_ENDPOINT = buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT);
5190
+ function buildEngineEndpoint(host, port) {
5191
+ const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
5192
+ return `http://${urlHost}:${port}`;
5193
+ }
5194
+ function isLocalEngineEndpoint(endpoint) {
5195
+ let url;
5196
+ try {
5197
+ url = new URL(endpoint);
5198
+ } catch (e5) {
5199
+ return false;
5200
+ }
5201
+ const hostname = url.hostname.toLowerCase();
5202
+ return hostname === "localhost" || hostname === "0.0.0.0" || hostname === "::" || hostname === "[::]" || hostname === "::1" || hostname === "[::1]" || /^127(?:\.\d{1,3}){0,3}$/.test(hostname);
5203
+ }
5204
+
4681
5205
  // src/utils/endpoint-parser.ts
4682
5206
  function tryParseEndpoint(ctx, options) {
4683
5207
  const {
@@ -4689,7 +5213,7 @@ function tryParseEndpoint(ctx, options) {
4689
5213
  let url;
4690
5214
  try {
4691
5215
  url = new URL(endpoint);
4692
- } catch (e2) {
5216
+ } catch (e6) {
4693
5217
  ctx.addIssue({
4694
5218
  code: "custom",
4695
5219
  message: `invalid URL: ${endpoint}`,
@@ -4764,7 +5288,7 @@ var ClientConfigSchemaBase = _v42.default.object({
4764
5288
  * Defaults to http://localhost:6420.
4765
5289
  */
4766
5290
  endpoint: _v42.default.string().optional().transform((val) => {
4767
- const resolved = _nullishCoalesce(_nullishCoalesce(val, () => ( _chunk7QKCGUTJcjs.getRivetEngine.call(void 0, ))), () => ( _chunk7QKCGUTJcjs.getRivetEndpoint.call(void 0, )));
5291
+ const resolved = _nullishCoalesce(_nullishCoalesce(val, () => ( _chunk2MOLY6AMcjs.getRivetEngine.call(void 0, ))), () => ( _chunk2MOLY6AMcjs.getRivetEndpoint.call(void 0, )));
4768
5292
  if (!resolved && !hasWarnedMissingEndpoint) {
4769
5293
  hasWarnedMissingEndpoint = true;
4770
5294
  console.warn(
@@ -4774,12 +5298,14 @@ var ClientConfigSchemaBase = _v42.default.object({
4774
5298
  return _nullishCoalesce(resolved, () => ( DEFAULT_ENDPOINT));
4775
5299
  }),
4776
5300
  /** Token to use to authenticate with the API. */
4777
- token: _v42.default.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunk7QKCGUTJcjs.getRivetToken.call(void 0, )))),
5301
+ token: _v42.default.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunk2MOLY6AMcjs.getRivetToken.call(void 0, )))),
5302
+ /** Issue and renew a client token on demand. Overrides the static token when provided. */
5303
+ getToken: _v42.default.custom().optional(),
4778
5304
  /** Namespace to connect to. */
4779
- namespace: _v42.default.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunk7QKCGUTJcjs.getRivetNamespace.call(void 0, )))),
5305
+ namespace: _v42.default.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunk2MOLY6AMcjs.getRivetNamespace.call(void 0, )))),
4780
5306
  /** Name of the envoy pool. This is used to group together envoys in to different pools. */
4781
- poolName: _v42.default.string().default(() => _nullishCoalesce(_chunk7QKCGUTJcjs.getRivetPool.call(void 0, ), () => ( "default"))),
4782
- encoding: _chunkRV5MAFDTcjs.EncodingSchema.default("bare"),
5307
+ poolName: _v42.default.string().default(() => _nullishCoalesce(_chunk2MOLY6AMcjs.getRivetPool.call(void 0, ), () => ( "default"))),
5308
+ encoding: _chunk2MOLY6AMcjs.EncodingSchema.default("bare"),
4783
5309
  headers: _v42.default.record(_v42.default.string(), _v42.default.string()).optional().default(() => ({})),
4784
5310
  gateway: _v42.default.object({
4785
5311
  skipReadyWait: _v42.default.boolean().optional().default(false)
@@ -4789,6 +5315,16 @@ var ClientConfigSchemaBase = _v42.default.object({
4789
5315
  // This is required in the client config in order to support
4790
5316
  // `proxyWebSocket`
4791
5317
  getUpgradeWebSocket: _v42.default.custom().optional(),
5318
+ /**
5319
+ * Bounds retries of refused requests: `percent` retries per 100 requests (default 10), with
5320
+ * up to `maxTokens` banked for bursts (default 100). A refusal past the budget is thrown.
5321
+ */
5322
+ retryBudget: _v42.default.object({
5323
+ percent: _v42.default.number().min(0).max(100).optional(),
5324
+ maxTokens: _v42.default.number().int().min(0).optional()
5325
+ }).optional(),
5326
+ /** Replaces global fetch for actor HTTP gateway requests. */
5327
+ fetch: _v42.default.custom().optional(),
4792
5328
  /** Whether to automatically perform health checks when the client is created. */
4793
5329
  disableMetadataLookup: _v42.default.boolean().optional().default(false),
4794
5330
  /**
@@ -4819,7 +5355,7 @@ function transformClientConfig(config, ctx) {
4819
5355
  ...config,
4820
5356
  endpoint: parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint,
4821
5357
  namespace: _nullishCoalesce(_nullishCoalesce((parsedEndpoint == null ? void 0 : parsedEndpoint.namespace), () => ( config.namespace)), () => ( "default")),
4822
- token: _nullishCoalesce((parsedEndpoint == null ? void 0 : parsedEndpoint.token), () => ( config.token))
5358
+ token: _nullishCoalesce(_nullishCoalesce((parsedEndpoint == null ? void 0 : parsedEndpoint.token), () => ( config.token)), () => ( (config.endpoint && isLocalEngineEndpoint(config.endpoint) ? "default" : void 0)))
4823
5359
  };
4824
5360
  }
4825
5361
  function convertRegistryConfigToClientConfig(config) {
@@ -4827,8 +5363,9 @@ function convertRegistryConfigToClientConfig(config) {
4827
5363
  return {
4828
5364
  endpoint: config.endpoint,
4829
5365
  token: config.token,
5366
+ getToken: void 0,
4830
5367
  namespace: config.namespace,
4831
- poolName: config.envoy.poolName,
5368
+ poolName: config.node.poolName,
4832
5369
  headers: config.headers,
4833
5370
  gateway: { skipReadyWait: false },
4834
5371
  encoding: "bare",
@@ -4840,119 +5377,6 @@ function convertRegistryConfigToClientConfig(config) {
4840
5377
  };
4841
5378
  }
4842
5379
 
4843
- // src/engine-client/api-utils.ts
4844
-
4845
-
4846
- // src/engine-client/log.ts
4847
- function logger2() {
4848
- return _chunk7QKCGUTJcjs.getLogger.call(void 0, "engine-client");
4849
- }
4850
-
4851
- // src/engine-client/api-utils.ts
4852
- function getEndpoint(config) {
4853
- return _nullishCoalesce(config.endpoint, () => ( "http://127.0.0.1:6420"));
4854
- }
4855
- async function apiCall(config, method, path, body) {
4856
- const endpoint = getEndpoint(config);
4857
- const url = _chunk7QKCGUTJcjs.combineUrlPath.call(void 0, endpoint, path, {
4858
- namespace: config.namespace
4859
- });
4860
- logger2().debug({ msg: "making api call", method, url });
4861
- const headers = {
4862
- ...config.headers
4863
- };
4864
- if (config.token) {
4865
- headers.Authorization = `Bearer ${config.token}`;
4866
- }
4867
- return await sendHttpRequest({
4868
- method,
4869
- url,
4870
- headers,
4871
- body,
4872
- encoding: "json",
4873
- skipParseResponse: false,
4874
- requestVersionedDataHandler: void 0,
4875
- requestVersion: void 0,
4876
- responseVersionedDataHandler: void 0,
4877
- responseVersion: void 0,
4878
- requestZodSchema: _v4.z.any(),
4879
- responseZodSchema: _v4.z.any(),
4880
- // Identity conversions (passthrough for generic API calls)
4881
- requestToJson: (value) => value,
4882
- requestToBare: (value) => value,
4883
- responseFromJson: (value) => value,
4884
- responseFromBare: (value) => value
4885
- });
4886
- }
4887
-
4888
- // src/engine-client/api-endpoints.ts
4889
- async function getActor(config, _, actorId) {
4890
- return apiCall(
4891
- config,
4892
- "GET",
4893
- `/actors?actor_ids=${encodeURIComponent(actorId)}`
4894
- );
4895
- }
4896
- async function getActorByKey(config, name, key) {
4897
- const serializedKey = _chunkVE2X4KMGcjs.serializeActorKey.call(void 0, key);
4898
- return apiCall(
4899
- config,
4900
- "GET",
4901
- `/actors?name=${encodeURIComponent(name)}&key=${encodeURIComponent(serializedKey)}`
4902
- );
4903
- }
4904
- async function listActorsByName(config, name) {
4905
- return apiCall(
4906
- config,
4907
- "GET",
4908
- `/actors?name=${encodeURIComponent(name)}`
4909
- );
4910
- }
4911
- async function getOrCreateActor(config, request) {
4912
- return apiCall(
4913
- config,
4914
- "PUT",
4915
- `/actors`,
4916
- request
4917
- );
4918
- }
4919
- async function createActor(config, request) {
4920
- return apiCall(
4921
- config,
4922
- "POST",
4923
- `/actors`,
4924
- request
4925
- );
4926
- }
4927
- async function destroyActor(config, actorId) {
4928
- return apiCall(
4929
- config,
4930
- "DELETE",
4931
- `/actors/${encodeURIComponent(actorId)}`
4932
- );
4933
- }
4934
- async function getMetadata(config) {
4935
- return apiCall(config, "GET", `/metadata`);
4936
- }
4937
- async function getDatacenters(config) {
4938
- return apiCall(config, "GET", `/datacenters`);
4939
- }
4940
- async function updateRunnerConfig(config, runnerName, request) {
4941
- return apiCall(
4942
- config,
4943
- "PUT",
4944
- `/runner-configs/${runnerName}`,
4945
- request
4946
- );
4947
- }
4948
- async function kvGet(config, actorId, key) {
4949
- return apiCall(
4950
- config,
4951
- "GET",
4952
- `/actors/${encodeURIComponent(actorId)}/kv/keys/${encodeURIComponent(key)}`
4953
- );
4954
- }
4955
-
4956
5380
  // src/engine-client/mod.ts
4957
5381
 
4958
5382
 
@@ -4969,23 +5393,27 @@ async function sendHttpRequestToGateway(runConfig, gatewayUrl, actorRequest, opt
4969
5393
  if (actorRequest.bodyUsed) {
4970
5394
  throw new Error("Request body has already been consumed");
4971
5395
  }
4972
- const reqBody = await actorRequest.arrayBuffer();
4973
- if (reqBody.byteLength !== 0) {
4974
- bodyToSend = reqBody;
5396
+ const bytes = await readRequestBody(actorRequest);
5397
+ if (bytes.byteLength > 0) {
5398
+ bodyToSend = bytes;
4975
5399
  guardHeaders.delete("transfer-encoding");
4976
5400
  guardHeaders.delete("content-length");
4977
5401
  }
4978
5402
  }
4979
- const guardRequest = new Request(gatewayUrl, {
5403
+ const fetchImpl = _nullishCoalesce(runConfig.fetch, () => ( fetch));
5404
+ return fetchImpl(gatewayUrl, {
4980
5405
  method: actorRequest.method,
4981
5406
  headers: guardHeaders,
4982
5407
  body: bodyToSend,
4983
- signal: actorRequest.signal
5408
+ signal: actorRequest.signal,
5409
+ mode: actorRequest.mode,
5410
+ credentials: actorRequest.credentials,
5411
+ redirect: actorRequest.redirect,
5412
+ referrer: actorRequest.referrer,
5413
+ referrerPolicy: actorRequest.referrerPolicy,
5414
+ integrity: actorRequest.integrity,
5415
+ keepalive: actorRequest.keepalive
4984
5416
  });
4985
- return mutableResponse(await fetch(guardRequest));
4986
- }
4987
- function mutableResponse(fetchRes) {
4988
- return new Response(fetchRes.body, fetchRes);
4989
5417
  }
4990
5418
  function buildGuardHeaders(runConfig, actorRequest, options) {
4991
5419
  const headers = new Headers();
@@ -4995,6 +5423,17 @@ function buildGuardHeaders(runConfig, actorRequest, options) {
4995
5423
  for (const [key, value] of Object.entries(runConfig.headers)) {
4996
5424
  headers.set(key, value);
4997
5425
  }
5426
+ for (const name of [HEADER_TRACEPARENT, HEADER_TRACESTATE]) {
5427
+ headers.delete(name);
5428
+ const value = actorRequest.headers.get(name);
5429
+ if (value !== null) {
5430
+ headers.set(name, value);
5431
+ }
5432
+ }
5433
+ const requestRayId = actorRequest.headers.get(HEADER_RIVET_RAY_ID);
5434
+ if (requestRayId !== null) {
5435
+ headers.set(HEADER_RIVET_RAY_ID, requestRayId);
5436
+ }
4998
5437
  if (runConfig.token) {
4999
5438
  headers.set(HEADER_RIVET_TOKEN, runConfig.token);
5000
5439
  }
@@ -5049,6 +5488,11 @@ function setRemoteHibernatableWebSocketAckTestHooks(websocket, token, enabled) {
5049
5488
  );
5050
5489
  }
5051
5490
 
5491
+ // src/engine-client/log.ts
5492
+ function logger2() {
5493
+ return _chunk2MOLY6AMcjs.getLogger.call(void 0, "engine-client");
5494
+ }
5495
+
5052
5496
  // src/engine-client/actor-websocket-client.ts
5053
5497
  var BufferedRemoteWebSocket = (_class2 = class {
5054
5498
  __init2() {this.CONNECTING = 0}
@@ -5179,7 +5623,7 @@ var BufferedRemoteWebSocket = (_class2 = class {
5179
5623
  function buildActorGatewayUrl(endpoint, actorId, token, path = "") {
5180
5624
  const tokenSegment = token !== void 0 ? `@${encodeURIComponent(token)}` : "";
5181
5625
  const gatewayPath = `/gateway/${encodeURIComponent(actorId)}${tokenSegment}${path}`;
5182
- return _chunk7QKCGUTJcjs.combineUrlPath.call(void 0, endpoint, gatewayPath);
5626
+ return _chunk2MOLY6AMcjs.combineUrlPath.call(void 0, endpoint, gatewayPath);
5183
5627
  }
5184
5628
  function buildActorQueryGatewayUrl(endpoint, namespace, query, token, path = "", maxInputSize = DEFAULT_MAX_QUERY_INPUT_SIZE, crashPolicy = void 0, runnerName, options = {}) {
5185
5629
  if (namespace.length === 0) {
@@ -5245,18 +5689,19 @@ function buildActorQueryGatewayUrl(endpoint, namespace, query, token, path = "",
5245
5689
  separator = "?";
5246
5690
  }
5247
5691
  const gatewayPath = `/gateway/${encodeURIComponent(name)}${path}${separator}${queryString}`;
5248
- return _chunk7QKCGUTJcjs.combineUrlPath.call(void 0, endpoint, gatewayPath);
5692
+ return _chunk2MOLY6AMcjs.combineUrlPath.call(void 0, endpoint, gatewayPath);
5249
5693
  }
5250
5694
  function pushKeyQueryParams(params, key) {
5251
- if (key.length > 0) {
5252
- params.append("rvt-key", key.join(","));
5695
+ const rvtKey = _chunkRTWH3AX3cjs.actorKeyToGatewayQuery.call(void 0, key);
5696
+ if (rvtKey !== void 0) {
5697
+ params.append("rvt-key", rvtKey);
5253
5698
  }
5254
5699
  }
5255
5700
  function pushInputQueryParam(params, input, maxInputSize) {
5256
5701
  if (input === void 0) {
5257
5702
  return;
5258
5703
  }
5259
- const encodedInput = _chunkRV5MAFDTcjs.encodeCborCompat.call(void 0, input);
5704
+ const encodedInput = _chunk2MOLY6AMcjs.encodeCborCompat.call(void 0, input);
5260
5705
  if (encodedInput.byteLength > maxInputSize) {
5261
5706
  throw new Error(
5262
5707
  `Actor query input exceeds maxInputSize (${encodedInput.byteLength} > ${maxInputSize} bytes). Increase client maxInputSize to allow larger query payloads.`
@@ -5265,14 +5710,15 @@ function pushInputQueryParam(params, input, maxInputSize) {
5265
5710
  params.append("rvt-input", uint8ArrayToBase64Url(encodedInput));
5266
5711
  }
5267
5712
  function uint8ArrayToBase64Url(value) {
5268
- return _chunkRV5MAFDTcjs.uint8ArrayToBase64.call(void 0, value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
5713
+ return _chunk2MOLY6AMcjs.uint8ArrayToBase64.call(void 0, value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
5269
5714
  }
5270
5715
  async function openWebSocketToGateway(runConfig, gatewayUrl, encoding, params, options = {}) {
5271
- const WebSocket2 = await _chunkND567FR5cjs.importWebSocket.call(void 0, );
5716
+ const WebSocket2 = await _chunkJUHXV3HFcjs.importWebSocket.call(void 0, );
5272
5717
  const ackHookToken = typeof process !== "undefined" && process.env.VITEST ? crypto.randomUUID() : void 0;
5273
5718
  logger2().debug({
5274
5719
  msg: "opening websocket to actor via guard",
5275
- gatewayUrl
5720
+ // Gateway URLs can embed credentials; never include the path or query in logs.
5721
+ origin: new URL(gatewayUrl).origin
5276
5722
  });
5277
5723
  const ws = new WebSocket2(
5278
5724
  gatewayUrl,
@@ -5328,6 +5774,113 @@ function buildWebSocketProtocols(runConfig, encoding, params, ackHookToken, targ
5328
5774
  return protocols;
5329
5775
  }
5330
5776
 
5777
+ // src/engine-client/api-utils.ts
5778
+
5779
+ function getEndpoint(config) {
5780
+ return _nullishCoalesce(config.endpoint, () => ( "http://127.0.0.1:6420"));
5781
+ }
5782
+ async function apiCall(config, method, path, body) {
5783
+ const endpoint = getEndpoint(config);
5784
+ const url = _chunk2MOLY6AMcjs.combineUrlPath.call(void 0, endpoint, path, {
5785
+ namespace: config.namespace
5786
+ });
5787
+ logger2().debug({ msg: "making api call", method, url });
5788
+ const headers = {
5789
+ ...config.headers
5790
+ };
5791
+ if (config.token) {
5792
+ headers.Authorization = `Bearer ${config.token}`;
5793
+ }
5794
+ return await sendHttpRequest({
5795
+ method,
5796
+ url,
5797
+ headers,
5798
+ body,
5799
+ encoding: "json",
5800
+ skipParseResponse: false,
5801
+ requestVersionedDataHandler: void 0,
5802
+ requestVersion: void 0,
5803
+ responseVersionedDataHandler: void 0,
5804
+ responseVersion: void 0,
5805
+ requestZodSchema: _v4.z.any(),
5806
+ responseZodSchema: _v4.z.any(),
5807
+ // Identity conversions (passthrough for generic API calls)
5808
+ requestToJson: (value) => value,
5809
+ requestToBare: (value) => value,
5810
+ responseFromJson: (value) => value,
5811
+ responseFromBare: (value) => value
5812
+ });
5813
+ }
5814
+
5815
+ // src/engine-client/api-endpoints.ts
5816
+ async function issueToken(config, options) {
5817
+ return apiCall(config, "POST", "/auth/tokens", {
5818
+ namespace: config.namespace,
5819
+ subject: options.subject,
5820
+ duration: options.expiresIn,
5821
+ grants: options.grants
5822
+ });
5823
+ }
5824
+ async function getActor(config, _, actorId) {
5825
+ return apiCall(
5826
+ config,
5827
+ "GET",
5828
+ `/actors?actor_ids=${encodeURIComponent(actorId)}`
5829
+ );
5830
+ }
5831
+ async function getActorByKey(config, name, key) {
5832
+ const serializedKey = _chunkRTWH3AX3cjs.serializeActorKey.call(void 0, key);
5833
+ return apiCall(
5834
+ config,
5835
+ "GET",
5836
+ `/actors?name=${encodeURIComponent(name)}&key=${encodeURIComponent(serializedKey)}`
5837
+ );
5838
+ }
5839
+ async function listActorsByName(config, name) {
5840
+ return apiCall(
5841
+ config,
5842
+ "GET",
5843
+ `/actors?name=${encodeURIComponent(name)}`
5844
+ );
5845
+ }
5846
+ async function getOrCreateActor(config, request) {
5847
+ return apiCall(
5848
+ config,
5849
+ "PUT",
5850
+ `/actors`,
5851
+ request
5852
+ );
5853
+ }
5854
+ async function createActor(config, request) {
5855
+ return apiCall(
5856
+ config,
5857
+ "POST",
5858
+ `/actors`,
5859
+ request
5860
+ );
5861
+ }
5862
+ async function destroyActor(config, actorId) {
5863
+ return apiCall(
5864
+ config,
5865
+ "DELETE",
5866
+ `/actors/${encodeURIComponent(actorId)}`
5867
+ );
5868
+ }
5869
+ async function getMetadata(config) {
5870
+ return apiCall(config, "GET", `/metadata`);
5871
+ }
5872
+ async function getDatacenters(config) {
5873
+ return apiCall(config, "GET", `/datacenters`);
5874
+ }
5875
+ async function updateRunnerConfig(config, runnerName, request) {
5876
+ return apiCall(
5877
+ config,
5878
+ "PUT",
5879
+ `/pools/${encodeURIComponent(runnerName)}`,
5880
+ Object.values(request.datacenters)[0]
5881
+ );
5882
+ }
5883
+
5331
5884
  // src/engine-client/metadata.ts
5332
5885
 
5333
5886
  var metadataLookupCache = /* @__PURE__ */ new Map();
@@ -5361,7 +5914,7 @@ async function lookupMetadataCached(config) {
5361
5914
  msg: "failed to fetch metadata, retrying",
5362
5915
  endpoint,
5363
5916
  attempt: error.attemptNumber,
5364
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, error)
5917
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, error)
5365
5918
  });
5366
5919
  }
5367
5920
  }
@@ -5373,7 +5926,7 @@ async function lookupMetadataCached(config) {
5373
5926
 
5374
5927
  // src/engine-client/ws-proxy.ts
5375
5928
  async function createWebSocketProxy(_c, targetUrl, protocols) {
5376
- const WebSocket2 = await _chunkND567FR5cjs.importWebSocket.call(void 0, );
5929
+ const WebSocket2 = await _chunkJUHXV3HFcjs.importWebSocket.call(void 0, );
5377
5930
  const state = {};
5378
5931
  return {
5379
5932
  onOpen: async (_event, clientWs) => {
@@ -5438,7 +5991,7 @@ async function createWebSocketProxy(_c, targetUrl, protocols) {
5438
5991
  logger2().error({
5439
5992
  msg: "target websocket error",
5440
5993
  targetUrl,
5441
- error: _chunk7QKCGUTJcjs.stringifyError.call(void 0, error)
5994
+ error: _chunk2MOLY6AMcjs.stringifyError.call(void 0, error)
5442
5995
  });
5443
5996
  closeWebSocketIfOpen(clientWs, 1011, "Target WebSocket error");
5444
5997
  });
@@ -5516,14 +6069,18 @@ function closeWebSocketIfOpen(ws, code, reason) {
5516
6069
  var RemoteEngineControlClient = class {
5517
6070
  #config;
5518
6071
  #metadataPromise;
6072
+ #tokenProvider;
6073
+ #webSocketTokens = /* @__PURE__ */ new WeakMap();
5519
6074
  constructor(runConfig) {
5520
- if (_chunk7QKCGUTJcjs.getNextPhase.call(void 0, ) === "phase-production-build") {
6075
+ if (_chunk2MOLY6AMcjs.getNextPhase.call(void 0, ) === "phase-production-build") {
5521
6076
  logger2().info(
5522
6077
  "detected next.js build phase, disabling health check"
5523
6078
  );
5524
6079
  runConfig.disableMetadataLookup = true;
5525
6080
  }
5526
6081
  this.#config = { ...runConfig };
6082
+ if (runConfig.getToken)
6083
+ this.#tokenProvider = new TokenProvider(runConfig.getToken);
5527
6084
  if (!runConfig.disableMetadataLookup) {
5528
6085
  this.#metadataPromise = lookupMetadataCached(this.#config).then(
5529
6086
  (metadataData) => {
@@ -5532,14 +6089,13 @@ var RemoteEngineControlClient = class {
5532
6089
  if (metadataData.clientNamespace) {
5533
6090
  this.#config.namespace = metadataData.clientNamespace;
5534
6091
  }
5535
- if (metadataData.clientToken) {
6092
+ if (metadataData.clientToken && !this.#tokenProvider) {
5536
6093
  this.#config.token = metadataData.clientToken;
5537
6094
  }
5538
6095
  logger2().info({
5539
6096
  msg: "overriding client endpoint",
5540
6097
  endpoint: metadataData.clientEndpoint,
5541
- namespace: metadataData.clientNamespace,
5542
- token: metadataData.clientToken
6098
+ namespace: metadataData.clientNamespace
5543
6099
  });
5544
6100
  }
5545
6101
  logger2().info({
@@ -5552,12 +6108,47 @@ var RemoteEngineControlClient = class {
5552
6108
  );
5553
6109
  }
5554
6110
  }
6111
+ async #authorizedConfig() {
6112
+ if (!this.#tokenProvider) return this.#config;
6113
+ return { ...this.#config, token: await this.#tokenProvider.current() };
6114
+ }
6115
+ async #withCredential(request, readOnly = false) {
6116
+ const config = await this.#authorizedConfig();
6117
+ try {
6118
+ return await request(config);
6119
+ } catch (error) {
6120
+ if (this.#tokenProvider && config.token && error instanceof _chunkMGI2VVF6cjs.RivetError && error.statusCode === 401 && isInvalidToken(error.group, error.code)) {
6121
+ if (readOnly) {
6122
+ const token = await this.#tokenProvider.refreshIfCurrent(
6123
+ config.token
6124
+ );
6125
+ return request({ ...this.#config, token });
6126
+ }
6127
+ await this.#tokenProvider.refreshIfCurrent(config.token);
6128
+ }
6129
+ throw error;
6130
+ }
6131
+ }
6132
+ async issueToken(options) {
6133
+ await this.#metadataPromise;
6134
+ const response = await this.#withCredential(
6135
+ (config) => issueToken(config, options)
6136
+ );
6137
+ return {
6138
+ token: response.token,
6139
+ issuedAt: response.issued_ts,
6140
+ expiresAt: response.expires_ts
6141
+ };
6142
+ }
5555
6143
  async getForId({
5556
6144
  name,
5557
6145
  actorId
5558
6146
  }) {
5559
6147
  await this.#metadataPromise;
5560
- const response = await getActor(this.#config, name, actorId);
6148
+ const response = await this.#withCredential(
6149
+ (config) => getActor(config, name, actorId),
6150
+ true
6151
+ );
5561
6152
  const actor = response.actors[0];
5562
6153
  if (!actor) return void 0;
5563
6154
  if (actor.name !== name) {
@@ -5578,7 +6169,10 @@ var RemoteEngineControlClient = class {
5578
6169
  await this.#metadataPromise;
5579
6170
  logger2().debug({ msg: "getWithKey: searching for actor", name, key });
5580
6171
  try {
5581
- const response = await getActorByKey(this.#config, name, key);
6172
+ const response = await this.#withCredential(
6173
+ (config) => getActorByKey(config, name, key),
6174
+ true
6175
+ );
5582
6176
  const actor = response.actors[0];
5583
6177
  if (!actor) return void 0;
5584
6178
  logger2().debug({
@@ -5589,7 +6183,7 @@ var RemoteEngineControlClient = class {
5589
6183
  });
5590
6184
  return apiActorToOutput(actor);
5591
6185
  } catch (error) {
5592
- if (error instanceof _chunk4FC7TVS6cjs.RivetError && error.group === "actor" && error.code === "not_found") {
6186
+ if (error instanceof _chunkMGI2VVF6cjs.RivetError && error.group === "actor" && error.code === "not_found") {
5593
6187
  return void 0;
5594
6188
  }
5595
6189
  throw error;
@@ -5597,48 +6191,86 @@ var RemoteEngineControlClient = class {
5597
6191
  }
5598
6192
  async getOrCreateWithKey(input) {
5599
6193
  await this.#metadataPromise;
5600
- const { name, key, input: actorInput, region, crashPolicy } = input;
6194
+ const {
6195
+ name,
6196
+ key,
6197
+ input: actorInput,
6198
+ region,
6199
+ crashPolicy,
6200
+ poolName
6201
+ } = input;
5601
6202
  logger2().info({
5602
6203
  msg: "getOrCreateWithKey: getting or creating actor via engine api",
5603
6204
  name,
5604
6205
  key
5605
6206
  });
5606
- const { actor, created } = await getOrCreateActor(this.#config, {
5607
- datacenter: region,
5608
- name,
5609
- key: _chunkVE2X4KMGcjs.serializeActorKey.call(void 0, key),
5610
- runner_name_selector: this.#config.poolName,
5611
- input: actorInput ? _chunkRV5MAFDTcjs.uint8ArrayToBase64.call(void 0,
5612
- _chunkRV5MAFDTcjs.encodeCborCompat.call(void 0, actorInput)
5613
- ) : void 0,
5614
- crash_policy: _nullishCoalesce(crashPolicy, () => ( "sleep"))
5615
- });
5616
- logger2().info({
5617
- msg: "getOrCreateWithKey: actor ready",
5618
- actorId: actor.actor_id,
5619
- name,
5620
- key,
5621
- created
5622
- });
5623
- return apiActorToOutput(actor);
6207
+ try {
6208
+ const { actor, created } = await this.#withCredential(
6209
+ (config) => getOrCreateActor(config, {
6210
+ datacenter: region,
6211
+ name,
6212
+ key: _chunkRTWH3AX3cjs.serializeActorKey.call(void 0, key),
6213
+ pool: _nullishCoalesce(poolName, () => ( this.#config.poolName)),
6214
+ input: actorInput ? _chunk2MOLY6AMcjs.uint8ArrayToBase64.call(void 0,
6215
+ _chunk2MOLY6AMcjs.encodeCborCompat.call(void 0, actorInput)
6216
+ ) : void 0,
6217
+ crash_policy: _nullishCoalesce(crashPolicy, () => ( "sleep"))
6218
+ })
6219
+ );
6220
+ logger2().info({
6221
+ msg: "getOrCreateWithKey: actor ready",
6222
+ actorId: actor.actor_id,
6223
+ name,
6224
+ key,
6225
+ created
6226
+ });
6227
+ return apiActorToOutput(actor);
6228
+ } catch (error) {
6229
+ if (error instanceof _chunkMGI2VVF6cjs.RivetError && error.group === "actor" && error.code === "key_reserved_in_different_datacenter") {
6230
+ logger2().warn({
6231
+ msg: "getOrCreateWithKey: key reserved in different datacenter, retrying as get",
6232
+ name,
6233
+ key
6234
+ });
6235
+ const response = await this.#withCredential(
6236
+ (config) => getActorByKey(config, name, key),
6237
+ true
6238
+ );
6239
+ const existing = response.actors[0];
6240
+ if (!existing) throw error;
6241
+ logger2().info({
6242
+ msg: "getOrCreateWithKey: resolved existing actor via get",
6243
+ actorId: existing.actor_id,
6244
+ name,
6245
+ key
6246
+ });
6247
+ return apiActorToOutput(existing);
6248
+ }
6249
+ throw error;
6250
+ }
5624
6251
  }
5625
6252
  async createActor({
5626
6253
  name,
5627
6254
  key,
5628
6255
  input,
5629
6256
  region,
5630
- crashPolicy
6257
+ crashPolicy,
6258
+ poolName
5631
6259
  }) {
5632
6260
  await this.#metadataPromise;
5633
6261
  logger2().info({ msg: "creating actor via engine api", name, key });
5634
- const result = await createActor(this.#config, {
5635
- datacenter: region,
5636
- name,
5637
- runner_name_selector: this.#config.poolName,
5638
- key: _chunkVE2X4KMGcjs.serializeActorKey.call(void 0, key),
5639
- input: input ? _chunkRV5MAFDTcjs.uint8ArrayToBase64.call(void 0, _chunkRV5MAFDTcjs.encodeCborCompat.call(void 0, input)) : void 0,
5640
- crash_policy: _nullishCoalesce(crashPolicy, () => ( "sleep"))
5641
- });
6262
+ const result = await this.#withCredential(
6263
+ (config) => createActor(config, {
6264
+ datacenter: region,
6265
+ name,
6266
+ pool: _nullishCoalesce(poolName, () => ( this.#config.poolName)),
6267
+ key: _chunkRTWH3AX3cjs.serializeActorKey.call(void 0, key),
6268
+ input: input ? _chunk2MOLY6AMcjs.uint8ArrayToBase64.call(void 0,
6269
+ _chunk2MOLY6AMcjs.encodeCborCompat.call(void 0, input)
6270
+ ) : void 0,
6271
+ crash_policy: _nullishCoalesce(crashPolicy, () => ( "sleep"))
6272
+ })
6273
+ );
5642
6274
  logger2().info({
5643
6275
  msg: "actor created",
5644
6276
  actorId: result.actor.actor_id,
@@ -5650,43 +6282,61 @@ var RemoteEngineControlClient = class {
5650
6282
  async listActors({ name }) {
5651
6283
  await this.#metadataPromise;
5652
6284
  logger2().debug({ msg: "listing actors via engine api", name });
5653
- const response = await listActorsByName(this.#config, name);
6285
+ const response = await this.#withCredential(
6286
+ (config) => listActorsByName(config, name),
6287
+ true
6288
+ );
5654
6289
  return response.actors.map(apiActorToOutput);
5655
6290
  }
5656
6291
  async destroyActor(actorId) {
5657
6292
  await this.#metadataPromise;
5658
6293
  logger2().info({ msg: "destroying actor via engine api", actorId });
5659
- await destroyActor(this.#config, actorId);
6294
+ await this.#withCredential((config) => destroyActor(config, actorId));
5660
6295
  logger2().info({ msg: "actor destroyed", actorId });
5661
6296
  }
5662
6297
  async sendRequest(target, actorRequest, options = {}) {
6298
+ var _a;
5663
6299
  await this.#metadataPromise;
5664
- const path = requestPath(actorRequest);
5665
- const gatewayUrl = this.#buildGatewayUrlForTarget(
5666
- target,
5667
- path,
5668
- options
5669
- );
6300
+ const config = await this.#authorizedConfig();
5670
6301
  const httpOptions = {
5671
6302
  ...options,
5672
6303
  directActorId: shouldSkipReadyWait(options) ? directActorIdFromTarget(target) : void 0
5673
6304
  };
5674
- return sendHttpRequestToGateway(
5675
- this.#config,
5676
- gatewayUrl,
6305
+ const send = (current) => sendHttpRequestToGateway(
6306
+ current,
6307
+ this.#buildGatewayUrlForTarget(
6308
+ current,
6309
+ target,
6310
+ requestPath(actorRequest),
6311
+ options
6312
+ ),
5677
6313
  actorRequest,
5678
6314
  httpOptions
5679
6315
  );
6316
+ const response = await send(config);
6317
+ if (!this.#tokenProvider || !config.token || !isInvalidTokenResponse(response))
6318
+ return response;
6319
+ if ((actorRequest.method === "GET" || actorRequest.method === "HEAD") && !("getOrCreateForKey" in target)) {
6320
+ const token = await this.#tokenProvider.refreshIfCurrent(
6321
+ config.token
6322
+ );
6323
+ await ((_a = response.body) == null ? void 0 : _a.cancel());
6324
+ return send({ ...this.#config, token });
6325
+ }
6326
+ await this.#tokenProvider.refreshIfCurrent(config.token);
6327
+ return response;
5680
6328
  }
5681
6329
  async openWebSocket(path, target, encoding, params, options = {}) {
5682
6330
  await this.#metadataPromise;
6331
+ const config = await this.#authorizedConfig();
5683
6332
  const gatewayUrl = this.#buildGatewayUrlForTarget(
6333
+ config,
5684
6334
  target,
5685
6335
  path,
5686
6336
  options
5687
6337
  );
5688
- return openWebSocketToGateway(
5689
- this.#config,
6338
+ const ws = await openWebSocketToGateway(
6339
+ config,
5690
6340
  gatewayUrl,
5691
6341
  encoding,
5692
6342
  params,
@@ -5695,26 +6345,60 @@ var RemoteEngineControlClient = class {
5695
6345
  directActorId: shouldSkipReadyWait(options) ? directActorIdFromTarget(target) : void 0
5696
6346
  }
5697
6347
  );
6348
+ this.#watchWebSocketAuth(ws, config.token);
6349
+ return ws;
6350
+ }
6351
+ async refreshAuthToken(ws) {
6352
+ const context2 = this.#webSocketTokens.get(ws);
6353
+ if (!(context2 == null ? void 0 : context2.refresh)) return false;
6354
+ await context2.refresh;
6355
+ return true;
6356
+ }
6357
+ #watchWebSocketAuth(ws, token) {
6358
+ const tokenProvider = this.#tokenProvider;
6359
+ if (!tokenProvider || !token) return;
6360
+ const context2 = {};
6361
+ this.#webSocketTokens.set(ws, context2);
6362
+ ws.addEventListener(
6363
+ "close",
6364
+ (event) => {
6365
+ if (event.code !== 1008 || !event.reason) return;
6366
+ const separator = event.reason.indexOf(".");
6367
+ if (separator < 0) return;
6368
+ const code = event.reason.slice(separator + 1).split(/[\s:#]/, 1)[0];
6369
+ if (isInvalidToken(event.reason.slice(0, separator), code)) {
6370
+ context2.refresh = tokenProvider.refreshIfCurrent(token).catch((error) => {
6371
+ logger2().warn(
6372
+ "failed to renew authentication token"
6373
+ );
6374
+ throw error;
6375
+ });
6376
+ context2.refresh.catch(() => {
6377
+ });
6378
+ }
6379
+ }
6380
+ );
5698
6381
  }
5699
6382
  async buildGatewayUrl(target, options = {}) {
5700
6383
  await this.#metadataPromise;
5701
- return this.#buildGatewayUrlForTarget(target, "", options);
6384
+ return this.#buildGatewayUrlForTarget(
6385
+ await this.#authorizedConfig(),
6386
+ target,
6387
+ "",
6388
+ options
6389
+ );
5702
6390
  }
5703
6391
  async proxyRequest(_c, actorRequest, actorId) {
5704
- await this.#metadataPromise;
5705
- const gatewayUrl = this.#buildGatewayUrlForTarget(
5706
- { directId: actorId },
5707
- requestPath(actorRequest)
5708
- );
5709
- return sendHttpRequestToGateway(this.#config, gatewayUrl, actorRequest);
6392
+ return this.sendRequest({ directId: actorId }, actorRequest);
5710
6393
  }
5711
6394
  async proxyWebSocket(c, path, actorId, encoding, params) {
5712
- var _a, _b;
6395
+ var _a;
5713
6396
  await this.#metadataPromise;
5714
- const upgradeWebSocket = (_b = (_a = this.#config).getUpgradeWebSocket) == null ? void 0 : _b.call(_a);
6397
+ const config = await this.#authorizedConfig();
6398
+ const upgradeWebSocket = (_a = config.getUpgradeWebSocket) == null ? void 0 : _a.call(config);
5715
6399
  _invariant2.default.call(void 0, upgradeWebSocket, "missing getUpgradeWebSocket");
5716
- const endpoint = getEndpoint(this.#config);
5717
- const guardUrl = _chunk7QKCGUTJcjs.combineUrlPath.call(void 0, endpoint, path);
6400
+ const endpoint = getEndpoint(config);
6401
+ const guardUrl = _chunk2MOLY6AMcjs.combineUrlPath.call(void 0, endpoint, path);
5718
6402
  const wsGuardUrl = guardUrl.replace("http://", "ws://");
5719
6403
  logger2().debug({
5720
6404
  msg: "forwarding websocket to actor via guard",
@@ -5723,7 +6407,7 @@ var RemoteEngineControlClient = class {
5723
6407
  guardUrl
5724
6408
  });
5725
6409
  const protocols = buildWebSocketProtocols(
5726
- this.#config,
6410
+ config,
5727
6411
  encoding,
5728
6412
  params,
5729
6413
  void 0,
@@ -5733,29 +6417,7 @@ var RemoteEngineControlClient = class {
5733
6417
  }
5734
6418
  );
5735
6419
  const args = await createWebSocketProxy(c, wsGuardUrl, protocols);
5736
- return await upgradeWebSocket(() => args)(c, _chunk7QKCGUTJcjs.noopNext.call(void 0, ));
5737
- }
5738
- async kvGet(actorId, key) {
5739
- await this.#metadataPromise;
5740
- logger2().debug({ msg: "getting kv value via engine api", key });
5741
- const response = await kvGet(
5742
- this.#config,
5743
- actorId,
5744
- new TextDecoder("utf8").decode(key)
5745
- );
5746
- return response.value;
5747
- }
5748
- async kvBatchGet(_actorId, _keys) {
5749
- throw new Error("kvBatchGet not supported on remote engine client");
5750
- }
5751
- async kvBatchPut(_actorId, _entries) {
5752
- throw new Error("kvBatchPut not supported on remote engine client");
5753
- }
5754
- async kvBatchDelete(_actorId, _keys) {
5755
- throw new Error("kvBatchDelete not supported on remote engine client");
5756
- }
5757
- async kvDeleteRange(_actorId, _start, _end) {
5758
- throw new Error("kvDeleteRange not supported on remote engine client");
6420
+ return await upgradeWebSocket(() => args)(c, _chunk2MOLY6AMcjs.noopNext.call(void 0, ));
5759
6421
  }
5760
6422
  displayInformation() {
5761
6423
  return { properties: {} };
@@ -5763,16 +6425,16 @@ var RemoteEngineControlClient = class {
5763
6425
  setGetUpgradeWebSocket(getUpgradeWebSocket) {
5764
6426
  this.#config.getUpgradeWebSocket = getUpgradeWebSocket;
5765
6427
  }
5766
- #buildGatewayUrlForTarget(target, path, options = {}) {
5767
- const endpoint = getEndpoint(this.#config);
6428
+ #buildGatewayUrlForTarget(config, target, path, options = {}) {
6429
+ const endpoint = getEndpoint(config);
5768
6430
  if (shouldSkipReadyWait(options) && directActorIdFromTarget(target) && canUseDirectSkipReadyWaitPath(path)) {
5769
- return _chunk7QKCGUTJcjs.combineUrlPath.call(void 0, endpoint, path);
6431
+ return _chunk2MOLY6AMcjs.combineUrlPath.call(void 0, endpoint, path);
5770
6432
  }
5771
6433
  if ("directId" in target) {
5772
6434
  return buildActorGatewayUrl(
5773
6435
  endpoint,
5774
6436
  target.directId,
5775
- this.#config.token,
6437
+ config.token,
5776
6438
  path
5777
6439
  );
5778
6440
  }
@@ -5780,20 +6442,20 @@ var RemoteEngineControlClient = class {
5780
6442
  return buildActorGatewayUrl(
5781
6443
  endpoint,
5782
6444
  target.getForId.actorId,
5783
- this.#config.token,
6445
+ config.token,
5784
6446
  path
5785
6447
  );
5786
6448
  }
5787
6449
  if ("getForKey" in target || "getOrCreateForKey" in target) {
5788
6450
  return buildActorQueryGatewayUrl(
5789
6451
  endpoint,
5790
- this.#config.namespace,
6452
+ config.namespace,
5791
6453
  target,
5792
- this.#config.token,
6454
+ config.token,
5793
6455
  path,
5794
- this.#config.maxInputSize,
6456
+ config.maxInputSize,
5795
6457
  void 0,
5796
- "getOrCreateForKey" in target ? this.#config.poolName : void 0,
6458
+ "getOrCreateForKey" in target ? _nullishCoalesce(target.getOrCreateForKey.poolName, () => ( config.poolName)) : void 0,
5797
6459
  options
5798
6460
  );
5799
6461
  }
@@ -5832,7 +6494,7 @@ function apiActorToOutput(actor) {
5832
6494
  return {
5833
6495
  actorId: actor.actor_id,
5834
6496
  name: actor.name,
5835
- key: _chunkVE2X4KMGcjs.deserializeActorKey.call(void 0, actor.key),
6497
+ key: _chunkRTWH3AX3cjs.deserializeActorKey.call(void 0, actor.key),
5836
6498
  createTs: actor.create_ts,
5837
6499
  startTs: _nullishCoalesce(actor.start_ts, () => ( null)),
5838
6500
  connectableTs: _nullishCoalesce(actor.connectable_ts, () => ( null)),
@@ -5859,5 +6521,12 @@ function apiActorToOutput(actor) {
5859
6521
 
5860
6522
 
5861
6523
 
5862
- exports.HEADER_CONN_PARAMS = HEADER_CONN_PARAMS; exports.ALLOWED_PUBLIC_HEADERS = ALLOWED_PUBLIC_HEADERS; exports.ActorClientError = ActorClientError; exports.ManagerError = ManagerError; exports.MalformedResponseMessage = MalformedResponseMessage; exports.ActorConnDisposed = ActorConnDisposed; exports.ActorConnRaw = ActorConnRaw; exports.ActorHandleRaw = ActorHandleRaw; exports.createClientWithDriver = createClientWithDriver; exports.tryParseEndpoint = tryParseEndpoint; exports.ClientConfigSchema = ClientConfigSchema; exports.convertRegistryConfigToClientConfig = convertRegistryConfigToClientConfig; exports.getMetadata = getMetadata; exports.getDatacenters = getDatacenters; exports.updateRunnerConfig = updateRunnerConfig; exports.RemoteEngineControlClient = RemoteEngineControlClient;
5863
- //# sourceMappingURL=chunk-NHUTYWKU.cjs.map
6524
+
6525
+
6526
+
6527
+
6528
+
6529
+
6530
+
6531
+ exports.HEADER_CONN_PARAMS = HEADER_CONN_PARAMS; exports.HEADER_ORIGINAL_REQUEST_URL = HEADER_ORIGINAL_REQUEST_URL; exports.ALLOWED_PUBLIC_HEADERS = ALLOWED_PUBLIC_HEADERS; exports.ActorClientError = ActorClientError; exports.ManagerError = ManagerError; exports.MalformedResponseMessage = MalformedResponseMessage; exports.ActorConnDisposed = ActorConnDisposed; exports.readActiveTraceHeaders = readActiveTraceHeaders; exports.runWithActorInvocationSpan = runWithActorInvocationSpan; exports.ActorConnRaw = ActorConnRaw; exports.isResponseLike = isResponseLike; exports.ActorHandleRaw = ActorHandleRaw; exports.createClientWithDriver = createClientWithDriver; exports.ENGINE_HOST = ENGINE_HOST; exports.ENGINE_PORT = ENGINE_PORT; exports.buildEngineEndpoint = buildEngineEndpoint; exports.isLocalEngineEndpoint = isLocalEngineEndpoint; exports.tryParseEndpoint = tryParseEndpoint; exports.ClientConfigSchema = ClientConfigSchema; exports.convertRegistryConfigToClientConfig = convertRegistryConfigToClientConfig; exports.getDatacenters = getDatacenters; exports.updateRunnerConfig = updateRunnerConfig; exports.RemoteEngineControlClient = RemoteEngineControlClient;
6532
+ //# sourceMappingURL=chunk-OTVJYZ2L.cjs.map