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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. package/dist/browser/client.d.ts +939 -104
  2. package/dist/browser/client.js +1867 -900
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +252 -129
  5. package/dist/browser/inspector/client.js +2079 -233
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/actor/errors.cjs +6 -2
  8. package/dist/tsup/actor/errors.cjs.map +1 -1
  9. package/dist/tsup/actor/errors.d.cts +1 -74
  10. package/dist/tsup/actor/errors.d.ts +1 -74
  11. package/dist/tsup/actor/errors.js +5 -1
  12. package/dist/tsup/agent-os/index.cjs +2408 -2029
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +932 -114
  15. package/dist/tsup/agent-os/index.d.ts +932 -114
  16. package/dist/tsup/agent-os/index.js +2412 -2033
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-J27CEW6F.js → chunk-2OBVQZX6.js} +6 -6
  19. package/dist/tsup/chunk-2OBVQZX6.js.map +1 -0
  20. package/dist/tsup/chunk-3ZWHWMFJ.js +14 -0
  21. package/dist/tsup/chunk-3ZWHWMFJ.js.map +1 -0
  22. package/dist/tsup/{chunk-AK57AL7S.cjs → chunk-4KGXFC6M.cjs} +238 -22
  23. package/dist/tsup/chunk-4KGXFC6M.cjs.map +1 -0
  24. package/dist/tsup/{chunk-CVHUXINE.js → chunk-5IU3MI7X.js} +594 -72
  25. package/dist/tsup/chunk-5IU3MI7X.js.map +1 -0
  26. package/dist/tsup/{chunk-VD7AZIBR.js → chunk-6CXQMHZR.js} +1161 -361
  27. package/dist/tsup/chunk-6CXQMHZR.js.map +1 -0
  28. package/dist/tsup/{chunk-SBEFJ4IQ.js → chunk-6W2UIH3X.js} +70 -8
  29. package/dist/tsup/chunk-6W2UIH3X.js.map +1 -0
  30. package/dist/tsup/{chunk-7MRGNVSR.js → chunk-6W5VGLFT.js} +237 -21
  31. package/dist/tsup/chunk-6W5VGLFT.js.map +1 -0
  32. package/dist/tsup/{chunk-RF3MEJV6.cjs → chunk-B73TBMMG.cjs} +18 -11
  33. package/dist/tsup/chunk-B73TBMMG.cjs.map +1 -0
  34. package/dist/tsup/chunk-D6TORRA4.js +243 -0
  35. package/dist/tsup/chunk-D6TORRA4.js.map +1 -0
  36. package/dist/tsup/{chunk-PXLJOMJD.js → chunk-FXT3HN32.js} +2 -2
  37. package/dist/tsup/{chunk-ZGWSH7YV.js → chunk-IXBD7BXC.js} +48 -72
  38. package/dist/tsup/chunk-IXBD7BXC.js.map +1 -0
  39. package/dist/tsup/{chunk-3BFYSYRU.js → chunk-JI6GZ2C2.js} +4 -12
  40. package/dist/tsup/chunk-JI6GZ2C2.js.map +1 -0
  41. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-JTHHCZCZ.js} +24 -1
  42. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  43. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-KVFIONKQ.cjs} +25 -2
  44. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  45. package/dist/tsup/{chunk-SPMMF6TR.cjs → chunk-LGOWPZJ5.cjs} +3 -3
  46. package/dist/tsup/chunk-LGOWPZJ5.cjs.map +1 -0
  47. package/dist/tsup/chunk-LYNWTX6R.cjs +14 -0
  48. package/dist/tsup/chunk-LYNWTX6R.cjs.map +1 -0
  49. package/dist/tsup/{chunk-LLD2D5LO.cjs → chunk-MYWZCDML.cjs} +4 -12
  50. package/dist/tsup/chunk-MYWZCDML.cjs.map +1 -0
  51. package/dist/tsup/{chunk-XSC2WWXD.js → chunk-NYDZLWHZ.js} +16 -9
  52. package/dist/tsup/chunk-NYDZLWHZ.js.map +1 -0
  53. package/dist/tsup/{chunk-AV54CVAG.cjs → chunk-RB7WUDX6.cjs} +1290 -490
  54. package/dist/tsup/chunk-RB7WUDX6.cjs.map +1 -0
  55. package/dist/tsup/{chunk-JTL6Y2UN.cjs → chunk-SPJORZMM.cjs} +49 -73
  56. package/dist/tsup/chunk-SPJORZMM.cjs.map +1 -0
  57. package/dist/tsup/chunk-SSMKIYEX.cjs +243 -0
  58. package/dist/tsup/chunk-SSMKIYEX.cjs.map +1 -0
  59. package/dist/tsup/{chunk-TQSL4NJ3.cjs → chunk-TQ4HSX2U.cjs} +72 -10
  60. package/dist/tsup/chunk-TQ4HSX2U.cjs.map +1 -0
  61. package/dist/tsup/{chunk-EVADNK6Z.cjs → chunk-U6ZQELGJ.cjs} +10 -10
  62. package/dist/tsup/chunk-U6ZQELGJ.cjs.map +1 -0
  63. package/dist/tsup/chunk-XLBMKZD3.cjs +1257 -0
  64. package/dist/tsup/chunk-XLBMKZD3.cjs.map +1 -0
  65. package/dist/tsup/client/mod.cjs +8 -9
  66. package/dist/tsup/client/mod.cjs.map +1 -1
  67. package/dist/tsup/client/mod.d.cts +18 -7
  68. package/dist/tsup/client/mod.d.ts +18 -7
  69. package/dist/tsup/client/mod.js +7 -8
  70. package/dist/tsup/common/log.cjs +5 -3
  71. package/dist/tsup/common/log.cjs.map +1 -1
  72. package/dist/tsup/common/log.d.cts +5 -1
  73. package/dist/tsup/common/log.d.ts +5 -1
  74. package/dist/tsup/common/log.js +6 -4
  75. package/dist/tsup/common/websocket.cjs +4 -4
  76. package/dist/tsup/common/websocket.cjs.map +1 -1
  77. package/dist/tsup/common/websocket.js +3 -3
  78. package/dist/tsup/{config-B3RIidaJ.d.ts → config-BXSV17G7.d.cts} +987 -72
  79. package/dist/tsup/{config-D6WxBYjV.d.cts → config-Bi1r6gI7.d.ts} +987 -72
  80. package/dist/tsup/{config-B9qUIHX4.d.ts → config-ey2I2zz5.d.cts} +82 -15
  81. package/dist/tsup/{config-B9qUIHX4.d.cts → config-ey2I2zz5.d.ts} +82 -15
  82. package/dist/tsup/context-4fJemY0D.d.cts +129 -0
  83. package/dist/tsup/context-D4sNYboo.d.ts +129 -0
  84. package/dist/tsup/db/drizzle.cjs +168 -103
  85. package/dist/tsup/db/drizzle.cjs.map +1 -1
  86. package/dist/tsup/db/drizzle.d.cts +8 -4
  87. package/dist/tsup/db/drizzle.d.ts +8 -4
  88. package/dist/tsup/db/drizzle.js +170 -105
  89. package/dist/tsup/db/drizzle.js.map +1 -1
  90. package/dist/tsup/db/mod.cjs +6 -163
  91. package/dist/tsup/db/mod.cjs.map +1 -1
  92. package/dist/tsup/db/mod.d.cts +12 -4
  93. package/dist/tsup/db/mod.d.ts +12 -4
  94. package/dist/tsup/db/mod.js +5 -162
  95. package/dist/tsup/db/mod.js.map +1 -1
  96. package/dist/tsup/dynamic/mod.cjs +24 -0
  97. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  98. package/dist/tsup/dynamic/mod.d.cts +38 -0
  99. package/dist/tsup/dynamic/mod.d.ts +38 -0
  100. package/dist/tsup/dynamic/mod.js +24 -0
  101. package/dist/tsup/dynamic/mod.js.map +1 -0
  102. package/dist/tsup/inspector/mod.cjs +47 -12
  103. package/dist/tsup/inspector/mod.cjs.map +1 -1
  104. package/dist/tsup/inspector/mod.d.cts +26 -136
  105. package/dist/tsup/inspector/mod.d.ts +26 -136
  106. package/dist/tsup/inspector/mod.js +46 -11
  107. package/dist/tsup/inspector/mod.js.map +1 -1
  108. package/dist/tsup/inspector/workflow.cjs +21 -0
  109. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  110. package/dist/tsup/inspector/workflow.d.cts +144 -0
  111. package/dist/tsup/inspector/workflow.d.ts +144 -0
  112. package/dist/tsup/inspector/workflow.js +21 -0
  113. package/dist/tsup/inspector/workflow.js.map +1 -0
  114. package/dist/tsup/inspector-tab/mod.cjs +162 -0
  115. package/dist/tsup/inspector-tab/mod.cjs.map +1 -0
  116. package/dist/tsup/inspector-tab/mod.d.cts +241 -0
  117. package/dist/tsup/inspector-tab/mod.d.ts +241 -0
  118. package/dist/tsup/inspector-tab/mod.js +162 -0
  119. package/dist/tsup/inspector-tab/mod.js.map +1 -0
  120. package/dist/tsup/mod.cjs +4268 -944
  121. package/dist/tsup/mod.cjs.map +1 -1
  122. package/dist/tsup/mod.d.cts +9 -8
  123. package/dist/tsup/mod.d.ts +9 -8
  124. package/dist/tsup/mod.js +4229 -905
  125. package/dist/tsup/mod.js.map +1 -1
  126. package/dist/tsup/test/mod.cjs +26 -21
  127. package/dist/tsup/test/mod.cjs.map +1 -1
  128. package/dist/tsup/test/mod.d.cts +7 -6
  129. package/dist/tsup/test/mod.d.ts +7 -6
  130. package/dist/tsup/test/mod.js +25 -20
  131. package/dist/tsup/test/mod.js.map +1 -1
  132. package/dist/tsup/unstable/migrations.cjs +101 -0
  133. package/dist/tsup/unstable/migrations.cjs.map +1 -0
  134. package/dist/tsup/unstable/migrations.d.cts +29 -0
  135. package/dist/tsup/unstable/migrations.d.ts +29 -0
  136. package/dist/tsup/unstable/migrations.js +101 -0
  137. package/dist/tsup/unstable/migrations.js.map +1 -0
  138. package/dist/tsup/utils-Bbz-3411.d.cts +162 -0
  139. package/dist/tsup/utils-BqdWVlzm.d.ts +162 -0
  140. package/dist/tsup/utils-vvJQyygr.d.cts +109 -0
  141. package/dist/tsup/utils-vvJQyygr.d.ts +109 -0
  142. package/dist/tsup/utils.cjs +7 -3
  143. package/dist/tsup/utils.cjs.map +1 -1
  144. package/dist/tsup/utils.d.cts +4 -147
  145. package/dist/tsup/utils.d.ts +4 -147
  146. package/dist/tsup/utils.js +6 -2
  147. package/dist/tsup/workflow/mod.cjs +517 -412
  148. package/dist/tsup/workflow/mod.cjs.map +1 -1
  149. package/dist/tsup/workflow/mod.d.cts +11 -10
  150. package/dist/tsup/workflow/mod.d.ts +11 -10
  151. package/dist/tsup/workflow/mod.js +511 -406
  152. package/dist/tsup/workflow/mod.js.map +1 -1
  153. package/package.json +62 -14
  154. package/src/actor/actions.ts +119 -0
  155. package/src/actor/config.test.ts +78 -0
  156. package/src/actor/config.ts +518 -96
  157. package/src/actor/contexts/index.ts +7 -2
  158. package/src/actor/definition.ts +38 -26
  159. package/src/actor/errors.ts +101 -89
  160. package/src/actor/keys.ts +2 -1
  161. package/src/actor/mod.ts +32 -21
  162. package/src/actor/schema.ts +2 -2
  163. package/src/agent-os/actor/cron.ts +37 -2
  164. package/src/agent-os/actor/index.ts +39 -19
  165. package/src/agent-os/actor/preview.ts +1 -2
  166. package/src/agent-os/actor/session.ts +2 -2
  167. package/src/agent-os/config.ts +1 -1
  168. package/src/agent-os/fs/database-vfs.ts +1 -1
  169. package/src/agent-os/index.ts +16 -15
  170. package/src/agent-os/types.ts +11 -0
  171. package/src/client/actor-common.ts +106 -53
  172. package/src/client/actor-conn.ts +94 -45
  173. package/src/client/actor-handle.ts +198 -79
  174. package/src/client/actor-query.ts +13 -6
  175. package/src/client/client.ts +43 -15
  176. package/src/client/config.ts +8 -0
  177. package/src/client/errors.ts +4 -2
  178. package/src/client/lifecycle-errors.ts +28 -4
  179. package/src/client/mod.ts +9 -4
  180. package/src/client/query.ts +3 -1
  181. package/src/client/queue.ts +8 -3
  182. package/src/client/raw-utils.ts +24 -16
  183. package/src/client/resolve-gateway-target.ts +3 -1
  184. package/src/client/utils.ts +36 -10
  185. package/src/common/actor-router-consts.ts +7 -0
  186. package/src/common/actor-websocket.ts +3 -1
  187. package/src/common/bare/actor-persist/v1.ts +205 -163
  188. package/src/common/bare/actor-persist/v2.ts +265 -213
  189. package/src/common/bare/actor-persist/v3.ts +176 -172
  190. package/src/common/bare/actor-persist/v4.ts +254 -253
  191. package/src/common/bare/generated/actor-runtime-socket-protocol/v1.ts +848 -0
  192. package/src/common/bare/generated/client-protocol/v4.ts +599 -0
  193. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  194. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  195. package/src/common/bare/transport/v1.ts +694 -542
  196. package/src/common/client-protocol-versioned.ts +176 -67
  197. package/src/common/client-protocol-zod.ts +7 -0
  198. package/src/common/client-protocol.ts +1 -1
  199. package/src/common/database/config.ts +103 -10
  200. package/src/common/database/mod.test.ts +364 -0
  201. package/src/common/database/mod.ts +278 -149
  202. package/src/common/database/native-database.test.ts +220 -0
  203. package/src/common/database/native-database.ts +394 -58
  204. package/src/common/database/shared.ts +25 -0
  205. package/src/common/encoding.ts +302 -38
  206. package/src/common/engine.ts +28 -1
  207. package/src/common/eventsource.ts +1 -1
  208. package/src/common/fetch-like.ts +49 -0
  209. package/src/common/inline-websocket-adapter.ts +14 -13
  210. package/src/common/inspector-transport.ts +12 -2
  211. package/src/common/log.ts +117 -14
  212. package/src/common/router.ts +49 -23
  213. package/src/common/utils.ts +23 -203
  214. package/src/common/websocket-interface.ts +1 -1
  215. package/src/db/drizzle.test.ts +164 -0
  216. package/src/db/drizzle.ts +207 -121
  217. package/src/db/mod.ts +6 -1
  218. package/src/devtools-loader/index.ts +4 -7
  219. package/src/devtools-loader/serve-devtools.ts +26 -0
  220. package/src/dynamic/instance.ts +32 -0
  221. package/src/dynamic/internal.ts +50 -0
  222. package/src/dynamic/isolate-runtime.ts +64 -0
  223. package/src/dynamic/mod.ts +32 -0
  224. package/src/engine-client/actor-http-client.ts +23 -4
  225. package/src/engine-client/actor-websocket-client.ts +32 -5
  226. package/src/engine-client/api-endpoints.ts +52 -2
  227. package/src/engine-client/api-utils.ts +2 -2
  228. package/src/engine-client/driver.ts +21 -17
  229. package/src/engine-client/mod.ts +116 -64
  230. package/src/engine-client/ws-proxy.ts +9 -4
  231. package/src/globals.d.ts +4 -0
  232. package/src/inspector/client.browser.ts +127 -15
  233. package/src/inspector/mod.ts +2 -4
  234. package/src/inspector/workflow.ts +61 -0
  235. package/src/inspector-tab/mod.ts +301 -0
  236. package/src/registry/config/envoy.ts +1 -2
  237. package/src/registry/config/index.ts +160 -53
  238. package/src/registry/config/serverless.ts +7 -1
  239. package/src/registry/index.ts +659 -96
  240. package/src/registry/napi-runtime.ts +1154 -0
  241. package/src/registry/native-validation.ts +10 -12
  242. package/src/registry/native.ts +2005 -955
  243. package/src/registry/process-metrics.ts +250 -0
  244. package/src/registry/run-handler-coordinator.test.ts +252 -0
  245. package/src/registry/run-handler-coordinator.ts +219 -0
  246. package/src/registry/runtime.test.ts +50 -0
  247. package/src/registry/runtime.ts +839 -0
  248. package/src/registry/wasm-runtime.ts +1283 -0
  249. package/src/registry/write-through-proxy.ts +141 -0
  250. package/src/serde.ts +8 -2
  251. package/src/serverless/configure.ts +102 -49
  252. package/src/test/mod.ts +2 -17
  253. package/src/test/ready.ts +22 -0
  254. package/src/unstable/migrations.test.ts +170 -0
  255. package/src/unstable/migrations.ts +141 -0
  256. package/src/utils/crypto.ts +14 -0
  257. package/src/utils/endpoint-parser.ts +1 -1
  258. package/src/utils/env-vars.ts +39 -0
  259. package/src/utils/node.ts +44 -28
  260. package/src/utils/router.ts +1 -1
  261. package/src/utils.ts +4 -2
  262. package/src/workflow/context.ts +683 -242
  263. package/src/workflow/driver.test.ts +62 -0
  264. package/src/workflow/driver.ts +246 -119
  265. package/src/workflow/inspector.ts +24 -24
  266. package/src/workflow/mod.ts +76 -84
  267. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  268. package/dist/tsup/chunk-3BFYSYRU.js.map +0 -1
  269. package/dist/tsup/chunk-6AVUJ52Q.cjs +0 -253
  270. package/dist/tsup/chunk-6AVUJ52Q.cjs.map +0 -1
  271. package/dist/tsup/chunk-7MRGNVSR.js.map +0 -1
  272. package/dist/tsup/chunk-7X7RVTFF.cjs +0 -735
  273. package/dist/tsup/chunk-7X7RVTFF.cjs.map +0 -1
  274. package/dist/tsup/chunk-AK57AL7S.cjs.map +0 -1
  275. package/dist/tsup/chunk-AV54CVAG.cjs.map +0 -1
  276. package/dist/tsup/chunk-CVHUXINE.js.map +0 -1
  277. package/dist/tsup/chunk-EVADNK6Z.cjs.map +0 -1
  278. package/dist/tsup/chunk-J27CEW6F.js.map +0 -1
  279. package/dist/tsup/chunk-JTL6Y2UN.cjs.map +0 -1
  280. package/dist/tsup/chunk-LLD2D5LO.cjs.map +0 -1
  281. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  282. package/dist/tsup/chunk-RF3MEJV6.cjs.map +0 -1
  283. package/dist/tsup/chunk-SB4MXRN2.js +0 -253
  284. package/dist/tsup/chunk-SB4MXRN2.js.map +0 -1
  285. package/dist/tsup/chunk-SBEFJ4IQ.js.map +0 -1
  286. package/dist/tsup/chunk-SPMMF6TR.cjs.map +0 -1
  287. package/dist/tsup/chunk-TQSL4NJ3.cjs.map +0 -1
  288. package/dist/tsup/chunk-VD7AZIBR.js.map +0 -1
  289. package/dist/tsup/chunk-XSC2WWXD.js.map +0 -1
  290. package/dist/tsup/chunk-ZGWSH7YV.js.map +0 -1
  291. package/dist/tsup/context-BxvHh9wi.d.cts +0 -92
  292. package/dist/tsup/context-CNIZBIKl.d.ts +0 -92
  293. package/dist/tsup/utils-fwx3o3K9.d.cts +0 -18
  294. package/dist/tsup/utils-fwx3o3K9.d.ts +0 -18
  295. package/src/actor/driver.ts +0 -141
  296. package/src/actor/instance/mod.ts +0 -2501
  297. package/src/drivers/engine/actor-driver.ts +0 -2470
  298. package/src/utils/serve.ts +0 -217
  299. /package/dist/tsup/{chunk-PXLJOMJD.js.map → chunk-FXT3HN32.js.map} +0 -0
@@ -1,2217 +1,2596 @@
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(); } }// src/agent-os/actor/db.ts
2
- async function migrateAgentOsTables(db2) {
3
- await db2.execute(`
4
- CREATE TABLE IF NOT EXISTS agent_os_preview_tokens (
5
- token TEXT PRIMARY KEY,
6
- port INTEGER NOT NULL,
7
- created_at INTEGER NOT NULL,
8
- expires_at INTEGER NOT NULL
9
- );
10
-
11
- CREATE INDEX IF NOT EXISTS idx_preview_tokens_expires_at
12
- ON agent_os_preview_tokens(expires_at);
13
-
14
- CREATE TABLE IF NOT EXISTS agent_os_fs_entries (
15
- path TEXT PRIMARY KEY,
16
- is_directory INTEGER NOT NULL DEFAULT 0,
17
- content BLOB,
18
- mode INTEGER NOT NULL DEFAULT 33188,
19
- uid INTEGER NOT NULL DEFAULT 0,
20
- gid INTEGER NOT NULL DEFAULT 0,
21
- size INTEGER NOT NULL DEFAULT 0,
22
- atime_ms INTEGER NOT NULL,
23
- mtime_ms INTEGER NOT NULL,
24
- ctime_ms INTEGER NOT NULL,
25
- birthtime_ms INTEGER NOT NULL,
26
- symlink_target TEXT,
27
- nlink INTEGER NOT NULL DEFAULT 1
28
- );
29
-
30
- CREATE INDEX IF NOT EXISTS idx_fs_entries_parent
31
- ON agent_os_fs_entries(path);
32
-
33
- CREATE TABLE IF NOT EXISTS agent_os_sessions (
34
- session_id TEXT PRIMARY KEY,
35
- agent_type TEXT NOT NULL,
36
- capabilities TEXT NOT NULL,
37
- agent_info TEXT,
38
- created_at INTEGER NOT NULL
39
- );
40
-
41
- CREATE TABLE IF NOT EXISTS agent_os_session_events (
42
- id INTEGER PRIMARY KEY AUTOINCREMENT,
43
- session_id TEXT NOT NULL,
44
- seq INTEGER NOT NULL,
45
- event TEXT NOT NULL,
46
- created_at INTEGER NOT NULL,
47
- FOREIGN KEY (session_id) REFERENCES agent_os_sessions(session_id) ON DELETE CASCADE
48
- );
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(); } }// src/agent-os/actor/index.ts
2
+ var _agentoscore = require('@rivet-dev/agent-os-core');
49
3
 
50
- CREATE INDEX IF NOT EXISTS idx_session_events_session_seq
51
- ON agent_os_session_events(session_id, seq);
52
- `);
53
- }
4
+ // src/actor/config.ts
5
+ var _v4 = require('zod/v4');
54
6
 
55
- // src/agent-os/fs/database-vfs.ts
56
- var _posix = require('path/posix'); var posixPath = _interopRequireWildcard(_posix);
57
- var S_IFDIR = 16384;
58
- var S_IFREG = 32768;
59
- var S_IFLNK = 40960;
60
- var DEFAULT_FILE_MODE = S_IFREG | 420;
61
- var DEFAULT_DIR_MODE = S_IFDIR | 493;
62
- function normPath(p) {
63
- const normalized = posixPath.normalize(`/${p}`);
64
- if (normalized.length > 1 && normalized.endsWith("/")) {
65
- return normalized.slice(0, -1);
7
+ // src/actor/actions.ts
8
+ function flattenActionHandlers(actions) {
9
+ const flattened = /* @__PURE__ */ Object.create(null);
10
+ for (const { name, handler } of collectActionEntries(actions)) {
11
+ flattened[name] = handler;
66
12
  }
67
- return normalized;
68
- }
69
- function parentPath(p) {
70
- const parent = posixPath.dirname(p);
71
- return parent;
72
- }
73
- function throwENOENT(path) {
74
- const err = new Error(`ENOENT: no such file or directory: ${path}`);
75
- err.name = "ENOENT";
76
- throw err;
77
- }
78
- function throwEEXIST(path) {
79
- const err = new Error(`EEXIST: file already exists: ${path}`);
80
- err.name = "EEXIST";
81
- throw err;
13
+ return flattened;
82
14
  }
83
- function throwENOTDIR(path) {
84
- const err = new Error(`ENOTDIR: not a directory: ${path}`);
85
- err.name = "ENOTDIR";
86
- throw err;
87
- }
88
- function throwEISDIR(path) {
89
- const err = new Error(`EISDIR: illegal operation on a directory: ${path}`);
90
- err.name = "EISDIR";
91
- throw err;
92
- }
93
- function throwENOTEMPTY(path) {
94
- const err = new Error(`ENOTEMPTY: directory not empty: ${path}`);
95
- err.name = "ENOTEMPTY";
96
- throw err;
97
- }
98
- function throwENOSYS(op) {
99
- const err = new Error(`ENOSYS: function not implemented: ${op}`);
100
- err.name = "ENOSYS";
101
- throw err;
15
+ function flattenActionInputSchemas(actions, schemas) {
16
+ if (schemas === void 0) return void 0;
17
+ if (!isRecord(schemas)) {
18
+ throw new TypeError("actionInputSchemas must be an object");
19
+ }
20
+ const flattened = /* @__PURE__ */ Object.create(null);
21
+ for (const { name, path } of collectActionEntries(actions)) {
22
+ const nestedSchema = lookupNestedSchema(schemas, path);
23
+ const flatSchema = schemas[name];
24
+ if (nestedSchema !== void 0 && flatSchema !== void 0 && nestedSchema !== flatSchema) {
25
+ throw new TypeError(
26
+ `Action input schema \`${name}\` is defined by both a nested path and a dotted key`
27
+ );
28
+ }
29
+ const schema = _nullishCoalesce(nestedSchema, () => ( flatSchema));
30
+ if (schema !== void 0) {
31
+ flattened[name] = schema;
32
+ }
33
+ }
34
+ return flattened;
102
35
  }
103
- function rowToStat(row) {
104
- return {
105
- mode: row.mode,
106
- size: row.size,
107
- isDirectory: row.is_directory === 1,
108
- isSymbolicLink: row.symlink_target !== null,
109
- atimeMs: row.atime_ms,
110
- mtimeMs: row.mtime_ms,
111
- ctimeMs: row.ctime_ms,
112
- birthtimeMs: row.birthtime_ms,
113
- ino: 0,
114
- nlink: row.nlink,
115
- uid: row.uid,
116
- gid: row.gid
117
- };
36
+ function collectActionEntries(actions) {
37
+ const entries = [];
38
+ const names = /* @__PURE__ */ new Set();
39
+ visitActionGroup(_nullishCoalesce(actions, () => ( {})), [], entries, names);
40
+ return entries;
118
41
  }
119
- function createDatabaseVfs(options) {
120
- const { db: db2 } = options;
121
- async function getEntry(path) {
122
- const rows = await db2.execute(
123
- "SELECT * FROM agent_os_fs_entries WHERE path = ?",
124
- path
42
+ function visitActionGroup(value, path, entries, names) {
43
+ if (!isRecord(value)) {
44
+ throw new TypeError(
45
+ `${formatActionPath(path)} must be an action handler or group`
125
46
  );
126
- return rows[0];
127
47
  }
128
- async function getEntryOrThrow(path) {
129
- const entry = await getEntry(path);
130
- if (!entry) {
131
- throwENOENT(path);
48
+ for (const [segment, child] of Object.entries(value)) {
49
+ const childPath = [...path, segment];
50
+ if (typeof child === "function") {
51
+ const name = childPath.join(".");
52
+ if (names.has(name)) {
53
+ throw new TypeError(
54
+ `Multiple action definitions flatten to \`${name}\``
55
+ );
56
+ }
57
+ names.add(name);
58
+ entries.push({
59
+ name,
60
+ path: childPath,
61
+ handler: child
62
+ });
63
+ } else {
64
+ visitActionGroup(child, childPath, entries, names);
132
65
  }
133
- return entry;
134
66
  }
135
- async function ensureParentExists(path) {
136
- const parent = parentPath(path);
137
- if (parent === path) return;
138
- const entry = await getEntry(parent);
139
- if (!entry) {
140
- throwENOENT(parent);
141
- }
142
- if (entry.is_directory !== 1) {
143
- throwENOTDIR(parent);
67
+ }
68
+ function lookupNestedSchema(schemas, path) {
69
+ let value = schemas;
70
+ for (const segment of path) {
71
+ if (!isRecord(value) || !Object.hasOwn(value, segment)) {
72
+ return void 0;
144
73
  }
74
+ value = value[segment];
145
75
  }
146
- async function getChildEntries(dirPath) {
147
- const prefix = dirPath === "/" ? "/" : `${dirPath}/`;
148
- const rows = await db2.execute(
149
- "SELECT * FROM agent_os_fs_entries WHERE path LIKE ? AND path != ?",
150
- `${prefix}%`,
151
- dirPath
152
- );
153
- return rows.filter((row) => {
154
- const relative = row.path.slice(prefix.length);
155
- return relative.length > 0 && !relative.includes("/");
76
+ return value;
77
+ }
78
+ function isRecord(value) {
79
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
80
+ return false;
81
+ }
82
+ const prototype = Object.getPrototypeOf(value);
83
+ return prototype === Object.prototype || prototype === null;
84
+ }
85
+ function formatActionPath(path) {
86
+ return path.length === 0 ? "actions" : `Action \`${path.join(".")}\``;
87
+ }
88
+
89
+ // src/actor/config.ts
90
+ var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
91
+ var zFunction = () => _v4.z.custom((val) => typeof val === "function");
92
+ var zActionTree = _v4.z.custom((value) => {
93
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
94
+ return false;
95
+ }
96
+ const prototype = Object.getPrototypeOf(value);
97
+ return prototype === Object.prototype || prototype === null;
98
+ }).superRefine((actions, ctx) => {
99
+ try {
100
+ flattenActionHandlers(actions);
101
+ } catch (error) {
102
+ ctx.addIssue({
103
+ code: "custom",
104
+ message: error instanceof Error ? error.message : "Invalid action definition"
156
105
  });
157
106
  }
158
- const rootInit = (async () => {
159
- const root = await getEntry("/");
160
- if (!root) {
161
- const now = Date.now();
162
- await db2.execute(
163
- `INSERT OR IGNORE INTO agent_os_fs_entries (path, is_directory, content, mode, uid, gid, size, atime_ms, mtime_ms, ctime_ms, birthtime_ms, symlink_target, nlink) VALUES (?, 1, NULL, ?, 0, 0, 0, ?, ?, ?, ?, NULL, 2)`,
164
- "/",
165
- DEFAULT_DIR_MODE,
166
- now,
167
- now,
168
- now,
169
- now
170
- );
171
- }
172
- })();
173
- const backend = {
174
- async readFile(p) {
175
- await rootInit;
176
- const path = normPath(p);
177
- const entry = await getEntryOrThrow(path);
178
- if (entry.is_directory === 1) {
179
- throwEISDIR(path);
180
- }
181
- return _nullishCoalesce(entry.content, () => ( new Uint8Array(0)));
182
- },
183
- async readTextFile(p) {
184
- const data = await backend.readFile(p);
185
- return new TextDecoder().decode(data);
186
- },
187
- async readDir(p) {
188
- await rootInit;
189
- const path = normPath(p);
190
- const entry = await getEntryOrThrow(path);
191
- if (entry.is_directory !== 1) {
192
- throwENOTDIR(path);
193
- }
194
- const children = await getChildEntries(path);
195
- return children.map((child) => posixPath.basename(child.path));
196
- },
197
- async readDirWithTypes(p) {
198
- await rootInit;
199
- const path = normPath(p);
200
- const entry = await getEntryOrThrow(path);
201
- if (entry.is_directory !== 1) {
202
- throwENOTDIR(path);
203
- }
204
- const children = await getChildEntries(path);
205
- return children.map((child) => ({
206
- name: posixPath.basename(child.path),
207
- isDirectory: child.is_directory === 1,
208
- isSymbolicLink: child.symlink_target !== null,
209
- ino: 0
210
- }));
211
- },
212
- async writeFile(p, content) {
213
- await rootInit;
214
- const path = normPath(p);
215
- await ensureParentExists(path);
216
- const existing = await getEntry(path);
217
- if (existing && existing.is_directory === 1) {
218
- throwEISDIR(path);
219
- }
220
- const data = typeof content === "string" ? new TextEncoder().encode(content) : content;
221
- const now = Date.now();
222
- if (existing) {
223
- await db2.execute(
224
- `UPDATE agent_os_fs_entries SET content = ?, size = ?, mtime_ms = ?, ctime_ms = ?, atime_ms = ? WHERE path = ?`,
225
- data,
226
- data.byteLength,
227
- now,
228
- now,
229
- now,
230
- path
231
- );
232
- } else {
233
- await db2.execute(
234
- `INSERT INTO agent_os_fs_entries (path, is_directory, content, mode, uid, gid, size, atime_ms, mtime_ms, ctime_ms, birthtime_ms, symlink_target, nlink) VALUES (?, 0, ?, ?, 0, 0, ?, ?, ?, ?, ?, NULL, 1)`,
235
- path,
236
- data,
237
- DEFAULT_FILE_MODE,
238
- data.byteLength,
239
- now,
240
- now,
241
- now,
242
- now
243
- );
244
- }
245
- },
246
- async createDir(p) {
247
- await rootInit;
248
- const path = normPath(p);
249
- await ensureParentExists(path);
250
- const existing = await getEntry(path);
251
- if (existing) {
252
- throwEEXIST(path);
107
+ });
108
+ var WorkflowInspectorConfigSchema = _v4.z.object({
109
+ getHistory: zFunction(),
110
+ getState: zFunction().optional(),
111
+ onHistoryUpdated: zFunction().optional(),
112
+ replayFromStep: zFunction().optional()
113
+ });
114
+ var RunInspectorConfigSchema = _v4.z.object({
115
+ workflow: WorkflowInspectorConfigSchema.optional()
116
+ }).optional();
117
+ var BUILTIN_INSPECTOR_TAB_IDS = [
118
+ "workflow",
119
+ "database",
120
+ "state",
121
+ "queue",
122
+ "schedules",
123
+ "connections",
124
+ "console"
125
+ ];
126
+ var BuiltinInspectorTabIdSchema = _v4.z.enum(BUILTIN_INSPECTOR_TAB_IDS);
127
+ var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
128
+ var CustomInspectorTabEntrySchema = _v4.z.object({
129
+ id: _v4.z.string().regex(
130
+ CUSTOM_INSPECTOR_TAB_ID_RE,
131
+ "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
132
+ ),
133
+ label: _v4.z.string().min(1),
134
+ source: _v4.z.string().min(1),
135
+ /**
136
+ * Optional icon id. The dashboard maps strings to glyphs (see its
137
+ * icon registry); unknown ids fall back to a generic icon.
138
+ */
139
+ icon: _v4.z.string().min(1).optional(),
140
+ hidden: _v4.z.literal(false).optional()
141
+ }).strict();
142
+ var HideInspectorTabEntrySchema = _v4.z.object({
143
+ id: BuiltinInspectorTabIdSchema,
144
+ hidden: _v4.z.literal(true)
145
+ }).strict();
146
+ var InspectorTabEntrySchema = _v4.z.union([
147
+ CustomInspectorTabEntrySchema,
148
+ HideInspectorTabEntrySchema
149
+ ]);
150
+ var ActorInspectorConfigSchema = _v4.z.object({
151
+ tabs: _v4.z.array(InspectorTabEntrySchema).default(() => [])
152
+ }).strict().refine(
153
+ (data) => {
154
+ const ids = data.tabs.map((t) => t.id);
155
+ return new Set(ids).size === ids.length;
156
+ },
157
+ { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
158
+ ).refine(
159
+ (data) => {
160
+ const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
161
+ return data.tabs.every(
162
+ (t) => t.hidden === true || !builtinSet.has(t.id)
163
+ );
164
+ },
165
+ {
166
+ message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
167
+ path: ["tabs"]
168
+ }
169
+ );
170
+ var RunConfigSchema = _v4.z.object({
171
+ /** Display name for the actor in the Inspector UI. */
172
+ name: _v4.z.string().optional(),
173
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
174
+ icon: _v4.z.string().optional(),
175
+ /** The run handler function. */
176
+ run: zFunction(),
177
+ /** Inspector integration for long-running run handlers. */
178
+ inspector: RunInspectorConfigSchema.optional()
179
+ });
180
+ var zRunHandler = _v4.z.union([zFunction(), RunConfigSchema]).optional();
181
+ var GlobalActorOptionsBaseSchema = _v4.z.object({
182
+ /** Display name for the actor in the Inspector UI. */
183
+ name: _v4.z.string().optional(),
184
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
185
+ icon: _v4.z.string().optional(),
186
+ /** Enables the experimental Actor Runtime Socket for this actor. */
187
+ enableActorRuntimeSocket: _v4.z.boolean().default(false),
188
+ /**
189
+ * Can hibernate WebSockets for onWebSocket.
190
+ *
191
+ * WebSockets using actions/events are hibernatable by default.
192
+ *
193
+ * @experimental
194
+ **/
195
+ canHibernateWebSocket: _v4.z.union([_v4.z.boolean(), zFunction()]).default(false)
196
+ }).strict();
197
+ var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
198
+ () => ({})
199
+ );
200
+ var InstanceActorOptionsBaseSchema = _v4.z.object({
201
+ createVarsTimeout: _v4.z.number().positive().default(5e3),
202
+ createConnStateTimeout: _v4.z.number().positive().default(5e3),
203
+ onBeforeConnectTimeout: _v4.z.number().positive().default(5e3),
204
+ onConnectTimeout: _v4.z.number().positive().default(5e3),
205
+ onMigrateTimeout: _v4.z.number().positive().default(3e4),
206
+ sleepGracePeriod: _v4.z.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
207
+ /** @deprecated `onDestroyTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
208
+ onDestroyTimeout: _v4.z.number().positive().optional(),
209
+ /** @deprecated `waitUntilTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
210
+ waitUntilTimeout: _v4.z.number().positive().optional(),
211
+ stateSaveInterval: _v4.z.number().positive().default(1e3),
212
+ actionTimeout: _v4.z.number().positive().default(6e4),
213
+ connectionLivenessTimeout: _v4.z.number().positive().default(2500),
214
+ connectionLivenessInterval: _v4.z.number().positive().default(5e3),
215
+ /** @deprecated Use `c.keepAwake(promise)` to scope keep-awake to a specific operation, or keep `noSleep` for actors that must stay awake indefinitely. Will be removed in 2.2.0. */
216
+ noSleep: _v4.z.boolean().default(false),
217
+ sleepTimeout: _v4.z.number().positive().default(3e4),
218
+ maxQueueSize: _v4.z.number().positive().default(1e3),
219
+ /** Maximum pending one-shot and recurring schedules. */
220
+ maxSchedules: _v4.z.number().int().nonnegative().default(1e3),
221
+ maxQueueMessageSize: _v4.z.number().positive().default(64 * 1024),
222
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
223
+ preloadMaxWorkflowBytes: _v4.z.number().nonnegative().optional(),
224
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
225
+ preloadMaxConnectionsBytes: _v4.z.number().nonnegative().optional()
226
+ }).strict();
227
+ var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
228
+ var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
229
+ InstanceActorOptionsBaseSchema.shape
230
+ ).strict().prefault(() => ({}));
231
+ var ActorConfigSchema = _v4.z.object({
232
+ onCreate: zFunction().optional(),
233
+ onDestroy: zFunction().optional(),
234
+ onMigrate: zFunction().optional(),
235
+ onWake: zFunction().optional(),
236
+ onSleep: zFunction().optional(),
237
+ run: zRunHandler,
238
+ onStateChange: zFunction().optional(),
239
+ onBeforeConnect: zFunction().optional(),
240
+ onConnect: zFunction().optional(),
241
+ onDisconnect: zFunction().optional(),
242
+ onBeforeActionResponse: zFunction().optional(),
243
+ onRequest: zFunction().optional(),
244
+ onWebSocket: zFunction().optional(),
245
+ actions: zActionTree.default(() => ({})),
246
+ actionInputSchemas: _v4.z.record(_v4.z.string(), _v4.z.any()).optional(),
247
+ connParamsSchema: _v4.z.any().optional(),
248
+ events: _v4.z.record(_v4.z.string(), _v4.z.any()).optional(),
249
+ queues: _v4.z.record(_v4.z.string(), _v4.z.any()).optional(),
250
+ state: _v4.z.any().optional(),
251
+ createState: zFunction().optional(),
252
+ connState: _v4.z.any().optional(),
253
+ createConnState: zFunction().optional(),
254
+ vars: _v4.z.any().optional(),
255
+ db: _v4.z.any().optional(),
256
+ createVars: zFunction().optional(),
257
+ options: ActorOptionsSchema,
258
+ inspector: ActorInspectorConfigSchema.optional()
259
+ }).strict().refine(
260
+ (data) => !(data.state !== void 0 && data.createState !== void 0),
261
+ {
262
+ message: "Cannot define both 'state' and 'createState'",
263
+ path: ["state"]
264
+ }
265
+ ).refine(
266
+ (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
267
+ {
268
+ message: "Cannot define both 'connState' and 'createConnState'",
269
+ path: ["connState"]
270
+ }
271
+ ).refine(
272
+ (data) => !(data.vars !== void 0 && data.createVars !== void 0),
273
+ {
274
+ message: "Cannot define both 'vars' and 'createVars'",
275
+ path: ["vars"]
276
+ }
277
+ );
278
+ var DocActorOptionsSchema = _v4.z.object({
279
+ name: _v4.z.string().optional().describe("Display name for the actor in the Inspector UI."),
280
+ icon: _v4.z.string().optional().describe(
281
+ "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
282
+ ),
283
+ enableActorRuntimeSocket: _v4.z.boolean().optional().describe(
284
+ "Enables the experimental Actor Runtime Socket for this actor. Default: false"
285
+ ),
286
+ createVarsTimeout: _v4.z.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
287
+ createConnStateTimeout: _v4.z.number().optional().describe(
288
+ "Timeout in ms for createConnState handler. Default: 5000"
289
+ ),
290
+ onMigrateTimeout: _v4.z.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
291
+ onBeforeConnectTimeout: _v4.z.number().optional().describe(
292
+ "Timeout in ms for onBeforeConnect handler. Default: 5000"
293
+ ),
294
+ onConnectTimeout: _v4.z.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
295
+ sleepGracePeriod: _v4.z.number().optional().describe(
296
+ `Max time in ms for the graceful shutdown window. Covers lifecycle hooks (onSleep, onDestroy), the run handler wait, async raw WebSocket handlers, disconnect callbacks, and final state serialization. Default: ${DEFAULT_SLEEP_GRACE_PERIOD}.`
297
+ ),
298
+ onDestroyTimeout: _v4.z.number().optional().describe(
299
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
300
+ ),
301
+ waitUntilTimeout: _v4.z.number().optional().describe(
302
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
303
+ ),
304
+ stateSaveInterval: _v4.z.number().optional().describe(
305
+ "Interval in ms between automatic state saves. Default: 1000"
306
+ ),
307
+ actionTimeout: _v4.z.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
308
+ connectionLivenessTimeout: _v4.z.number().optional().describe(
309
+ "Timeout in ms for connection liveness checks. Default: 2500"
310
+ ),
311
+ connectionLivenessInterval: _v4.z.number().optional().describe(
312
+ "Interval in ms between connection liveness checks. Default: 5000"
313
+ ),
314
+ noSleep: _v4.z.boolean().optional().describe(
315
+ "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
316
+ ),
317
+ sleepTimeout: _v4.z.number().optional().describe(
318
+ "Time in ms of inactivity before the actor sleeps. Default: 30000"
319
+ ),
320
+ maxQueueSize: _v4.z.number().optional().describe(
321
+ "Maximum number of queue messages before rejecting new messages. Default: 1000"
322
+ ),
323
+ maxSchedules: _v4.z.number().int().nonnegative().optional().describe(
324
+ "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
325
+ ),
326
+ maxQueueMessageSize: _v4.z.number().optional().describe(
327
+ "Maximum size of each queue message in bytes. Default: 65536"
328
+ ),
329
+ canHibernateWebSocket: _v4.z.boolean().optional().describe(
330
+ "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
331
+ )
332
+ }).describe("Actor options for timeouts and behavior configuration.");
333
+ var DocActorConfigSchema = _v4.z.object({
334
+ state: _v4.z.unknown().optional().describe(
335
+ "Initial state value for the actor. Cannot be used with createState."
336
+ ),
337
+ createState: _v4.z.unknown().optional().describe(
338
+ "Function to create initial state. Receives context and input. Cannot be used with state."
339
+ ),
340
+ connState: _v4.z.unknown().optional().describe(
341
+ "Initial connection state value. Cannot be used with createConnState."
342
+ ),
343
+ createConnState: _v4.z.unknown().optional().describe(
344
+ "Function to create connection state. Receives context and connection params. The pending connection is not visible in c.conns until this succeeds. Cannot be used with connState."
345
+ ),
346
+ vars: _v4.z.unknown().optional().describe(
347
+ "Initial ephemeral variables value. Cannot be used with createVars."
348
+ ),
349
+ createVars: _v4.z.unknown().optional().describe(
350
+ "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
351
+ ),
352
+ db: _v4.z.unknown().optional().describe("Database provider instance for the actor."),
353
+ onCreate: _v4.z.unknown().optional().describe(
354
+ "Called when the actor is first initialized. Use to initialize state."
355
+ ),
356
+ onDestroy: _v4.z.unknown().optional().describe("Called when the actor is destroyed."),
357
+ onMigrate: _v4.z.unknown().optional().describe(
358
+ "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
359
+ ),
360
+ onWake: _v4.z.unknown().optional().describe(
361
+ "Called when the actor wakes up and is ready to receive connections and actions."
362
+ ),
363
+ onSleep: _v4.z.unknown().optional().describe(
364
+ "Called when the actor is stopping or sleeping. Use to clean up resources."
365
+ ),
366
+ run: _v4.z.unknown().optional().describe(
367
+ "Called after actor starts. Does not block startup. Use for background tasks like queue processing or tick loops. If it exits, the actor follows the normal idle sleep timeout once idle. If it throws, the actor logs the error and then follows the normal idle sleep timeout once idle."
368
+ ),
369
+ onStateChange: _v4.z.unknown().optional().describe(
370
+ "Called when the actor's state changes. State changes within this hook won't trigger recursion."
371
+ ),
372
+ onBeforeConnect: _v4.z.unknown().optional().describe(
373
+ "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
374
+ ),
375
+ onConnect: _v4.z.unknown().optional().describe(
376
+ "Called when a client successfully connects. The connection is visible in c.conns before this runs."
377
+ ),
378
+ onDisconnect: _v4.z.unknown().optional().describe("Called when a client disconnects."),
379
+ onBeforeActionResponse: _v4.z.unknown().optional().describe(
380
+ "Called before sending an action response. Use to transform output."
381
+ ),
382
+ onRequest: _v4.z.unknown().optional().describe(
383
+ "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
384
+ ),
385
+ onWebSocket: _v4.z.unknown().optional().describe(
386
+ "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
387
+ ),
388
+ actions: _v4.z.record(_v4.z.string(), _v4.z.unknown()).optional().describe(
389
+ "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
390
+ ),
391
+ actionInputSchemas: _v4.z.record(_v4.z.string(), _v4.z.unknown()).optional().describe(
392
+ "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
393
+ ),
394
+ connParamsSchema: _v4.z.unknown().optional().describe(
395
+ "Optional schema for validating connection params in native runtimes."
396
+ ),
397
+ events: _v4.z.record(_v4.z.string(), _v4.z.unknown()).optional().describe("Map of event names to schemas."),
398
+ queues: _v4.z.record(_v4.z.string(), _v4.z.unknown()).optional().describe("Map of queue names to schemas."),
399
+ options: DocActorOptionsSchema.optional()
400
+ }).describe("Actor configuration passed to the actor() function.");
401
+
402
+ // src/common/log.ts
403
+
404
+
405
+
406
+ var _pino = require('pino');
407
+
408
+
409
+ // src/actor/errors.ts
410
+ function isTypedErrorTag(value) {
411
+ return value === "ActorError" || value === "RivetError";
412
+ }
413
+ function isRivetErrorLike(error) {
414
+ return typeof error === "object" && error !== null && "group" in error && typeof error.group === "string" && "code" in error && typeof error.code === "string" && "message" in error && typeof error.message === "string" && (!("rayId" in error) || error.rayId === void 0 || typeof error.rayId === "string") && (!("__type" in error) || isTypedErrorTag(error.__type));
415
+ }
416
+ function isRivetErrorCode(error, group, code) {
417
+ return isRivetErrorLike(error) && error.group === group && error.code === code;
418
+ }
419
+
420
+ // package.json
421
+ var package_default = {
422
+ name: "rivetkit",
423
+ version: "0.0.0-main.49693dc",
424
+ description: "Lightweight libraries for building stateful actors on edge platforms",
425
+ license: "Apache-2.0",
426
+ keywords: [
427
+ "rivetkit",
428
+ "stateful",
429
+ "serverless",
430
+ "actors",
431
+ "agents",
432
+ "realtime",
433
+ "websocket",
434
+ "actors",
435
+ "framework"
436
+ ],
437
+ files: [
438
+ "dist",
439
+ "schemas",
440
+ "src",
441
+ "package.json"
442
+ ],
443
+ type: "module",
444
+ exports: {
445
+ ".": {
446
+ import: {
447
+ types: "./dist/tsup/mod.d.ts",
448
+ default: "./dist/tsup/mod.js"
449
+ },
450
+ require: {
451
+ types: "./dist/tsup/mod.d.cts",
452
+ default: "./dist/tsup/mod.cjs"
253
453
  }
254
- const now = Date.now();
255
- await db2.execute(
256
- `INSERT INTO agent_os_fs_entries (path, is_directory, content, mode, uid, gid, size, atime_ms, mtime_ms, ctime_ms, birthtime_ms, symlink_target, nlink) VALUES (?, 1, NULL, ?, 0, 0, 0, ?, ?, ?, ?, NULL, 2)`,
257
- path,
258
- DEFAULT_DIR_MODE,
259
- now,
260
- now,
261
- now,
262
- now
263
- );
264
454
  },
265
- async mkdir(p, options2) {
266
- await rootInit;
267
- const path = normPath(p);
268
- if (options2 == null ? void 0 : options2.recursive) {
269
- const parts = path.split("/").filter(Boolean);
270
- let current = "";
271
- for (const part of parts) {
272
- current += `/${part}`;
273
- const existing = await getEntry(current);
274
- if (!existing) {
275
- const now = Date.now();
276
- await db2.execute(
277
- `INSERT INTO agent_os_fs_entries (path, is_directory, content, mode, uid, gid, size, atime_ms, mtime_ms, ctime_ms, birthtime_ms, symlink_target, nlink) VALUES (?, 1, NULL, ?, 0, 0, 0, ?, ?, ?, ?, NULL, 2)`,
278
- current,
279
- DEFAULT_DIR_MODE,
280
- now,
281
- now,
282
- now,
283
- now
284
- );
285
- } else if (existing.is_directory !== 1) {
286
- throwENOTDIR(current);
287
- }
288
- }
289
- } else {
290
- await backend.createDir(p);
455
+ "./workflow": {
456
+ import: {
457
+ types: "./dist/tsup/workflow/mod.d.ts",
458
+ default: "./dist/tsup/workflow/mod.js"
459
+ },
460
+ require: {
461
+ types: "./dist/tsup/workflow/mod.d.cts",
462
+ default: "./dist/tsup/workflow/mod.cjs"
291
463
  }
292
464
  },
293
- async exists(p) {
294
- await rootInit;
295
- const path = normPath(p);
296
- const entry = await getEntry(path);
297
- return entry !== void 0;
298
- },
299
- async stat(p) {
300
- await rootInit;
301
- const path = normPath(p);
302
- const entry = await getEntryOrThrow(path);
303
- return rowToStat(entry);
304
- },
305
- async removeFile(p) {
306
- await rootInit;
307
- const path = normPath(p);
308
- const entry = await getEntryOrThrow(path);
309
- if (entry.is_directory === 1) {
310
- throwEISDIR(path);
465
+ "./test": {
466
+ import: {
467
+ types: "./dist/tsup/test/mod.d.ts",
468
+ default: "./dist/tsup/test/mod.js"
469
+ },
470
+ require: {
471
+ types: "./dist/tsup/test/mod.d.cts",
472
+ default: "./dist/tsup/test/mod.cjs"
311
473
  }
312
- await db2.execute(
313
- "DELETE FROM agent_os_fs_entries WHERE path = ?",
314
- path
315
- );
316
474
  },
317
- async removeDir(p) {
318
- await rootInit;
319
- const path = normPath(p);
320
- const entry = await getEntryOrThrow(path);
321
- if (entry.is_directory !== 1) {
322
- throwENOTDIR(path);
323
- }
324
- const children = await getChildEntries(path);
325
- if (children.length > 0) {
326
- throwENOTEMPTY(path);
475
+ "./db": {
476
+ import: {
477
+ types: "./dist/tsup/db/mod.d.ts",
478
+ default: "./dist/tsup/db/mod.js"
479
+ },
480
+ require: {
481
+ types: "./dist/tsup/db/mod.d.cts",
482
+ default: "./dist/tsup/db/mod.cjs"
327
483
  }
328
- await db2.execute(
329
- "DELETE FROM agent_os_fs_entries WHERE path = ?",
330
- path
331
- );
332
484
  },
333
- async rename(oldPath, newPath) {
334
- await rootInit;
335
- const from = normPath(oldPath);
336
- const to = normPath(newPath);
337
- const entry = await getEntryOrThrow(from);
338
- await ensureParentExists(to);
339
- const destEntry = await getEntry(to);
340
- if (destEntry) {
341
- if (destEntry.is_directory === 1) {
342
- const children = await getChildEntries(to);
343
- if (children.length > 0) {
344
- throwENOTEMPTY(to);
345
- }
346
- }
347
- await db2.execute(
348
- "DELETE FROM agent_os_fs_entries WHERE path = ?",
349
- to
350
- );
351
- }
352
- if (entry.is_directory === 1) {
353
- const prefix = from === "/" ? "/" : `${from}/`;
354
- const newPrefix = to === "/" ? "/" : `${to}/`;
355
- const descendants = await db2.execute(
356
- "SELECT path FROM agent_os_fs_entries WHERE path LIKE ?",
357
- `${prefix}%`
358
- );
359
- for (const desc of descendants) {
360
- const newDescPath = newPrefix + desc.path.slice(prefix.length);
361
- await db2.execute(
362
- "UPDATE agent_os_fs_entries SET path = ? WHERE path = ?",
363
- newDescPath,
364
- desc.path
365
- );
366
- }
485
+ "./db/drizzle": {
486
+ import: {
487
+ types: "./dist/tsup/db/drizzle.d.ts",
488
+ default: "./dist/tsup/db/drizzle.js"
489
+ },
490
+ require: {
491
+ types: "./dist/tsup/db/drizzle.d.cts",
492
+ default: "./dist/tsup/db/drizzle.cjs"
367
493
  }
368
- const now = Date.now();
369
- await db2.execute(
370
- "UPDATE agent_os_fs_entries SET path = ?, ctime_ms = ? WHERE path = ?",
371
- to,
372
- now,
373
- from
374
- );
375
494
  },
376
- async realpath(p) {
377
- await rootInit;
378
- const path = normPath(p);
379
- const entry = await getEntryOrThrow(path);
380
- if (entry.symlink_target !== null) {
381
- return normPath(entry.symlink_target);
495
+ "./unstable/migrations": {
496
+ import: {
497
+ types: "./dist/tsup/unstable/migrations.d.ts",
498
+ default: "./dist/tsup/unstable/migrations.js"
499
+ },
500
+ require: {
501
+ types: "./dist/tsup/unstable/migrations.d.cts",
502
+ default: "./dist/tsup/unstable/migrations.cjs"
382
503
  }
383
- return path;
384
504
  },
385
- async symlink(target, linkPath) {
386
- await rootInit;
387
- const link = normPath(linkPath);
388
- await ensureParentExists(link);
389
- const existing = await getEntry(link);
390
- if (existing) {
391
- throwEEXIST(link);
505
+ "./dynamic": {
506
+ import: {
507
+ types: "./dist/tsup/dynamic/mod.d.ts",
508
+ default: "./dist/tsup/dynamic/mod.js"
509
+ },
510
+ require: {
511
+ types: "./dist/tsup/dynamic/mod.d.cts",
512
+ default: "./dist/tsup/dynamic/mod.cjs"
392
513
  }
393
- const now = Date.now();
394
- await db2.execute(
395
- `INSERT INTO agent_os_fs_entries (path, is_directory, content, mode, uid, gid, size, atime_ms, mtime_ms, ctime_ms, birthtime_ms, symlink_target, nlink) VALUES (?, 0, NULL, ?, 0, 0, ?, ?, ?, ?, ?, ?, 1)`,
396
- link,
397
- S_IFLNK | 511,
398
- target.length,
399
- now,
400
- now,
401
- now,
402
- now,
403
- target
404
- );
405
514
  },
406
- async readlink(p) {
407
- await rootInit;
408
- const path = normPath(p);
409
- const entry = await getEntryOrThrow(path);
410
- if (entry.symlink_target === null) {
411
- const err = new Error(`EINVAL: not a symlink: ${path}`);
412
- err.name = "EINVAL";
413
- throw err;
515
+ "./client": {
516
+ import: {
517
+ browser: {
518
+ types: "./dist/browser/client.d.ts",
519
+ default: "./dist/browser/client.js"
520
+ },
521
+ types: "./dist/tsup/client/mod.d.ts",
522
+ default: "./dist/tsup/client/mod.js"
523
+ },
524
+ require: {
525
+ types: "./dist/tsup/client/mod.d.cts",
526
+ default: "./dist/tsup/client/mod.cjs"
414
527
  }
415
- return entry.symlink_target;
416
- },
417
- async lstat(p) {
418
- return backend.stat(p);
419
- },
420
- async link(oldPath, newPath) {
421
- throwENOSYS("link");
422
528
  },
423
- async chmod(p, mode) {
424
- await rootInit;
425
- const path = normPath(p);
426
- await getEntryOrThrow(path);
427
- const now = Date.now();
428
- await db2.execute(
429
- "UPDATE agent_os_fs_entries SET mode = ?, ctime_ms = ? WHERE path = ?",
430
- mode,
431
- now,
432
- path
433
- );
529
+ "./log": {
530
+ import: {
531
+ types: "./dist/tsup/common/log.d.ts",
532
+ default: "./dist/tsup/common/log.js"
533
+ },
534
+ require: {
535
+ types: "./dist/tsup/common/log.d.cts",
536
+ default: "./dist/tsup/common/log.cjs"
537
+ }
434
538
  },
435
- async chown(p, uid, gid) {
436
- await rootInit;
437
- const path = normPath(p);
438
- await getEntryOrThrow(path);
439
- const now = Date.now();
440
- await db2.execute(
441
- "UPDATE agent_os_fs_entries SET uid = ?, gid = ?, ctime_ms = ? WHERE path = ?",
442
- uid,
443
- gid,
444
- now,
445
- path
446
- );
539
+ "./errors": {
540
+ import: {
541
+ types: "./dist/tsup/actor/errors.d.ts",
542
+ default: "./dist/tsup/actor/errors.js"
543
+ },
544
+ require: {
545
+ types: "./dist/tsup/actor/errors.d.cts",
546
+ default: "./dist/tsup/actor/errors.cjs"
547
+ }
447
548
  },
448
- async utimes(p, atime, mtime) {
449
- await rootInit;
450
- const path = normPath(p);
451
- await getEntryOrThrow(path);
452
- const now = Date.now();
453
- await db2.execute(
454
- "UPDATE agent_os_fs_entries SET atime_ms = ?, mtime_ms = ?, ctime_ms = ? WHERE path = ?",
455
- atime,
456
- mtime,
457
- now,
458
- path
459
- );
549
+ "./inspector": {
550
+ import: {
551
+ types: "./dist/tsup/inspector/mod.d.ts",
552
+ default: "./dist/tsup/inspector/mod.js"
553
+ },
554
+ require: {
555
+ types: "./dist/tsup/inspector/mod.d.cts",
556
+ default: "./dist/tsup/inspector/mod.cjs"
557
+ }
460
558
  },
461
- async truncate(p, length) {
462
- await rootInit;
463
- const path = normPath(p);
464
- const entry = await getEntryOrThrow(path);
465
- if (entry.is_directory === 1) {
466
- throwEISDIR(path);
559
+ "./experimental/inspector/workflow": {
560
+ import: {
561
+ types: "./dist/tsup/inspector/workflow.d.ts",
562
+ default: "./dist/tsup/inspector/workflow.js"
563
+ },
564
+ require: {
565
+ types: "./dist/tsup/inspector/workflow.d.cts",
566
+ default: "./dist/tsup/inspector/workflow.cjs"
467
567
  }
468
- const existing = _nullishCoalesce(entry.content, () => ( new Uint8Array(0)));
469
- let newContent;
470
- if (length >= existing.byteLength) {
471
- newContent = new Uint8Array(length);
472
- newContent.set(existing);
473
- } else {
474
- newContent = existing.slice(0, length);
568
+ },
569
+ "./inspector-tab": {
570
+ import: {
571
+ types: "./dist/tsup/inspector-tab/mod.d.ts",
572
+ default: "./dist/tsup/inspector-tab/mod.js"
573
+ },
574
+ require: {
575
+ types: "./dist/tsup/inspector-tab/mod.d.cts",
576
+ default: "./dist/tsup/inspector-tab/mod.cjs"
475
577
  }
476
- const now = Date.now();
477
- await db2.execute(
478
- "UPDATE agent_os_fs_entries SET content = ?, size = ?, mtime_ms = ?, ctime_ms = ? WHERE path = ?",
479
- newContent,
480
- length,
481
- now,
482
- now,
483
- path
484
- );
485
578
  },
486
- async pread(p, offset, length) {
487
- await rootInit;
488
- const path = normPath(p);
489
- const entry = await getEntryOrThrow(path);
490
- if (entry.is_directory === 1) {
491
- throwEISDIR(path);
579
+ "./inspector/client": {
580
+ import: {
581
+ types: "./dist/browser/inspector/client.d.ts",
582
+ default: "./dist/browser/inspector/client.js"
492
583
  }
493
- const content = _nullishCoalesce(entry.content, () => ( new Uint8Array(0)));
494
- const end = Math.min(offset + length, content.byteLength);
495
- if (offset >= content.byteLength) {
496
- return new Uint8Array(0);
584
+ },
585
+ "./utils": {
586
+ import: {
587
+ types: "./dist/tsup/utils.d.ts",
588
+ default: "./dist/tsup/utils.js"
589
+ },
590
+ require: {
591
+ types: "./dist/tsup/utils.d.cts",
592
+ default: "./dist/tsup/utils.cjs"
497
593
  }
498
- return content.slice(offset, end);
499
594
  },
500
- async pwrite(p, offset, data) {
501
- await rootInit;
502
- const path = normPath(p);
503
- const entry = await getEntryOrThrow(path);
504
- if (entry.is_directory === 1) {
505
- throwEISDIR(path);
595
+ "./agent-os": {
596
+ import: {
597
+ types: "./dist/tsup/agent-os/index.d.ts",
598
+ default: "./dist/tsup/agent-os/index.js"
599
+ },
600
+ require: {
601
+ types: "./dist/tsup/agent-os/index.d.cts",
602
+ default: "./dist/tsup/agent-os/index.cjs"
603
+ }
604
+ }
605
+ },
606
+ engines: {
607
+ node: ">=22.0.0"
608
+ },
609
+ sideEffects: [
610
+ "./dist/tsup/chunk-*.js",
611
+ "./dist/tsup/chunk-*.cjs"
612
+ ],
613
+ scripts: {
614
+ build: "tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/utils.ts src/workflow/mod.ts src/test/mod.ts src/inspector/mod.ts src/inspector/workflow.ts src/inspector-tab/mod.ts src/db/mod.ts src/db/drizzle.ts src/dynamic/mod.ts src/unstable/migrations.ts && tsup src/agent-os/index.ts --no-clean --out-dir dist/tsup/agent-os && node scripts/check-built-commonjs.mjs",
615
+ "build:browser": "tsup --config tsup.browser.config.ts",
616
+ "check-types": "tsc --noEmit",
617
+ lint: "biome check . && pnpm run check:test-skips && pnpm run check:wait-for-comments",
618
+ "lint:fix": "biome check --write .",
619
+ "check:test-skips": "tsx scripts/check-annotated-skips.ts",
620
+ "check:wait-for-comments": "tsx scripts/check-wait-for-comments.ts",
621
+ format: "biome format .",
622
+ "format:write": "biome format --write .",
623
+ test: "vitest run",
624
+ "test:platforms": "pnpm run build && RIVETKIT_INCLUDE_PLATFORM_TESTS=1 vitest run tests/platforms --passWithNoTests",
625
+ "test:watch": "vitest",
626
+ "dump-asyncapi": "tsx scripts/dump-asyncapi.ts",
627
+ "registry-config-schema-gen": "tsx scripts/registry-config-schema-gen.ts",
628
+ "actor-config-schema-gen": "tsx scripts/actor-config-schema-gen.ts"
629
+ },
630
+ dependencies: {
631
+ "@hono/zod-openapi": "^1.1.5",
632
+ "@rivet-dev/agent-os-core": "^0.1.1",
633
+ "@rivetkit/bare-ts": "^0.6.2",
634
+ "@rivetkit/engine-cli": "workspace:*",
635
+ "@rivetkit/engine-envoy-protocol": "workspace:*",
636
+ "@rivetkit/on-change": "6.0.1",
637
+ "@rivetkit/rivetkit-napi": "workspace:*",
638
+ "@rivetkit/rivetkit-wasm": "workspace:*",
639
+ "@rivetkit/traces": "workspace:*",
640
+ "@rivetkit/virtual-websocket": "workspace:*",
641
+ "@rivetkit/workflow-engine": "workspace:*",
642
+ "cbor-x": "^1.6.0",
643
+ "drizzle-orm": "^0.44.2",
644
+ hono: "^4.7.0",
645
+ invariant: "^2.2.4",
646
+ "p-retry": "^6.2.1",
647
+ pino: "^9.5.0",
648
+ uuid: "^12.0.0",
649
+ vbare: "^0.0.4",
650
+ zod: "^4.1.0"
651
+ },
652
+ devDependencies: {
653
+ "@biomejs/biome": "^2.3",
654
+ "@copilotkit/llmock": "^1.6.0",
655
+ "@hono/node-server": "^1.18.2",
656
+ "@hono/node-ws": "^1.1.1",
657
+ "@rivet-dev/agent-os-common": "*",
658
+ "@rivet-dev/agent-os-pi": "^0.1.1",
659
+ "@standard-schema/spec": "^1.0.0",
660
+ "@types/invariant": "^2",
661
+ "@types/node": "^22.13.1",
662
+ eventsource: "^4.0.0",
663
+ "get-port": "^7.1.0",
664
+ tsup: "^8.4.0",
665
+ tsx: "^4.19.4",
666
+ typescript: "^5.7.3",
667
+ "vite-tsconfig-paths": "^5.1.4",
668
+ vitest: "^3.1.1",
669
+ ws: "^8.18.1"
670
+ },
671
+ peerDependencies: {
672
+ "drizzle-kit": "^0.31.2",
673
+ eventsource: "^4.0.0",
674
+ ws: "^8.0.0"
675
+ },
676
+ peerDependenciesMeta: {
677
+ "drizzle-kit": {
678
+ optional: true
679
+ },
680
+ eventsource: {
681
+ optional: true
682
+ },
683
+ ws: {
684
+ optional: true
685
+ }
686
+ },
687
+ stableVersion: "0.8.0"
688
+ };
689
+
690
+ // src/utils.ts
691
+ var VERSION = package_default.version;
692
+ function getEnvUniversal(key) {
693
+ if (typeof Deno !== "undefined") {
694
+ return Deno.env.get(key);
695
+ } else if (typeof process !== "undefined") {
696
+ return process.env[key];
697
+ }
698
+ }
699
+
700
+ // src/utils/env-vars.ts
701
+ var getLogLevel = () => _nullishCoalesce(getEnvUniversal("RIVET_LOG_LEVEL"), () => ( getEnvUniversal("LOG_LEVEL")));
702
+ var getLogTarget = () => getEnvUniversal("RIVET_LOG_TARGET") === "1";
703
+ var getLogTimestamp = () => getEnvUniversal("RIVET_LOG_TIMESTAMP") === "1";
704
+
705
+ // src/common/log.ts
706
+ var baseLogger;
707
+ var configuredLogLevel;
708
+ var loggerCache = /* @__PURE__ */ new Map();
709
+ var LogLevelSchema = _v4.z.enum([
710
+ "trace",
711
+ "debug",
712
+ "info",
713
+ "warn",
714
+ "error",
715
+ "fatal",
716
+ "silent"
717
+ ]);
718
+ function getPinoLevel(logLevel) {
719
+ if (logLevel) {
720
+ return logLevel;
721
+ }
722
+ if (configuredLogLevel) {
723
+ return configuredLogLevel;
724
+ }
725
+ const raw = (getLogLevel() || "warn").toString().toLowerCase();
726
+ const parsed = LogLevelSchema.safeParse(raw);
727
+ if (parsed.success) {
728
+ return parsed.data;
729
+ }
730
+ return "info";
731
+ }
732
+ function getIncludeTarget() {
733
+ return getLogTarget();
734
+ }
735
+ function makeDefaultLogger(logLevel) {
736
+ return _pino.pino.call(void 0,
737
+ {
738
+ level: getPinoLevel(logLevel),
739
+ messageKey: "msg",
740
+ // Do not include pid/hostname in output
741
+ base: {},
742
+ errorKey: "error",
743
+ // Keep the numeric level so the logfmt sink can match Pino's levels.
744
+ formatters: {
745
+ level(_label, number) {
746
+ return { level: number };
747
+ }
748
+ },
749
+ timestamp: getLogTimestamp() ? _pino.stdTimeFunctions.epochTime : false
750
+ },
751
+ createLogfmtDestination()
752
+ );
753
+ }
754
+ function configureDefaultLogger(logLevel) {
755
+ if (logLevel) {
756
+ configuredLogLevel = logLevel;
757
+ }
758
+ baseLogger = makeDefaultLogger(logLevel);
759
+ loggerCache.clear();
760
+ }
761
+ function getBaseLogger() {
762
+ if (!baseLogger) {
763
+ configureDefaultLogger();
764
+ }
765
+ return baseLogger;
766
+ }
767
+ function getLogger(name = "default") {
768
+ const cached = loggerCache.get(name);
769
+ if (cached) {
770
+ return cached;
771
+ }
772
+ const base = getBaseLogger();
773
+ const child = getIncludeTarget() ? base.child({ target: name }) : base;
774
+ loggerCache.set(name, child);
775
+ return child;
776
+ }
777
+ var PINO_LEVEL_LABELS = {
778
+ 10: "trace",
779
+ 20: "debug",
780
+ 30: "info",
781
+ 40: "warn",
782
+ 50: "error",
783
+ 60: "fatal"
784
+ };
785
+ function createLogfmtDestination() {
786
+ return {
787
+ write(msg) {
788
+ var _a;
789
+ const line = formatLogfmtLine(msg);
790
+ if (typeof process !== "undefined" && ((_a = process.stdout) == null ? void 0 : _a.write)) {
791
+ process.stdout.write(`${line}
792
+ `);
793
+ } else {
794
+ console.log(line);
506
795
  }
507
- const content = _nullishCoalesce(entry.content, () => ( new Uint8Array(0)));
508
- const end = offset + data.byteLength;
509
- const newSize = Math.max(content.byteLength, end);
510
- const buf = new Uint8Array(newSize);
511
- buf.set(content);
512
- buf.set(data, offset);
513
- const now = Date.now();
514
- await db2.execute(
515
- `UPDATE agent_os_fs_entries SET content = ?, size = ?, mtime_ms = ?, ctime_ms = ? WHERE path = ?`,
516
- buf,
517
- newSize,
518
- now,
519
- now,
520
- path
521
- );
522
796
  }
523
797
  };
524
- return backend;
798
+ }
799
+ function formatLogfmtLine(raw) {
800
+ let data;
801
+ try {
802
+ data = JSON.parse(raw);
803
+ } catch (e2) {
804
+ return raw.trimEnd();
805
+ }
806
+ const parts = [];
807
+ appendLogfmtEntry(parts, "level", formatPinoLevel(data.level));
808
+ if (data.time !== void 0) {
809
+ appendLogfmtEntry(parts, "ts", data.time);
810
+ }
811
+ for (const [key, value] of Object.entries(data)) {
812
+ if (key === "level" || key === "time") {
813
+ continue;
814
+ }
815
+ appendLogfmtEntry(parts, key, value);
816
+ }
817
+ return parts.join(" ");
818
+ }
819
+ function formatPinoLevel(level) {
820
+ if (typeof level === "number") {
821
+ return _nullishCoalesce(PINO_LEVEL_LABELS[level], () => ( level.toString()));
822
+ }
823
+ if (typeof level === "string") {
824
+ return level.toLowerCase();
825
+ }
826
+ return "info";
827
+ }
828
+ function appendLogfmtEntry(parts, key, value) {
829
+ const safeKey = key.replace(/[\s="]/g, "");
830
+ if (safeKey.length === 0) {
831
+ return;
832
+ }
833
+ parts.push(`${safeKey}=${formatLogfmtValue(value)}`);
834
+ }
835
+ function formatLogfmtValue(value) {
836
+ if (typeof value === "number" || typeof value === "boolean") {
837
+ return String(value);
838
+ }
839
+ if (value === null || value === void 0) {
840
+ return "null";
841
+ }
842
+ if (typeof value === "string") {
843
+ return quoteLogfmtString(value);
844
+ }
845
+ return quoteLogfmtString(JSON.stringify(value));
846
+ }
847
+ function quoteLogfmtString(value) {
848
+ if (!/[\s="]/.test(value)) {
849
+ return value;
850
+ }
851
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
525
852
  }
526
853
 
527
- // src/agent-os/actor/index.ts
528
- var _agentoscore = require('@rivet-dev/agent-os-core');
854
+ // src/actor/log.ts
855
+ function loggerWithoutContext() {
856
+ return getLogger("actor-runtime");
857
+ }
529
858
 
530
- // src/actor/config.ts
531
- var _v4 = require('zod/v4');
532
- var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
533
- var zFunction = () => _v4.z.custom((val) => typeof val === "function");
534
- var WorkflowInspectorConfigSchema = _v4.z.object({
535
- getHistory: zFunction(),
536
- onHistoryUpdated: zFunction().optional(),
537
- replayFromStep: zFunction().optional()
538
- });
539
- var RunInspectorConfigSchema = _v4.z.object({
540
- workflow: WorkflowInspectorConfigSchema.optional()
541
- }).optional();
542
- var RunConfigSchema = _v4.z.object({
543
- /** Display name for the actor in the Inspector UI. */
544
- name: _v4.z.string().optional(),
545
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
546
- icon: _v4.z.string().optional(),
547
- /** The run handler function. */
548
- run: zFunction(),
549
- /** Inspector integration for long-running run handlers. */
550
- inspector: RunInspectorConfigSchema.optional()
551
- });
552
- var zRunHandler = _v4.z.union([zFunction(), RunConfigSchema]).optional();
553
- var GlobalActorOptionsBaseSchema = _v4.z.object({
554
- /** Display name for the actor in the Inspector UI. */
555
- name: _v4.z.string().optional(),
556
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
557
- icon: _v4.z.string().optional(),
558
- /**
559
- * Can hibernate WebSockets for onWebSocket.
560
- *
561
- * WebSockets using actions/events are hibernatable by default.
562
- *
563
- * @experimental
564
- **/
565
- canHibernateWebSocket: _v4.z.union([_v4.z.boolean(), zFunction()]).default(false)
566
- }).strict();
567
- var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
568
- () => ({})
569
- );
570
- var InstanceActorOptionsBaseSchema = _v4.z.object({
571
- createVarsTimeout: _v4.z.number().positive().default(5e3),
572
- createConnStateTimeout: _v4.z.number().positive().default(5e3),
573
- onBeforeConnectTimeout: _v4.z.number().positive().default(5e3),
574
- onConnectTimeout: _v4.z.number().positive().default(5e3),
575
- onMigrateTimeout: _v4.z.number().positive().default(3e4),
576
- sleepGracePeriod: _v4.z.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
577
- /** @deprecated `onDestroyTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
578
- onDestroyTimeout: _v4.z.number().positive().optional(),
579
- /** @deprecated `waitUntilTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
580
- waitUntilTimeout: _v4.z.number().positive().optional(),
581
- stateSaveInterval: _v4.z.number().positive().default(1e3),
582
- actionTimeout: _v4.z.number().positive().default(6e4),
583
- connectionLivenessTimeout: _v4.z.number().positive().default(2500),
584
- connectionLivenessInterval: _v4.z.number().positive().default(5e3),
585
- /** @deprecated Use `c.keepAwake(promise)` to scope keep-awake to a specific operation, or keep `noSleep` for actors that must stay awake indefinitely. Will be removed in 2.2.0. */
586
- noSleep: _v4.z.boolean().default(false),
587
- sleepTimeout: _v4.z.number().positive().default(3e4),
588
- maxQueueSize: _v4.z.number().positive().default(1e3),
589
- maxQueueMessageSize: _v4.z.number().positive().default(64 * 1024),
590
- /** Override RivetKit's workflow preload budget for this actor. Set to 0 to disable workflow preloading. */
591
- preloadMaxWorkflowBytes: _v4.z.number().nonnegative().optional(),
592
- /** Override RivetKit's connections preload budget for this actor. Set to 0 to disable connections preloading. */
593
- preloadMaxConnectionsBytes: _v4.z.number().nonnegative().optional()
594
- }).strict();
595
- var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
596
- var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
597
- InstanceActorOptionsBaseSchema.shape
598
- ).strict().prefault(() => ({}));
599
- var ActorConfigSchema = _v4.z.object({
600
- onCreate: zFunction().optional(),
601
- onDestroy: zFunction().optional(),
602
- onMigrate: zFunction().optional(),
603
- onWake: zFunction().optional(),
604
- onSleep: zFunction().optional(),
605
- run: zRunHandler,
606
- onStateChange: zFunction().optional(),
607
- onBeforeConnect: zFunction().optional(),
608
- onConnect: zFunction().optional(),
609
- onDisconnect: zFunction().optional(),
610
- onBeforeActionResponse: zFunction().optional(),
611
- onRequest: zFunction().optional(),
612
- onWebSocket: zFunction().optional(),
613
- actions: _v4.z.record(_v4.z.string(), zFunction()).default(() => ({})),
614
- actionInputSchemas: _v4.z.record(_v4.z.string(), _v4.z.any()).optional(),
615
- connParamsSchema: _v4.z.any().optional(),
616
- events: _v4.z.record(_v4.z.string(), _v4.z.any()).optional(),
617
- queues: _v4.z.record(_v4.z.string(), _v4.z.any()).optional(),
618
- state: _v4.z.any().optional(),
619
- createState: zFunction().optional(),
620
- connState: _v4.z.any().optional(),
621
- createConnState: zFunction().optional(),
622
- vars: _v4.z.any().optional(),
623
- db: _v4.z.any().optional(),
624
- createVars: zFunction().optional(),
625
- options: ActorOptionsSchema
626
- }).strict().refine(
627
- (data) => !(data.state !== void 0 && data.createState !== void 0),
628
- {
629
- message: "Cannot define both 'state' and 'createState'",
630
- path: ["state"]
859
+ // src/actor/definition.ts
860
+ var warnedDeprecatedOptionKeys = /* @__PURE__ */ new Set();
861
+ var DEPRECATED_OPTION_MESSAGES = {
862
+ onDestroyTimeout: "Configure `sleepGracePeriod` instead, which bounds the entire graceful shutdown window for both sleep and destroy.",
863
+ waitUntilTimeout: "Configure `sleepGracePeriod` instead, which bounds the entire graceful shutdown window for both sleep and destroy.",
864
+ preloadMaxWorkflowBytes: "Internal storage moved to SQLite and no longer uses KV preloading.",
865
+ preloadMaxConnectionsBytes: "Internal storage moved to SQLite and no longer uses KV preloading."
866
+ };
867
+ function warnDeprecatedOptionKeys(options) {
868
+ if (!options || typeof options !== "object") return;
869
+ const opts = options;
870
+ for (const [key, detail] of Object.entries(DEPRECATED_OPTION_MESSAGES)) {
871
+ if (opts[key] !== void 0 && !warnedDeprecatedOptionKeys.has(key)) {
872
+ warnedDeprecatedOptionKeys.add(key);
873
+ loggerWithoutContext().warn({
874
+ msg: `actor option \`${key}\` is deprecated and is now ignored. ${detail} Will be removed in 2.2.0.`
875
+ });
876
+ }
631
877
  }
632
- ).refine(
633
- (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
634
- {
635
- message: "Cannot define both 'connState' and 'createConnState'",
636
- path: ["connState"]
878
+ }
879
+ var ActorDefinition = class {
880
+ #config;
881
+ constructor(config) {
882
+ this.#config = config;
637
883
  }
638
- ).refine(
639
- (data) => !(data.vars !== void 0 && data.createVars !== void 0),
640
- {
641
- message: "Cannot define both 'vars' and 'createVars'",
642
- path: ["vars"]
884
+ get config() {
885
+ return this.#config;
886
+ }
887
+ };
888
+ function actor(input) {
889
+ warnDeprecatedOptionKeys(
890
+ input == null ? void 0 : input.options
891
+ );
892
+ const config = ActorConfigSchema.parse(input);
893
+ flattenActionHandlers(config.actions);
894
+ flattenActionInputSchemas(config.actions, config.actionInputSchemas);
895
+ return new ActorDefinition(config);
896
+ }
897
+
898
+ // src/actor/schema.ts
899
+ function event(options) {
900
+ return _nullishCoalesce(options, () => ( {}));
901
+ }
902
+
903
+ // src/common/database/shared.ts
904
+ var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
905
+ function isManualTransactionControl(query) {
906
+ return /^\s*(?:BEGIN|SAVEPOINT|COMMIT|END|ROLLBACK)\b/i.test(query);
907
+ }
908
+ function validateTransactionTimeout(timeout) {
909
+ if (timeout !== void 0 && (!Number.isFinite(timeout) || timeout <= 0)) {
910
+ throw new Error(
911
+ "db.transaction() timeout must be a positive finite number of milliseconds"
912
+ );
913
+ }
914
+ }
915
+ function validateTransactionName(name) {
916
+ if (name === void 0) {
917
+ return;
918
+ }
919
+ if (name.length === 0) {
920
+ throw new Error("db.transaction() name must not be empty");
921
+ }
922
+ }
923
+ function isSqliteBindingValue(value) {
924
+ if (value === null || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || value instanceof Uint8Array) {
925
+ return true;
926
+ }
927
+ if (Array.isArray(value)) {
928
+ return value.every((item) => typeof item === "number");
929
+ }
930
+ return false;
931
+ }
932
+ function isPlainObject(value) {
933
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
934
+ return false;
935
+ }
936
+ return Object.getPrototypeOf(value) === Object.prototype;
937
+ }
938
+ function isSqliteBindingObject(value) {
939
+ if (!isPlainObject(value)) {
940
+ return false;
941
+ }
942
+ return Object.values(value).every((entry) => isSqliteBindingValue(entry));
943
+ }
944
+ function toSqliteBindings(input) {
945
+ if (Array.isArray(input)) {
946
+ for (const value of input) {
947
+ if (!isSqliteBindingValue(value)) {
948
+ throw new Error(
949
+ `unsupported sqlite binding type: ${typeof value}`
950
+ );
951
+ }
952
+ }
953
+ return input;
954
+ }
955
+ if (isSqliteBindingObject(input)) {
956
+ return input;
957
+ }
958
+ throw new Error("unsupported sqlite binding collection");
959
+ }
960
+
961
+ // src/common/database/mod.ts
962
+ var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
963
+ var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
964
+ function hasMultipleStatements(query) {
965
+ const trimmed = query.trim().replace(/;+$/, "").trimEnd();
966
+ return trimmed.includes(";");
967
+ }
968
+ function db({
969
+ onMigrate,
970
+ warnOnManualTransactions = true,
971
+ profiling
972
+ } = {}) {
973
+ const provider = {
974
+ sqliteProfiling: profiling,
975
+ createClient: async (ctx) => {
976
+ const nativeDatabaseProvider = ctx.nativeDatabaseProvider;
977
+ if (!nativeDatabaseProvider) {
978
+ throw new Error(
979
+ "native SQLite is required, but the current runtime did not provide a native database provider"
980
+ );
981
+ }
982
+ const db2 = await nativeDatabaseProvider.open(ctx.actorId);
983
+ let closed = false;
984
+ let manualTransactionWarned = false;
985
+ const ensureOpen = () => {
986
+ if (closed) {
987
+ throw new Error(
988
+ "Database is closed. This usually means a background timer (setInterval, setTimeout) or a stray promise is still running after the actor stopped. Use c.abortSignal to clean up timers before the actor shuts down."
989
+ );
990
+ }
991
+ };
992
+ const createClient = (target, transactionScoped = false, stateTransactionContext) => {
993
+ const client2 = {
994
+ execute: async (query, ...args) => {
995
+ var _a, _b, _c, _d;
996
+ ensureOpen();
997
+ if (!transactionScoped && warnOnManualTransactions && !manualTransactionWarned && !hasMultipleStatements(query) && isManualTransactionControl(query)) {
998
+ manualTransactionWarned = true;
999
+ getLogger("database").warn(
1000
+ { actorId: ctx.actorId },
1001
+ "Manual cross-call SQLite transactions can interleave with other actor work. Use db.transaction() for coordinated transactions. Set warnOnManualTransactions: false in your db(...) configuration to disable this warning."
1002
+ );
1003
+ }
1004
+ const kvReadsBefore = _nullishCoalesce(((_a = ctx.metrics) == null ? void 0 : _a.totalKvReads), () => ( 0));
1005
+ const kvWritesBefore = _nullishCoalesce(((_b = ctx.metrics) == null ? void 0 : _b.totalKvWrites), () => ( 0));
1006
+ const start = performance.now();
1007
+ try {
1008
+ if (args.length > 0) {
1009
+ const bindings = args.length === 1 && isSqliteBindingObject(args[0]) ? toSqliteBindings(args[0]) : toSqliteBindings(args);
1010
+ const { rows, columns } = await target.execute(
1011
+ query,
1012
+ bindings
1013
+ );
1014
+ return rows.map(
1015
+ (row) => rowToObject(row, columns)
1016
+ );
1017
+ }
1018
+ if (!hasMultipleStatements(query)) {
1019
+ const { rows, columns } = await target.execute(
1020
+ query,
1021
+ void 0
1022
+ );
1023
+ return rows.map(
1024
+ (row) => rowToObject(row, columns)
1025
+ );
1026
+ }
1027
+ return await execMultiStatement(
1028
+ target,
1029
+ query
1030
+ );
1031
+ } finally {
1032
+ const durationMs = performance.now() - start;
1033
+ (_c = ctx.metrics) == null ? void 0 : _c.trackSql(query, durationMs);
1034
+ if (ctx.metrics) {
1035
+ const kvReads = ctx.metrics.totalKvReads - kvReadsBefore;
1036
+ const kvWrites = ctx.metrics.totalKvWrites - kvWritesBefore;
1037
+ (_d = ctx.log) == null ? void 0 : _d.debug({
1038
+ msg: "sql query",
1039
+ query: query.slice(0, 120),
1040
+ durationMs,
1041
+ kvReads,
1042
+ kvWrites
1043
+ });
1044
+ }
1045
+ }
1046
+ },
1047
+ transaction: async (callback, options) => {
1048
+ var _a, _b;
1049
+ validateTransactionTimeout(options == null ? void 0 : options.timeout);
1050
+ validateTransactionName(options == null ? void 0 : options.name);
1051
+ if (transactionScoped && ((_a = options == null ? void 0 : options.experimental) == null ? void 0 : _a.includeState)) {
1052
+ throw new Error(
1053
+ "experimental.includeState is not supported for nested transactions"
1054
+ );
1055
+ }
1056
+ const includeState = ((_b = options == null ? void 0 : options.experimental) == null ? void 0 : _b.includeState) === true;
1057
+ const stateScope = includeState && stateTransactionContext ? await stateTransactionContext.enter() : void 0;
1058
+ try {
1059
+ const transaction = includeState ? await (() => {
1060
+ const beginStateTransaction = ctx.nativeDatabaseProvider && nativeStateTransactionOpeners.get(
1061
+ ctx.nativeDatabaseProvider
1062
+ );
1063
+ if (!beginStateTransaction) {
1064
+ throw new Error(
1065
+ "experimental.includeState is only supported by RivetKit's embedded database provider"
1066
+ );
1067
+ }
1068
+ return beginStateTransaction(
1069
+ options == null ? void 0 : options.timeout,
1070
+ stateScope
1071
+ );
1072
+ })() : await db2.beginTransaction(
1073
+ options == null ? void 0 : options.timeout,
1074
+ options == null ? void 0 : options.name
1075
+ );
1076
+ const tx = createClient(transaction, true);
1077
+ try {
1078
+ const result = await callback(tx);
1079
+ await transaction.commit();
1080
+ return result;
1081
+ } catch (error) {
1082
+ try {
1083
+ await transaction.rollback();
1084
+ } catch (e3) {
1085
+ }
1086
+ throw error;
1087
+ }
1088
+ } finally {
1089
+ if (stateScope !== void 0) {
1090
+ stateTransactionContext == null ? void 0 : stateTransactionContext.exit(stateScope);
1091
+ }
1092
+ }
1093
+ },
1094
+ close: async () => {
1095
+ if (!closed) {
1096
+ closed = true;
1097
+ await db2.close();
1098
+ }
1099
+ },
1100
+ nativeMetrics: () => {
1101
+ var _a;
1102
+ return _nullishCoalesce(((_a = db2.nativeMetrics) == null ? void 0 : _a.call(db2)), () => ( null));
1103
+ }
1104
+ };
1105
+ if (!transactionScoped) {
1106
+ nativeStateTransactionClientBinders.set(
1107
+ client2,
1108
+ (context) => createClient(target, false, context)
1109
+ );
1110
+ }
1111
+ return client2;
1112
+ };
1113
+ const client = createClient(db2);
1114
+ return client;
1115
+ },
1116
+ onMigrate: async (client) => {
1117
+ if (onMigrate) {
1118
+ await withMigrationSavepoint(
1119
+ client,
1120
+ (leased) => onMigrate(leased)
1121
+ );
1122
+ }
1123
+ }
1124
+ };
1125
+ return provider;
1126
+ }
1127
+ function rowToObject(row, columns) {
1128
+ const rowObj = {};
1129
+ for (let i = 0; i < columns.length; i++) {
1130
+ rowObj[columns[i]] = row[i];
643
1131
  }
1132
+ return rowObj;
1133
+ }
1134
+ async function execMultiStatement(db2, query) {
1135
+ const results = [];
1136
+ let columnNames = null;
1137
+ await db2.exec(query, (row, columns) => {
1138
+ if (!columnNames) {
1139
+ columnNames = columns;
1140
+ }
1141
+ results.push(rowToObject(row, columnNames));
1142
+ });
1143
+ return results;
1144
+ }
1145
+ async function withMigrationSavepoint(client, callback) {
1146
+ return await client.transaction(
1147
+ async (transaction) => {
1148
+ await transaction.execute("SAVEPOINT __rivet_on_migrate");
1149
+ try {
1150
+ const result = await callback(transaction);
1151
+ await transaction.execute(
1152
+ "RELEASE SAVEPOINT __rivet_on_migrate"
1153
+ );
1154
+ return result;
1155
+ } catch (error) {
1156
+ try {
1157
+ await transaction.execute(
1158
+ "ROLLBACK TO SAVEPOINT __rivet_on_migrate"
1159
+ );
1160
+ } finally {
1161
+ await transaction.execute(
1162
+ "RELEASE SAVEPOINT __rivet_on_migrate"
1163
+ );
1164
+ }
1165
+ throw error;
1166
+ }
1167
+ },
1168
+ {
1169
+ name: "rivetkit-migration",
1170
+ timeout: MIGRATION_TRANSACTION_TIMEOUT_MS
1171
+ }
1172
+ );
1173
+ }
1174
+
1175
+ // src/agent-os/config.ts
1176
+
1177
+ var zFunction2 = () => _v4.z.custom((val) => typeof val === "function");
1178
+ var AgentOsOptionsSchema = _v4.z.custom(
1179
+ (val) => typeof val === "object" && val !== null
644
1180
  );
645
- var DocActorOptionsSchema = _v4.z.object({
646
- name: _v4.z.string().optional().describe("Display name for the actor in the Inspector UI."),
647
- icon: _v4.z.string().optional().describe(
648
- "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
649
- ),
650
- createVarsTimeout: _v4.z.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
651
- createConnStateTimeout: _v4.z.number().optional().describe(
652
- "Timeout in ms for createConnState handler. Default: 5000"
653
- ),
654
- onMigrateTimeout: _v4.z.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
655
- onBeforeConnectTimeout: _v4.z.number().optional().describe(
656
- "Timeout in ms for onBeforeConnect handler. Default: 5000"
657
- ),
658
- onConnectTimeout: _v4.z.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
659
- sleepGracePeriod: _v4.z.number().optional().describe(
660
- `Max time in ms for the graceful shutdown window. Covers lifecycle hooks (onSleep, onDestroy), the run handler abort wait, async raw WebSocket handlers, disconnect callbacks, and final state serialization. Default: ${DEFAULT_SLEEP_GRACE_PERIOD}.`
661
- ),
662
- onDestroyTimeout: _v4.z.number().optional().describe(
663
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
664
- ),
665
- waitUntilTimeout: _v4.z.number().optional().describe(
666
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
667
- ),
668
- stateSaveInterval: _v4.z.number().optional().describe(
669
- "Interval in ms between automatic state saves. Default: 1000"
670
- ),
671
- actionTimeout: _v4.z.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
672
- connectionLivenessTimeout: _v4.z.number().optional().describe(
673
- "Timeout in ms for connection liveness checks. Default: 2500"
674
- ),
675
- connectionLivenessInterval: _v4.z.number().optional().describe(
676
- "Interval in ms between connection liveness checks. Default: 5000"
677
- ),
678
- noSleep: _v4.z.boolean().optional().describe(
679
- "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
680
- ),
681
- sleepTimeout: _v4.z.number().optional().describe(
682
- "Time in ms of inactivity before the actor sleeps. Default: 30000"
683
- ),
684
- maxQueueSize: _v4.z.number().optional().describe(
685
- "Maximum number of queue messages before rejecting new messages. Default: 1000"
686
- ),
687
- maxQueueMessageSize: _v4.z.number().optional().describe(
688
- "Maximum size of each queue message in bytes. Default: 65536"
689
- ),
690
- canHibernateWebSocket: _v4.z.boolean().optional().describe(
691
- "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
692
- ),
693
- preloadMaxWorkflowBytes: _v4.z.number().optional().describe(
694
- "Override RivetKit's workflow preload budget for this actor. Set to 0 to disable workflow preloading."
695
- ),
696
- preloadMaxConnectionsBytes: _v4.z.number().optional().describe(
697
- "Override RivetKit's connections preload budget for this actor. Set to 0 to disable connections preloading."
698
- )
699
- }).describe("Actor options for timeouts and behavior configuration.");
700
- var DocActorConfigSchema = _v4.z.object({
701
- state: _v4.z.unknown().optional().describe(
702
- "Initial state value for the actor. Cannot be used with createState."
703
- ),
704
- createState: _v4.z.unknown().optional().describe(
705
- "Function to create initial state. Receives context and input. Cannot be used with state."
706
- ),
707
- connState: _v4.z.unknown().optional().describe(
708
- "Initial connection state value. Cannot be used with createConnState."
709
- ),
710
- createConnState: _v4.z.unknown().optional().describe(
711
- "Function to create connection state. Receives context and connection params. Cannot be used with connState."
712
- ),
713
- vars: _v4.z.unknown().optional().describe(
714
- "Initial ephemeral variables value. Cannot be used with createVars."
715
- ),
716
- createVars: _v4.z.unknown().optional().describe(
717
- "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
718
- ),
719
- db: _v4.z.unknown().optional().describe("Database provider instance for the actor."),
720
- onCreate: _v4.z.unknown().optional().describe(
721
- "Called when the actor is first initialized. Use to initialize state."
722
- ),
723
- onDestroy: _v4.z.unknown().optional().describe("Called when the actor is destroyed."),
724
- onMigrate: _v4.z.unknown().optional().describe(
725
- "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
726
- ),
727
- onWake: _v4.z.unknown().optional().describe(
728
- "Called when the actor wakes up and is ready to receive connections and actions."
729
- ),
730
- onSleep: _v4.z.unknown().optional().describe(
731
- "Called when the actor is stopping or sleeping. Use to clean up resources."
732
- ),
733
- run: _v4.z.unknown().optional().describe(
734
- "Called after actor starts. Does not block startup. Use for background tasks like queue processing or tick loops. If it exits, the actor follows the normal idle sleep timeout once idle. If it throws, the actor logs the error and then follows the normal idle sleep timeout once idle."
735
- ),
736
- onStateChange: _v4.z.unknown().optional().describe(
737
- "Called when the actor's state changes. State changes within this hook won't trigger recursion."
738
- ),
739
- onBeforeConnect: _v4.z.unknown().optional().describe(
740
- "Called before a client connects. Throw an error to reject the connection."
741
- ),
742
- onConnect: _v4.z.unknown().optional().describe("Called when a client successfully connects."),
743
- onDisconnect: _v4.z.unknown().optional().describe("Called when a client disconnects."),
744
- onBeforeActionResponse: _v4.z.unknown().optional().describe(
745
- "Called before sending an action response. Use to transform output."
746
- ),
747
- onRequest: _v4.z.unknown().optional().describe(
748
- "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
749
- ),
750
- onWebSocket: _v4.z.unknown().optional().describe(
751
- "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
752
- ),
753
- actions: _v4.z.record(_v4.z.string(), _v4.z.unknown()).optional().describe(
754
- "Map of action name to handler function. Defaults to an empty object."
755
- ),
756
- actionInputSchemas: _v4.z.record(_v4.z.string(), _v4.z.unknown()).optional().describe(
757
- "Optional schema map for validating action argument tuples in native runtimes."
758
- ),
759
- connParamsSchema: _v4.z.unknown().optional().describe(
760
- "Optional schema for validating connection params in native runtimes."
761
- ),
762
- events: _v4.z.record(_v4.z.string(), _v4.z.unknown()).optional().describe("Map of event names to schemas."),
763
- queues: _v4.z.record(_v4.z.string(), _v4.z.unknown()).optional().describe("Map of queue names to schemas."),
764
- options: DocActorOptionsSchema.optional()
765
- }).describe("Actor configuration passed to the actor() function.");
1181
+ var agentOsActorConfigSchema = _v4.z.object({
1182
+ options: AgentOsOptionsSchema.optional(),
1183
+ preview: _v4.z.object({
1184
+ defaultExpiresInSeconds: _v4.z.number().positive().default(3600),
1185
+ maxExpiresInSeconds: _v4.z.number().positive().default(86400)
1186
+ }).strict().prefault(() => ({})),
1187
+ onBeforeConnect: zFunction2().optional(),
1188
+ onSessionEvent: zFunction2().optional(),
1189
+ onPermissionRequest: zFunction2().optional()
1190
+ }).strict();
766
1191
 
767
- // src/common/log.ts
1192
+ // src/agent-os/actor/db.ts
1193
+ async function migrateAgentOsTables(db2) {
1194
+ await db2.execute(`
1195
+ CREATE TABLE IF NOT EXISTS agent_os_preview_tokens (
1196
+ token TEXT PRIMARY KEY,
1197
+ port INTEGER NOT NULL,
1198
+ created_at INTEGER NOT NULL,
1199
+ expires_at INTEGER NOT NULL
1200
+ );
1201
+
1202
+ CREATE INDEX IF NOT EXISTS idx_preview_tokens_expires_at
1203
+ ON agent_os_preview_tokens(expires_at);
1204
+
1205
+ CREATE TABLE IF NOT EXISTS agent_os_fs_entries (
1206
+ path TEXT PRIMARY KEY,
1207
+ is_directory INTEGER NOT NULL DEFAULT 0,
1208
+ content BLOB,
1209
+ mode INTEGER NOT NULL DEFAULT 33188,
1210
+ uid INTEGER NOT NULL DEFAULT 0,
1211
+ gid INTEGER NOT NULL DEFAULT 0,
1212
+ size INTEGER NOT NULL DEFAULT 0,
1213
+ atime_ms INTEGER NOT NULL,
1214
+ mtime_ms INTEGER NOT NULL,
1215
+ ctime_ms INTEGER NOT NULL,
1216
+ birthtime_ms INTEGER NOT NULL,
1217
+ symlink_target TEXT,
1218
+ nlink INTEGER NOT NULL DEFAULT 1
1219
+ );
768
1220
 
1221
+ CREATE INDEX IF NOT EXISTS idx_fs_entries_parent
1222
+ ON agent_os_fs_entries(path);
769
1223
 
1224
+ CREATE TABLE IF NOT EXISTS agent_os_sessions (
1225
+ session_id TEXT PRIMARY KEY,
1226
+ agent_type TEXT NOT NULL,
1227
+ capabilities TEXT NOT NULL,
1228
+ agent_info TEXT,
1229
+ created_at INTEGER NOT NULL
1230
+ );
770
1231
 
771
- var _pino = require('pino');
1232
+ CREATE TABLE IF NOT EXISTS agent_os_session_events (
1233
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1234
+ session_id TEXT NOT NULL,
1235
+ seq INTEGER NOT NULL,
1236
+ event TEXT NOT NULL,
1237
+ created_at INTEGER NOT NULL,
1238
+ FOREIGN KEY (session_id) REFERENCES agent_os_sessions(session_id) ON DELETE CASCADE
1239
+ );
1240
+
1241
+ CREATE INDEX IF NOT EXISTS idx_session_events_session_seq
1242
+ ON agent_os_session_events(session_id, seq);
1243
+ `);
1244
+ }
1245
+
1246
+ // src/agent-os/actor/filesystem.ts
1247
+ function buildFilesystemActions(config) {
1248
+ return {
1249
+ readFile: async (c, path) => {
1250
+ const agentOs2 = await ensureVm(c, config);
1251
+ return agentOs2.readFile(path);
1252
+ },
1253
+ writeFile: async (c, path, content) => {
1254
+ const agentOs2 = await ensureVm(c, config);
1255
+ await agentOs2.writeFile(path, content);
1256
+ },
1257
+ readFiles: async (c, paths) => {
1258
+ const agentOs2 = await ensureVm(c, config);
1259
+ return agentOs2.readFiles(paths);
1260
+ },
1261
+ writeFiles: async (c, entries) => {
1262
+ const agentOs2 = await ensureVm(c, config);
1263
+ return agentOs2.writeFiles(entries);
1264
+ },
1265
+ mkdir: async (c, path, options) => {
1266
+ const agentOs2 = await ensureVm(c, config);
1267
+ await agentOs2.mkdir(path, options);
1268
+ },
1269
+ readdir: async (c, path) => {
1270
+ const agentOs2 = await ensureVm(c, config);
1271
+ return agentOs2.readdir(path);
1272
+ },
1273
+ readdirRecursive: async (c, path, options) => {
1274
+ const agentOs2 = await ensureVm(c, config);
1275
+ return agentOs2.readdirRecursive(path, options);
1276
+ },
1277
+ stat: async (c, path) => {
1278
+ const agentOs2 = await ensureVm(c, config);
1279
+ return agentOs2.stat(path);
1280
+ },
1281
+ exists: async (c, path) => {
1282
+ const agentOs2 = await ensureVm(c, config);
1283
+ return agentOs2.exists(path);
1284
+ },
1285
+ move: async (c, from, to) => {
1286
+ const agentOs2 = await ensureVm(c, config);
1287
+ await agentOs2.move(from, to);
1288
+ },
1289
+ deleteFile: async (c, path, options) => {
1290
+ const agentOs2 = await ensureVm(c, config);
1291
+ await agentOs2.delete(path, options);
1292
+ },
1293
+ // TODO: mountFs and unmountFs are not exposed as actor actions because
1294
+ // filesystem drivers (VirtualFileSystem) are not serializable over the
1295
+ // network. Mount filesystems via the `options.mounts` config in agentOs()
1296
+ // instead. See: https://github.com/rivet-dev/rivet/issues/XXXX
1297
+ listAgents: async (c) => {
1298
+ const agentOs2 = await ensureVm(c, config);
1299
+ return agentOs2.listAgents();
1300
+ }
1301
+ };
1302
+ }
772
1303
 
1304
+ // src/agent-os/actor/network.ts
1305
+ function buildNetworkActions(config) {
1306
+ return {
1307
+ vmFetch: async (c, port, url, options) => {
1308
+ const agentOs2 = await ensureVm(c, config);
1309
+ const headers = new Headers(options == null ? void 0 : options.headers);
1310
+ const request = new Request(url, {
1311
+ method: _nullishCoalesce((options == null ? void 0 : options.method), () => ( "GET")),
1312
+ headers,
1313
+ body: _nullishCoalesce((options == null ? void 0 : options.body), () => ( null))
1314
+ });
1315
+ const response = await agentOs2.fetch(port, request);
1316
+ const responseHeaders = {};
1317
+ response.headers.forEach((value, key) => {
1318
+ responseHeaders[key] = value;
1319
+ });
1320
+ const body = new Uint8Array(await response.arrayBuffer());
1321
+ return {
1322
+ status: response.status,
1323
+ statusText: response.statusText,
1324
+ headers: responseHeaders,
1325
+ body
1326
+ };
1327
+ }
1328
+ };
1329
+ }
773
1330
 
774
- // src/actor/errors.ts
775
- function isTypedErrorTag(value) {
776
- return value === "ActorError" || value === "RivetError";
1331
+ // src/agent-os/actor/preview.ts
1332
+ var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto);
1333
+ function generateToken() {
1334
+ const bytes = _crypto2.default.randomBytes(32);
1335
+ const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
1336
+ let token = "";
1337
+ for (let i = 0; i < 32; i++) {
1338
+ token += alphabet[bytes[i] % alphabet.length];
1339
+ }
1340
+ return token;
777
1341
  }
778
- function isRivetErrorLike(error) {
779
- return typeof error === "object" && error !== null && "group" in error && typeof error.group === "string" && "code" in error && typeof error.code === "string" && "message" in error && typeof error.message === "string" && (!("__type" in error) || isTypedErrorTag(error.__type));
1342
+ var CORS_HEADERS = {
1343
+ "Access-Control-Allow-Origin": "*",
1344
+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
1345
+ "Access-Control-Allow-Headers": "*"
1346
+ };
1347
+ function addCorsHeaders(response) {
1348
+ const headers = new Headers(response.headers);
1349
+ for (const [key, value] of Object.entries(CORS_HEADERS)) {
1350
+ headers.set(key, value);
1351
+ }
1352
+ return new Response(response.body, {
1353
+ status: response.status,
1354
+ statusText: response.statusText,
1355
+ headers
1356
+ });
780
1357
  }
781
- function isRivetErrorCode(error, group, code) {
782
- return isRivetErrorLike(error) && error.group === group && error.code === code;
1358
+ function buildOnRequestHandler(config) {
1359
+ return async (c, request) => {
1360
+ var _a;
1361
+ const url = new URL(request.url);
1362
+ const pathname = url.pathname;
1363
+ const match = pathname.match(/^\/fetch\/([a-z0-9]+)(\/.*)?$/);
1364
+ if (!match) {
1365
+ return new Response("Not Found", { status: 404 });
1366
+ }
1367
+ if (request.method === "OPTIONS") {
1368
+ return new Response(null, { status: 204, headers: CORS_HEADERS });
1369
+ }
1370
+ const token = match[1];
1371
+ const remainingPath = _nullishCoalesce(match[2], () => ( "/"));
1372
+ const now = Date.now();
1373
+ const rows = await c.db.execute(
1374
+ `SELECT port FROM agent_os_preview_tokens WHERE token = ? AND expires_at > ?`,
1375
+ token,
1376
+ now
1377
+ );
1378
+ if (rows.length === 0) {
1379
+ c.log.warn({ msg: "agent-os preview auth failed", token });
1380
+ return addCorsHeaders(new Response("Forbidden", { status: 403 }));
1381
+ }
1382
+ const port = (_a = rows[0]) == null ? void 0 : _a.port;
1383
+ const agentOs2 = await ensureVm(
1384
+ c,
1385
+ config
1386
+ );
1387
+ const vmUrl = `http://localhost:${port}${remainingPath}${url.search}`;
1388
+ const vmRequest = new Request(vmUrl, {
1389
+ method: request.method,
1390
+ headers: request.headers,
1391
+ body: request.body,
1392
+ duplex: "half"
1393
+ });
1394
+ const vmResponse = await agentOs2.fetch(port, vmRequest);
1395
+ c.log.info({
1396
+ msg: "agent-os preview request proxied",
1397
+ port,
1398
+ method: request.method,
1399
+ path: remainingPath,
1400
+ status: vmResponse.status
1401
+ });
1402
+ return addCorsHeaders(vmResponse);
1403
+ };
783
1404
  }
784
-
785
- // package.json
786
- var package_default = {
787
- name: "rivetkit",
788
- version: "0.0.0-main.41efcce",
789
- description: "Lightweight libraries for building stateful actors on edge platforms",
790
- license: "Apache-2.0",
791
- keywords: [
792
- "rivetkit",
793
- "stateful",
794
- "serverless",
795
- "actors",
796
- "agents",
797
- "realtime",
798
- "websocket",
799
- "actors",
800
- "framework"
801
- ],
802
- files: [
803
- "dist",
804
- "schemas",
805
- "src",
806
- "package.json"
807
- ],
808
- type: "module",
809
- exports: {
810
- ".": {
811
- import: {
812
- types: "./dist/tsup/mod.d.ts",
813
- default: "./dist/tsup/mod.js"
814
- },
815
- require: {
816
- types: "./dist/tsup/mod.d.cts",
817
- default: "./dist/tsup/mod.cjs"
818
- }
819
- },
820
- "./workflow": {
821
- import: {
822
- types: "./dist/tsup/workflow/mod.d.ts",
823
- default: "./dist/tsup/workflow/mod.js"
824
- },
825
- require: {
826
- types: "./dist/tsup/workflow/mod.d.cts",
827
- default: "./dist/tsup/workflow/mod.cjs"
828
- }
829
- },
830
- "./test": {
831
- import: {
832
- types: "./dist/tsup/test/mod.d.ts",
833
- default: "./dist/tsup/test/mod.js"
834
- },
835
- require: {
836
- types: "./dist/tsup/test/mod.d.cts",
837
- default: "./dist/tsup/test/mod.cjs"
838
- }
839
- },
840
- "./db": {
841
- import: {
842
- types: "./dist/tsup/db/mod.d.ts",
843
- default: "./dist/tsup/db/mod.js"
844
- },
845
- require: {
846
- types: "./dist/tsup/db/mod.d.cts",
847
- default: "./dist/tsup/db/mod.cjs"
1405
+ function buildPreviewActions(config) {
1406
+ return {
1407
+ createSignedPreviewUrl: async (c, port, expiresInSeconds) => {
1408
+ await ensureVm(c, config);
1409
+ const effectiveExpires = _nullishCoalesce(expiresInSeconds, () => ( config.preview.defaultExpiresInSeconds));
1410
+ const maxExpires = config.preview.maxExpiresInSeconds;
1411
+ if (effectiveExpires < 1 || effectiveExpires > maxExpires) {
1412
+ throw new Error(
1413
+ `expiresInSeconds must be between 1 and ${maxExpires}`
1414
+ );
848
1415
  }
1416
+ const token = generateToken();
1417
+ const now = Date.now();
1418
+ const expiresAt = now + effectiveExpires * 1e3;
1419
+ await c.db.execute(
1420
+ `INSERT INTO agent_os_preview_tokens (token, port, created_at, expires_at)
1421
+ VALUES (?, ?, ?, ?)`,
1422
+ token,
1423
+ port,
1424
+ now,
1425
+ expiresAt
1426
+ );
1427
+ await c.db.execute(
1428
+ `DELETE FROM agent_os_preview_tokens WHERE expires_at <= ?`,
1429
+ now
1430
+ );
1431
+ const path = `/request/fetch/${token}`;
1432
+ c.log.info({
1433
+ msg: "agent-os preview token created",
1434
+ port,
1435
+ expiresInSeconds: effectiveExpires
1436
+ });
1437
+ return { path, token, port, expiresAt };
849
1438
  },
850
- "./db/drizzle": {
851
- import: {
852
- types: "./dist/tsup/db/drizzle.d.ts",
853
- default: "./dist/tsup/db/drizzle.js"
854
- },
855
- require: {
856
- types: "./dist/tsup/db/drizzle.d.cts",
857
- default: "./dist/tsup/db/drizzle.cjs"
858
- }
1439
+ expireSignedPreviewUrl: async (c, token) => {
1440
+ await c.db.execute(
1441
+ `DELETE FROM agent_os_preview_tokens WHERE token = ?`,
1442
+ token
1443
+ );
1444
+ c.log.info({ msg: "agent-os preview token expired", token });
1445
+ }
1446
+ };
1447
+ }
1448
+
1449
+ // src/agent-os/actor/process.ts
1450
+ function broadcastProcessEvent(c, name, payload) {
1451
+ try {
1452
+ c.broadcast(name, payload);
1453
+ } catch (error) {
1454
+ if (isRivetErrorCode(error, "actor", "stopping")) {
1455
+ return;
1456
+ }
1457
+ throw error;
1458
+ }
1459
+ }
1460
+ function buildProcessActions(config) {
1461
+ return {
1462
+ exec: async (c, command, options) => {
1463
+ const agentOs2 = await ensureVm(c, config);
1464
+ return agentOs2.exec(command, options);
859
1465
  },
860
- "./client": {
861
- import: {
862
- browser: {
863
- types: "./dist/browser/client.d.ts",
864
- default: "./dist/browser/client.js"
1466
+ spawn: async (c, command, args, options) => {
1467
+ const agentOs2 = await ensureVm(c, config);
1468
+ const { pid } = agentOs2.spawn(command, args, {
1469
+ ...options,
1470
+ onStdout: (data) => {
1471
+ var _a;
1472
+ broadcastProcessEvent(c, "processOutput", {
1473
+ pid,
1474
+ stream: "stdout",
1475
+ data
1476
+ });
1477
+ (_a = options == null ? void 0 : options.onStdout) == null ? void 0 : _a.call(options, data);
865
1478
  },
866
- types: "./dist/tsup/client/mod.d.ts",
867
- default: "./dist/tsup/client/mod.js"
868
- },
869
- require: {
870
- types: "./dist/tsup/client/mod.d.cts",
871
- default: "./dist/tsup/client/mod.cjs"
872
- }
1479
+ onStderr: (data) => {
1480
+ var _a;
1481
+ broadcastProcessEvent(c, "processOutput", {
1482
+ pid,
1483
+ stream: "stderr",
1484
+ data
1485
+ });
1486
+ (_a = options == null ? void 0 : options.onStderr) == null ? void 0 : _a.call(options, data);
1487
+ }
1488
+ });
1489
+ c.vars.activeProcesses.add(pid);
1490
+ syncPreventSleep(c);
1491
+ c.log.info({
1492
+ msg: "agent-os process spawned",
1493
+ pid,
1494
+ command
1495
+ });
1496
+ agentOs2.waitProcess(pid).then((exitCode) => {
1497
+ broadcastProcessEvent(c, "processExit", { pid, exitCode });
1498
+ c.log.info({
1499
+ msg: "agent-os process exited",
1500
+ pid,
1501
+ exitCode
1502
+ });
1503
+ }).catch(() => {
1504
+ }).finally(() => {
1505
+ c.vars.activeProcesses.delete(pid);
1506
+ syncPreventSleep(c);
1507
+ });
1508
+ return { pid };
873
1509
  },
874
- "./log": {
875
- import: {
876
- types: "./dist/tsup/common/log.d.ts",
877
- default: "./dist/tsup/common/log.js"
878
- },
879
- require: {
880
- types: "./dist/tsup/common/log.d.cts",
881
- default: "./dist/tsup/common/log.cjs"
882
- }
1510
+ writeProcessStdin: async (c, pid, data) => {
1511
+ const agentOs2 = await ensureVm(c, config);
1512
+ agentOs2.writeProcessStdin(pid, data);
883
1513
  },
884
- "./errors": {
885
- import: {
886
- types: "./dist/tsup/actor/errors.d.ts",
887
- default: "./dist/tsup/actor/errors.js"
888
- },
889
- require: {
890
- types: "./dist/tsup/actor/errors.d.cts",
891
- default: "./dist/tsup/actor/errors.cjs"
892
- }
1514
+ closeProcessStdin: async (c, pid) => {
1515
+ const agentOs2 = await ensureVm(c, config);
1516
+ agentOs2.closeProcessStdin(pid);
893
1517
  },
894
- "./inspector": {
895
- import: {
896
- types: "./dist/tsup/inspector/mod.d.ts",
897
- default: "./dist/tsup/inspector/mod.js"
898
- },
899
- require: {
900
- types: "./dist/tsup/inspector/mod.d.cts",
901
- default: "./dist/tsup/inspector/mod.cjs"
902
- }
1518
+ waitProcess: async (c, pid) => {
1519
+ const agentOs2 = await ensureVm(c, config);
1520
+ return agentOs2.waitProcess(pid);
903
1521
  },
904
- "./inspector/client": {
905
- import: {
906
- types: "./dist/browser/inspector/client.d.ts",
907
- default: "./dist/browser/inspector/client.js"
908
- }
1522
+ listProcesses: async (c) => {
1523
+ const agentOs2 = await ensureVm(c, config);
1524
+ return agentOs2.listProcesses();
909
1525
  },
910
- "./utils": {
911
- import: {
912
- types: "./dist/tsup/utils.d.ts",
913
- default: "./dist/tsup/utils.js"
914
- },
915
- require: {
916
- types: "./dist/tsup/utils.d.cts",
917
- default: "./dist/tsup/utils.cjs"
918
- }
1526
+ allProcesses: async (c) => {
1527
+ const agentOs2 = await ensureVm(c, config);
1528
+ return agentOs2.allProcesses();
919
1529
  },
920
- "./agent-os": {
921
- import: {
922
- types: "./dist/tsup/agent-os/index.d.ts",
923
- default: "./dist/tsup/agent-os/index.js"
924
- },
925
- require: {
926
- types: "./dist/tsup/agent-os/index.d.cts",
927
- default: "./dist/tsup/agent-os/index.cjs"
928
- }
929
- }
930
- },
931
- engines: {
932
- node: ">=22.0.0"
933
- },
934
- sideEffects: [
935
- "./dist/tsup/chunk-*.js",
936
- "./dist/tsup/chunk-*.cjs"
937
- ],
938
- scripts: {
939
- build: "tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/utils.ts src/workflow/mod.ts src/test/mod.ts src/inspector/mod.ts src/db/mod.ts src/db/drizzle.ts && tsup src/agent-os/index.ts --no-clean --out-dir dist/tsup/agent-os",
940
- "build:browser": "tsup --config tsup.browser.config.ts",
941
- "check-types": "tsc --noEmit",
942
- lint: "biome check . && pnpm run check:test-skips && pnpm run check:wait-for-comments",
943
- "lint:fix": "biome check --write .",
944
- "check:test-skips": "tsx scripts/check-annotated-skips.ts",
945
- "check:wait-for-comments": "tsx scripts/check-wait-for-comments.ts",
946
- format: "biome format .",
947
- "format:write": "biome format --write .",
948
- test: "vitest run",
949
- "test:watch": "vitest",
950
- "dump-asyncapi": "tsx scripts/dump-asyncapi.ts",
951
- "registry-config-schema-gen": "tsx scripts/registry-config-schema-gen.ts",
952
- "actor-config-schema-gen": "tsx scripts/actor-config-schema-gen.ts"
953
- },
954
- dependencies: {
955
- "@rivet-dev/agent-os-core": "^0.1.1",
956
- "@hono/node-server": "^1.18.2",
957
- "@hono/node-ws": "^1.1.1",
958
- "@hono/zod-openapi": "^1.1.5",
959
- "@rivetkit/bare-ts": "^0.6.2",
960
- "@rivetkit/engine-cli": "workspace:*",
961
- "@rivetkit/engine-envoy-protocol": "workspace:*",
962
- "@rivetkit/rivetkit-napi": "workspace:*",
963
- "@rivetkit/traces": "workspace:*",
964
- "@rivetkit/virtual-websocket": "workspace:*",
965
- "@rivetkit/workflow-engine": "workspace:*",
966
- "cbor-x": "^1.6.0",
967
- "drizzle-orm": "^0.44.2",
968
- "get-port": "^7.1.0",
969
- hono: "^4.7.0",
970
- invariant: "^2.2.4",
971
- "p-retry": "^6.2.1",
972
- pino: "^9.5.0",
973
- uuid: "^12.0.0",
974
- vbare: "^0.0.4",
975
- zod: "^4.1.0"
976
- },
977
- devDependencies: {
978
- "@copilotkit/llmock": "^1.6.0",
979
- "@rivet-dev/agent-os-common": "*",
980
- "@rivet-dev/agent-os-pi": "^0.1.1",
981
- "@biomejs/biome": "^2.3",
982
- "@standard-schema/spec": "^1.0.0",
983
- "@types/invariant": "^2",
984
- "@types/node": "^22.13.1",
985
- eventsource: "^4.0.0",
986
- tsup: "^8.4.0",
987
- tsx: "^4.19.4",
988
- typescript: "^5.7.3",
989
- "vite-tsconfig-paths": "^5.1.4",
990
- vitest: "^3.1.1",
991
- ws: "^8.18.1"
992
- },
993
- peerDependencies: {
994
- "drizzle-kit": "^0.31.2",
995
- eventsource: "^4.0.0",
996
- ws: "^8.0.0"
997
- },
998
- peerDependenciesMeta: {
999
- "drizzle-kit": {
1000
- optional: true
1530
+ processTree: async (c) => {
1531
+ const agentOs2 = await ensureVm(c, config);
1532
+ return agentOs2.processTree();
1001
1533
  },
1002
- eventsource: {
1003
- optional: true
1534
+ getProcess: async (c, pid) => {
1535
+ const agentOs2 = await ensureVm(c, config);
1536
+ return agentOs2.getProcess(pid);
1004
1537
  },
1005
- ws: {
1006
- optional: true
1007
- }
1008
- },
1009
- stableVersion: "0.8.0"
1010
- };
1011
-
1012
- // src/utils.ts
1013
- var VERSION = package_default.version;
1014
- function getEnvUniversal(key) {
1015
- if (typeof Deno !== "undefined") {
1016
- return Deno.env.get(key);
1017
- } else if (typeof process !== "undefined") {
1018
- return process.env[key];
1019
- }
1020
- }
1021
-
1022
- // src/utils/env-vars.ts
1023
- var getLogLevel = () => _nullishCoalesce(getEnvUniversal("RIVET_LOG_LEVEL"), () => ( getEnvUniversal("LOG_LEVEL")));
1024
- var getLogTarget = () => getEnvUniversal("RIVET_LOG_TARGET") === "1";
1025
- var getLogTimestamp = () => getEnvUniversal("RIVET_LOG_TIMESTAMP") === "1";
1026
-
1027
- // src/common/log.ts
1028
- var baseLogger;
1029
- var configuredLogLevel;
1030
- var loggerCache = /* @__PURE__ */ new Map();
1031
- var LogLevelSchema = _v4.z.enum([
1032
- "trace",
1033
- "debug",
1034
- "info",
1035
- "warn",
1036
- "error",
1037
- "fatal",
1038
- "silent"
1039
- ]);
1040
- function getPinoLevel(logLevel) {
1041
- if (logLevel) {
1042
- return logLevel;
1043
- }
1044
- if (configuredLogLevel) {
1045
- return configuredLogLevel;
1046
- }
1047
- const raw = (getLogLevel() || "warn").toString().toLowerCase();
1048
- const parsed = LogLevelSchema.safeParse(raw);
1049
- if (parsed.success) {
1050
- return parsed.data;
1051
- }
1052
- return "info";
1053
- }
1054
- function getIncludeTarget() {
1055
- return getLogTarget();
1056
- }
1057
- function configureDefaultLogger(logLevel) {
1058
- if (logLevel) {
1059
- configuredLogLevel = logLevel;
1060
- }
1061
- baseLogger = _pino.pino.call(void 0, {
1062
- level: getPinoLevel(logLevel),
1063
- messageKey: "msg",
1064
- // Do not include pid/hostname in output
1065
- base: {},
1066
- // Keep a string level in the output
1067
- formatters: {
1068
- level(_label, number) {
1069
- return { level: number };
1070
- }
1538
+ stopProcess: async (c, pid) => {
1539
+ const agentOs2 = await ensureVm(c, config);
1540
+ agentOs2.stopProcess(pid);
1071
1541
  },
1072
- timestamp: getLogTimestamp() ? _pino.stdTimeFunctions.epochTime : false
1073
- });
1074
- loggerCache.clear();
1075
- }
1076
- function getBaseLogger() {
1077
- if (!baseLogger) {
1078
- configureDefaultLogger();
1079
- }
1080
- return baseLogger;
1081
- }
1082
- function getLogger(name = "default") {
1083
- const cached = loggerCache.get(name);
1084
- if (cached) {
1085
- return cached;
1086
- }
1087
- const base = getBaseLogger();
1088
- const child = getIncludeTarget() ? base.child({ target: name }) : base;
1089
- loggerCache.set(name, child);
1090
- return child;
1091
- }
1092
-
1093
- // src/actor/log.ts
1094
- function loggerWithoutContext() {
1095
- return getLogger("actor-runtime");
1542
+ killProcess: async (c, pid) => {
1543
+ const agentOs2 = await ensureVm(c, config);
1544
+ agentOs2.killProcess(pid);
1545
+ }
1546
+ };
1096
1547
  }
1097
1548
 
1098
- // src/actor/definition.ts
1099
- var warnedDeprecatedTimeoutKeys = /* @__PURE__ */ new Set();
1100
- function warnDeprecatedShutdownTimeoutKeys(options) {
1101
- if (!options || typeof options !== "object") return;
1102
- const opts = options;
1103
- for (const key of ["onDestroyTimeout", "waitUntilTimeout"]) {
1104
- if (opts[key] !== void 0 && !warnedDeprecatedTimeoutKeys.has(key)) {
1105
- warnedDeprecatedTimeoutKeys.add(key);
1106
- loggerWithoutContext().warn({
1107
- msg: `actor option \`${key}\` is deprecated and is now ignored. Configure \`sleepGracePeriod\` instead, which bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0.`
1108
- });
1549
+ // src/agent-os/actor/session.ts
1550
+ function stripFunctions(value) {
1551
+ if (value === null || value === void 0) return value;
1552
+ if (typeof value === "function") return void 0;
1553
+ if (typeof value !== "object") return value;
1554
+ if (Array.isArray(value)) return value.map(stripFunctions);
1555
+ const out = {};
1556
+ for (const [k, v] of Object.entries(value)) {
1557
+ if (typeof v !== "function") {
1558
+ out[k] = stripFunctions(v);
1109
1559
  }
1110
1560
  }
1561
+ return out;
1111
1562
  }
1112
- var ActorDefinition = class {
1113
- #config;
1114
- constructor(config) {
1115
- this.#config = config;
1116
- }
1117
- get config() {
1118
- return this.#config;
1563
+ function assertSessionExists(c, sessionId) {
1564
+ if (!c.vars.sessions.has(sessionId)) {
1565
+ throw new Error(`session not found: ${sessionId}`);
1119
1566
  }
1120
- };
1121
- function actor(input) {
1122
- warnDeprecatedShutdownTimeoutKeys(
1123
- input == null ? void 0 : input.options
1567
+ }
1568
+ function toSessionRecord(agentOs2, sessionId, agentType) {
1569
+ return {
1570
+ sessionId,
1571
+ agentType,
1572
+ capabilities: _nullishCoalesce(agentOs2.getSessionCapabilities(sessionId), () => ( {})),
1573
+ agentInfo: agentOs2.getSessionAgentInfo(sessionId)
1574
+ };
1575
+ }
1576
+ async function persistSession(c, agentOs2, sessionId, agentType) {
1577
+ const now = Date.now();
1578
+ const capabilities = _nullishCoalesce(agentOs2.getSessionCapabilities(sessionId), () => ( {}));
1579
+ const agentInfo = agentOs2.getSessionAgentInfo(sessionId);
1580
+ await c.db.execute(
1581
+ `INSERT OR REPLACE INTO agent_os_sessions (session_id, agent_type, capabilities, agent_info, created_at)
1582
+ VALUES (?, ?, ?, ?, ?)`,
1583
+ sessionId,
1584
+ agentType,
1585
+ JSON.stringify(capabilities),
1586
+ agentInfo ? JSON.stringify(agentInfo) : null,
1587
+ now
1124
1588
  );
1125
- const config = ActorConfigSchema.parse(input);
1126
- return new ActorDefinition(config);
1127
1589
  }
1128
-
1129
- // src/actor/schema.ts
1130
- function event(options) {
1131
- return _nullishCoalesce(options, () => ( {}));
1590
+ async function persistSessionEvent(c, sessionId, event2) {
1591
+ var _a;
1592
+ const now = Date.now();
1593
+ const rows = await c.db.execute(
1594
+ `SELECT MAX(seq) as max_seq FROM agent_os_session_events WHERE session_id = ?`,
1595
+ sessionId
1596
+ );
1597
+ const nextSeq = (_nullishCoalesce(((_a = rows[0]) == null ? void 0 : _a.max_seq), () => ( -1))) + 1;
1598
+ await c.db.execute(
1599
+ `INSERT INTO agent_os_session_events (session_id, seq, event, created_at)
1600
+ VALUES (?, ?, ?, ?)`,
1601
+ sessionId,
1602
+ nextSeq,
1603
+ JSON.stringify(event2),
1604
+ now
1605
+ );
1132
1606
  }
1133
-
1134
- // src/common/database/shared.ts
1135
- function isSqliteBindingValue(value) {
1136
- if (value === null || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || value instanceof Uint8Array) {
1137
- return true;
1138
- }
1139
- if (Array.isArray(value)) {
1140
- return value.every((item) => typeof item === "number");
1141
- }
1142
- return false;
1607
+ async function deletePersistedSession(c, sessionId) {
1608
+ await c.db.execute(
1609
+ `DELETE FROM agent_os_session_events WHERE session_id = ?`,
1610
+ sessionId
1611
+ );
1612
+ await c.db.execute(
1613
+ `DELETE FROM agent_os_sessions WHERE session_id = ?`,
1614
+ sessionId
1615
+ );
1143
1616
  }
1144
- function isPlainObject(value) {
1145
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1146
- return false;
1147
- }
1148
- return Object.getPrototypeOf(value) === Object.prototype;
1617
+ function subscribeToSession(c, agentOs2, sessionId, parsedConfig) {
1618
+ agentOs2.onSessionEvent(sessionId, (event2) => {
1619
+ c.broadcast(
1620
+ "sessionEvent",
1621
+ JSON.parse(JSON.stringify({ sessionId, event: event2 }))
1622
+ );
1623
+ persistSessionEvent(c, sessionId, event2).catch(
1624
+ (error) => c.log.error({
1625
+ msg: "agent-os failed to persist session event",
1626
+ sessionId,
1627
+ error
1628
+ })
1629
+ );
1630
+ if (parsedConfig.onSessionEvent) {
1631
+ runHook(
1632
+ c,
1633
+ "onSessionEvent",
1634
+ () => {
1635
+ var _a;
1636
+ return (_a = parsedConfig.onSessionEvent) == null ? void 0 : _a.call(parsedConfig, c, sessionId, event2);
1637
+ }
1638
+ );
1639
+ }
1640
+ });
1641
+ agentOs2.onPermissionRequest(sessionId, (request) => {
1642
+ c.broadcast(
1643
+ "permissionRequest",
1644
+ JSON.parse(JSON.stringify({ sessionId, request }))
1645
+ );
1646
+ if (parsedConfig.onPermissionRequest) {
1647
+ runHook(
1648
+ c,
1649
+ "onPermissionRequest",
1650
+ () => {
1651
+ var _a;
1652
+ return (_a = parsedConfig.onPermissionRequest) == null ? void 0 : _a.call(parsedConfig, c, sessionId, request);
1653
+ }
1654
+ );
1655
+ }
1656
+ });
1657
+ c.vars.sessions.add(sessionId);
1149
1658
  }
1150
- function isSqliteBindingObject(value) {
1151
- if (!isPlainObject(value)) {
1152
- return false;
1153
- }
1154
- return Object.values(value).every((entry) => isSqliteBindingValue(entry));
1659
+ function buildSessionActions(config) {
1660
+ return {
1661
+ createSession: async (c, agentType, options) => {
1662
+ const agentOs2 = await ensureVm(c, config);
1663
+ const { sessionId } = await agentOs2.createSession(
1664
+ agentType,
1665
+ options
1666
+ );
1667
+ subscribeToSession(c, agentOs2, sessionId, config);
1668
+ await persistSession(c, agentOs2, sessionId, agentType);
1669
+ c.log.info({
1670
+ msg: "agent-os session created",
1671
+ sessionId,
1672
+ agentType
1673
+ });
1674
+ return toSessionRecord(agentOs2, sessionId, agentType);
1675
+ },
1676
+ listSessions: async (c) => {
1677
+ const agentOs2 = await ensureVm(c, config);
1678
+ return agentOs2.listSessions();
1679
+ },
1680
+ getSession: async (c, sessionId) => {
1681
+ assertSessionExists(c, sessionId);
1682
+ const agentOs2 = await ensureVm(c, config);
1683
+ const info = agentOs2.listSessions().find((s) => s.sessionId === sessionId);
1684
+ if (!info) {
1685
+ throw new Error(`session not found: ${sessionId}`);
1686
+ }
1687
+ return toSessionRecord(agentOs2, sessionId, info.agentType);
1688
+ },
1689
+ destroySession: async (c, sessionId) => {
1690
+ const agentOs2 = await ensureVm(c, config);
1691
+ await agentOs2.destroySession(sessionId);
1692
+ c.vars.sessions.delete(sessionId);
1693
+ c.vars.activeSessionIds.delete(sessionId);
1694
+ syncPreventSleep(c);
1695
+ await deletePersistedSession(c, sessionId);
1696
+ c.log.info({ msg: "agent-os session destroyed", sessionId });
1697
+ },
1698
+ resumeSession: async (c, sessionId) => {
1699
+ const agentOs2 = await ensureVm(c, config);
1700
+ return agentOs2.resumeSession(sessionId);
1701
+ },
1702
+ closeSession: async (c, sessionId) => {
1703
+ const agentOs2 = await ensureVm(c, config);
1704
+ agentOs2.closeSession(sessionId);
1705
+ c.vars.sessions.delete(sessionId);
1706
+ c.vars.activeSessionIds.delete(sessionId);
1707
+ syncPreventSleep(c);
1708
+ await deletePersistedSession(c, sessionId);
1709
+ c.log.info({ msg: "agent-os session closed", sessionId });
1710
+ }
1711
+ };
1155
1712
  }
1156
- function toSqliteBindings(input) {
1157
- if (Array.isArray(input)) {
1158
- for (const value of input) {
1159
- if (!isSqliteBindingValue(value)) {
1713
+ function buildPromptActions(_config) {
1714
+ return {
1715
+ sendPrompt: async (c, sessionId, text) => {
1716
+ if (c.aborted) {
1160
1717
  throw new Error(
1161
- `unsupported sqlite binding type: ${typeof value}`
1718
+ "actor is shutting down, cannot start new prompt"
1162
1719
  );
1163
1720
  }
1721
+ assertSessionExists(c, sessionId);
1722
+ const agentOs2 = c.vars.agentOs;
1723
+ if (!agentOs2) {
1724
+ throw new Error("VM not initialized");
1725
+ }
1726
+ c.vars.activeSessionIds.add(sessionId);
1727
+ syncPreventSleep(c);
1728
+ c.log.info({ msg: "agent-os prompt turn started", sessionId });
1729
+ const start = Date.now();
1730
+ try {
1731
+ const result = await agentOs2.prompt(sessionId, text);
1732
+ return {
1733
+ response: JSON.parse(JSON.stringify(result.response)),
1734
+ text: result.text
1735
+ };
1736
+ } finally {
1737
+ c.vars.activeSessionIds.delete(sessionId);
1738
+ syncPreventSleep(c);
1739
+ c.log.info({
1740
+ msg: "agent-os prompt turn ended",
1741
+ sessionId,
1742
+ durationMs: Date.now() - start
1743
+ });
1744
+ }
1745
+ },
1746
+ cancelPrompt: async (c, sessionId) => {
1747
+ assertSessionExists(c, sessionId);
1748
+ const agentOs2 = c.vars.agentOs;
1749
+ if (!agentOs2) {
1750
+ throw new Error("VM not initialized");
1751
+ }
1752
+ return stripFunctions(
1753
+ agentOs2.cancelSession(sessionId)
1754
+ );
1755
+ },
1756
+ respondPermission: async (c, sessionId, permissionId, reply) => {
1757
+ assertSessionExists(c, sessionId);
1758
+ const agentOs2 = c.vars.agentOs;
1759
+ if (!agentOs2) {
1760
+ throw new Error("VM not initialized");
1761
+ }
1762
+ return stripFunctions(
1763
+ agentOs2.respondPermission(sessionId, permissionId, reply)
1764
+ );
1164
1765
  }
1165
- return input;
1166
- }
1167
- if (isSqliteBindingObject(input)) {
1168
- return input;
1169
- }
1170
- throw new Error("unsupported sqlite binding collection");
1171
- }
1172
- var AsyncMutex = class {
1173
- #locked = false;
1174
- #waiting = [];
1175
- async acquire() {
1176
- while (this.#locked) {
1177
- await new Promise((resolve) => this.#waiting.push(resolve));
1178
- }
1179
- this.#locked = true;
1180
- }
1181
- release() {
1182
- this.#locked = false;
1183
- const next = this.#waiting.shift();
1184
- if (next) {
1185
- next();
1186
- }
1187
- }
1188
- async run(fn) {
1189
- await this.acquire();
1190
- try {
1191
- return await fn();
1192
- } finally {
1193
- this.release();
1194
- }
1195
- }
1196
- };
1197
-
1198
- // src/common/database/mod.ts
1199
- function sqlReturnsRows(query) {
1200
- const token = query.trimStart().slice(0, 16).toUpperCase();
1201
- if (token.startsWith("PRAGMA")) {
1202
- return !/^PRAGMA\b[\s\S]*=/.test(query.trim());
1203
- }
1204
- return token.startsWith("SELECT") || token.startsWith("WITH") || /\bRETURNING\b/i.test(query);
1205
- }
1206
- function hasMultipleStatements(query) {
1207
- const trimmed = query.trim().replace(/;+$/, "").trimEnd();
1208
- return trimmed.includes(";");
1209
- }
1210
- function isPragmaAssignment(query) {
1211
- return /^PRAGMA\b[\s\S]*=/.test(query.trim());
1766
+ };
1212
1767
  }
1213
- function db({
1214
- onMigrate
1215
- } = {}) {
1768
+ function buildConfigActions(_config) {
1216
1769
  return {
1217
- createClient: async (ctx) => {
1218
- var _a;
1219
- const nativeDatabaseProvider = ctx.nativeDatabaseProvider;
1220
- if (!nativeDatabaseProvider) {
1221
- throw new Error(
1222
- "native SQLite is required, but the current runtime did not provide a native database provider"
1223
- );
1770
+ setMode: async (c, sessionId, modeId) => {
1771
+ assertSessionExists(c, sessionId);
1772
+ const agentOs2 = c.vars.agentOs;
1773
+ if (!agentOs2) {
1774
+ throw new Error("VM not initialized");
1224
1775
  }
1225
- const db2 = await nativeDatabaseProvider.open(ctx.actorId);
1226
- (_a = ctx.metrics) == null ? void 0 : _a.setSqliteVfsMetricsSource(() => {
1227
- var _a2;
1228
- return _nullishCoalesce(((_a2 = db2.getSqliteVfsMetrics) == null ? void 0 : _a2.call(db2)), () => ( null));
1229
- });
1230
- let closed = false;
1231
- const mutex = new AsyncMutex();
1232
- const ensureOpen = () => {
1233
- if (closed) {
1234
- throw new Error(
1235
- "Database is closed. This usually means a background timer (setInterval, setTimeout) or a stray promise is still running after the actor stopped. Use c.abortSignal to clean up timers before the actor shuts down."
1236
- );
1237
- }
1238
- };
1239
- const client = {
1240
- execute: async (query, ...args) => {
1241
- return await mutex.run(async () => {
1242
- var _a2, _b, _c, _d;
1243
- ensureOpen();
1244
- const kvReadsBefore = _nullishCoalesce(((_a2 = ctx.metrics) == null ? void 0 : _a2.totalKvReads), () => ( 0));
1245
- const kvWritesBefore = _nullishCoalesce(((_b = ctx.metrics) == null ? void 0 : _b.totalKvWrites), () => ( 0));
1246
- const start = performance.now();
1247
- let result;
1248
- if (args.length > 0) {
1249
- const bindings = args.length === 1 && isSqliteBindingObject(args[0]) ? toSqliteBindings(args[0]) : toSqliteBindings(args);
1250
- const returnsRows = sqlReturnsRows(query);
1251
- if (returnsRows) {
1252
- const { rows, columns } = await db2.query(
1253
- query,
1254
- bindings
1255
- );
1256
- result = rows.map((row) => {
1257
- const rowObj = {};
1258
- for (let i = 0; i < columns.length; i++) {
1259
- rowObj[columns[i]] = row[i];
1260
- }
1261
- return rowObj;
1262
- });
1263
- } else {
1264
- await db2.run(query, bindings);
1265
- result = [];
1266
- }
1267
- } else {
1268
- const returnsRows = sqlReturnsRows(query);
1269
- if (!hasMultipleStatements(query)) {
1270
- if (returnsRows) {
1271
- const { rows, columns } = await db2.query(query);
1272
- result = rows.map((row) => {
1273
- const rowObj = {};
1274
- for (let i = 0; i < columns.length; i++) {
1275
- rowObj[columns[i]] = row[i];
1276
- }
1277
- return rowObj;
1278
- });
1279
- } else if (isPragmaAssignment(query)) {
1280
- await db2.run(query);
1281
- result = [];
1282
- } else {
1283
- const results = [];
1284
- let columnNames = null;
1285
- await db2.exec(
1286
- query,
1287
- (row, columns) => {
1288
- if (!columnNames) {
1289
- columnNames = columns;
1290
- }
1291
- const rowObj = {};
1292
- for (let i = 0; i < row.length; i++) {
1293
- rowObj[columnNames[i]] = row[i];
1294
- }
1295
- results.push(rowObj);
1296
- }
1297
- );
1298
- result = results;
1299
- }
1300
- } else {
1301
- const results = [];
1302
- let columnNames = null;
1303
- await db2.exec(
1304
- query,
1305
- (row, columns) => {
1306
- if (!columnNames) {
1307
- columnNames = columns;
1308
- }
1309
- const rowObj = {};
1310
- for (let i = 0; i < row.length; i++) {
1311
- rowObj[columnNames[i]] = row[i];
1312
- }
1313
- results.push(rowObj);
1314
- }
1315
- );
1316
- result = results;
1317
- }
1318
- }
1319
- const durationMs = performance.now() - start;
1320
- (_c = ctx.metrics) == null ? void 0 : _c.trackSql(query, durationMs);
1321
- if (ctx.metrics) {
1322
- const kvReads = ctx.metrics.totalKvReads - kvReadsBefore;
1323
- const kvWrites = ctx.metrics.totalKvWrites - kvWritesBefore;
1324
- (_d = ctx.log) == null ? void 0 : _d.debug({
1325
- msg: "sql query",
1326
- query: query.slice(0, 120),
1327
- durationMs,
1328
- kvReads,
1329
- kvWrites
1330
- });
1331
- }
1332
- return result;
1333
- });
1334
- },
1335
- close: async () => {
1336
- const shouldClose = await mutex.run(async () => {
1337
- if (closed) return false;
1338
- closed = true;
1339
- return true;
1340
- });
1341
- if (shouldClose) {
1342
- await db2.close();
1343
- }
1344
- }
1345
- };
1346
- return client;
1776
+ return stripFunctions(
1777
+ agentOs2.setSessionMode(sessionId, modeId)
1778
+ );
1347
1779
  },
1348
- onMigrate: async (client) => {
1349
- if (onMigrate) {
1350
- await onMigrate(client);
1780
+ getModes: async (c, sessionId) => {
1781
+ assertSessionExists(c, sessionId);
1782
+ const agentOs2 = c.vars.agentOs;
1783
+ if (!agentOs2) {
1784
+ throw new Error("VM not initialized");
1785
+ }
1786
+ return agentOs2.getSessionModes(sessionId);
1787
+ },
1788
+ setModel: async (c, sessionId, model) => {
1789
+ assertSessionExists(c, sessionId);
1790
+ const agentOs2 = c.vars.agentOs;
1791
+ if (!agentOs2) {
1792
+ throw new Error("VM not initialized");
1793
+ }
1794
+ return stripFunctions(
1795
+ agentOs2.setSessionModel(sessionId, model)
1796
+ );
1797
+ },
1798
+ setThoughtLevel: async (c, sessionId, level) => {
1799
+ assertSessionExists(c, sessionId);
1800
+ const agentOs2 = c.vars.agentOs;
1801
+ if (!agentOs2) {
1802
+ throw new Error("VM not initialized");
1803
+ }
1804
+ return stripFunctions(
1805
+ agentOs2.setSessionThoughtLevel(sessionId, level)
1806
+ );
1807
+ },
1808
+ getConfigOptions: async (c, sessionId) => {
1809
+ assertSessionExists(c, sessionId);
1810
+ const agentOs2 = c.vars.agentOs;
1811
+ if (!agentOs2) {
1812
+ throw new Error("VM not initialized");
1813
+ }
1814
+ return agentOs2.getSessionConfigOptions(sessionId);
1815
+ },
1816
+ getEvents: async (c, sessionId, options) => {
1817
+ assertSessionExists(c, sessionId);
1818
+ const agentOs2 = c.vars.agentOs;
1819
+ if (!agentOs2) {
1820
+ throw new Error("VM not initialized");
1821
+ }
1822
+ return agentOs2.getSessionEvents(sessionId, options).map((e) => e.notification);
1823
+ },
1824
+ getSequencedEvents: async (c, sessionId, options) => {
1825
+ assertSessionExists(c, sessionId);
1826
+ const agentOs2 = c.vars.agentOs;
1827
+ if (!agentOs2) {
1828
+ throw new Error("VM not initialized");
1829
+ }
1830
+ return agentOs2.getSessionEvents(sessionId, options);
1831
+ },
1832
+ rawSend: async (c, sessionId, method, params) => {
1833
+ assertSessionExists(c, sessionId);
1834
+ const agentOs2 = c.vars.agentOs;
1835
+ if (!agentOs2) {
1836
+ throw new Error("VM not initialized");
1351
1837
  }
1838
+ return stripFunctions(
1839
+ agentOs2.rawSessionSend(sessionId, method, params)
1840
+ );
1352
1841
  }
1353
1842
  };
1354
1843
  }
1355
-
1356
- // src/agent-os/config.ts
1357
-
1358
- var zFunction2 = () => _v4.z.custom((val) => typeof val === "function");
1359
- var AgentOsOptionsSchema = _v4.z.custom(
1360
- (val) => typeof val === "object" && val !== null
1361
- );
1362
- var agentOsActorConfigSchema = _v4.z.object({
1363
- options: AgentOsOptionsSchema.optional(),
1364
- preview: _v4.z.object({
1365
- defaultExpiresInSeconds: _v4.z.number().positive().default(3600),
1366
- maxExpiresInSeconds: _v4.z.number().positive().default(86400)
1367
- }).strict().prefault(() => ({})),
1368
- onBeforeConnect: zFunction2().optional(),
1369
- onSessionEvent: zFunction2().optional(),
1370
- onPermissionRequest: zFunction2().optional()
1371
- }).strict();
1372
-
1373
- // src/agent-os/actor/cron.ts
1374
- function buildCronActions(config) {
1844
+ function buildSessionPersistenceActions(_config) {
1375
1845
  return {
1376
- scheduleCron: async (c, options) => {
1377
- const agentOs2 = await ensureVm(c, config);
1378
- const job = agentOs2.scheduleCron({
1379
- id: options.id,
1380
- schedule: options.schedule,
1381
- action: options.action,
1382
- overlap: options.overlap
1383
- });
1384
- c.log.info({
1385
- msg: "agent-os cron job scheduled",
1386
- jobId: job.id,
1387
- schedule: options.schedule
1388
- });
1389
- return { id: job.id };
1390
- },
1391
- listCronJobs: async (c) => {
1392
- const agentOs2 = await ensureVm(c, config);
1393
- return agentOs2.listCronJobs();
1846
+ listPersistedSessions: async (c) => {
1847
+ const rows = await c.db.execute(
1848
+ `SELECT session_id, agent_type, capabilities, agent_info, created_at
1849
+ FROM agent_os_sessions
1850
+ ORDER BY created_at ASC`
1851
+ );
1852
+ return rows.map((row) => ({
1853
+ sessionId: row.session_id,
1854
+ agentType: row.agent_type,
1855
+ capabilities: JSON.parse(row.capabilities),
1856
+ agentInfo: row.agent_info ? JSON.parse(row.agent_info) : null,
1857
+ createdAt: row.created_at
1858
+ }));
1394
1859
  },
1395
- cancelCronJob: async (c, id) => {
1396
- const agentOs2 = await ensureVm(c, config);
1397
- agentOs2.cancelCronJob(id);
1398
- c.log.info({ msg: "agent-os cron job cancelled", jobId: id });
1860
+ getSessionEvents: async (c, sessionId) => {
1861
+ const rows = await c.db.execute(
1862
+ `SELECT session_id, seq, event, created_at
1863
+ FROM agent_os_session_events
1864
+ WHERE session_id = ?
1865
+ ORDER BY seq ASC`,
1866
+ sessionId
1867
+ );
1868
+ return rows.map((row) => ({
1869
+ sessionId: row.session_id,
1870
+ seq: row.seq,
1871
+ event: JSON.parse(row.event),
1872
+ createdAt: row.created_at
1873
+ }));
1399
1874
  }
1400
1875
  };
1401
1876
  }
1402
1877
 
1403
- // src/agent-os/actor/network.ts
1404
- function buildNetworkActions(config) {
1878
+ // src/agent-os/actor/shell.ts
1879
+ function buildShellActions(config) {
1405
1880
  return {
1406
- vmFetch: async (c, port, url, options) => {
1881
+ openShell: async (c, options) => {
1407
1882
  const agentOs2 = await ensureVm(c, config);
1408
- const headers = new Headers(options == null ? void 0 : options.headers);
1409
- const request = new Request(url, {
1410
- method: _nullishCoalesce((options == null ? void 0 : options.method), () => ( "GET")),
1411
- headers,
1412
- body: _nullishCoalesce((options == null ? void 0 : options.body), () => ( null))
1413
- });
1414
- const response = await agentOs2.fetch(port, request);
1415
- const responseHeaders = {};
1416
- response.headers.forEach((value, key) => {
1417
- responseHeaders[key] = value;
1883
+ const { shellId } = agentOs2.openShell(options);
1884
+ agentOs2.onShellData(shellId, (data) => {
1885
+ c.broadcast("shellData", { shellId, data });
1418
1886
  });
1419
- const body = new Uint8Array(await response.arrayBuffer());
1420
- return {
1421
- status: response.status,
1422
- statusText: response.statusText,
1423
- headers: responseHeaders,
1424
- body
1425
- };
1887
+ c.vars.activeShells.add(shellId);
1888
+ syncPreventSleep(c);
1889
+ c.log.info({ msg: "agent-os shell opened", shellId });
1890
+ return { shellId };
1891
+ },
1892
+ writeShell: async (c, shellId, data) => {
1893
+ const agentOs2 = await ensureVm(c, config);
1894
+ agentOs2.writeShell(shellId, data);
1895
+ },
1896
+ resizeShell: async (c, shellId, cols, rows) => {
1897
+ const agentOs2 = await ensureVm(c, config);
1898
+ agentOs2.resizeShell(shellId, cols, rows);
1899
+ },
1900
+ closeShell: async (c, shellId) => {
1901
+ const agentOs2 = await ensureVm(c, config);
1902
+ agentOs2.closeShell(shellId);
1903
+ c.vars.activeShells.delete(shellId);
1904
+ syncPreventSleep(c);
1905
+ c.log.info({ msg: "agent-os shell closed", shellId });
1426
1906
  }
1427
1907
  };
1428
1908
  }
1429
1909
 
1430
- // src/agent-os/actor/preview.ts
1431
- var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto);
1432
- function generateToken() {
1433
- const bytes = _crypto2.default.randomBytes(32);
1434
- const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
1435
- let token = "";
1436
- for (let i = 0; i < 32; i++) {
1437
- token += alphabet[bytes[i] % alphabet.length];
1910
+ // src/agent-os/actor/index.ts
1911
+ async function ensureVm(c, config) {
1912
+ if (c.vars.agentOs) {
1913
+ return c.vars.agentOs;
1438
1914
  }
1439
- return token;
1915
+ const start = Date.now();
1916
+ const options = buildVmOptions(config.options);
1917
+ const agentOs2 = await _agentoscore.AgentOs.create(options);
1918
+ c.vars.agentOs = agentOs2;
1919
+ agentOs2.onCronEvent((cronEvent) => {
1920
+ c.broadcast("cronEvent", { event: cronEvent });
1921
+ });
1922
+ c.broadcast("vmBooted", {});
1923
+ c.log.info({
1924
+ msg: "agent-os vm booted",
1925
+ bootDurationMs: Date.now() - start
1926
+ });
1927
+ return agentOs2;
1440
1928
  }
1441
- var CORS_HEADERS = {
1442
- "Access-Control-Allow-Origin": "*",
1443
- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
1444
- "Access-Control-Allow-Headers": "*"
1445
- };
1446
- function addCorsHeaders(response) {
1447
- const headers = new Headers(response.headers);
1448
- for (const [key, value] of Object.entries(CORS_HEADERS)) {
1449
- headers.set(key, value);
1929
+ function buildVmOptions(userOptions) {
1930
+ const userMounts = _nullishCoalesce((userOptions == null ? void 0 : userOptions.mounts), () => ( []));
1931
+ const hasWorkdirMount = userMounts.some(
1932
+ (m) => m.path === "/home/user"
1933
+ );
1934
+ if (hasWorkdirMount) {
1935
+ return _nullishCoalesce(userOptions, () => ( {}));
1450
1936
  }
1451
- return new Response(response.body, {
1452
- status: response.status,
1453
- statusText: response.statusText,
1454
- headers
1937
+ const memMount = {
1938
+ path: "/home/user",
1939
+ driver: _agentoscore.createInMemoryFileSystem.call(void 0, )
1940
+ };
1941
+ return {
1942
+ ...userOptions,
1943
+ mounts: [memMount, ...userMounts]
1944
+ };
1945
+ }
1946
+ function syncPreventSleep(c) {
1947
+ const shouldPrevent = c.vars.activeSessionIds.size > 0 || c.vars.activeProcesses.size > 0 || c.vars.activeHooks.size > 0 || c.vars.activeShells.size > 0;
1948
+ c.setPreventSleep(shouldPrevent);
1949
+ c.log.info({
1950
+ msg: "agent-os prevent sleep sync",
1951
+ preventSleep: shouldPrevent,
1952
+ activeSessions: c.vars.activeSessionIds.size,
1953
+ activeProcesses: c.vars.activeProcesses.size,
1954
+ activeHooks: c.vars.activeHooks.size,
1955
+ activeShells: c.vars.activeShells.size
1455
1956
  });
1456
1957
  }
1457
- function buildOnRequestHandler(config) {
1458
- return async (c, request) => {
1459
- var _a;
1460
- const url = new URL(request.url);
1461
- const pathname = url.pathname;
1462
- const match = pathname.match(/^\/fetch\/([a-z0-9]+)(\/.*)?$/);
1463
- if (!match) {
1464
- return new Response("Not Found", { status: 404 });
1465
- }
1466
- if (request.method === "OPTIONS") {
1467
- return new Response(null, { status: 204, headers: CORS_HEADERS });
1468
- }
1469
- const token = match[1];
1470
- const remainingPath = _nullishCoalesce(match[2], () => ( "/"));
1471
- const now = Date.now();
1472
- const rows = await c.db.execute(
1473
- `SELECT port FROM agent_os_preview_tokens WHERE token = ? AND expires_at > ?`,
1474
- token,
1475
- now
1476
- );
1477
- if (rows.length === 0) {
1478
- c.log.warn({ msg: "agent-os preview auth failed", token });
1479
- return addCorsHeaders(new Response("Forbidden", { status: 403 }));
1480
- }
1481
- const port = (_a = rows[0]) == null ? void 0 : _a.port;
1482
- const agentOs2 = await ensureVm(
1483
- c,
1484
- config
1485
- );
1486
- const vmUrl = `http://localhost:${port}${remainingPath}${url.search}`;
1487
- const vmRequest = new Request(vmUrl, {
1488
- method: request.method,
1489
- headers: request.headers,
1490
- body: request.body,
1491
- duplex: "half"
1492
- });
1493
- const vmResponse = await agentOs2.fetch(port, vmRequest);
1494
- c.log.info({
1495
- msg: "agent-os preview request proxied",
1496
- port,
1497
- method: request.method,
1498
- path: remainingPath,
1499
- status: vmResponse.status
1500
- });
1501
- return addCorsHeaders(vmResponse);
1502
- };
1958
+ function runHook(c, name, callback) {
1959
+ const promise = Promise.resolve(callback()).catch(
1960
+ (error) => c.log.error({ msg: "agent-os hook failed", hookName: name, error })
1961
+ ).finally(() => {
1962
+ c.vars.activeHooks.delete(promise);
1963
+ syncPreventSleep(c);
1964
+ });
1965
+ c.vars.activeHooks.add(promise);
1966
+ syncPreventSleep(c);
1967
+ c.waitUntil(promise);
1503
1968
  }
1504
- function buildPreviewActions(config) {
1505
- return {
1506
- createSignedPreviewUrl: async (c, port, expiresInSeconds) => {
1507
- await ensureVm(c, config);
1508
- const effectiveExpires = _nullishCoalesce(expiresInSeconds, () => ( config.preview.defaultExpiresInSeconds));
1509
- const maxExpires = config.preview.maxExpiresInSeconds;
1510
- if (effectiveExpires < 1 || effectiveExpires > maxExpires) {
1511
- throw new Error(
1512
- `expiresInSeconds must be between 1 and ${maxExpires}`
1513
- );
1969
+ function agentOs(config) {
1970
+ const parsedConfig = agentOsActorConfigSchema.parse(
1971
+ config
1972
+ );
1973
+ const actions = {
1974
+ ...buildSessionActions(parsedConfig),
1975
+ ...buildPromptActions(parsedConfig),
1976
+ ...buildConfigActions(parsedConfig),
1977
+ ...buildSessionPersistenceActions(parsedConfig),
1978
+ ...buildProcessActions(parsedConfig),
1979
+ ...buildFilesystemActions(parsedConfig),
1980
+ ...buildPreviewActions(parsedConfig),
1981
+ ...buildShellActions(parsedConfig),
1982
+ ...buildCronActions(parsedConfig),
1983
+ ...buildNetworkActions(parsedConfig)
1984
+ };
1985
+ return actor({
1986
+ options: {
1987
+ sleepGracePeriod: 9e5,
1988
+ actionTimeout: 9e5
1989
+ },
1990
+ createState: async () => ({}),
1991
+ createVars: () => ({
1992
+ agentOs: null,
1993
+ activeSessionIds: /* @__PURE__ */ new Set(),
1994
+ activeProcesses: /* @__PURE__ */ new Set(),
1995
+ activeHooks: /* @__PURE__ */ new Set(),
1996
+ activeShells: /* @__PURE__ */ new Set(),
1997
+ sessions: /* @__PURE__ */ new Set()
1998
+ }),
1999
+ db: db({
2000
+ onMigrate: migrateAgentOsTables
2001
+ }),
2002
+ events: {
2003
+ sessionEvent: sessionEventToken,
2004
+ permissionRequest: permissionRequestToken,
2005
+ vmBooted: vmBootedToken,
2006
+ vmShutdown: vmShutdownToken,
2007
+ processOutput: processOutputToken,
2008
+ processExit: processExitToken,
2009
+ shellData: shellDataToken,
2010
+ cronEvent: cronEventToken
2011
+ },
2012
+ onBeforeConnect: parsedConfig.onBeforeConnect ? async (ctx, params) => {
2013
+ var _a;
2014
+ if (ctx.request) {
2015
+ const url = new URL(ctx.request.url);
2016
+ if (url.pathname.startsWith("/fetch/")) {
2017
+ return;
2018
+ }
1514
2019
  }
1515
- const token = generateToken();
1516
- const now = Date.now();
1517
- const expiresAt = now + effectiveExpires * 1e3;
1518
- await c.db.execute(
1519
- `INSERT INTO agent_os_preview_tokens (token, port, created_at, expires_at)
1520
- VALUES (?, ?, ?, ?)`,
1521
- token,
1522
- port,
1523
- now,
1524
- expiresAt
1525
- );
1526
- await c.db.execute(
1527
- `DELETE FROM agent_os_preview_tokens WHERE expires_at <= ?`,
1528
- now
1529
- );
1530
- const path = `/request/fetch/${token}`;
2020
+ await ((_a = parsedConfig.onBeforeConnect) == null ? void 0 : _a.call(parsedConfig, ctx, params));
2021
+ } : void 0,
2022
+ onRequest: buildOnRequestHandler(parsedConfig),
2023
+ onSleep: async (c) => {
1531
2024
  c.log.info({
1532
- msg: "agent-os preview token created",
1533
- port,
1534
- expiresInSeconds: effectiveExpires
2025
+ msg: "agent-os vm shutdown for sleep",
2026
+ activeSessions: c.vars.sessions.size,
2027
+ activeProcesses: c.vars.activeProcesses.size,
2028
+ activeShells: c.vars.activeShells.size
1535
2029
  });
1536
- return { path, token, port, expiresAt };
2030
+ if (c.vars.agentOs) {
2031
+ await c.vars.agentOs.dispose();
2032
+ c.vars.agentOs = null;
2033
+ }
2034
+ c.broadcast("vmShutdown", { reason: "sleep" });
1537
2035
  },
1538
- expireSignedPreviewUrl: async (c, token) => {
1539
- await c.db.execute(
1540
- `DELETE FROM agent_os_preview_tokens WHERE token = ?`,
1541
- token
1542
- );
1543
- c.log.info({ msg: "agent-os preview token expired", token });
1544
- }
1545
- };
2036
+ onDestroy: async (c) => {
2037
+ c.log.info({
2038
+ msg: "agent-os vm shutdown for destroy",
2039
+ activeSessions: c.vars.sessions.size,
2040
+ activeProcesses: c.vars.activeProcesses.size,
2041
+ activeShells: c.vars.activeShells.size
2042
+ });
2043
+ if (c.vars.agentOs) {
2044
+ await c.vars.agentOs.dispose();
2045
+ c.vars.agentOs = null;
2046
+ }
2047
+ c.broadcast("vmShutdown", { reason: "destroy" });
2048
+ },
2049
+ actions
2050
+ });
1546
2051
  }
1547
-
1548
- // src/agent-os/actor/process.ts
1549
- function broadcastProcessEvent(c, name, payload) {
1550
- try {
1551
- c.broadcast(name, payload);
1552
- } catch (error) {
1553
- if (isRivetErrorCode(error, "actor", "stopping")) {
1554
- return;
1555
- }
1556
- throw error;
2052
+ var sessionEventToken = event();
2053
+ var permissionRequestToken = event();
2054
+ var vmBootedToken = event();
2055
+ var vmShutdownToken = event();
2056
+ var processOutputToken = event();
2057
+ var processExitToken = event();
2058
+ var shellDataToken = event();
2059
+ var cronEventToken = event();
2060
+
2061
+ // src/agent-os/actor/cron.ts
2062
+ function serializeCronAction(action) {
2063
+ var _a;
2064
+ switch (action.type) {
2065
+ case "session":
2066
+ return {
2067
+ type: "session",
2068
+ agentType: action.agentType,
2069
+ prompt: action.prompt,
2070
+ cwd: (_a = action.options) == null ? void 0 : _a.cwd
2071
+ };
2072
+ case "exec":
2073
+ return {
2074
+ type: "exec",
2075
+ command: action.command,
2076
+ args: action.args
2077
+ };
2078
+ case "callback":
2079
+ throw new TypeError("callback cron actions are not serializable");
1557
2080
  }
1558
2081
  }
1559
- function buildProcessActions(config) {
2082
+ function serializeCronJob(job) {
2083
+ var _a, _b;
1560
2084
  return {
1561
- exec: async (c, command, options) => {
1562
- const agentOs2 = await ensureVm(c, config);
1563
- return agentOs2.exec(command, options);
1564
- },
1565
- spawn: async (c, command, args, options) => {
2085
+ id: job.id,
2086
+ schedule: job.schedule,
2087
+ action: serializeCronAction(job.action),
2088
+ overlap: job.overlap,
2089
+ lastRun: (_a = job.lastRun) == null ? void 0 : _a.toISOString(),
2090
+ nextRun: (_b = job.nextRun) == null ? void 0 : _b.toISOString(),
2091
+ runCount: job.runCount,
2092
+ running: job.running
2093
+ };
2094
+ }
2095
+ function buildCronActions(config) {
2096
+ return {
2097
+ scheduleCron: async (c, options) => {
1566
2098
  const agentOs2 = await ensureVm(c, config);
1567
- const { pid } = agentOs2.spawn(command, args, {
1568
- ...options,
1569
- onStdout: (data) => {
1570
- var _a;
1571
- broadcastProcessEvent(c, "processOutput", {
1572
- pid,
1573
- stream: "stdout",
1574
- data
1575
- });
1576
- (_a = options == null ? void 0 : options.onStdout) == null ? void 0 : _a.call(options, data);
1577
- },
1578
- onStderr: (data) => {
1579
- var _a;
1580
- broadcastProcessEvent(c, "processOutput", {
1581
- pid,
1582
- stream: "stderr",
1583
- data
1584
- });
1585
- (_a = options == null ? void 0 : options.onStderr) == null ? void 0 : _a.call(options, data);
1586
- }
2099
+ const job = agentOs2.scheduleCron({
2100
+ id: options.id,
2101
+ schedule: options.schedule,
2102
+ action: options.action,
2103
+ overlap: options.overlap
1587
2104
  });
1588
- c.vars.activeProcesses.add(pid);
1589
- syncPreventSleep(c);
1590
2105
  c.log.info({
1591
- msg: "agent-os process spawned",
1592
- pid,
1593
- command
1594
- });
1595
- agentOs2.waitProcess(pid).then((exitCode) => {
1596
- broadcastProcessEvent(c, "processExit", { pid, exitCode });
1597
- c.log.info({
1598
- msg: "agent-os process exited",
1599
- pid,
1600
- exitCode
1601
- });
1602
- }).catch(() => {
1603
- }).finally(() => {
1604
- c.vars.activeProcesses.delete(pid);
1605
- syncPreventSleep(c);
2106
+ msg: "agent-os cron job scheduled",
2107
+ jobId: job.id,
2108
+ schedule: options.schedule
1606
2109
  });
1607
- return { pid };
1608
- },
1609
- writeProcessStdin: async (c, pid, data) => {
1610
- const agentOs2 = await ensureVm(c, config);
1611
- agentOs2.writeProcessStdin(pid, data);
1612
- },
1613
- closeProcessStdin: async (c, pid) => {
1614
- const agentOs2 = await ensureVm(c, config);
1615
- agentOs2.closeProcessStdin(pid);
1616
- },
1617
- waitProcess: async (c, pid) => {
1618
- const agentOs2 = await ensureVm(c, config);
1619
- return agentOs2.waitProcess(pid);
1620
- },
1621
- listProcesses: async (c) => {
1622
- const agentOs2 = await ensureVm(c, config);
1623
- return agentOs2.listProcesses();
1624
- },
1625
- allProcesses: async (c) => {
1626
- const agentOs2 = await ensureVm(c, config);
1627
- return agentOs2.allProcesses();
1628
- },
1629
- processTree: async (c) => {
1630
- const agentOs2 = await ensureVm(c, config);
1631
- return agentOs2.processTree();
1632
- },
1633
- getProcess: async (c, pid) => {
1634
- const agentOs2 = await ensureVm(c, config);
1635
- return agentOs2.getProcess(pid);
2110
+ return { id: job.id };
1636
2111
  },
1637
- stopProcess: async (c, pid) => {
2112
+ listCronJobs: async (c) => {
1638
2113
  const agentOs2 = await ensureVm(c, config);
1639
- agentOs2.stopProcess(pid);
2114
+ return agentOs2.listCronJobs().map(serializeCronJob);
1640
2115
  },
1641
- killProcess: async (c, pid) => {
2116
+ cancelCronJob: async (c, id) => {
1642
2117
  const agentOs2 = await ensureVm(c, config);
1643
- agentOs2.killProcess(pid);
2118
+ agentOs2.cancelCronJob(id);
2119
+ c.log.info({ msg: "agent-os cron job cancelled", jobId: id });
1644
2120
  }
1645
2121
  };
1646
2122
  }
1647
2123
 
1648
- // src/agent-os/actor/session.ts
1649
- function stripFunctions(value) {
1650
- if (value === null || value === void 0) return value;
1651
- if (typeof value === "function") return void 0;
1652
- if (typeof value !== "object") return value;
1653
- if (Array.isArray(value)) return value.map(stripFunctions);
1654
- const out = {};
1655
- for (const [k, v] of Object.entries(value)) {
1656
- if (typeof v !== "function") {
1657
- out[k] = stripFunctions(v);
1658
- }
2124
+ // src/agent-os/fs/database-vfs.ts
2125
+ var _posix = require('path/posix'); var posixPath = _interopRequireWildcard(_posix);
2126
+ var S_IFDIR = 16384;
2127
+ var S_IFREG = 32768;
2128
+ var S_IFLNK = 40960;
2129
+ var DEFAULT_FILE_MODE = S_IFREG | 420;
2130
+ var DEFAULT_DIR_MODE = S_IFDIR | 493;
2131
+ function normPath(p) {
2132
+ const normalized = posixPath.normalize(`/${p}`);
2133
+ if (normalized.length > 1 && normalized.endsWith("/")) {
2134
+ return normalized.slice(0, -1);
1659
2135
  }
1660
- return out;
2136
+ return normalized;
1661
2137
  }
1662
- function assertSessionExists(c, sessionId) {
1663
- if (!c.vars.sessions.has(sessionId)) {
1664
- throw new Error(`session not found: ${sessionId}`);
1665
- }
2138
+ function parentPath(p) {
2139
+ const parent = posixPath.dirname(p);
2140
+ return parent;
1666
2141
  }
1667
- function toSessionRecord(agentOs2, sessionId, agentType) {
1668
- return {
1669
- sessionId,
1670
- agentType,
1671
- capabilities: _nullishCoalesce(agentOs2.getSessionCapabilities(sessionId), () => ( {})),
1672
- agentInfo: agentOs2.getSessionAgentInfo(sessionId)
1673
- };
2142
+ function throwENOENT(path) {
2143
+ const err = new Error(`ENOENT: no such file or directory: ${path}`);
2144
+ err.name = "ENOENT";
2145
+ throw err;
1674
2146
  }
1675
- async function persistSession(c, agentOs2, sessionId, agentType) {
1676
- const now = Date.now();
1677
- const capabilities = _nullishCoalesce(agentOs2.getSessionCapabilities(sessionId), () => ( {}));
1678
- const agentInfo = agentOs2.getSessionAgentInfo(sessionId);
1679
- await c.db.execute(
1680
- `INSERT OR REPLACE INTO agent_os_sessions (session_id, agent_type, capabilities, agent_info, created_at)
1681
- VALUES (?, ?, ?, ?, ?)`,
1682
- sessionId,
1683
- agentType,
1684
- JSON.stringify(capabilities),
1685
- agentInfo ? JSON.stringify(agentInfo) : null,
1686
- now
1687
- );
2147
+ function throwEEXIST(path) {
2148
+ const err = new Error(`EEXIST: file already exists: ${path}`);
2149
+ err.name = "EEXIST";
2150
+ throw err;
1688
2151
  }
1689
- async function persistSessionEvent(c, sessionId, event2) {
1690
- var _a;
1691
- const now = Date.now();
1692
- const rows = await c.db.execute(
1693
- `SELECT MAX(seq) as max_seq FROM agent_os_session_events WHERE session_id = ?`,
1694
- sessionId
1695
- );
1696
- const nextSeq = (_nullishCoalesce(((_a = rows[0]) == null ? void 0 : _a.max_seq), () => ( -1))) + 1;
1697
- await c.db.execute(
1698
- `INSERT INTO agent_os_session_events (session_id, seq, event, created_at)
1699
- VALUES (?, ?, ?, ?)`,
1700
- sessionId,
1701
- nextSeq,
1702
- JSON.stringify(event2),
1703
- now
1704
- );
2152
+ function throwENOTDIR(path) {
2153
+ const err = new Error(`ENOTDIR: not a directory: ${path}`);
2154
+ err.name = "ENOTDIR";
2155
+ throw err;
1705
2156
  }
1706
- async function deletePersistedSession(c, sessionId) {
1707
- await c.db.execute(
1708
- `DELETE FROM agent_os_session_events WHERE session_id = ?`,
1709
- sessionId
1710
- );
1711
- await c.db.execute(
1712
- `DELETE FROM agent_os_sessions WHERE session_id = ?`,
1713
- sessionId
1714
- );
2157
+ function throwEISDIR(path) {
2158
+ const err = new Error(`EISDIR: illegal operation on a directory: ${path}`);
2159
+ err.name = "EISDIR";
2160
+ throw err;
1715
2161
  }
1716
- function subscribeToSession(c, agentOs2, sessionId, parsedConfig) {
1717
- agentOs2.onSessionEvent(sessionId, (event2) => {
1718
- c.broadcast(
1719
- "sessionEvent",
1720
- JSON.parse(JSON.stringify({ sessionId, event: event2 }))
1721
- );
1722
- persistSessionEvent(c, sessionId, event2).catch(
1723
- (err) => c.log.error({
1724
- msg: "agent-os failed to persist session event",
1725
- sessionId,
1726
- error: err
1727
- })
2162
+ function throwENOTEMPTY(path) {
2163
+ const err = new Error(`ENOTEMPTY: directory not empty: ${path}`);
2164
+ err.name = "ENOTEMPTY";
2165
+ throw err;
2166
+ }
2167
+ function throwENOSYS(op) {
2168
+ const err = new Error(`ENOSYS: function not implemented: ${op}`);
2169
+ err.name = "ENOSYS";
2170
+ throw err;
2171
+ }
2172
+ function rowToStat(row) {
2173
+ return {
2174
+ mode: row.mode,
2175
+ size: row.size,
2176
+ isDirectory: row.is_directory === 1,
2177
+ isSymbolicLink: row.symlink_target !== null,
2178
+ atimeMs: row.atime_ms,
2179
+ mtimeMs: row.mtime_ms,
2180
+ ctimeMs: row.ctime_ms,
2181
+ birthtimeMs: row.birthtime_ms,
2182
+ ino: 0,
2183
+ nlink: row.nlink,
2184
+ uid: row.uid,
2185
+ gid: row.gid
2186
+ };
2187
+ }
2188
+ function createDatabaseVfs(options) {
2189
+ const { db: db2 } = options;
2190
+ async function getEntry(path) {
2191
+ const rows = await db2.execute(
2192
+ "SELECT * FROM agent_os_fs_entries WHERE path = ?",
2193
+ path
1728
2194
  );
1729
- if (parsedConfig.onSessionEvent) {
1730
- runHook(
1731
- c,
1732
- "onSessionEvent",
1733
- () => {
1734
- var _a;
1735
- return (_a = parsedConfig.onSessionEvent) == null ? void 0 : _a.call(parsedConfig, c, sessionId, event2);
1736
- }
1737
- );
2195
+ return rows[0];
2196
+ }
2197
+ async function getEntryOrThrow(path) {
2198
+ const entry = await getEntry(path);
2199
+ if (!entry) {
2200
+ throwENOENT(path);
2201
+ }
2202
+ return entry;
2203
+ }
2204
+ async function ensureParentExists(path) {
2205
+ const parent = parentPath(path);
2206
+ if (parent === path) return;
2207
+ const entry = await getEntry(parent);
2208
+ if (!entry) {
2209
+ throwENOENT(parent);
1738
2210
  }
1739
- });
1740
- agentOs2.onPermissionRequest(sessionId, (request) => {
1741
- c.broadcast(
1742
- "permissionRequest",
1743
- JSON.parse(JSON.stringify({ sessionId, request }))
2211
+ if (entry.is_directory !== 1) {
2212
+ throwENOTDIR(parent);
2213
+ }
2214
+ }
2215
+ async function getChildEntries(dirPath) {
2216
+ const prefix = dirPath === "/" ? "/" : `${dirPath}/`;
2217
+ const rows = await db2.execute(
2218
+ "SELECT * FROM agent_os_fs_entries WHERE path LIKE ? AND path != ?",
2219
+ `${prefix}%`,
2220
+ dirPath
1744
2221
  );
1745
- if (parsedConfig.onPermissionRequest) {
1746
- runHook(
1747
- c,
1748
- "onPermissionRequest",
1749
- () => {
1750
- var _a;
1751
- return (_a = parsedConfig.onPermissionRequest) == null ? void 0 : _a.call(parsedConfig, c, sessionId, request);
1752
- }
2222
+ return rows.filter((row) => {
2223
+ const relative = row.path.slice(prefix.length);
2224
+ return relative.length > 0 && !relative.includes("/");
2225
+ });
2226
+ }
2227
+ const rootInit = (async () => {
2228
+ const root = await getEntry("/");
2229
+ if (!root) {
2230
+ const now = Date.now();
2231
+ await db2.execute(
2232
+ `INSERT OR IGNORE INTO agent_os_fs_entries (path, is_directory, content, mode, uid, gid, size, atime_ms, mtime_ms, ctime_ms, birthtime_ms, symlink_target, nlink) VALUES (?, 1, NULL, ?, 0, 0, 0, ?, ?, ?, ?, NULL, 2)`,
2233
+ "/",
2234
+ DEFAULT_DIR_MODE,
2235
+ now,
2236
+ now,
2237
+ now,
2238
+ now
1753
2239
  );
1754
2240
  }
1755
- });
1756
- c.vars.sessions.add(sessionId);
1757
- }
1758
- function buildSessionActions(config) {
1759
- return {
1760
- createSession: async (c, agentType, options) => {
1761
- const agentOs2 = await ensureVm(c, config);
1762
- const { sessionId } = await agentOs2.createSession(
1763
- agentType,
1764
- options
1765
- );
1766
- subscribeToSession(c, agentOs2, sessionId, config);
1767
- await persistSession(c, agentOs2, sessionId, agentType);
1768
- c.log.info({
1769
- msg: "agent-os session created",
1770
- sessionId,
1771
- agentType
1772
- });
1773
- return toSessionRecord(agentOs2, sessionId, agentType);
1774
- },
1775
- listSessions: async (c) => {
1776
- const agentOs2 = await ensureVm(c, config);
1777
- return agentOs2.listSessions();
1778
- },
1779
- getSession: async (c, sessionId) => {
1780
- assertSessionExists(c, sessionId);
1781
- const agentOs2 = await ensureVm(c, config);
1782
- const info = agentOs2.listSessions().find((s) => s.sessionId === sessionId);
1783
- if (!info) {
1784
- throw new Error(`session not found: ${sessionId}`);
2241
+ })();
2242
+ const backend = {
2243
+ async readFile(p) {
2244
+ await rootInit;
2245
+ const path = normPath(p);
2246
+ const entry = await getEntryOrThrow(path);
2247
+ if (entry.is_directory === 1) {
2248
+ throwEISDIR(path);
1785
2249
  }
1786
- return toSessionRecord(agentOs2, sessionId, info.agentType);
1787
- },
1788
- destroySession: async (c, sessionId) => {
1789
- const agentOs2 = await ensureVm(c, config);
1790
- await agentOs2.destroySession(sessionId);
1791
- c.vars.sessions.delete(sessionId);
1792
- c.vars.activeSessionIds.delete(sessionId);
1793
- syncPreventSleep(c);
1794
- await deletePersistedSession(c, sessionId);
1795
- c.log.info({ msg: "agent-os session destroyed", sessionId });
1796
- },
1797
- resumeSession: async (c, sessionId) => {
1798
- const agentOs2 = await ensureVm(c, config);
1799
- return agentOs2.resumeSession(sessionId);
2250
+ return _nullishCoalesce(entry.content, () => ( new Uint8Array(0)));
1800
2251
  },
1801
- closeSession: async (c, sessionId) => {
1802
- const agentOs2 = await ensureVm(c, config);
1803
- agentOs2.closeSession(sessionId);
1804
- c.vars.sessions.delete(sessionId);
1805
- c.vars.activeSessionIds.delete(sessionId);
1806
- syncPreventSleep(c);
1807
- await deletePersistedSession(c, sessionId);
1808
- c.log.info({ msg: "agent-os session closed", sessionId });
1809
- }
1810
- };
1811
- }
1812
- function buildPromptActions(_config) {
1813
- return {
1814
- sendPrompt: async (c, sessionId, text) => {
1815
- if (c.aborted) {
1816
- throw new Error(
1817
- "actor is shutting down, cannot start new prompt"
1818
- );
1819
- }
1820
- assertSessionExists(c, sessionId);
1821
- const agentOs2 = c.vars.agentOs;
1822
- if (!agentOs2) {
1823
- throw new Error("VM not initialized");
1824
- }
1825
- c.vars.activeSessionIds.add(sessionId);
1826
- syncPreventSleep(c);
1827
- c.log.info({ msg: "agent-os prompt turn started", sessionId });
1828
- const start = Date.now();
1829
- try {
1830
- const result = await agentOs2.prompt(sessionId, text);
1831
- return {
1832
- response: JSON.parse(JSON.stringify(result.response)),
1833
- text: result.text
1834
- };
1835
- } finally {
1836
- c.vars.activeSessionIds.delete(sessionId);
1837
- syncPreventSleep(c);
1838
- c.log.info({
1839
- msg: "agent-os prompt turn ended",
1840
- sessionId,
1841
- durationMs: Date.now() - start
1842
- });
1843
- }
2252
+ async readTextFile(p) {
2253
+ const data = await backend.readFile(p);
2254
+ return new TextDecoder().decode(data);
1844
2255
  },
1845
- cancelPrompt: async (c, sessionId) => {
1846
- assertSessionExists(c, sessionId);
1847
- const agentOs2 = c.vars.agentOs;
1848
- if (!agentOs2) {
1849
- throw new Error("VM not initialized");
2256
+ async readDir(p) {
2257
+ await rootInit;
2258
+ const path = normPath(p);
2259
+ const entry = await getEntryOrThrow(path);
2260
+ if (entry.is_directory !== 1) {
2261
+ throwENOTDIR(path);
1850
2262
  }
1851
- return stripFunctions(
1852
- agentOs2.cancelSession(sessionId)
1853
- );
2263
+ const children = await getChildEntries(path);
2264
+ return children.map((child) => posixPath.basename(child.path));
1854
2265
  },
1855
- respondPermission: async (c, sessionId, permissionId, reply) => {
1856
- assertSessionExists(c, sessionId);
1857
- const agentOs2 = c.vars.agentOs;
1858
- if (!agentOs2) {
1859
- throw new Error("VM not initialized");
1860
- }
1861
- return stripFunctions(
1862
- agentOs2.respondPermission(sessionId, permissionId, reply)
1863
- );
1864
- }
1865
- };
1866
- }
1867
- function buildConfigActions(_config) {
1868
- return {
1869
- setMode: async (c, sessionId, modeId) => {
1870
- assertSessionExists(c, sessionId);
1871
- const agentOs2 = c.vars.agentOs;
1872
- if (!agentOs2) {
1873
- throw new Error("VM not initialized");
2266
+ async readDirWithTypes(p) {
2267
+ await rootInit;
2268
+ const path = normPath(p);
2269
+ const entry = await getEntryOrThrow(path);
2270
+ if (entry.is_directory !== 1) {
2271
+ throwENOTDIR(path);
1874
2272
  }
1875
- return stripFunctions(
1876
- agentOs2.setSessionMode(sessionId, modeId)
1877
- );
2273
+ const children = await getChildEntries(path);
2274
+ return children.map((child) => ({
2275
+ name: posixPath.basename(child.path),
2276
+ isDirectory: child.is_directory === 1,
2277
+ isSymbolicLink: child.symlink_target !== null,
2278
+ ino: 0
2279
+ }));
1878
2280
  },
1879
- getModes: async (c, sessionId) => {
1880
- assertSessionExists(c, sessionId);
1881
- const agentOs2 = c.vars.agentOs;
1882
- if (!agentOs2) {
1883
- throw new Error("VM not initialized");
2281
+ async writeFile(p, content) {
2282
+ await rootInit;
2283
+ const path = normPath(p);
2284
+ await ensureParentExists(path);
2285
+ const existing = await getEntry(path);
2286
+ if (existing && existing.is_directory === 1) {
2287
+ throwEISDIR(path);
1884
2288
  }
1885
- return agentOs2.getSessionModes(sessionId);
1886
- },
1887
- setModel: async (c, sessionId, model) => {
1888
- assertSessionExists(c, sessionId);
1889
- const agentOs2 = c.vars.agentOs;
1890
- if (!agentOs2) {
1891
- throw new Error("VM not initialized");
2289
+ const data = typeof content === "string" ? new TextEncoder().encode(content) : content;
2290
+ const now = Date.now();
2291
+ if (existing) {
2292
+ await db2.execute(
2293
+ `UPDATE agent_os_fs_entries SET content = ?, size = ?, mtime_ms = ?, ctime_ms = ?, atime_ms = ? WHERE path = ?`,
2294
+ data,
2295
+ data.byteLength,
2296
+ now,
2297
+ now,
2298
+ now,
2299
+ path
2300
+ );
2301
+ } else {
2302
+ await db2.execute(
2303
+ `INSERT INTO agent_os_fs_entries (path, is_directory, content, mode, uid, gid, size, atime_ms, mtime_ms, ctime_ms, birthtime_ms, symlink_target, nlink) VALUES (?, 0, ?, ?, 0, 0, ?, ?, ?, ?, ?, NULL, 1)`,
2304
+ path,
2305
+ data,
2306
+ DEFAULT_FILE_MODE,
2307
+ data.byteLength,
2308
+ now,
2309
+ now,
2310
+ now,
2311
+ now
2312
+ );
1892
2313
  }
1893
- return stripFunctions(
1894
- agentOs2.setSessionModel(sessionId, model)
1895
- );
1896
2314
  },
1897
- setThoughtLevel: async (c, sessionId, level) => {
1898
- assertSessionExists(c, sessionId);
1899
- const agentOs2 = c.vars.agentOs;
1900
- if (!agentOs2) {
1901
- throw new Error("VM not initialized");
2315
+ async createDir(p) {
2316
+ await rootInit;
2317
+ const path = normPath(p);
2318
+ await ensureParentExists(path);
2319
+ const existing = await getEntry(path);
2320
+ if (existing) {
2321
+ throwEEXIST(path);
1902
2322
  }
1903
- return stripFunctions(
1904
- agentOs2.setSessionThoughtLevel(sessionId, level)
2323
+ const now = Date.now();
2324
+ await db2.execute(
2325
+ `INSERT INTO agent_os_fs_entries (path, is_directory, content, mode, uid, gid, size, atime_ms, mtime_ms, ctime_ms, birthtime_ms, symlink_target, nlink) VALUES (?, 1, NULL, ?, 0, 0, 0, ?, ?, ?, ?, NULL, 2)`,
2326
+ path,
2327
+ DEFAULT_DIR_MODE,
2328
+ now,
2329
+ now,
2330
+ now,
2331
+ now
1905
2332
  );
1906
2333
  },
1907
- getConfigOptions: async (c, sessionId) => {
1908
- assertSessionExists(c, sessionId);
1909
- const agentOs2 = c.vars.agentOs;
1910
- if (!agentOs2) {
1911
- throw new Error("VM not initialized");
2334
+ async mkdir(p, options2) {
2335
+ await rootInit;
2336
+ const path = normPath(p);
2337
+ if (options2 == null ? void 0 : options2.recursive) {
2338
+ const parts = path.split("/").filter(Boolean);
2339
+ let current = "";
2340
+ for (const part of parts) {
2341
+ current += `/${part}`;
2342
+ const existing = await getEntry(current);
2343
+ if (!existing) {
2344
+ const now = Date.now();
2345
+ await db2.execute(
2346
+ `INSERT INTO agent_os_fs_entries (path, is_directory, content, mode, uid, gid, size, atime_ms, mtime_ms, ctime_ms, birthtime_ms, symlink_target, nlink) VALUES (?, 1, NULL, ?, 0, 0, 0, ?, ?, ?, ?, NULL, 2)`,
2347
+ current,
2348
+ DEFAULT_DIR_MODE,
2349
+ now,
2350
+ now,
2351
+ now,
2352
+ now
2353
+ );
2354
+ } else if (existing.is_directory !== 1) {
2355
+ throwENOTDIR(current);
2356
+ }
2357
+ }
2358
+ } else {
2359
+ await backend.createDir(p);
1912
2360
  }
1913
- return agentOs2.getSessionConfigOptions(sessionId);
1914
2361
  },
1915
- getEvents: async (c, sessionId, options) => {
1916
- assertSessionExists(c, sessionId);
1917
- const agentOs2 = c.vars.agentOs;
1918
- if (!agentOs2) {
1919
- throw new Error("VM not initialized");
1920
- }
1921
- return agentOs2.getSessionEvents(sessionId, options).map((e) => e.notification);
2362
+ async exists(p) {
2363
+ await rootInit;
2364
+ const path = normPath(p);
2365
+ const entry = await getEntry(path);
2366
+ return entry !== void 0;
1922
2367
  },
1923
- getSequencedEvents: async (c, sessionId, options) => {
1924
- assertSessionExists(c, sessionId);
1925
- const agentOs2 = c.vars.agentOs;
1926
- if (!agentOs2) {
1927
- throw new Error("VM not initialized");
1928
- }
1929
- return agentOs2.getSessionEvents(sessionId, options);
2368
+ async stat(p) {
2369
+ await rootInit;
2370
+ const path = normPath(p);
2371
+ const entry = await getEntryOrThrow(path);
2372
+ return rowToStat(entry);
1930
2373
  },
1931
- rawSend: async (c, sessionId, method, params) => {
1932
- assertSessionExists(c, sessionId);
1933
- const agentOs2 = c.vars.agentOs;
1934
- if (!agentOs2) {
1935
- throw new Error("VM not initialized");
2374
+ async removeFile(p) {
2375
+ await rootInit;
2376
+ const path = normPath(p);
2377
+ const entry = await getEntryOrThrow(path);
2378
+ if (entry.is_directory === 1) {
2379
+ throwEISDIR(path);
1936
2380
  }
1937
- return stripFunctions(
1938
- agentOs2.rawSessionSend(sessionId, method, params)
1939
- );
1940
- }
1941
- };
1942
- }
1943
- function buildSessionPersistenceActions(_config) {
1944
- return {
1945
- listPersistedSessions: async (c) => {
1946
- const rows = await c.db.execute(
1947
- `SELECT session_id, agent_type, capabilities, agent_info, created_at
1948
- FROM agent_os_sessions
1949
- ORDER BY created_at ASC`
2381
+ await db2.execute(
2382
+ "DELETE FROM agent_os_fs_entries WHERE path = ?",
2383
+ path
1950
2384
  );
1951
- return rows.map((row) => ({
1952
- sessionId: row.session_id,
1953
- agentType: row.agent_type,
1954
- capabilities: JSON.parse(row.capabilities),
1955
- agentInfo: row.agent_info ? JSON.parse(row.agent_info) : null,
1956
- createdAt: row.created_at
1957
- }));
1958
2385
  },
1959
- getSessionEvents: async (c, sessionId) => {
1960
- const rows = await c.db.execute(
1961
- `SELECT session_id, seq, event, created_at
1962
- FROM agent_os_session_events
1963
- WHERE session_id = ?
1964
- ORDER BY seq ASC`,
1965
- sessionId
2386
+ async removeDir(p) {
2387
+ await rootInit;
2388
+ const path = normPath(p);
2389
+ const entry = await getEntryOrThrow(path);
2390
+ if (entry.is_directory !== 1) {
2391
+ throwENOTDIR(path);
2392
+ }
2393
+ const children = await getChildEntries(path);
2394
+ if (children.length > 0) {
2395
+ throwENOTEMPTY(path);
2396
+ }
2397
+ await db2.execute(
2398
+ "DELETE FROM agent_os_fs_entries WHERE path = ?",
2399
+ path
1966
2400
  );
1967
- return rows.map((row) => ({
1968
- sessionId: row.session_id,
1969
- seq: row.seq,
1970
- event: JSON.parse(row.event),
1971
- createdAt: row.created_at
1972
- }));
1973
- }
1974
- };
1975
- }
1976
-
1977
- // src/agent-os/actor/shell.ts
1978
- function buildShellActions(config) {
1979
- return {
1980
- openShell: async (c, options) => {
1981
- const agentOs2 = await ensureVm(c, config);
1982
- const { shellId } = agentOs2.openShell(options);
1983
- agentOs2.onShellData(shellId, (data) => {
1984
- c.broadcast("shellData", { shellId, data });
1985
- });
1986
- c.vars.activeShells.add(shellId);
1987
- syncPreventSleep(c);
1988
- c.log.info({ msg: "agent-os shell opened", shellId });
1989
- return { shellId };
1990
- },
1991
- writeShell: async (c, shellId, data) => {
1992
- const agentOs2 = await ensureVm(c, config);
1993
- agentOs2.writeShell(shellId, data);
1994
- },
1995
- resizeShell: async (c, shellId, cols, rows) => {
1996
- const agentOs2 = await ensureVm(c, config);
1997
- agentOs2.resizeShell(shellId, cols, rows);
1998
- },
1999
- closeShell: async (c, shellId) => {
2000
- const agentOs2 = await ensureVm(c, config);
2001
- agentOs2.closeShell(shellId);
2002
- c.vars.activeShells.delete(shellId);
2003
- syncPreventSleep(c);
2004
- c.log.info({ msg: "agent-os shell closed", shellId });
2005
- }
2006
- };
2007
- }
2008
-
2009
- // src/agent-os/actor/index.ts
2010
- async function ensureVm(c, config) {
2011
- if (c.vars.agentOs) {
2012
- return c.vars.agentOs;
2013
- }
2014
- const start = Date.now();
2015
- const options = buildVmOptions(config.options);
2016
- const agentOs2 = await _agentoscore.AgentOs.create(options);
2017
- c.vars.agentOs = agentOs2;
2018
- agentOs2.onCronEvent((cronEvent) => {
2019
- c.broadcast("cronEvent", { event: cronEvent });
2020
- });
2021
- c.broadcast("vmBooted", {});
2022
- c.log.info({
2023
- msg: "agent-os vm booted",
2024
- bootDurationMs: Date.now() - start
2025
- });
2026
- return agentOs2;
2027
- }
2028
- function buildVmOptions(userOptions) {
2029
- const userMounts = _nullishCoalesce((userOptions == null ? void 0 : userOptions.mounts), () => ( []));
2030
- const hasWorkdirMount = userMounts.some(
2031
- (m) => m.path === "/home/user"
2032
- );
2033
- if (hasWorkdirMount) {
2034
- return _nullishCoalesce(userOptions, () => ( {}));
2035
- }
2036
- const memMount = {
2037
- path: "/home/user",
2038
- driver: _agentoscore.createInMemoryFileSystem.call(void 0, )
2039
- };
2040
- return {
2041
- ...userOptions,
2042
- mounts: [memMount, ...userMounts]
2043
- };
2044
- }
2045
- function syncPreventSleep(c) {
2046
- const shouldPrevent = c.vars.activeSessionIds.size > 0 || c.vars.activeProcesses.size > 0 || c.vars.activeHooks.size > 0 || c.vars.activeShells.size > 0;
2047
- c.setPreventSleep(shouldPrevent);
2048
- c.log.info({
2049
- msg: "agent-os prevent sleep sync",
2050
- preventSleep: shouldPrevent,
2051
- activeSessions: c.vars.activeSessionIds.size,
2052
- activeProcesses: c.vars.activeProcesses.size,
2053
- activeHooks: c.vars.activeHooks.size,
2054
- activeShells: c.vars.activeShells.size
2055
- });
2056
- }
2057
- function runHook(c, name, callback) {
2058
- const promise = Promise.resolve(callback()).catch(
2059
- (error) => c.log.error({ msg: "agent-os hook failed", hookName: name, error })
2060
- ).finally(() => {
2061
- c.vars.activeHooks.delete(promise);
2062
- syncPreventSleep(c);
2063
- });
2064
- c.vars.activeHooks.add(promise);
2065
- syncPreventSleep(c);
2066
- c.waitUntil(promise);
2067
- }
2068
- function agentOs(config) {
2069
- const parsedConfig = agentOsActorConfigSchema.parse(
2070
- config
2071
- );
2072
- return actor({
2073
- options: {
2074
- sleepGracePeriod: 9e5,
2075
- actionTimeout: 9e5
2076
- },
2077
- createState: async () => ({}),
2078
- createVars: () => ({
2079
- agentOs: null,
2080
- activeSessionIds: /* @__PURE__ */ new Set(),
2081
- activeProcesses: /* @__PURE__ */ new Set(),
2082
- activeHooks: /* @__PURE__ */ new Set(),
2083
- activeShells: /* @__PURE__ */ new Set(),
2084
- sessions: /* @__PURE__ */ new Set()
2085
- }),
2086
- db: db({
2087
- onMigrate: migrateAgentOsTables
2088
- }),
2089
- events: {
2090
- sessionEvent: sessionEventToken,
2091
- permissionRequest: permissionRequestToken,
2092
- vmBooted: vmBootedToken,
2093
- vmShutdown: vmShutdownToken,
2094
- processOutput: processOutputToken,
2095
- processExit: processExitToken,
2096
- shellData: shellDataToken,
2097
- cronEvent: cronEventToken
2098
2401
  },
2099
- onBeforeConnect: parsedConfig.onBeforeConnect ? async (ctx, params) => {
2100
- var _a;
2101
- if (ctx.request) {
2102
- const url = new URL(ctx.request.url);
2103
- if (url.pathname.startsWith("/fetch/")) {
2104
- return;
2402
+ async rename(oldPath, newPath) {
2403
+ await rootInit;
2404
+ const from = normPath(oldPath);
2405
+ const to = normPath(newPath);
2406
+ const entry = await getEntryOrThrow(from);
2407
+ await ensureParentExists(to);
2408
+ const destEntry = await getEntry(to);
2409
+ if (destEntry) {
2410
+ if (destEntry.is_directory === 1) {
2411
+ const children = await getChildEntries(to);
2412
+ if (children.length > 0) {
2413
+ throwENOTEMPTY(to);
2414
+ }
2105
2415
  }
2416
+ await db2.execute(
2417
+ "DELETE FROM agent_os_fs_entries WHERE path = ?",
2418
+ to
2419
+ );
2106
2420
  }
2107
- await ((_a = parsedConfig.onBeforeConnect) == null ? void 0 : _a.call(parsedConfig, ctx, params));
2108
- } : void 0,
2109
- onRequest: buildOnRequestHandler(parsedConfig),
2110
- onSleep: async (c) => {
2111
- c.log.info({
2112
- msg: "agent-os vm shutdown for sleep",
2113
- activeSessions: c.vars.sessions.size,
2114
- activeProcesses: c.vars.activeProcesses.size,
2115
- activeShells: c.vars.activeShells.size
2116
- });
2117
- if (c.vars.agentOs) {
2118
- await c.vars.agentOs.dispose();
2119
- c.vars.agentOs = null;
2421
+ if (entry.is_directory === 1) {
2422
+ const prefix = from === "/" ? "/" : `${from}/`;
2423
+ const newPrefix = to === "/" ? "/" : `${to}/`;
2424
+ const descendants = await db2.execute(
2425
+ "SELECT path FROM agent_os_fs_entries WHERE path LIKE ?",
2426
+ `${prefix}%`
2427
+ );
2428
+ for (const desc of descendants) {
2429
+ const newDescPath = newPrefix + desc.path.slice(prefix.length);
2430
+ await db2.execute(
2431
+ "UPDATE agent_os_fs_entries SET path = ? WHERE path = ?",
2432
+ newDescPath,
2433
+ desc.path
2434
+ );
2435
+ }
2120
2436
  }
2121
- c.broadcast("vmShutdown", { reason: "sleep" });
2437
+ const now = Date.now();
2438
+ await db2.execute(
2439
+ "UPDATE agent_os_fs_entries SET path = ?, ctime_ms = ? WHERE path = ?",
2440
+ to,
2441
+ now,
2442
+ from
2443
+ );
2122
2444
  },
2123
- onDestroy: async (c) => {
2124
- c.log.info({
2125
- msg: "agent-os vm shutdown for destroy",
2126
- activeSessions: c.vars.sessions.size,
2127
- activeProcesses: c.vars.activeProcesses.size,
2128
- activeShells: c.vars.activeShells.size
2129
- });
2130
- if (c.vars.agentOs) {
2131
- await c.vars.agentOs.dispose();
2132
- c.vars.agentOs = null;
2445
+ async realpath(p) {
2446
+ await rootInit;
2447
+ const path = normPath(p);
2448
+ const entry = await getEntryOrThrow(path);
2449
+ if (entry.symlink_target !== null) {
2450
+ return normPath(entry.symlink_target);
2133
2451
  }
2134
- c.broadcast("vmShutdown", { reason: "destroy" });
2135
- },
2136
- actions: {
2137
- ...buildSessionActions(parsedConfig),
2138
- ...buildPromptActions(parsedConfig),
2139
- ...buildConfigActions(parsedConfig),
2140
- ...buildSessionPersistenceActions(parsedConfig),
2141
- ...buildProcessActions(parsedConfig),
2142
- ...buildFilesystemActions(parsedConfig),
2143
- ...buildPreviewActions(parsedConfig),
2144
- ...buildShellActions(parsedConfig),
2145
- ...buildCronActions(parsedConfig),
2146
- ...buildNetworkActions(parsedConfig)
2147
- }
2148
- });
2149
- }
2150
- var sessionEventToken = event();
2151
- var permissionRequestToken = event();
2152
- var vmBootedToken = event();
2153
- var vmShutdownToken = event();
2154
- var processOutputToken = event();
2155
- var processExitToken = event();
2156
- var shellDataToken = event();
2157
- var cronEventToken = event();
2158
-
2159
- // src/agent-os/actor/filesystem.ts
2160
- function buildFilesystemActions(config) {
2161
- return {
2162
- readFile: async (c, path) => {
2163
- const agentOs2 = await ensureVm(c, config);
2164
- return agentOs2.readFile(path);
2165
- },
2166
- writeFile: async (c, path, content) => {
2167
- const agentOs2 = await ensureVm(c, config);
2168
- await agentOs2.writeFile(path, content);
2452
+ return path;
2169
2453
  },
2170
- readFiles: async (c, paths) => {
2171
- const agentOs2 = await ensureVm(c, config);
2172
- return agentOs2.readFiles(paths);
2454
+ async symlink(target, linkPath) {
2455
+ await rootInit;
2456
+ const link = normPath(linkPath);
2457
+ await ensureParentExists(link);
2458
+ const existing = await getEntry(link);
2459
+ if (existing) {
2460
+ throwEEXIST(link);
2461
+ }
2462
+ const now = Date.now();
2463
+ await db2.execute(
2464
+ `INSERT INTO agent_os_fs_entries (path, is_directory, content, mode, uid, gid, size, atime_ms, mtime_ms, ctime_ms, birthtime_ms, symlink_target, nlink) VALUES (?, 0, NULL, ?, 0, 0, ?, ?, ?, ?, ?, ?, 1)`,
2465
+ link,
2466
+ S_IFLNK | 511,
2467
+ target.length,
2468
+ now,
2469
+ now,
2470
+ now,
2471
+ now,
2472
+ target
2473
+ );
2173
2474
  },
2174
- writeFiles: async (c, entries) => {
2175
- const agentOs2 = await ensureVm(c, config);
2176
- return agentOs2.writeFiles(entries);
2475
+ async readlink(p) {
2476
+ await rootInit;
2477
+ const path = normPath(p);
2478
+ const entry = await getEntryOrThrow(path);
2479
+ if (entry.symlink_target === null) {
2480
+ const err = new Error(`EINVAL: not a symlink: ${path}`);
2481
+ err.name = "EINVAL";
2482
+ throw err;
2483
+ }
2484
+ return entry.symlink_target;
2177
2485
  },
2178
- mkdir: async (c, path, options) => {
2179
- const agentOs2 = await ensureVm(c, config);
2180
- await agentOs2.mkdir(path, options);
2486
+ async lstat(p) {
2487
+ return backend.stat(p);
2181
2488
  },
2182
- readdir: async (c, path) => {
2183
- const agentOs2 = await ensureVm(c, config);
2184
- return agentOs2.readdir(path);
2489
+ async link(_oldPath, _newPath) {
2490
+ throwENOSYS("link");
2185
2491
  },
2186
- readdirRecursive: async (c, path, options) => {
2187
- const agentOs2 = await ensureVm(c, config);
2188
- return agentOs2.readdirRecursive(path, options);
2492
+ async chmod(p, mode) {
2493
+ await rootInit;
2494
+ const path = normPath(p);
2495
+ await getEntryOrThrow(path);
2496
+ const now = Date.now();
2497
+ await db2.execute(
2498
+ "UPDATE agent_os_fs_entries SET mode = ?, ctime_ms = ? WHERE path = ?",
2499
+ mode,
2500
+ now,
2501
+ path
2502
+ );
2189
2503
  },
2190
- stat: async (c, path) => {
2191
- const agentOs2 = await ensureVm(c, config);
2192
- return agentOs2.stat(path);
2504
+ async chown(p, uid, gid) {
2505
+ await rootInit;
2506
+ const path = normPath(p);
2507
+ await getEntryOrThrow(path);
2508
+ const now = Date.now();
2509
+ await db2.execute(
2510
+ "UPDATE agent_os_fs_entries SET uid = ?, gid = ?, ctime_ms = ? WHERE path = ?",
2511
+ uid,
2512
+ gid,
2513
+ now,
2514
+ path
2515
+ );
2193
2516
  },
2194
- exists: async (c, path) => {
2195
- const agentOs2 = await ensureVm(c, config);
2196
- return agentOs2.exists(path);
2517
+ async utimes(p, atime, mtime) {
2518
+ await rootInit;
2519
+ const path = normPath(p);
2520
+ await getEntryOrThrow(path);
2521
+ const now = Date.now();
2522
+ await db2.execute(
2523
+ "UPDATE agent_os_fs_entries SET atime_ms = ?, mtime_ms = ?, ctime_ms = ? WHERE path = ?",
2524
+ atime,
2525
+ mtime,
2526
+ now,
2527
+ path
2528
+ );
2197
2529
  },
2198
- move: async (c, from, to) => {
2199
- const agentOs2 = await ensureVm(c, config);
2200
- await agentOs2.move(from, to);
2530
+ async truncate(p, length) {
2531
+ await rootInit;
2532
+ const path = normPath(p);
2533
+ const entry = await getEntryOrThrow(path);
2534
+ if (entry.is_directory === 1) {
2535
+ throwEISDIR(path);
2536
+ }
2537
+ const existing = _nullishCoalesce(entry.content, () => ( new Uint8Array(0)));
2538
+ let newContent;
2539
+ if (length >= existing.byteLength) {
2540
+ newContent = new Uint8Array(length);
2541
+ newContent.set(existing);
2542
+ } else {
2543
+ newContent = existing.slice(0, length);
2544
+ }
2545
+ const now = Date.now();
2546
+ await db2.execute(
2547
+ "UPDATE agent_os_fs_entries SET content = ?, size = ?, mtime_ms = ?, ctime_ms = ? WHERE path = ?",
2548
+ newContent,
2549
+ length,
2550
+ now,
2551
+ now,
2552
+ path
2553
+ );
2201
2554
  },
2202
- deleteFile: async (c, path, options) => {
2203
- const agentOs2 = await ensureVm(c, config);
2204
- await agentOs2.delete(path, options);
2555
+ async pread(p, offset, length) {
2556
+ await rootInit;
2557
+ const path = normPath(p);
2558
+ const entry = await getEntryOrThrow(path);
2559
+ if (entry.is_directory === 1) {
2560
+ throwEISDIR(path);
2561
+ }
2562
+ const content = _nullishCoalesce(entry.content, () => ( new Uint8Array(0)));
2563
+ const end = Math.min(offset + length, content.byteLength);
2564
+ if (offset >= content.byteLength) {
2565
+ return new Uint8Array(0);
2566
+ }
2567
+ return content.slice(offset, end);
2205
2568
  },
2206
- // TODO: mountFs and unmountFs are not exposed as actor actions because
2207
- // filesystem drivers (VirtualFileSystem) are not serializable over the
2208
- // network. Mount filesystems via the `options.mounts` config in agentOs()
2209
- // instead. See: https://github.com/rivet-dev/rivet/issues/XXXX
2210
- listAgents: async (c) => {
2211
- const agentOs2 = await ensureVm(c, config);
2212
- return agentOs2.listAgents();
2569
+ async pwrite(p, offset, data) {
2570
+ await rootInit;
2571
+ const path = normPath(p);
2572
+ const entry = await getEntryOrThrow(path);
2573
+ if (entry.is_directory === 1) {
2574
+ throwEISDIR(path);
2575
+ }
2576
+ const content = _nullishCoalesce(entry.content, () => ( new Uint8Array(0)));
2577
+ const end = offset + data.byteLength;
2578
+ const newSize = Math.max(content.byteLength, end);
2579
+ const buf = new Uint8Array(newSize);
2580
+ buf.set(content);
2581
+ buf.set(data, offset);
2582
+ const now = Date.now();
2583
+ await db2.execute(
2584
+ `UPDATE agent_os_fs_entries SET content = ?, size = ?, mtime_ms = ?, ctime_ms = ? WHERE path = ?`,
2585
+ buf,
2586
+ newSize,
2587
+ now,
2588
+ now,
2589
+ path
2590
+ );
2213
2591
  }
2214
2592
  };
2593
+ return backend;
2215
2594
  }
2216
2595
 
2217
2596