rivetkit 0.0.0-skip-ready-wait-flatten-client-options.1cae221 → 0.0.0-sqlite-uds.4e59a38

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