@rivet-dev/agentos 0.0.0-main.2f99c77 → 0.0.0-main.5ac5a14

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 (36) hide show
  1. package/assets/inspector-tabs-app/assets/__vite-browser-external-2447137e-BIHI7g3E.js +1 -0
  2. package/assets/inspector-tabs-app/assets/agentos-hero-logo-E3fapwXM.svg +74 -0
  3. package/assets/inspector-tabs-app/assets/filesystem-C-x0K5sy.js +1 -0
  4. package/assets/inspector-tabs-app/assets/hooks-DU8a-cwM.js +1 -0
  5. package/assets/inspector-tabs-app/assets/index-7G_DbdZ6.js +110 -0
  6. package/assets/inspector-tabs-app/assets/index-DG_s1YoH.css +1 -0
  7. package/assets/inspector-tabs-app/assets/scroll-area-kPbv4IGy.js +1 -0
  8. package/assets/inspector-tabs-app/assets/sed-BwsOyU9v.svg +1 -0
  9. package/assets/inspector-tabs-app/assets/system-D98yBhMj.js +2 -0
  10. package/assets/inspector-tabs-app/assets/terminal-Bv9GKv4q.js +13 -0
  11. package/assets/inspector-tabs-app/assets/transcript-kMbm_tF8.js +1 -0
  12. package/assets/inspector-tabs-app/assets/useSuspenseQuery-ChN8rnBd.js +1 -0
  13. package/assets/inspector-tabs-app/assets/vm-boot-gate-rpuO0b5W.js +1 -0
  14. package/assets/inspector-tabs-app/assets/vm-status-badges-09qyfN_A.js +5 -0
  15. package/assets/inspector-tabs-app/index.html +2 -2
  16. package/dist/chunk-V6TY7KAL.js +8 -0
  17. package/dist/chunk-V6TY7KAL.js.map +1 -0
  18. package/dist/client.js.map +1 -1
  19. package/dist/index.d.ts +403 -712
  20. package/dist/index.js +1835 -310
  21. package/dist/index.js.map +1 -1
  22. package/dist/node.d.ts +67 -0
  23. package/dist/node.js +275 -0
  24. package/dist/node.js.map +1 -0
  25. package/package.json +26 -15
  26. package/assets/inspector-tabs-app/assets/badge-Coq9s9H6.js +0 -1
  27. package/assets/inspector-tabs-app/assets/filesystem-_yeTmDH7.js +0 -1
  28. package/assets/inspector-tabs-app/assets/index-C50G2vhD.js +0 -125
  29. package/assets/inspector-tabs-app/assets/index-Dt5XhJ9h.css +0 -1
  30. package/assets/inspector-tabs-app/assets/mounts-C0eJmxpt.js +0 -1
  31. package/assets/inspector-tabs-app/assets/processes-CvN1MFLy.js +0 -1
  32. package/assets/inspector-tabs-app/assets/scroll-area-DzL-iGyn.js +0 -1
  33. package/assets/inspector-tabs-app/assets/software-BjGEcqMs.js +0 -1
  34. package/assets/inspector-tabs-app/assets/transcript-BKLxbOF5.js +0 -1
  35. package/assets/inspector-tabs-app/assets/useQuery-RSkOi56s.js +0 -1
  36. package/assets/inspector-tabs-app/assets/useSuspenseQuery-CpwiXRj_.js +0 -1
package/dist/index.js CHANGED
@@ -1,307 +1,1737 @@
1
+ import {
2
+ __publicField
3
+ } from "./chunk-V6TY7KAL.js";
4
+
1
5
  // src/index.ts
2
6
  import { setup as rivetkitSetup } from "rivetkit";
7
+ export * from "@rivet-dev/agentos-core";
3
8
 
4
9
  // src/actor.ts
5
- import { dirname as dirname2, join as join2 } from "path";
6
- import { fileURLToPath as fileURLToPath2 } from "url";
7
- import common from "@agentos-software/common";
8
- import { OPT_AGENTOS_ROOT } from "@rivet-dev/agentos-core";
9
- import { getSidecarPath } from "@rivet-dev/agentos-sidecar";
10
- import {
11
- actor
12
- } from "rivetkit";
13
-
14
- // src/config.ts
10
+ import crypto from "crypto";
11
+ import { dirname, join } from "path";
12
+ import { fileURLToPath } from "url";
15
13
  import {
16
- agentOsOptionFieldSchemas,
17
- nativeMountConfigSchema,
18
- sharedSidecarConfigSchema
14
+ AgentOs
19
15
  } from "@rivet-dev/agentos-core";
20
- import { z } from "zod/v4";
21
- var zFunction = () => z.custom((val) => typeof val === "function");
22
- var nativeAgentOsOptionsSchema = z.object({
23
- software: agentOsOptionFieldSchemas.software,
24
- defaultSoftware: agentOsOptionFieldSchemas.defaultSoftware,
25
- loopbackExemptPorts: agentOsOptionFieldSchemas.loopbackExemptPorts,
26
- allowedNodeBuiltins: agentOsOptionFieldSchemas.allowedNodeBuiltins,
27
- rootFilesystem: agentOsOptionFieldSchemas.rootFilesystem,
28
- mounts: z.array(nativeMountConfigSchema).optional(),
29
- additionalInstructions: agentOsOptionFieldSchemas.additionalInstructions,
30
- permissions: agentOsOptionFieldSchemas.permissions,
31
- sidecar: sharedSidecarConfigSchema.optional(),
32
- limits: agentOsOptionFieldSchemas.limits
33
- }).strict();
34
- var agentOsActorOptionsSchema = z.record(z.string(), z.unknown()).optional();
35
- var agentOsActorConfigSchema = z.object({
36
- options: nativeAgentOsOptionsSchema.optional(),
37
- actorOptions: agentOsActorOptionsSchema,
38
- preview: z.object({
39
- defaultExpiresInSeconds: z.number().positive().default(3600),
40
- maxExpiresInSeconds: z.number().positive().default(86400)
41
- }).strict().prefault(() => ({})),
42
- onBeforeConnect: zFunction().optional(),
43
- onSessionEvent: zFunction().optional(),
44
- onPermissionRequest: zFunction().optional()
45
- }).strict();
16
+ import {
17
+ actor,
18
+ event,
19
+ UserError
20
+ } from "rivetkit";
21
+ import { db } from "rivetkit/db";
22
+ import { migrations } from "rivetkit/unstable/migrations";
46
23
 
47
- // src/plugin-binary.ts
48
- import { existsSync } from "fs";
24
+ // src/shell-replay.ts
25
+ import { readFile } from "fs/promises";
49
26
  import { createRequire } from "module";
50
- import { dirname, join } from "path";
51
- import { fileURLToPath } from "url";
52
- var PLUGIN_BIN_ENV = "AGENTOS_PLUGIN_BIN";
53
- function libraryName() {
54
- switch (process.platform) {
55
- case "darwin":
56
- return "libagentos_actor_plugin.dylib";
57
- case "win32":
58
- return "agentos_actor_plugin.dll";
59
- default:
60
- return "libagentos_actor_plugin.so";
27
+ var MAX_REPLAY_SHELLS = 32;
28
+ var MAX_SCROLLBACK_LINES = 1e3;
29
+ var MAX_COLS = 1e3;
30
+ var MAX_ROWS = 1e3;
31
+ var DEFAULT_COLS = 80;
32
+ var DEFAULT_ROWS = 24;
33
+ var ghosttyPromise;
34
+ async function loadGhostty() {
35
+ ghosttyPromise ?? (ghosttyPromise = (async () => {
36
+ const require2 = createRequire(import.meta.url);
37
+ const { Ghostty } = await import("ghostty-web");
38
+ const bytes = await readFile(
39
+ require2.resolve("ghostty-web/ghostty-vt.wasm")
40
+ );
41
+ const webAssembly = Reflect.get(globalThis, "WebAssembly");
42
+ if (!webAssembly) {
43
+ throw new Error("WebAssembly is unavailable in this runtime");
44
+ }
45
+ const { instance } = await webAssembly.instantiate(bytes, {
46
+ env: { log: () => {
47
+ } }
48
+ });
49
+ const GhosttyConstructor = Ghostty;
50
+ return new GhosttyConstructor(instance);
51
+ })());
52
+ return ghosttyPromise;
53
+ }
54
+ var CELL_BOLD = 1;
55
+ var CELL_ITALIC = 2;
56
+ var CELL_UNDERLINE = 4;
57
+ var CELL_STRIKETHROUGH = 8;
58
+ var CELL_INVERSE = 16;
59
+ var CELL_INVISIBLE = 32;
60
+ var CELL_BLINK = 64;
61
+ var CELL_FAINT = 128;
62
+ var RESTORED_DEC_MODES = [
63
+ 1,
64
+ // DECCKM — application cursor keys
65
+ 7,
66
+ // DECAWM — autowrap
67
+ 1e3,
68
+ // mouse: click tracking
69
+ 1002,
70
+ // mouse: button-event tracking
71
+ 1003,
72
+ // mouse: any-event tracking
73
+ 1004,
74
+ // focus in/out reporting
75
+ 1005,
76
+ // mouse: UTF-8 coordinates
77
+ 1006,
78
+ // mouse: SGR coordinates
79
+ 1015,
80
+ // mouse: urxvt coordinates
81
+ 2004
82
+ // bracketed paste
83
+ ];
84
+ var DEFAULT_STYLE = { fg: null, bg: null, flags: 0 };
85
+ function rgb(r, g, b) {
86
+ return r << 16 | g << 8 | b;
87
+ }
88
+ function styleOf(cell, defaultFg, defaultBg) {
89
+ const fg = rgb(cell.fg_r, cell.fg_g, cell.fg_b);
90
+ const bg = rgb(cell.bg_r, cell.bg_g, cell.bg_b);
91
+ return {
92
+ fg: fg === defaultFg ? null : fg,
93
+ bg: bg === defaultBg ? null : bg,
94
+ flags: cell.flags
95
+ };
96
+ }
97
+ function sameStyle(a, b) {
98
+ return a.fg === b.fg && a.bg === b.bg && a.flags === b.flags;
99
+ }
100
+ function sgr(style) {
101
+ const params = [0];
102
+ if (style.flags & CELL_BOLD) params.push(1);
103
+ if (style.flags & CELL_FAINT) params.push(2);
104
+ if (style.flags & CELL_ITALIC) params.push(3);
105
+ if (style.flags & CELL_UNDERLINE) params.push(4);
106
+ if (style.flags & CELL_BLINK) params.push(5);
107
+ if (style.flags & CELL_INVERSE) params.push(7);
108
+ if (style.flags & CELL_INVISIBLE) params.push(8);
109
+ if (style.flags & CELL_STRIKETHROUGH) params.push(9);
110
+ if (style.fg !== null) {
111
+ params.push(
112
+ 38,
113
+ 2,
114
+ style.fg >> 16 & 255,
115
+ style.fg >> 8 & 255,
116
+ style.fg & 255
117
+ );
118
+ }
119
+ if (style.bg !== null) {
120
+ params.push(
121
+ 48,
122
+ 2,
123
+ style.bg >> 16 & 255,
124
+ style.bg >> 8 & 255,
125
+ style.bg & 255
126
+ );
127
+ }
128
+ return `\x1B[${params.join(";")}m`;
129
+ }
130
+ function serializeRow(cells, cols, defaultFg, defaultBg, graphemeAt) {
131
+ let lastMeaningful = -1;
132
+ for (let x = 0; x < cols; x++) {
133
+ const cell = cells[x];
134
+ if (!cell) continue;
135
+ const blank = cell.codepoint === 0 || cell.codepoint === 32;
136
+ if (!blank || !sameStyle(styleOf(cell, defaultFg, defaultBg), DEFAULT_STYLE)) {
137
+ lastMeaningful = x;
138
+ }
139
+ }
140
+ if (lastMeaningful < 0) return "\x1B[0m\x1B[K";
141
+ let out = "";
142
+ let current = DEFAULT_STYLE;
143
+ out += sgr(current);
144
+ for (let x = 0; x <= lastMeaningful; x++) {
145
+ const cell = cells[x];
146
+ if (!cell) {
147
+ out += " ";
148
+ continue;
149
+ }
150
+ if (cell.width === 0) continue;
151
+ const style = styleOf(cell, defaultFg, defaultBg);
152
+ if (!sameStyle(style, current)) {
153
+ out += sgr(style);
154
+ current = style;
155
+ }
156
+ if (cell.grapheme_len > 0) {
157
+ out += graphemeAt(x);
158
+ } else if (cell.codepoint === 0) {
159
+ out += " ";
160
+ } else {
161
+ out += String.fromCodePoint(cell.codepoint);
162
+ }
61
163
  }
164
+ return `${out}\x1B[0m\x1B[K`;
62
165
  }
63
- function getPlatformPackageName() {
64
- const { platform, arch } = process;
65
- switch (platform) {
66
- case "linux":
67
- if (arch === "x64") return "@rivet-dev/agentos-plugin-linux-x64-gnu";
68
- if (arch === "arm64") return "@rivet-dev/agentos-plugin-linux-arm64-gnu";
69
- break;
70
- case "darwin":
71
- if (arch === "x64") return "@rivet-dev/agentos-plugin-darwin-x64";
72
- if (arch === "arm64") return "@rivet-dev/agentos-plugin-darwin-arm64";
73
- break;
74
- default:
75
- break;
76
- }
77
- return null;
166
+ function clamp(value, fallback, max) {
167
+ if (!Number.isFinite(value) || value === void 0 || value <= 0)
168
+ return fallback;
169
+ return Math.min(Math.floor(value), max);
78
170
  }
79
- function getPluginPath() {
80
- const override = process.env[PLUGIN_BIN_ENV];
81
- if (override) {
82
- if (!existsSync(override)) {
171
+ var ShellReplayStore = class {
172
+ constructor() {
173
+ __publicField(this, "entries", /* @__PURE__ */ new Map());
174
+ __publicField(this, "ghostty", null);
175
+ }
176
+ /** Instantiates the WASM module. Callers must await this before opening a
177
+ * shell so that `open` itself can be synchronous: a PTY starts producing
178
+ * output the moment it exists, and any await between opening it and
179
+ * subscribing is a window where output is lost to every consumer. */
180
+ async warm() {
181
+ this.ghostty ?? (this.ghostty = await loadGhostty());
182
+ }
183
+ open(shellId, cols, rows) {
184
+ if (this.entries.has(shellId)) return;
185
+ if (this.entries.size >= MAX_REPLAY_SHELLS) {
83
186
  throw new Error(
84
- `${PLUGIN_BIN_ENV} is set to ${override} but the file does not exist`
187
+ `agent-os shell replay limit reached (${MAX_REPLAY_SHELLS} emulators); close a shell or raise MAX_REPLAY_SHELLS in shell-replay.ts`
85
188
  );
86
189
  }
87
- return override;
88
- }
89
- const lib = libraryName();
90
- const here = dirname(fileURLToPath(import.meta.url));
91
- for (const profile of ["release", "debug"]) {
92
- const candidate = join(here, "..", "..", "..", "target", profile, lib);
93
- if (existsSync(candidate)) {
94
- return candidate;
190
+ if (!this.ghostty) {
191
+ throw new Error("agent-os shell replay used before warm() resolved");
95
192
  }
193
+ const width = clamp(cols, DEFAULT_COLS, MAX_COLS);
194
+ const height = clamp(rows, DEFAULT_ROWS, MAX_ROWS);
195
+ const term = this.ghostty.createTerminal(width, height, {
196
+ scrollbackLimit: MAX_SCROLLBACK_LINES
197
+ });
198
+ term.write("\x1Bc");
199
+ this.entries.set(shellId, { term, cols: width, rows: height, seq: 0 });
96
200
  }
97
- const platformPkg = getPlatformPackageName();
98
- if (!platformPkg) {
99
- throw new Error(
100
- `@rivet-dev/agentos: unsupported platform ${process.platform}/${process.arch}. The Agent OS actor plugin currently supports linux and darwin on x64 and arm64. Set ${PLUGIN_BIN_ENV} to a local cdylib to override.`
101
- );
201
+ /** Feeds one broadcast chunk and returns its sequence number. Clients use
202
+ * it to drop chunks a snapshot already contains. Returns 0 when this shell
203
+ * has no emulator, which clients read as "no replay available". */
204
+ feed(shellId, data) {
205
+ const entry = this.entries.get(shellId);
206
+ if (!entry) return 0;
207
+ entry.term.write(data);
208
+ return ++entry.seq;
102
209
  }
103
- const require2 = createRequire(import.meta.url);
104
- let pkgJsonPath;
105
- try {
106
- pkgJsonPath = require2.resolve(`${platformPkg}/package.json`);
107
- } catch {
108
- throw new Error(
109
- `@rivet-dev/agentos: platform package ${platformPkg} is not installed.
110
- This usually means the platform is unsupported or optionalDependencies
111
- were skipped during install. Try: npm install --include=optional ${platformPkg}
112
- Or set ${PLUGIN_BIN_ENV} to a local cdylib, or build it with
113
- \`cargo build -p agentos-actor-plugin\`.`
210
+ resize(shellId, cols, rows) {
211
+ const entry = this.entries.get(shellId);
212
+ if (!entry) return;
213
+ entry.cols = clamp(cols, entry.cols, MAX_COLS);
214
+ entry.rows = clamp(rows, entry.rows, MAX_ROWS);
215
+ entry.term.resize(entry.cols, entry.rows);
216
+ }
217
+ close(shellId) {
218
+ const entry = this.entries.get(shellId);
219
+ if (!entry) return;
220
+ this.entries.delete(shellId);
221
+ entry.term.free();
222
+ }
223
+ has(shellId) {
224
+ return this.entries.has(shellId);
225
+ }
226
+ snapshot(shellId, mode) {
227
+ const entry = this.entries.get(shellId);
228
+ if (!entry) return null;
229
+ const { term, cols, rows, seq } = entry;
230
+ const base = { shellId, seq, cols, rows };
231
+ if (mode === "none") return { ...base, mode, data: "" };
232
+ term.update();
233
+ const colors = term.getColors();
234
+ const defaultFg = rgb(
235
+ colors.foreground.r,
236
+ colors.foreground.g,
237
+ colors.foreground.b
238
+ );
239
+ const defaultBg = rgb(
240
+ colors.background.r,
241
+ colors.background.g,
242
+ colors.background.b
114
243
  );
244
+ const alternate = term.isAlternateScreen();
245
+ let out = "\x1Bc";
246
+ if (mode === "scrollback" && !alternate) {
247
+ const available = Math.min(
248
+ term.getScrollbackLength(),
249
+ MAX_SCROLLBACK_LINES
250
+ );
251
+ for (let i = available; i > 0; i--) {
252
+ const offset = i - 1;
253
+ const line = term.getScrollbackLine(offset);
254
+ if (!line) continue;
255
+ out += serializeRow(
256
+ line,
257
+ cols,
258
+ defaultFg,
259
+ defaultBg,
260
+ (col) => term.getScrollbackGraphemeString(offset, col)
261
+ );
262
+ out += "\r\n";
263
+ }
264
+ }
265
+ if (alternate) out += "\x1B[?1049h";
266
+ for (const decMode of RESTORED_DEC_MODES) {
267
+ out += term.getMode(decMode) ? `\x1B[?${decMode}h` : `\x1B[?${decMode}l`;
268
+ }
269
+ const viewport = term.getViewport();
270
+ out += "\x1B[H";
271
+ for (let y = 0; y < rows; y++) {
272
+ if (y > 0) out += "\r\n";
273
+ const row = viewport.slice(y * cols, (y + 1) * cols);
274
+ out += serializeRow(
275
+ row,
276
+ cols,
277
+ defaultFg,
278
+ defaultBg,
279
+ (col) => term.getGraphemeString(y, col)
280
+ );
281
+ }
282
+ const cursor = term.getCursor();
283
+ const cy = Math.min(Math.max(cursor.viewportY, 0), rows - 1) + 1;
284
+ const cx = Math.min(Math.max(cursor.viewportX, 0), cols - 1) + 1;
285
+ out += `\x1B[0m\x1B[${cy};${cx}H`;
286
+ out += cursor.visible ? "\x1B[?25h" : "\x1B[?25l";
287
+ return { ...base, mode, data: out };
115
288
  }
116
- return join(dirname(pkgJsonPath), lib);
117
- }
289
+ };
118
290
 
119
291
  // src/actor.ts
120
- function nodeModulesMount(hostNodeModulesDir, opts) {
121
- const readOnly = opts?.readOnly ?? true;
122
- return {
123
- path: "/root/node_modules",
124
- plugin: {
125
- id: "host_dir",
126
- config: { hostPath: hostNodeModulesDir, readOnly }
127
- },
128
- readOnly
129
- };
292
+ var DEFAULT_ACTION_TIMEOUT_MS = 2147483647;
293
+ var DEFAULT_SLEEP_GRACE_PERIOD_MS = 15 * 6e4;
294
+ var DEFAULT_PREVIEW_TTL_SECONDS = 3600;
295
+ var MAX_PREVIEW_TTL_SECONDS = 86400;
296
+ var DEFAULT_MAX_ACTIVE_PREVIEW_TOKENS = 1024;
297
+ var DEFAULT_MAX_SESSION_SUBSCRIPTIONS = 1e4;
298
+ var DEFAULT_MAX_DYNAMIC_MOUNTS = 1e4;
299
+ var DEFAULT_MAX_LINKED_SOFTWARE = 1e4;
300
+ var ACTOR_SQLITE_CHUNK_SIZE = 512 * 1024;
301
+ var ACTOR_SQLITE_INLINE_THRESHOLD = 64 * 1024;
302
+ var ROOT_NAMESPACE = "agentos-root";
303
+ var PREVIEW_PATH_PATTERN = /^\/fetch\/([a-f0-9]{48})(\/.*)?$/;
304
+ var MAX_SQLITE_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
305
+ var MAX_OPEN_SHELLS = 32;
306
+ var ACTOR_SQLITE_MIGRATIONS = [
307
+ {
308
+ version: 1,
309
+ sql: `
310
+ CREATE TABLE agentos_actor_preview_tokens (
311
+ token TEXT PRIMARY KEY CHECK (length(token) = 48 AND token NOT GLOB '*[^0-9a-f]*'),
312
+ port INTEGER NOT NULL CHECK (port BETWEEN 1 AND 65535),
313
+ created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND ${MAX_SQLITE_SAFE_INTEGER}),
314
+ expires_at_ms INTEGER NOT NULL CHECK (expires_at_ms > created_at_ms AND expires_at_ms <= ${MAX_SQLITE_SAFE_INTEGER})
315
+ ) STRICT;
316
+ CREATE INDEX agentos_actor_preview_tokens_by_expiry
317
+ ON agentos_actor_preview_tokens(expires_at_ms);
318
+ CREATE TABLE agentos_actor_dynamic_mounts (
319
+ path TEXT PRIMARY KEY CHECK (substr(path, 1, 1) = '/' AND instr(path, char(0)) = 0),
320
+ descriptor_json TEXT NOT NULL CHECK (json_valid(descriptor_json) AND json_type(descriptor_json) = 'object')
321
+ ) STRICT;
322
+ CREATE TABLE agentos_actor_linked_software (
323
+ path TEXT PRIMARY KEY CHECK (length(path) > 0 AND instr(path, char(0)) = 0),
324
+ descriptor_json TEXT NOT NULL CHECK (json_valid(descriptor_json) AND json_type(descriptor_json) = 'object')
325
+ ) STRICT;
326
+ `
327
+ }
328
+ ];
329
+ var builtInEvents = {
330
+ sessionEvent: event(),
331
+ vmBooted: event(),
332
+ vmShutdown: event(),
333
+ processOutput: event(),
334
+ processExit: event(),
335
+ shellData: event(),
336
+ cronEvent: event(),
337
+ agentExit: event(),
338
+ shellStderr: event(),
339
+ shellExit: event()
340
+ };
341
+ var runtimes = /* @__PURE__ */ new Map();
342
+ var optionResolvers = /* @__PURE__ */ new WeakMap();
343
+ var vmStartResolvers = /* @__PURE__ */ new WeakMap();
344
+ var vmStopResolvers = /* @__PURE__ */ new WeakMap();
345
+ var vmDisposedResolvers = /* @__PURE__ */ new WeakMap();
346
+ var HEALTH_WARNINGS_CAP = 50;
347
+ var HEALTH_AGENT_EXITS_CAP = 50;
348
+ var healthBuffers = /* @__PURE__ */ new Map();
349
+ function healthBuffersFor(actorId) {
350
+ let buffers = healthBuffers.get(actorId);
351
+ if (!buffers) {
352
+ buffers = { warnings: [], agentExits: [] };
353
+ healthBuffers.set(actorId, buffers);
354
+ }
355
+ return buffers;
130
356
  }
131
- function toRecord(value) {
132
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
357
+ function pushCapped(buffer, item, cap) {
358
+ buffer.push(item);
359
+ while (buffer.length > cap) buffer.shift();
133
360
  }
134
- function normalizePackageRef(value) {
135
- if (typeof value === "string") {
136
- return { path: value };
137
- }
138
- const record = toRecord(value);
139
- if (typeof record.packagePath === "string") {
140
- return { path: record.packagePath };
361
+ function runtimeFor(c) {
362
+ let runtime = runtimes.get(c.actorId);
363
+ if (!runtime) {
364
+ runtime = {
365
+ vm: null,
366
+ bootedVm: null,
367
+ openShells: /* @__PURE__ */ new Map(),
368
+ shellReplay: new ShellReplayStore(),
369
+ subscribedSessions: /* @__PURE__ */ new Map(),
370
+ vmCleanupRan: false,
371
+ fetchStreamHolds: /* @__PURE__ */ new Map()
372
+ };
373
+ runtimes.set(c.actorId, runtime);
141
374
  }
142
- for (const legacy of ["packageTar", "packageDir", "commandDir", "dir"]) {
143
- if (typeof record[legacy] === "string") {
375
+ return runtime;
376
+ }
377
+ async function runVmDisposedHook(runtime, c, reason) {
378
+ if (runtime.vmCleanupRan) return;
379
+ runtime.vmCleanupRan = true;
380
+ await runtime.onVmDisposed?.(c, reason);
381
+ }
382
+ async function ensureVm(c, options) {
383
+ const runtime = runtimeFor(c);
384
+ if (runtime.vm !== null) return runtime.vm;
385
+ const startedAt = Date.now();
386
+ runtime.vmCleanupRan = false;
387
+ runtime.vm = (async () => {
388
+ runtime.onVmStop = options ? vmStopResolvers.get(options) : void 0;
389
+ runtime.onVmDisposed = options ? vmDisposedResolvers.get(options) : void 0;
390
+ const resolvedOptions = {
391
+ ...options,
392
+ ...options && optionResolvers.has(options) ? await optionResolvers.get(options)?.(c) : void 0
393
+ };
394
+ if (resolvedOptions.rootFilesystem) {
395
+ throw new Error(
396
+ "agentOS() owns rootFilesystem so it can persist directly through the actor SQLite UDS; resolveOptions may configure mounts but not rootFilesystem"
397
+ );
398
+ }
399
+ if (resolvedOptions.database) {
400
+ throw new Error(
401
+ "agentOS() owns database and injects the actor SQLite UDS descriptor; resolveOptions cannot replace it"
402
+ );
403
+ }
404
+ if (resolvedOptions.sandbox && "client" in resolvedOptions.sandbox) {
144
405
  throw new Error(
145
- `agentOS package ref uses removed field "${legacy}"; packages are referenced by a single \`packagePath\` \u2014 rebuild @agentos-software/* dependencies or pass { packagePath }`
406
+ "agentOS() cannot share sandbox: { client } across actor instances; resolveOptions must use sandbox: { provider }"
146
407
  );
147
408
  }
409
+ const actorRuntimeSocket = c.actorRuntimeSocket;
410
+ if (typeof actorRuntimeSocket !== "function") {
411
+ throw new Error(
412
+ "AgentOS actors require a RivetKit runtime with Actor Runtime Socket support"
413
+ );
414
+ }
415
+ const { path } = await actorRuntimeSocket.call(c);
416
+ const mountRows = await c.db.execute(
417
+ "SELECT descriptor_json FROM agentos_actor_dynamic_mounts ORDER BY path"
418
+ );
419
+ const softwareRows = await c.db.execute(
420
+ "SELECT descriptor_json FROM agentos_actor_linked_software ORDER BY path"
421
+ );
422
+ const vm = await AgentOs.create({
423
+ ...resolvedOptions,
424
+ database: { type: "actor_uds", path },
425
+ onAgentExit: (event2) => {
426
+ c.log.error({
427
+ msg: "agent-os agent adapter exited unexpectedly",
428
+ ...event2
429
+ });
430
+ pushCapped(
431
+ healthBuffersFor(c.actorId).agentExits,
432
+ {
433
+ ts: Date.now(),
434
+ sessionId: event2.sessionId,
435
+ agentType: event2.agentType,
436
+ exitCode: event2.exitCode,
437
+ restart: event2.restart,
438
+ restartCount: event2.restartCount
439
+ },
440
+ HEALTH_AGENT_EXITS_CAP
441
+ );
442
+ c.broadcast("agentExit", event2);
443
+ try {
444
+ resolvedOptions.onAgentExit?.(event2);
445
+ } catch (error) {
446
+ c.log.error({
447
+ msg: "agent-os onAgentExit hook failed",
448
+ sessionId: event2.sessionId,
449
+ error
450
+ });
451
+ }
452
+ },
453
+ onLimitWarning: (warning) => {
454
+ c.log.warn({
455
+ msg: "agent-os runtime limit is near capacity",
456
+ ...warning
457
+ });
458
+ pushCapped(
459
+ healthBuffersFor(c.actorId).warnings,
460
+ { ts: Date.now(), ...warning },
461
+ HEALTH_WARNINGS_CAP
462
+ );
463
+ try {
464
+ options?.onLimitWarning?.(warning);
465
+ } catch (error) {
466
+ c.log.error({
467
+ msg: "agent-os onLimitWarning hook failed",
468
+ limit: warning.limit,
469
+ error
470
+ });
471
+ }
472
+ },
473
+ rootFilesystem: {
474
+ type: "native",
475
+ plugin: {
476
+ id: "chunked_actor_sqlite",
477
+ config: {
478
+ namespace: ROOT_NAMESPACE,
479
+ chunkSize: ACTOR_SQLITE_CHUNK_SIZE,
480
+ inlineThreshold: ACTOR_SQLITE_INLINE_THRESHOLD,
481
+ uid: resolvedOptions.user?.euid ?? resolvedOptions.user?.uid ?? 1e3,
482
+ gid: resolvedOptions.user?.egid ?? resolvedOptions.user?.gid ?? 1e3
483
+ }
484
+ }
485
+ }
486
+ });
487
+ try {
488
+ for (const row of mountRows) {
489
+ await vm.filesystem.mount(
490
+ JSON.parse(row.descriptor_json)
491
+ );
492
+ }
493
+ for (const row of softwareRows) {
494
+ await vm.software.link(
495
+ JSON.parse(row.descriptor_json)
496
+ );
497
+ }
498
+ } catch (error) {
499
+ await vm.dispose();
500
+ throw error;
501
+ }
502
+ const onVmStart = options ? vmStartResolvers.get(options) : void 0;
503
+ if (onVmStart) {
504
+ try {
505
+ await onVmStart(c, vm);
506
+ } catch (error) {
507
+ try {
508
+ await vm.dispose();
509
+ } catch (disposeError) {
510
+ c.log.error({
511
+ msg: "failed to dispose AgentOS VM after start hook failure",
512
+ disposeError
513
+ });
514
+ } finally {
515
+ await runVmDisposedHook(runtime, c, "error");
516
+ }
517
+ throw error;
518
+ }
519
+ }
520
+ vm.onCronEvent((cronEvent) => c.broadcast("cronEvent", cronEvent));
521
+ runtime.bootedVm = vm;
522
+ c.broadcast("vmBooted", {});
523
+ c.log.info({
524
+ msg: "agent-os vm booted",
525
+ bootDurationMs: Date.now() - startedAt
526
+ });
527
+ return vm;
528
+ })();
529
+ try {
530
+ return await runtime.vm;
531
+ } catch (error) {
532
+ runtime.vm = null;
533
+ runtime.bootedVm = null;
534
+ c.log.error({
535
+ msg: "agent-os vm bootstrap failed",
536
+ actorId: c.actorId,
537
+ error
538
+ });
539
+ await runVmDisposedHook(runtime, c, "error");
540
+ throw error;
148
541
  }
149
- return void 0;
150
542
  }
151
- function normalizedPackageRefs(software) {
152
- const refs = [];
153
- const seen = /* @__PURE__ */ new Set();
154
- for (const entry of software.flat()) {
155
- const ref = normalizePackageRef(entry);
156
- if (!ref || seen.has(ref.path)) continue;
157
- seen.add(ref.path);
158
- refs.push(ref);
159
- }
160
- return refs;
543
+ async function disposeVm(c, reason) {
544
+ if (reason === "destroy") healthBuffers.delete(c.actorId);
545
+ const runtime = runtimes.get(c.actorId);
546
+ if (!runtime) return;
547
+ const vm = runtime.vm;
548
+ runtime.bootedVm = null;
549
+ runtimes.delete(c.actorId);
550
+ for (const unsubscribers of runtime.subscribedSessions.values()) {
551
+ for (const unsubscribe of unsubscribers) unsubscribe();
552
+ }
553
+ runtime.subscribedSessions.clear();
554
+ for (const release of runtime.fetchStreamHolds.values()) release();
555
+ runtime.fetchStreamHolds.clear();
556
+ if (vm) {
557
+ const failures = [];
558
+ try {
559
+ const resolvedVm = await vm;
560
+ try {
561
+ await runtime.onVmStop?.(c, resolvedVm, reason);
562
+ } catch (error) {
563
+ failures.push(error);
564
+ }
565
+ try {
566
+ await resolvedVm.dispose();
567
+ } catch (error) {
568
+ failures.push(error);
569
+ }
570
+ } catch (error) {
571
+ failures.push(error);
572
+ }
573
+ try {
574
+ await runVmDisposedHook(runtime, c, reason);
575
+ } catch (error) {
576
+ failures.push(error);
577
+ }
578
+ if (failures.length === 1) throw failures[0];
579
+ if (failures.length > 1) {
580
+ const aggregate = new Error(
581
+ "failed to stop, dispose, or clean up AgentOS VM"
582
+ );
583
+ aggregate.errors = failures;
584
+ throw aggregate;
585
+ }
586
+ }
587
+ c.broadcast("vmShutdown", { reason });
161
588
  }
162
- function buildConfigJson(parsed) {
163
- const options = nativeAgentOsOptionsSchema.parse(
164
- parsed.options ?? {}
165
- );
166
- const softwareInput = Array.isArray(options.software) ? options.software : [];
167
- const defaultSoftwareEnabled = options.defaultSoftware !== false;
168
- const packageRefs = normalizedPackageRefs(
169
- defaultSoftwareEnabled ? [common, ...softwareInput] : softwareInput
170
- );
171
- const packages = packageRefs.map((ref) => ({ packagePath: ref.path }));
172
- const mounts = serializeNativeMounts(options.mounts);
173
- const sidecar = serializeSidecar(options.sidecar);
174
- return JSON.stringify({
175
- // The actor forwards ONLY package dirs; the sidecar resolves each agent from
176
- // the projected `/opt/agentos/<name>/current/agentos-package.json` (no
177
- // client-side adapter-entrypoint resolution — see root CLAUDE.md).
178
- packages,
179
- packagesMountAt: OPT_AGENTOS_ROOT,
180
- additionalInstructions: options.additionalInstructions,
181
- loopbackExemptPorts: options.loopbackExemptPorts,
182
- allowedNodeBuiltins: options.allowedNodeBuiltins,
183
- permissions: options.permissions,
184
- rootFilesystem: options.rootFilesystem,
185
- mounts,
186
- limits: options.limits,
187
- sidecar
188
- });
589
+ function matchPreviewPath(pathname) {
590
+ return pathname.match(PREVIEW_PATH_PATTERN);
189
591
  }
190
- function serializeNativeMounts(input) {
191
- if (input == null) return void 0;
192
- if (!Array.isArray(input)) {
193
- throw new Error("agentOS() options.mounts must be an array");
194
- }
195
- return input.map((mount, index) => {
196
- if (!mount || typeof mount !== "object") {
197
- throw new Error(`agentOS() options.mounts[${index}] must be an object`);
592
+ function validateAgentOsActorMigrationLadder(migrations2) {
593
+ if (migrations2.length === 0) {
594
+ throw new Error("AgentOS actor SQLite migration ladder must not be empty");
595
+ }
596
+ for (const [index, migration] of migrations2.entries()) {
597
+ const expectedVersion = index + 1;
598
+ if (migration.version !== expectedVersion) {
599
+ throw new Error(
600
+ `invalid AgentOS actor SQLite migration ladder: expected version ${expectedVersion}, received ${migration.version}`
601
+ );
198
602
  }
199
- const record = mount;
200
- if (record.driver !== void 0) {
603
+ if (migration.sql.trim().length === 0) {
201
604
  throw new Error(
202
- "agentOS() only supports Native mounts across the NAPI boundary; Plain mounts with driver callbacks are not serializable"
605
+ `invalid AgentOS actor SQLite migration ${migration.version}: SQL is empty`
203
606
  );
204
607
  }
205
- if (record.filesystem !== void 0) {
608
+ if (/(?:^|;)\s*(?:BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\b/im.test(
609
+ migration.sql
610
+ )) {
206
611
  throw new Error(
207
- "agentOS() only supports Native mounts across the NAPI boundary; Overlay mounts are not serializable"
612
+ `invalid AgentOS actor SQLite migration ${migration.version}: transaction control belongs to the migration provider`
208
613
  );
209
614
  }
210
- const plugin = record.plugin;
211
- if (typeof record.path !== "string" || !plugin || typeof plugin !== "object" || typeof plugin.id !== "string") {
615
+ if (/\b(?:FOREIGN\s+KEY|REFERENCES)\b/i.test(migration.sql)) {
212
616
  throw new Error(
213
- `agentOS() options.mounts[${index}] must be a Native mount with { path, plugin: { id, config? } }`
617
+ `invalid AgentOS actor SQLite migration ${migration.version}: foreign keys are not used in the actor-owned schema`
618
+ );
619
+ }
620
+ for (const statement of migration.sql.split(";")) {
621
+ if (/^\s*CREATE\s+TABLE\b/i.test(statement) && !/[)]\s*STRICT\s*$/i.test(statement)) {
622
+ throw new Error(
623
+ `invalid AgentOS actor SQLite migration ${migration.version}: every actor-owned table must be STRICT`
624
+ );
625
+ }
626
+ }
627
+ const ownedIdentifiers = migration.sql.match(/\bagentos_[a-z0-9_]+\b/gi);
628
+ if (!ownedIdentifiers || ownedIdentifiers.some(
629
+ (identifier) => !identifier.startsWith("agentos_actor_")
630
+ )) {
631
+ throw new Error(
632
+ `invalid AgentOS actor SQLite migration ${migration.version}: migrations may reference only agentos_actor_* tables and indexes`
214
633
  );
215
634
  }
216
- return {
217
- path: record.path,
218
- plugin: {
219
- id: plugin.id,
220
- config: plugin.config
221
- },
222
- readOnly: typeof record.readOnly === "boolean" ? record.readOnly : void 0
223
- };
224
- });
225
- }
226
- function serializeSidecar(input) {
227
- if (input == null) return void 0;
228
- if (!input || typeof input !== "object") {
229
- throw new Error("agentOS() options.sidecar must be an object");
230
635
  }
231
- const record = input;
232
- if (record.kind === "explicit" || record.handle !== void 0) {
233
- throw new Error(
234
- "agentOS() only supports sidecar shared pool configuration across the NAPI boundary; explicit sidecar handles are not serializable"
636
+ }
637
+ async function migrateAgentOsActorTables(database) {
638
+ validateAgentOsActorMigrationLadder(ACTOR_SQLITE_MIGRATIONS);
639
+ await runAgentOsActorMigrations(database);
640
+ }
641
+ var runAgentOsActorMigrations = migrations({
642
+ tableName: "agentos_actor_schema_version",
643
+ migrations: ACTOR_SQLITE_MIGRATIONS
644
+ });
645
+ async function assertActorCollectionCapacity(c, table, key, limit, label, configKey) {
646
+ const existing = await c.db.execute(
647
+ `SELECT 1 AS present FROM ${table} WHERE path = ? LIMIT 1`,
648
+ key
649
+ );
650
+ if (existing.length > 0) return;
651
+ const rows = await c.db.execute(
652
+ `SELECT COUNT(*) AS count FROM ${table}`
653
+ );
654
+ const count = Number(rows[0]?.count ?? 0);
655
+ if (count >= limit) {
656
+ throw new UserError(
657
+ `${label} limit ${limit} reached; raise ${configKey} to persist more`,
658
+ {
659
+ code: `agentos_${configKey === "maxDynamicMounts" ? "dynamic_mount" : "linked_software"}_limit`,
660
+ metadata: { limit }
661
+ }
235
662
  );
236
663
  }
237
- if (record.kind !== void 0 && record.kind !== "shared") {
238
- throw new Error('agentOS() options.sidecar.kind must be "shared"');
664
+ if (count + 1 === Math.ceil(limit * 0.8)) {
665
+ c.log.warn({
666
+ msg: `${label} are near the limit of ${limit}; raise ${configKey} to persist more`,
667
+ count: count + 1,
668
+ limit
669
+ });
239
670
  }
240
- return typeof record.pool === "string" ? { pool: record.pool } : {};
241
671
  }
242
- function buildNativeFactoryBuilder(parsed, actorOptions) {
243
- return (runtime) => {
244
- if (runtime.kind !== "napi") {
245
- throw new Error(
246
- `agentOS() is only supported on the native NAPI runtime (current runtime kind: ${runtime.kind})`
672
+ function trackSessionEvents(c, vm, sessionId, hooks, maxSessionSubscriptions) {
673
+ const runtime = runtimeFor(c);
674
+ if (runtime.subscribedSessions.has(sessionId)) return;
675
+ if (runtime.subscribedSessions.size >= maxSessionSubscriptions) {
676
+ throw new UserError(
677
+ `session subscription limit ${maxSessionSubscriptions} reached; raise maxSessionSubscriptions to observe more sessions`,
678
+ {
679
+ code: "agentos_session_subscription_limit",
680
+ metadata: { limit: maxSessionSubscriptions }
681
+ }
682
+ );
683
+ }
684
+ const nextCount = runtime.subscribedSessions.size + 1;
685
+ if (nextCount === Math.ceil(maxSessionSubscriptions * 0.8)) {
686
+ c.log.warn({
687
+ msg: `session subscriptions are near the limit of ${maxSessionSubscriptions}; raise maxSessionSubscriptions to observe more sessions`,
688
+ subscriptionCount: nextCount,
689
+ limit: maxSessionSubscriptions
690
+ });
691
+ }
692
+ const unsubscribeSession = vm.onSessionEvent(
693
+ sessionId,
694
+ (notification) => {
695
+ const serialized = JSON.parse(
696
+ JSON.stringify(notification)
247
697
  );
698
+ c.broadcast("sessionEvent", serialized);
699
+ if (hooks.onSessionEvent) {
700
+ void c.keepAwake(
701
+ Promise.resolve().then(() => hooks.onSessionEvent?.(c, sessionId, serialized)).catch(
702
+ (error) => c.log.error({
703
+ msg: "agent-os session event hook failed",
704
+ sessionId,
705
+ error
706
+ })
707
+ )
708
+ );
709
+ }
248
710
  }
249
- if (!runtime.createNativePluginFactory) {
250
- throw new Error(
251
- "runtime.createNativePluginFactory is not implemented on the active CoreRuntime"
711
+ );
712
+ runtime.subscribedSessions.set(sessionId, [unsubscribeSession]);
713
+ }
714
+ function untrackSessionEvents(c, sessionId) {
715
+ const unsubscribers = runtimeFor(c).subscribedSessions.get(sessionId);
716
+ if (!unsubscribers) return;
717
+ for (const unsubscribe of unsubscribers) unsubscribe();
718
+ runtimeFor(c).subscribedSessions.delete(sessionId);
719
+ }
720
+ function trackFetchStream(c, streamId) {
721
+ const runtime = runtimeFor(c);
722
+ if (runtime.fetchStreamHolds.has(streamId)) return;
723
+ const hold = new Promise((resolve) => {
724
+ runtime.fetchStreamHolds.set(streamId, resolve);
725
+ });
726
+ void c.keepAwake(hold).catch(
727
+ (error) => c.log.error({
728
+ msg: "agent-os fetch stream hold failed",
729
+ streamId,
730
+ error
731
+ })
732
+ );
733
+ }
734
+ function releaseFetchStream(c, streamId) {
735
+ const runtime = runtimeFor(c);
736
+ runtime.fetchStreamHolds.get(streamId)?.();
737
+ runtime.fetchStreamHolds.delete(streamId);
738
+ }
739
+ function decodeActorData(value) {
740
+ if (value === void 0) return void 0;
741
+ if (typeof value !== "object" || value === null || !("encoding" in value) || !("data" in value)) {
742
+ throw new UserError("stdin must be tagged UTF-8 or base64 actor data", {
743
+ code: "agentos_execution_invalid_actor_data"
744
+ });
745
+ }
746
+ const input = value;
747
+ if (typeof input.data !== "string") {
748
+ throw new UserError("actor data must contain a string", {
749
+ code: "agentos_execution_invalid_actor_data"
750
+ });
751
+ }
752
+ if (input.encoding === "utf8") return input.data;
753
+ if (input.encoding === "base64")
754
+ return new Uint8Array(Buffer.from(input.data, "base64"));
755
+ throw new UserError("actor data encoding must be utf8 or base64", {
756
+ code: "agentos_execution_invalid_actor_data"
757
+ });
758
+ }
759
+ function actorExecutionArgs(args) {
760
+ return args.map((arg) => {
761
+ if (typeof arg !== "object" || arg === null || Array.isArray(arg))
762
+ return arg;
763
+ const options = arg;
764
+ for (const field of ["signal", "onStdout", "onStderr"]) {
765
+ if (options[field] !== void 0) {
766
+ throw new UserError(`${field} is not available on actor actions`, {
767
+ code: "agentos_execution_non_serializable_option"
768
+ });
769
+ }
770
+ }
771
+ const normalized = { ...options };
772
+ if ("stdin" in normalized)
773
+ normalized.stdin = decodeActorData(normalized.stdin);
774
+ return normalized;
775
+ });
776
+ }
777
+ function actorSpawnArgs(options) {
778
+ return options === void 0 ? [] : actorExecutionArgs([options]);
779
+ }
780
+ async function runActorExecution(c, operation, options) {
781
+ const vm = await ensureVm(c, options);
782
+ return c.keepAwake(operation(vm));
783
+ }
784
+ async function runActorSpawn(c, operation, options) {
785
+ const vm = await ensureVm(c, options);
786
+ const process = await operation(vm);
787
+ const unsubscribeOutput = vm.onProcessOutput(
788
+ process.pid,
789
+ (event2) => c.broadcast("processOutput", event2)
790
+ );
791
+ const unsubscribeExit = vm.onProcessExit(
792
+ process.pid,
793
+ (event2) => c.broadcast("processExit", event2)
794
+ );
795
+ void c.keepAwake(
796
+ vm.process.wait(process.pid).finally(() => {
797
+ unsubscribeOutput();
798
+ unsubscribeExit();
799
+ })
800
+ ).catch(
801
+ (error) => c.log.error({
802
+ msg: "agent-os process wait failed",
803
+ pid: process.pid,
804
+ error
805
+ })
806
+ );
807
+ return process;
808
+ }
809
+ function createAgentOsActions(options, hooks = {}, preview = {}, maxSessionSubscriptions = DEFAULT_MAX_SESSION_SUBSCRIPTIONS, maxDynamicMounts = DEFAULT_MAX_DYNAMIC_MOUNTS, maxLinkedSoftware = DEFAULT_MAX_LINKED_SOFTWARE) {
810
+ const defaultPreviewTtlSeconds = preview.defaultExpiresInSeconds ?? DEFAULT_PREVIEW_TTL_SECONDS;
811
+ const maxPreviewTtlSeconds = preview.maxExpiresInSeconds ?? MAX_PREVIEW_TTL_SECONDS;
812
+ const maxActivePreviewTokens = preview.maxActiveTokens ?? DEFAULT_MAX_ACTIVE_PREVIEW_TOKENS;
813
+ if (!Number.isFinite(defaultPreviewTtlSeconds) || defaultPreviewTtlSeconds <= 0 || !Number.isFinite(maxPreviewTtlSeconds) || maxPreviewTtlSeconds <= 0 || defaultPreviewTtlSeconds > maxPreviewTtlSeconds) {
814
+ throw new UserError(
815
+ "preview expiry bounds must be positive and the default cannot exceed the maximum",
816
+ { code: "agentos_preview_invalid_config" }
817
+ );
818
+ }
819
+ if (!Number.isInteger(maxActivePreviewTokens) || maxActivePreviewTokens < 1) {
820
+ throw new UserError("preview.maxActiveTokens must be a positive integer", {
821
+ code: "agentos_preview_invalid_config"
822
+ });
823
+ }
824
+ if (!Number.isInteger(maxSessionSubscriptions) || maxSessionSubscriptions < 1) {
825
+ throw new UserError("maxSessionSubscriptions must be a positive integer", {
826
+ code: "agentos_session_subscription_invalid_config"
827
+ });
828
+ }
829
+ if (!Number.isInteger(maxDynamicMounts) || maxDynamicMounts < 1) {
830
+ throw new UserError("maxDynamicMounts must be a positive integer", {
831
+ code: "agentos_dynamic_mount_invalid_config"
832
+ });
833
+ }
834
+ if (!Number.isInteger(maxLinkedSoftware) || maxLinkedSoftware < 1) {
835
+ throw new UserError("maxLinkedSoftware must be a positive integer", {
836
+ code: "agentos_linked_software_invalid_config"
837
+ });
838
+ }
839
+ const flat = {
840
+ readFile: async (c, ...args) => {
841
+ try {
842
+ return await (await ensureVm(c, options)).filesystem.readFile(...args);
843
+ } catch (error) {
844
+ c.log.error({
845
+ msg: "agent-os readFile action failed",
846
+ path: args[0],
847
+ error
848
+ });
849
+ throw error;
850
+ }
851
+ },
852
+ writeFile: async (c, ...args) => (await ensureVm(c, options)).filesystem.writeFile(...args),
853
+ readFiles: async (c, ...args) => (await ensureVm(c, options)).filesystem.readFiles(...args),
854
+ writeFiles: async (c, ...args) => (await ensureVm(c, options)).filesystem.writeFiles(...args),
855
+ stat: async (c, ...args) => (await ensureVm(c, options)).filesystem.stat(...args),
856
+ mkdir: async (c, ...args) => (await ensureVm(c, options)).filesystem.mkdir(...args),
857
+ readdir: async (c, ...args) => (await ensureVm(c, options)).filesystem.readdir(...args),
858
+ readdirEntries: async (c, ...args) => (await ensureVm(c, options)).filesystem.readdirEntries(...args),
859
+ readdirRecursive: async (c, ...args) => (await ensureVm(c, options)).filesystem.readdirRecursive(...args),
860
+ exists: async (c, ...args) => (await ensureVm(c, options)).filesystem.exists(...args),
861
+ move: async (c, ...args) => (await ensureVm(c, options)).filesystem.move(...args),
862
+ remove: async (c, ...args) => (await ensureVm(c, options)).filesystem.remove(...args),
863
+ exec: async (c, command, actorOptions) => runActorExecution(
864
+ c,
865
+ (vm) => vm.process.exec(
866
+ command,
867
+ ...actorExecutionArgs([actorOptions])
868
+ ),
869
+ options
870
+ ),
871
+ execArgv: async (c, command, args = [], actorOptions) => runActorExecution(
872
+ c,
873
+ (vm) => vm.process.execFile(
874
+ command,
875
+ args,
876
+ ...actorExecutionArgs([actorOptions])
877
+ ),
878
+ options
879
+ ),
880
+ spawn: async (c, command, args = [], actorOptions) => runActorSpawn(
881
+ c,
882
+ (vm) => vm.process.spawn(
883
+ command,
884
+ args,
885
+ ...actorSpawnArgs(actorOptions)
886
+ ),
887
+ options
888
+ ),
889
+ createContext: async (c, contextId) => (await ensureVm(c, options)).createContext(contextId),
890
+ executeJavaScript: async (c, source, actorOptions) => runActorExecution(
891
+ c,
892
+ (vm) => vm.javascript.execute(
893
+ source,
894
+ ...actorExecutionArgs([actorOptions])
895
+ ),
896
+ options
897
+ ),
898
+ evaluateJavaScript: async (c, expression, actorOptions) => runActorExecution(
899
+ c,
900
+ (vm) => vm.javascript.evaluate(
901
+ expression,
902
+ ...actorExecutionArgs([actorOptions])
903
+ ),
904
+ options
905
+ ),
906
+ executeJavaScriptFile: async (c, path, actorOptions) => runActorExecution(
907
+ c,
908
+ (vm) => vm.javascript.executeFile(
909
+ path,
910
+ ...actorExecutionArgs([actorOptions])
911
+ ),
912
+ options
913
+ ),
914
+ spawnJavaScript: async (c, source, actorOptions) => runActorSpawn(
915
+ c,
916
+ (vm) => vm.javascript.spawn(
917
+ source,
918
+ ...actorSpawnArgs(actorOptions)
919
+ ),
920
+ options
921
+ ),
922
+ spawnJavaScriptFile: async (c, path, actorOptions) => runActorSpawn(
923
+ c,
924
+ (vm) => vm.javascript.spawnFile(
925
+ path,
926
+ ...actorSpawnArgs(actorOptions)
927
+ ),
928
+ options
929
+ ),
930
+ executeTypeScript: async (c, source, actorOptions) => runActorExecution(
931
+ c,
932
+ (vm) => vm.typescript.execute(
933
+ source,
934
+ ...actorExecutionArgs([actorOptions])
935
+ ),
936
+ options
937
+ ),
938
+ evaluateTypeScript: async (c, expression, actorOptions) => runActorExecution(
939
+ c,
940
+ (vm) => vm.typescript.evaluate(
941
+ expression,
942
+ ...actorExecutionArgs([actorOptions])
943
+ ),
944
+ options
945
+ ),
946
+ executeTypeScriptFile: async (c, path, actorOptions) => runActorExecution(
947
+ c,
948
+ (vm) => vm.typescript.executeFile(
949
+ path,
950
+ ...actorExecutionArgs([actorOptions])
951
+ ),
952
+ options
953
+ ),
954
+ spawnTypeScript: async (c, source, actorOptions) => runActorSpawn(
955
+ c,
956
+ (vm) => vm.typescript.spawn(
957
+ source,
958
+ ...actorSpawnArgs(actorOptions)
959
+ ),
960
+ options
961
+ ),
962
+ spawnTypeScriptFile: async (c, path, actorOptions) => runActorSpawn(
963
+ c,
964
+ (vm) => vm.typescript.spawnFile(
965
+ path,
966
+ ...actorSpawnArgs(actorOptions)
967
+ ),
968
+ options
969
+ ),
970
+ checkTypeScript: async (c, source, actorOptions) => runActorExecution(
971
+ c,
972
+ (vm) => vm.typescript.check(
973
+ source,
974
+ ...actorExecutionArgs([actorOptions])
975
+ ),
976
+ options
977
+ ),
978
+ checkTypeScriptProject: async (c, actorOptions) => runActorExecution(
979
+ c,
980
+ (vm) => vm.typescript.checkProject(
981
+ ...actorExecutionArgs([actorOptions])
982
+ ),
983
+ options
984
+ ),
985
+ installNpmPackages: async (c, ...args) => runActorExecution(
986
+ c,
987
+ (vm) => vm.javascript.npm.install(...actorExecutionArgs(args)),
988
+ options
989
+ ),
990
+ executeNpmScript: async (c, script, actorOptions) => runActorExecution(
991
+ c,
992
+ (vm) => vm.javascript.npm.runScript(
993
+ script,
994
+ ...actorExecutionArgs([actorOptions])
995
+ ),
996
+ options
997
+ ),
998
+ executeNpmPackage: async (c, packageSpec, actorOptions) => runActorExecution(
999
+ c,
1000
+ (vm) => vm.javascript.npm.runPackage(
1001
+ packageSpec,
1002
+ ...actorExecutionArgs([actorOptions])
1003
+ ),
1004
+ options
1005
+ ),
1006
+ executePython: async (c, source, actorOptions) => runActorExecution(
1007
+ c,
1008
+ (vm) => vm.python.execute(
1009
+ source,
1010
+ ...actorExecutionArgs([actorOptions])
1011
+ ),
1012
+ options
1013
+ ),
1014
+ evaluatePython: async (c, expression, actorOptions) => runActorExecution(
1015
+ c,
1016
+ (vm) => vm.python.evaluate(
1017
+ expression,
1018
+ ...actorExecutionArgs([actorOptions])
1019
+ ),
1020
+ options
1021
+ ),
1022
+ executePythonFile: async (c, path, actorOptions) => runActorExecution(
1023
+ c,
1024
+ (vm) => vm.python.executeFile(
1025
+ path,
1026
+ ...actorExecutionArgs([actorOptions])
1027
+ ),
1028
+ options
1029
+ ),
1030
+ executePythonModule: async (c, module, actorOptions) => runActorExecution(
1031
+ c,
1032
+ (vm) => vm.python.executeModule(
1033
+ module,
1034
+ ...actorExecutionArgs([actorOptions])
1035
+ ),
1036
+ options
1037
+ ),
1038
+ spawnPython: async (c, source, actorOptions) => runActorSpawn(
1039
+ c,
1040
+ (vm) => vm.python.spawn(source, ...actorSpawnArgs(actorOptions)),
1041
+ options
1042
+ ),
1043
+ spawnPythonFile: async (c, path, actorOptions) => runActorSpawn(
1044
+ c,
1045
+ (vm) => vm.python.spawnFile(
1046
+ path,
1047
+ ...actorSpawnArgs(actorOptions)
1048
+ ),
1049
+ options
1050
+ ),
1051
+ spawnPythonModule: async (c, module, actorOptions) => runActorSpawn(
1052
+ c,
1053
+ (vm) => vm.python.spawnModule(
1054
+ module,
1055
+ ...actorSpawnArgs(actorOptions)
1056
+ ),
1057
+ options
1058
+ ),
1059
+ installPythonPackages: async (c, ...args) => runActorExecution(
1060
+ c,
1061
+ (vm) => vm.python.install(...actorExecutionArgs(args)),
1062
+ options
1063
+ ),
1064
+ getContext: async (c, ...args) => (await ensureVm(c, options)).contexts.get(...args),
1065
+ listContexts: async (c) => (await ensureVm(c, options)).contexts.list(),
1066
+ resetContext: async (c, ...args) => (await ensureVm(c, options)).contexts.reset(...args),
1067
+ deleteContext: async (c, ...args) => (await ensureVm(c, options)).contexts.delete(...args),
1068
+ waitProcess: async (c, ...args) => (await ensureVm(c, options)).process.wait(...args),
1069
+ killProcess: async (c, ...args) => (await ensureVm(c, options)).process.kill(...args),
1070
+ signalProcess: async (c, ...args) => (await ensureVm(c, options)).process.signal(...args),
1071
+ listProcesses: async (c) => (await ensureVm(c, options)).process.list(),
1072
+ processTree: async (c) => (await ensureVm(c, options)).process.tree(),
1073
+ getProcess: async (c, ...args) => (await ensureVm(c, options)).process.get(...args),
1074
+ writeProcessStdin: async (c, ...args) => (await ensureVm(c, options)).process.writeStdin(...args),
1075
+ closeProcessStdin: async (c, ...args) => (await ensureVm(c, options)).process.closeStdin(...args),
1076
+ resizeProcessPty: async (c, ...args) => (await ensureVm(c, options)).process.resizePty(...args),
1077
+ readProcessOutput: async (c, ...args) => {
1078
+ const replay = await (await ensureVm(c, options)).process.readOutput(
1079
+ ...args
1080
+ );
1081
+ return {
1082
+ ...replay,
1083
+ events: replay.events.map((event2) => ({
1084
+ ...event2,
1085
+ chunk: {
1086
+ encoding: "base64",
1087
+ data: Buffer.from(event2.chunk).toString("base64")
1088
+ }
1089
+ }))
1090
+ };
1091
+ },
1092
+ openShell: async (c, ...args) => {
1093
+ const vm = await ensureVm(c, options);
1094
+ const runtime = runtimeFor(c);
1095
+ if (runtime.openShells.size >= MAX_OPEN_SHELLS) {
1096
+ throw new Error(
1097
+ `agent-os shell limit reached (${MAX_OPEN_SHELLS} open); close a shell or raise MAX_OPEN_SHELLS`
1098
+ );
1099
+ }
1100
+ await runtime.shellReplay.warm();
1101
+ const shell = vm.terminal.open(...args);
1102
+ runtime.openShells.set(shell.shellId, { openedAt: Date.now() });
1103
+ runtime.shellReplay.open(shell.shellId, args[0]?.cols, args[0]?.rows);
1104
+ const unsubscribeData = vm.onShellData(
1105
+ shell.shellId,
1106
+ (event2) => c.broadcast("shellData", {
1107
+ ...event2,
1108
+ seq: runtime.shellReplay.feed(event2.shellId, event2.data)
1109
+ })
1110
+ );
1111
+ const unsubscribeStderr = vm.onShellStderr(
1112
+ shell.shellId,
1113
+ (event2) => (
1114
+ // A diagnostic tap carrying bytes `shellData` already delivered, so
1115
+ // it is never folded into replay and carries no sequence.
1116
+ c.broadcast("shellStderr", { ...event2, seq: 0 })
1117
+ )
1118
+ );
1119
+ const unsubscribeExit = vm.onShellExit(
1120
+ shell.shellId,
1121
+ (event2) => c.broadcast("shellExit", event2)
1122
+ );
1123
+ void c.keepAwake(
1124
+ vm.terminal.wait(shell.shellId).finally(() => {
1125
+ runtime.openShells.delete(shell.shellId);
1126
+ runtime.shellReplay.close(shell.shellId);
1127
+ unsubscribeData();
1128
+ unsubscribeStderr();
1129
+ unsubscribeExit();
1130
+ })
1131
+ ).catch(
1132
+ (error) => c.log.error({
1133
+ msg: "agent-os shell wait failed",
1134
+ shellId: shell.shellId,
1135
+ error
1136
+ })
1137
+ );
1138
+ return shell;
1139
+ },
1140
+ // Observe-only: enumerates shells this actor opened without booting a
1141
+ // sleeping VM (a sleeping VM has none). Clients must not track shell ids
1142
+ // themselves — a shell outlives the page that opened it and keeps the VM
1143
+ // awake, so it has to stay discoverable.
1144
+ listShells: async (c) => {
1145
+ const runtime = runtimes.get(c.actorId);
1146
+ if (!runtime?.bootedVm) return [];
1147
+ return [...runtime.openShells.entries()].map(([shellId, entry]) => ({ shellId, openedAt: entry.openedAt })).sort((a, b) => a.openedAt - b.openedAt);
1148
+ },
1149
+ writeShell: async (c, ...args) => (await ensureVm(c, options)).terminal.write(...args),
1150
+ resizeShell: async (c, ...args) => {
1151
+ const result = (await ensureVm(c, options)).terminal.resize(...args);
1152
+ runtimeFor(c).shellReplay.resize(args[0], args[1], args[2]);
1153
+ return result;
1154
+ },
1155
+ // Observe-only, like `listShells`: repainting a shell must never boot a
1156
+ // VM, and a sleeping VM has no live shells to repaint. Returns `null`
1157
+ // for an unknown shell so a client falls back to no replay.
1158
+ shellSnapshot: async (c, shellId, mode = "screen") => {
1159
+ const runtime = runtimes.get(c.actorId);
1160
+ if (!runtime?.bootedVm) return null;
1161
+ return runtime.shellReplay.snapshot(shellId, mode);
1162
+ },
1163
+ closeShell: async (c, ...args) => (await ensureVm(c, options)).terminal.close(...args),
1164
+ waitShell: async (c, ...args) => (await ensureVm(c, options)).terminal.wait(...args),
1165
+ httpRequest: async (c, ...args) => (await ensureVm(c, options)).network.httpRequest(...args),
1166
+ vmFetch: async (c, port, url, requestOptions) => {
1167
+ const vm = await ensureVm(c, options);
1168
+ const body = requestOptions?.body instanceof Uint8Array ? Buffer.from(requestOptions.body) : requestOptions?.body;
1169
+ const response = await vm.fetch(
1170
+ port,
1171
+ new Request(url, {
1172
+ method: requestOptions?.method ?? "GET",
1173
+ headers: requestOptions?.headers,
1174
+ body
1175
+ })
1176
+ );
1177
+ const headers = {};
1178
+ const rawHeaders = [];
1179
+ response.headers.forEach((value, key) => {
1180
+ headers[key] = value;
1181
+ if (key !== "set-cookie") rawHeaders.push([key, value]);
1182
+ });
1183
+ for (const value of response.headers.getSetCookie?.() ?? []) {
1184
+ rawHeaders.push(["set-cookie", value]);
1185
+ }
1186
+ return {
1187
+ status: response.status,
1188
+ statusText: response.statusText,
1189
+ headers,
1190
+ rawHeaders,
1191
+ body: new Uint8Array(await response.arrayBuffer())
1192
+ };
1193
+ },
1194
+ vmFetchStreamStart: async (c, port, url, requestOptions) => {
1195
+ const vm = await ensureVm(c, options);
1196
+ const body = requestOptions?.body instanceof Uint8Array ? Buffer.from(requestOptions.body) : requestOptions?.body;
1197
+ const head = await vm.fetchStreamStart(
1198
+ port,
1199
+ new Request(url, {
1200
+ method: requestOptions?.method ?? "GET",
1201
+ headers: requestOptions?.headers,
1202
+ body
1203
+ })
1204
+ );
1205
+ trackFetchStream(c, head.streamId);
1206
+ const headers = {};
1207
+ for (const [name, value] of head.headers) headers[name] = value;
1208
+ return { ...head, headers, rawHeaders: head.headers };
1209
+ },
1210
+ vmFetchStreamRead: async (c, streamId, maxBytes) => {
1211
+ try {
1212
+ const chunk = await (await ensureVm(c, options)).fetchStreamRead(
1213
+ streamId,
1214
+ maxBytes
1215
+ );
1216
+ if (chunk.done) releaseFetchStream(c, streamId);
1217
+ return chunk;
1218
+ } catch (error) {
1219
+ releaseFetchStream(c, streamId);
1220
+ throw error;
1221
+ }
1222
+ },
1223
+ vmFetchStreamCancel: async (c, streamId) => {
1224
+ try {
1225
+ await (await ensureVm(c, options)).fetchStreamCancel(streamId);
1226
+ } finally {
1227
+ releaseFetchStream(c, streamId);
1228
+ }
1229
+ },
1230
+ scheduleCron: async (c, cronOptions) => {
1231
+ const job = (await ensureVm(c, options)).cron.schedule(
1232
+ cronOptions
1233
+ );
1234
+ return { id: job.id };
1235
+ },
1236
+ listCronJobs: async (c) => (await ensureVm(c, options)).cron.list(),
1237
+ cancelCronJob: async (c, ...args) => (await ensureVm(c, options)).cron.cancel(...args),
1238
+ listAgents: async (c) => (await ensureVm(c, options)).agents.list(),
1239
+ // Observe-only: reports VM liveness and the post-mortem buffers without
1240
+ // ever booting the VM (deliberately no ensureVm).
1241
+ health: async (c) => {
1242
+ const runtime = runtimes.get(c.actorId);
1243
+ const buffers = healthBuffersFor(c.actorId);
1244
+ let booted = false;
1245
+ let sessions = null;
1246
+ let sidecar = null;
1247
+ const vm = runtime?.bootedVm;
1248
+ if (runtime && vm) {
1249
+ booted = true;
1250
+ sessions = runtime.subscribedSessions.size;
1251
+ const description = vm.sidecar.describe();
1252
+ sidecar = {
1253
+ state: description.state,
1254
+ activeVmCount: description.activeVmCount
1255
+ };
1256
+ }
1257
+ return {
1258
+ booted,
1259
+ sessions,
1260
+ sidecar,
1261
+ warnings: [...buffers.warnings],
1262
+ agentExits: [...buffers.agentExits],
1263
+ stderrTail: []
1264
+ };
1265
+ },
1266
+ openSession: async (c, input) => {
1267
+ const vm = await ensureVm(c, options);
1268
+ try {
1269
+ await vm.sessions.open(input);
1270
+ } catch (error) {
1271
+ const message = error instanceof Error ? error.message : String(error);
1272
+ const causeCode = typeof error?.code === "string" ? error.code : void 0;
1273
+ c.log.error({
1274
+ msg: "agent-os openSession action failed",
1275
+ sessionId: input.sessionId ?? "main",
1276
+ agent: input.agent,
1277
+ causeCode,
1278
+ error
1279
+ });
1280
+ throw new UserError(`AgentOS openSession failed: ${message}`, {
1281
+ code: "agentos_session_open_failed",
1282
+ metadata: causeCode ? { causeCode } : void 0
1283
+ });
1284
+ }
1285
+ trackSessionEvents(
1286
+ c,
1287
+ vm,
1288
+ input.sessionId ?? "main",
1289
+ hooks,
1290
+ maxSessionSubscriptions
1291
+ );
1292
+ },
1293
+ getSession: async (c, ...args) => (await ensureVm(c, options)).sessions.get(...args),
1294
+ listSessions: async (c, ...args) => (await ensureVm(c, options)).sessions.list(...args),
1295
+ deleteSession: async (c, ...args) => {
1296
+ const result = await (await ensureVm(c, options)).sessions.delete(
1297
+ ...args
1298
+ );
1299
+ untrackSessionEvents(c, args[0]?.sessionId ?? "main");
1300
+ return result;
1301
+ },
1302
+ unloadSession: async (c, ...args) => {
1303
+ const result = await (await ensureVm(c, options)).sessions.unload(
1304
+ ...args
1305
+ );
1306
+ untrackSessionEvents(c, args[0]?.sessionId ?? "main");
1307
+ return result;
1308
+ },
1309
+ prompt: async (c, input) => {
1310
+ const vm = await ensureVm(c, options);
1311
+ const sessionId = input.sessionId ?? "main";
1312
+ trackSessionEvents(c, vm, sessionId, hooks, maxSessionSubscriptions);
1313
+ try {
1314
+ return await c.keepAwake(vm.sessions.prompt(input));
1315
+ } catch (error) {
1316
+ const message = error instanceof Error ? error.message : String(error);
1317
+ const causeCode = typeof error?.code === "string" ? error.code : void 0;
1318
+ c.log.error({
1319
+ msg: "agent-os prompt action failed",
1320
+ sessionId,
1321
+ causeCode,
1322
+ error
1323
+ });
1324
+ throw new UserError(`AgentOS prompt failed: ${message}`, {
1325
+ code: "agentos_prompt_failed",
1326
+ metadata: causeCode ? { causeCode } : void 0
1327
+ });
1328
+ }
1329
+ },
1330
+ cancelPrompt: async (c, ...args) => (await ensureVm(c, options)).sessions.cancelPrompt(...args),
1331
+ respondPermission: async (c, ...args) => (await ensureVm(c, options)).sessions.respondPermission(...args),
1332
+ readHistory: async (c, ...args) => (await ensureVm(c, options)).sessions.readHistory(...args),
1333
+ getSessionConfig: async (c, ...args) => (await ensureVm(c, options)).sessions.getConfig(...args),
1334
+ setSessionConfigOption: async (c, ...args) => (await ensureVm(c, options)).sessions.setConfigOption(...args),
1335
+ getSessionCapabilities: async (c, ...args) => (await ensureVm(c, options)).sessions.getCapabilities(...args),
1336
+ getSessionAgentInfo: async (c, ...args) => (await ensureVm(c, options)).sessions.getAgentInfo(...args),
1337
+ createPreviewUrl: async (c, port, ttlSeconds = defaultPreviewTtlSeconds) => {
1338
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
1339
+ throw new UserError(
1340
+ "port must be an integer between 1 and 65535; pass a valid VM listener port",
1341
+ { code: "agentos_preview_invalid_port" }
1342
+ );
1343
+ if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0 || ttlSeconds > maxPreviewTtlSeconds)
1344
+ throw new UserError(
1345
+ `ttlSeconds must be greater than 0 and at most ${maxPreviewTtlSeconds}; raise preview.maxExpiresInSeconds to allow a longer lifetime`,
1346
+ { code: "agentos_preview_invalid_ttl" }
1347
+ );
1348
+ const token = crypto.randomBytes(24).toString("hex");
1349
+ const createdAt = Date.now();
1350
+ const expiresAt = createdAt + ttlSeconds * 1e3;
1351
+ await c.db.execute(
1352
+ "DELETE FROM agentos_actor_preview_tokens WHERE expires_at_ms <= ?",
1353
+ createdAt
1354
+ );
1355
+ const counts = await c.db.execute(
1356
+ "SELECT COUNT(*) AS count FROM agentos_actor_preview_tokens"
1357
+ );
1358
+ const activeTokenCount = Number(counts[0]?.count ?? 0);
1359
+ if (activeTokenCount >= maxActivePreviewTokens) {
1360
+ throw new UserError(
1361
+ `preview token limit ${maxActivePreviewTokens} reached; raise preview.maxActiveTokens to allow more`,
1362
+ {
1363
+ code: "agentos_preview_token_limit",
1364
+ metadata: { limit: maxActivePreviewTokens }
1365
+ }
1366
+ );
1367
+ }
1368
+ const nextActiveTokenCount = activeTokenCount + 1;
1369
+ const warningThreshold = Math.ceil(maxActivePreviewTokens * 0.8);
1370
+ if (nextActiveTokenCount === warningThreshold) {
1371
+ c.log.warn({
1372
+ msg: `preview tokens are near the limit of ${maxActivePreviewTokens}; raise preview.maxActiveTokens to allow more`,
1373
+ activeTokenCount: nextActiveTokenCount,
1374
+ limit: maxActivePreviewTokens
1375
+ });
1376
+ }
1377
+ await c.db.execute(
1378
+ "INSERT INTO agentos_actor_preview_tokens (token, port, created_at_ms, expires_at_ms) VALUES (?, ?, ?, ?)",
1379
+ token,
1380
+ port,
1381
+ createdAt,
1382
+ expiresAt
1383
+ );
1384
+ return { path: `/fetch/${token}`, token, port, expiresAt };
1385
+ },
1386
+ expirePreviewUrl: async (c, token) => {
1387
+ await c.db.execute(
1388
+ "DELETE FROM agentos_actor_preview_tokens WHERE token = ?",
1389
+ token
1390
+ );
1391
+ },
1392
+ exportRootFilesystem: async (c, ...args) => (await ensureVm(c, options)).filesystem.export(...args),
1393
+ mountFs: async (c, descriptor) => {
1394
+ await assertActorCollectionCapacity(
1395
+ c,
1396
+ "agentos_actor_dynamic_mounts",
1397
+ descriptor.path,
1398
+ maxDynamicMounts,
1399
+ "dynamic mounts",
1400
+ "maxDynamicMounts"
1401
+ );
1402
+ const vm = await ensureVm(c, options);
1403
+ await vm.filesystem.mount(descriptor);
1404
+ try {
1405
+ await c.db.execute(
1406
+ "INSERT INTO agentos_actor_dynamic_mounts (path, descriptor_json) VALUES (?, ?) ON CONFLICT(path) DO UPDATE SET descriptor_json = excluded.descriptor_json",
1407
+ descriptor.path,
1408
+ JSON.stringify(descriptor)
1409
+ );
1410
+ } catch (error) {
1411
+ try {
1412
+ await vm.filesystem.unmount(descriptor.path);
1413
+ } catch (rollbackError) {
1414
+ c.log.error({
1415
+ msg: "agent-os dynamic mount rollback failed",
1416
+ path: descriptor.path,
1417
+ error: rollbackError
1418
+ });
1419
+ }
1420
+ throw error;
1421
+ }
1422
+ },
1423
+ unmountFs: async (c, path) => {
1424
+ const rows = await c.db.execute(
1425
+ "SELECT descriptor_json FROM agentos_actor_dynamic_mounts WHERE path = ?",
1426
+ path
1427
+ );
1428
+ const vm = await ensureVm(c, options);
1429
+ await vm.filesystem.unmount(path);
1430
+ try {
1431
+ await c.db.execute(
1432
+ "DELETE FROM agentos_actor_dynamic_mounts WHERE path = ?",
1433
+ path
1434
+ );
1435
+ } catch (error) {
1436
+ if (rows[0]) {
1437
+ try {
1438
+ await vm.filesystem.mount(
1439
+ JSON.parse(rows[0].descriptor_json)
1440
+ );
1441
+ } catch (rollbackError) {
1442
+ c.log.error({
1443
+ msg: "agent-os dynamic unmount rollback failed",
1444
+ path,
1445
+ error: rollbackError
1446
+ });
1447
+ }
1448
+ }
1449
+ throw error;
1450
+ }
1451
+ },
1452
+ listMounts: async (c) => (await ensureVm(c, options)).filesystem.listMounts(),
1453
+ listSoftware: async (c) => (await ensureVm(c, options)).software.list(),
1454
+ linkSoftware: async (c, descriptor) => {
1455
+ await assertActorCollectionCapacity(
1456
+ c,
1457
+ "agentos_actor_linked_software",
1458
+ descriptor.path,
1459
+ maxLinkedSoftware,
1460
+ "linked software packages",
1461
+ "maxLinkedSoftware"
1462
+ );
1463
+ await c.db.execute(
1464
+ "INSERT INTO agentos_actor_linked_software (path, descriptor_json) VALUES (?, ?) ON CONFLICT(path) DO UPDATE SET descriptor_json = excluded.descriptor_json",
1465
+ descriptor.path,
1466
+ JSON.stringify(descriptor)
252
1467
  );
1468
+ try {
1469
+ await (await ensureVm(c, options)).software.link(descriptor);
1470
+ } catch (error) {
1471
+ try {
1472
+ await c.db.execute(
1473
+ "DELETE FROM agentos_actor_linked_software WHERE path = ?",
1474
+ descriptor.path
1475
+ );
1476
+ } catch (rollbackError) {
1477
+ c.log.error({
1478
+ msg: "agent-os linked software rollback failed",
1479
+ path: descriptor.path,
1480
+ error: rollbackError
1481
+ });
1482
+ }
1483
+ throw error;
1484
+ }
1485
+ }
1486
+ };
1487
+ const nested = {
1488
+ createContext: flat.createContext,
1489
+ process: {
1490
+ exec: flat.exec,
1491
+ execFile: flat.execArgv,
1492
+ spawn: flat.spawn,
1493
+ get: flat.getProcess,
1494
+ list: flat.listProcesses,
1495
+ tree: flat.processTree,
1496
+ wait: flat.waitProcess,
1497
+ signal: flat.signalProcess,
1498
+ kill: flat.killProcess,
1499
+ writeStdin: flat.writeProcessStdin,
1500
+ closeStdin: flat.closeProcessStdin,
1501
+ resizePty: flat.resizeProcessPty,
1502
+ readOutput: flat.readProcessOutput
1503
+ },
1504
+ javascript: {
1505
+ execute: flat.executeJavaScript,
1506
+ evaluate: flat.evaluateJavaScript,
1507
+ executeFile: flat.executeJavaScriptFile,
1508
+ spawn: flat.spawnJavaScript,
1509
+ spawnFile: flat.spawnJavaScriptFile,
1510
+ npm: {
1511
+ install: flat.installNpmPackages,
1512
+ runScript: flat.executeNpmScript,
1513
+ runPackage: flat.executeNpmPackage
1514
+ }
1515
+ },
1516
+ typescript: {
1517
+ execute: flat.executeTypeScript,
1518
+ evaluate: flat.evaluateTypeScript,
1519
+ executeFile: flat.executeTypeScriptFile,
1520
+ spawn: flat.spawnTypeScript,
1521
+ spawnFile: flat.spawnTypeScriptFile,
1522
+ check: flat.checkTypeScript,
1523
+ checkProject: flat.checkTypeScriptProject
1524
+ },
1525
+ python: {
1526
+ execute: flat.executePython,
1527
+ evaluate: flat.evaluatePython,
1528
+ executeFile: flat.executePythonFile,
1529
+ executeModule: flat.executePythonModule,
1530
+ spawn: flat.spawnPython,
1531
+ spawnFile: flat.spawnPythonFile,
1532
+ spawnModule: flat.spawnPythonModule,
1533
+ install: flat.installPythonPackages
1534
+ },
1535
+ contexts: {
1536
+ get: flat.getContext,
1537
+ list: flat.listContexts,
1538
+ reset: flat.resetContext,
1539
+ delete: flat.deleteContext
1540
+ },
1541
+ terminal: {
1542
+ open: flat.openShell,
1543
+ list: flat.listShells,
1544
+ snapshot: flat.shellSnapshot,
1545
+ write: flat.writeShell,
1546
+ resize: flat.resizeShell,
1547
+ wait: flat.waitShell,
1548
+ close: flat.closeShell
1549
+ },
1550
+ filesystem: {
1551
+ readFile: flat.readFile,
1552
+ writeFile: flat.writeFile,
1553
+ readFiles: flat.readFiles,
1554
+ writeFiles: flat.writeFiles,
1555
+ stat: flat.stat,
1556
+ mkdir: flat.mkdir,
1557
+ readdir: flat.readdir,
1558
+ readdirEntries: flat.readdirEntries,
1559
+ readdirRecursive: flat.readdirRecursive,
1560
+ exists: flat.exists,
1561
+ move: flat.move,
1562
+ remove: flat.remove,
1563
+ export: flat.exportRootFilesystem,
1564
+ mount: flat.mountFs,
1565
+ unmount: flat.unmountFs,
1566
+ listMounts: flat.listMounts
1567
+ },
1568
+ network: {
1569
+ httpRequest: flat.httpRequest
1570
+ },
1571
+ software: {
1572
+ list: flat.listSoftware,
1573
+ link: flat.linkSoftware
1574
+ },
1575
+ agents: {
1576
+ list: flat.listAgents
1577
+ },
1578
+ sessions: {
1579
+ open: flat.openSession,
1580
+ get: flat.getSession,
1581
+ list: flat.listSessions,
1582
+ delete: flat.deleteSession,
1583
+ unload: flat.unloadSession,
1584
+ prompt: flat.prompt,
1585
+ cancelPrompt: flat.cancelPrompt,
1586
+ respondPermission: flat.respondPermission,
1587
+ readHistory: flat.readHistory,
1588
+ getConfig: flat.getSessionConfig,
1589
+ setConfigOption: flat.setSessionConfigOption,
1590
+ getCapabilities: flat.getSessionCapabilities,
1591
+ getAgentInfo: flat.getSessionAgentInfo
1592
+ },
1593
+ cron: {
1594
+ schedule: flat.scheduleCron,
1595
+ list: flat.listCronJobs,
1596
+ cancel: flat.cancelCronJob
253
1597
  }
254
- const options = {
255
- // Resolve the prebuilt agent-os actor plugin cdylib; RivetKit `dlopen`s
256
- // it through the generic native-plugin ABI.
257
- pluginPath: getPluginPath(),
258
- // Opaque config envelope the plugin parses (config.rs::AgentOsConfigJson).
259
- configJson: buildConfigJson(parsed),
260
- // RivetKit's native-plugin bridge owns the runtime ActorConfig for
261
- // cdylib actors, so forward the merged per-actor lifecycle options too.
262
- actorOptions,
263
- // Resolve the prebuilt sidecar binary from the npm package so the plugin
264
- // spawns the bundled binary rather than relying on `agentos-sidecar`
265
- // being on PATH.
266
- sidecarPath: getSidecarPath(),
267
- // Custom inspector tabs. The native-plugin path bypasses the normal
268
- // actor-config assembly (`buildActorConfig`/`inspectorTabs`), so the
269
- // tabs MUST ride on the plugin options: the Rust NAPI binding
270
- // `from_native_plugin` forwards `inspectorTabs` into the actor config so
271
- // the dashboard serves `/inspector/custom-tabs/<id>/` and advertises them
272
- // in `tab-config`. (Setting `actor({ inspector })` alone does nothing for
273
- // native-plugin actors.)
274
- inspectorTabs: AGENTOS_INSPECTOR_CONFIG.tabs
275
- };
276
- return runtime.createNativePluginFactory(options);
1598
+ };
1599
+ return {
1600
+ ...nested,
1601
+ // Legacy flat actions from the pre-language-execution API. Keep these
1602
+ // as aliases to the canonical nested handlers.
1603
+ readFile: nested.filesystem.readFile,
1604
+ writeFile: nested.filesystem.writeFile,
1605
+ readFiles: nested.filesystem.readFiles,
1606
+ writeFiles: nested.filesystem.writeFiles,
1607
+ stat: nested.filesystem.stat,
1608
+ mkdir: nested.filesystem.mkdir,
1609
+ readdir: nested.filesystem.readdir,
1610
+ readdirEntries: nested.filesystem.readdirEntries,
1611
+ readdirRecursive: nested.filesystem.readdirRecursive,
1612
+ exists: nested.filesystem.exists,
1613
+ move: nested.filesystem.move,
1614
+ remove: nested.filesystem.remove,
1615
+ exportRootFilesystem: nested.filesystem.export,
1616
+ mountFs: nested.filesystem.mount,
1617
+ unmountFs: nested.filesystem.unmount,
1618
+ listMounts: nested.filesystem.listMounts,
1619
+ exec: async (c, ...args) => (await ensureVm(c, options)).exec(...args),
1620
+ execArgv: async (c, ...args) => (await ensureVm(c, options)).execArgv(...args),
1621
+ spawn: nested.process.spawn,
1622
+ waitProcess: nested.process.wait,
1623
+ killProcess: nested.process.kill,
1624
+ listProcesses: nested.process.list,
1625
+ processTree: nested.process.tree,
1626
+ getProcess: nested.process.get,
1627
+ writeProcessStdin: nested.process.writeStdin,
1628
+ closeProcessStdin: nested.process.closeStdin,
1629
+ openShell: nested.terminal.open,
1630
+ listShells: nested.terminal.list,
1631
+ shellSnapshot: nested.terminal.snapshot,
1632
+ writeShell: nested.terminal.write,
1633
+ resizeShell: nested.terminal.resize,
1634
+ closeShell: nested.terminal.close,
1635
+ waitShell: nested.terminal.wait,
1636
+ httpRequest: nested.network.httpRequest,
1637
+ vmFetch: flat.vmFetch,
1638
+ vmFetchStreamStart: flat.vmFetchStreamStart,
1639
+ vmFetchStreamRead: flat.vmFetchStreamRead,
1640
+ vmFetchStreamCancel: flat.vmFetchStreamCancel,
1641
+ scheduleCron: nested.cron.schedule,
1642
+ listCronJobs: nested.cron.list,
1643
+ cancelCronJob: nested.cron.cancel,
1644
+ listAgents: nested.agents.list,
1645
+ openSession: nested.sessions.open,
1646
+ getSession: nested.sessions.get,
1647
+ listSessions: nested.sessions.list,
1648
+ deleteSession: nested.sessions.delete,
1649
+ unloadSession: nested.sessions.unload,
1650
+ prompt: nested.sessions.prompt,
1651
+ cancelPrompt: nested.sessions.cancelPrompt,
1652
+ respondPermission: nested.sessions.respondPermission,
1653
+ readHistory: nested.sessions.readHistory,
1654
+ getSessionConfig: nested.sessions.getConfig,
1655
+ setSessionConfigOption: nested.sessions.setConfigOption,
1656
+ getSessionCapabilities: nested.sessions.getCapabilities,
1657
+ getSessionAgentInfo: nested.sessions.getAgentInfo,
1658
+ listSoftware: nested.software.list,
1659
+ linkSoftware: nested.software.link,
1660
+ // Preview URLs are RivetKit-specific and intentionally stay flat.
1661
+ createPreviewUrl: flat.createPreviewUrl,
1662
+ expirePreviewUrl: flat.expirePreviewUrl,
1663
+ // Observe-only runtime health, also RivetKit-specific.
1664
+ health: flat.health
277
1665
  };
278
1666
  }
279
- var ACTOR_NEVER_HIT_MS = 60 * 60 * 1e3;
280
- var ACTOR_NEVER_HIT_MESSAGE_BYTES = 512 * 1024 * 1024;
281
- var DEFAULT_AGENTOS_ACTOR_OPTIONS = {
282
- // Connection/setup lifecycle (stock 5s each) — the websocket setup path that
283
- // was timing out at 5000ms and dropping all streamed events.
284
- onBeforeConnectTimeout: ACTOR_NEVER_HIT_MS,
285
- onConnectTimeout: ACTOR_NEVER_HIT_MS,
286
- createVarsTimeout: ACTOR_NEVER_HIT_MS,
287
- createConnStateTimeout: ACTOR_NEVER_HIT_MS,
288
- onMigrateTimeout: ACTOR_NEVER_HIT_MS,
289
- // Action/RPC lifecycle (stock 60s) — long multi-step prompt turns.
290
- actionTimeout: ACTOR_NEVER_HIT_MS,
291
- // Idle/keepalive — don't reap a live session or sleep mid-turn (stock
292
- // connectionLivenessTimeout 2.5s, sleepTimeout 30s). The liveness *interval*
293
- // (ping cadence) is intentionally left at its small default.
294
- connectionLivenessTimeout: ACTOR_NEVER_HIT_MS,
295
- sleepTimeout: ACTOR_NEVER_HIT_MS,
296
- // Payload sizes — large prompts/results. `maxQueueMessageSize` is the
297
- // per-actor message cap (stock 64 KiB); the transport-level
298
- // max{Incoming,Outgoing}MessageSize live on the registry/setup config (see
299
- // AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULTS), not on per-actor options.
300
- maxQueueSize: 1e6,
301
- maxQueueMessageSize: ACTOR_NEVER_HIT_MESSAGE_BYTES
302
- };
303
- var INSPECTOR_TABS_ASSET_DIR = join2(
304
- dirname2(fileURLToPath2(import.meta.url)),
1667
+ var agentOsOptionKeys = [
1668
+ "software",
1669
+ "defaultSoftware",
1670
+ "loopbackExemptPorts",
1671
+ "allowedNodeBuiltins",
1672
+ "highResolutionTime",
1673
+ "database",
1674
+ "rootFilesystem",
1675
+ "mounts",
1676
+ "sandbox",
1677
+ "scheduleDriver",
1678
+ "bindings",
1679
+ "permissions",
1680
+ "sidecar",
1681
+ "limits",
1682
+ "onAgentStderr",
1683
+ "onAgentExit",
1684
+ "onLimitWarning"
1685
+ ];
1686
+ function splitConfig(config) {
1687
+ const actorConfig = { ...config };
1688
+ const agentOsOptions = {};
1689
+ for (const key of agentOsOptionKeys) {
1690
+ if (key in actorConfig) {
1691
+ agentOsOptions[key] = actorConfig[key];
1692
+ delete actorConfig[key];
1693
+ }
1694
+ }
1695
+ const onSessionEvent = actorConfig.onSessionEvent;
1696
+ const preview = actorConfig.preview;
1697
+ const resolveOptions = actorConfig.resolveOptions;
1698
+ const onVmStart = actorConfig.onVmStart;
1699
+ const onVmStop = actorConfig.onVmStop;
1700
+ const onVmDisposed = actorConfig.onVmDisposed;
1701
+ const maxSessionSubscriptions = actorConfig.maxSessionSubscriptions;
1702
+ const maxDynamicMounts = actorConfig.maxDynamicMounts;
1703
+ const maxLinkedSoftware = actorConfig.maxLinkedSoftware;
1704
+ delete actorConfig.onSessionEvent;
1705
+ delete actorConfig.preview;
1706
+ delete actorConfig.resolveOptions;
1707
+ delete actorConfig.onVmStart;
1708
+ delete actorConfig.onVmStop;
1709
+ delete actorConfig.onVmDisposed;
1710
+ delete actorConfig.maxSessionSubscriptions;
1711
+ delete actorConfig.maxDynamicMounts;
1712
+ delete actorConfig.maxLinkedSoftware;
1713
+ return {
1714
+ actorConfig,
1715
+ agentOsOptions,
1716
+ hooks: { onSessionEvent },
1717
+ preview,
1718
+ resolveOptions,
1719
+ onVmStart,
1720
+ onVmStop,
1721
+ onVmDisposed,
1722
+ maxSessionSubscriptions,
1723
+ maxDynamicMounts,
1724
+ maxLinkedSoftware
1725
+ };
1726
+ }
1727
+ function assertNoReservedKeys(kind, custom, builtIns) {
1728
+ for (const key of Object.keys(custom ?? {})) {
1729
+ if (key in builtIns)
1730
+ throw new Error(`agentOS() ${kind} name is reserved: ${key}`);
1731
+ }
1732
+ }
1733
+ var INSPECTOR_TABS_ASSET_DIR = join(
1734
+ dirname(fileURLToPath(import.meta.url)),
305
1735
  "..",
306
1736
  "assets",
307
1737
  "inspector-tabs-app"
@@ -321,86 +1751,181 @@ var AGENTOS_INSPECTOR_CONFIG = {
321
1751
  icon: "folder-tree"
322
1752
  },
323
1753
  {
324
- id: "processes",
325
- label: "Processes",
326
- source: INSPECTOR_TABS_ASSET_DIR,
327
- icon: "microchip"
328
- },
329
- {
330
- id: "software",
331
- label: "Software",
1754
+ id: "terminal",
1755
+ label: "Terminal",
332
1756
  source: INSPECTOR_TABS_ASSET_DIR,
333
- icon: "box-archive"
1757
+ icon: "terminal"
334
1758
  },
335
1759
  {
336
- id: "mounts",
337
- label: "Mounts",
1760
+ id: "system",
1761
+ label: "System",
338
1762
  source: INSPECTOR_TABS_ASSET_DIR,
339
- icon: "hard-drive"
1763
+ icon: "layer-group"
340
1764
  },
1765
+ // Processes/software/mounts live as sections inside the System tab.
1766
+ // `metadata` is dashboard-owned and not hideable (the schema only
1767
+ // accepts the six built-in ids below), so it stays.
341
1768
  ...["workflow", "database", "state", "queue", "connections", "console"].map(
342
1769
  (id) => ({ id, hidden: true })
343
1770
  )
344
1771
  ]
345
1772
  };
346
- function createAgentOS(config) {
347
- const parsed = agentOsActorConfigSchema.parse(
348
- config
1773
+ function createAgentOS(config = {}) {
1774
+ const split = splitConfig(config);
1775
+ const actorConfig = split.actorConfig;
1776
+ const {
1777
+ agentOsOptions,
1778
+ hooks,
1779
+ preview,
1780
+ maxSessionSubscriptions,
1781
+ maxDynamicMounts,
1782
+ maxLinkedSoftware
1783
+ } = split;
1784
+ if (split.resolveOptions)
1785
+ optionResolvers.set(agentOsOptions, split.resolveOptions);
1786
+ if (split.onVmStart) vmStartResolvers.set(agentOsOptions, split.onVmStart);
1787
+ if (split.onVmStop) vmStopResolvers.set(agentOsOptions, split.onVmStop);
1788
+ if (split.onVmDisposed)
1789
+ vmDisposedResolvers.set(agentOsOptions, split.onVmDisposed);
1790
+ if (agentOsOptions.sandbox && "client" in agentOsOptions.sandbox) {
1791
+ throw new Error(
1792
+ "agentOS() cannot share sandbox: { client } across actor instances; use sandbox: { provider } so each actor VM starts its own client"
1793
+ );
1794
+ }
1795
+ if (agentOsOptions.rootFilesystem) {
1796
+ throw new Error(
1797
+ "agentOS() owns rootFilesystem so it can persist directly through the actor SQLite UDS; use mounts for additional filesystems"
1798
+ );
1799
+ }
1800
+ if (agentOsOptions.database) {
1801
+ throw new Error(
1802
+ "agentOS() owns database and injects the actor SQLite UDS descriptor; standalone AgentOs clients may choose a SQLite file"
1803
+ );
1804
+ }
1805
+ const actions = createAgentOsActions(
1806
+ agentOsOptions,
1807
+ hooks,
1808
+ preview,
1809
+ maxSessionSubscriptions,
1810
+ maxDynamicMounts,
1811
+ maxLinkedSoftware
349
1812
  );
350
- const userActorOptions = parsed.actorOptions;
351
- const actorOptions = {
352
- ...DEFAULT_AGENTOS_ACTOR_OPTIONS,
353
- ...userActorOptions ?? {}
354
- };
355
- const definition = actor({
356
- actions: {},
357
- options: actorOptions,
1813
+ assertNoReservedKeys("action", actorConfig.actions, actions);
1814
+ assertNoReservedKeys("event", actorConfig.events, builtInEvents);
1815
+ const userOnWake = actorConfig.onWake;
1816
+ const userOnSleep = actorConfig.onSleep;
1817
+ const userOnDestroy = actorConfig.onDestroy;
1818
+ const userOnRequest = actorConfig.onRequest;
1819
+ const userOnBeforeConnect = actorConfig.onBeforeConnect;
1820
+ return actor({
1821
+ ...actorConfig,
1822
+ options: {
1823
+ actionTimeout: DEFAULT_ACTION_TIMEOUT_MS,
1824
+ sleepGracePeriod: DEFAULT_SLEEP_GRACE_PERIOD_MS,
1825
+ ...actorConfig.options,
1826
+ enableActorRuntimeSocket: true
1827
+ },
358
1828
  // Register the custom agent-os inspector tabs (and hide the built-in
359
- // rivetkit tabs) so the dashboard renders the agent-os UI. Without this
360
- // the shipped tab assets are never surfaced.
361
- inspector: AGENTOS_INSPECTOR_CONFIG
1829
+ // rivetkit tabs) so the dashboard renders the agent-os UI. Without
1830
+ // this the shipped tab assets are never surfaced. A caller-supplied
1831
+ // inspector config wins.
1832
+ inspector: actorConfig.inspector ?? AGENTOS_INSPECTOR_CONFIG,
1833
+ db: db({ onMigrate: migrateAgentOsActorTables }),
1834
+ events: { ...actorConfig.events ?? {}, ...builtInEvents },
1835
+ actions: { ...actorConfig.actions ?? {}, ...actions },
1836
+ onBeforeConnect: async (c, params) => {
1837
+ if (c.request && matchPreviewPath(new URL(c.request.url).pathname) !== null) {
1838
+ return;
1839
+ }
1840
+ await userOnBeforeConnect?.(c, params);
1841
+ },
1842
+ onWake: async (c) => {
1843
+ try {
1844
+ await userOnWake?.(c);
1845
+ } catch (error) {
1846
+ await disposeVm(c, "error");
1847
+ throw error;
1848
+ }
1849
+ },
1850
+ onSleep: async (c) => {
1851
+ try {
1852
+ await userOnSleep?.(c);
1853
+ } finally {
1854
+ await disposeVm(c, "sleep");
1855
+ }
1856
+ },
1857
+ onDestroy: async (c) => {
1858
+ try {
1859
+ await userOnDestroy?.(c);
1860
+ } finally {
1861
+ await disposeVm(c, "destroy");
1862
+ }
1863
+ },
1864
+ onRequest: async (c, request) => {
1865
+ const url = new URL(request.url);
1866
+ const match = matchPreviewPath(url.pathname);
1867
+ if (!match) {
1868
+ const response2 = await userOnRequest?.(c, request);
1869
+ return response2 ?? new Response("Not Found", { status: 404 });
1870
+ }
1871
+ if (request.method === "OPTIONS")
1872
+ return new Response(null, {
1873
+ status: 204,
1874
+ headers: {
1875
+ "access-control-allow-origin": "*",
1876
+ "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
1877
+ "access-control-allow-headers": "*"
1878
+ }
1879
+ });
1880
+ const now = Date.now();
1881
+ await c.db.execute(
1882
+ "DELETE FROM agentos_actor_preview_tokens WHERE expires_at_ms <= ?",
1883
+ now
1884
+ );
1885
+ const rows = await c.db.execute(
1886
+ "SELECT port FROM agentos_actor_preview_tokens WHERE token = ? AND expires_at_ms > ?",
1887
+ match[1],
1888
+ now
1889
+ );
1890
+ if (!rows[0])
1891
+ return new Response("Preview URL expired or invalid", { status: 403 });
1892
+ const target = new URL(request.url);
1893
+ target.pathname = match[2] ?? "/";
1894
+ const vm = await ensureVm(c, agentOsOptions);
1895
+ const requestHeaders = {};
1896
+ request.headers.forEach((value, key) => {
1897
+ requestHeaders[key] = value;
1898
+ });
1899
+ const response = await vm.network.httpRequest({
1900
+ port: rows[0].port,
1901
+ path: `${target.pathname}${target.search}`,
1902
+ method: request.method,
1903
+ headers: requestHeaders,
1904
+ ...request.method === "GET" || request.method === "HEAD" ? {} : { body: new Uint8Array(await request.arrayBuffer()) }
1905
+ });
1906
+ const headers = new Headers(response.headers);
1907
+ headers.set("access-control-allow-origin", "*");
1908
+ return new Response(Buffer.from(response.body), {
1909
+ status: response.status,
1910
+ statusText: response.statusText,
1911
+ headers
1912
+ });
1913
+ }
362
1914
  });
363
- definition.nativeFactoryBuilder = buildNativeFactoryBuilder(
364
- parsed,
365
- actorOptions
366
- );
367
- return definition;
368
1915
  }
369
1916
 
370
1917
  // src/index.ts
371
- import { defineSoftware } from "@rivet-dev/agentos-core";
372
1918
  var AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT = 512 * 1024 * 1024;
373
1919
  var setup = ((input) => rivetkitSetup({
1920
+ ...input,
374
1921
  maxIncomingMessageSize: AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT,
375
1922
  maxOutgoingMessageSize: AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT,
376
- ...input
1923
+ experimentalActorUds: true
377
1924
  }));
378
- function agentOS(config = {}) {
379
- const {
380
- preview,
381
- actorOptions,
382
- onBeforeConnect,
383
- onSessionEvent,
384
- onPermissionRequest,
385
- ...options
386
- } = config;
387
- return createAgentOS({
388
- options,
389
- actorOptions,
390
- preview,
391
- onBeforeConnect,
392
- onSessionEvent: onSessionEvent ? (_ctx, sessionId, event) => onSessionEvent(sessionId, event) : void 0,
393
- onPermissionRequest: onPermissionRequest ? (_ctx, sessionId, request) => onPermissionRequest(sessionId, request) : void 0
394
- });
395
- }
396
1925
  export {
397
- agentOS,
398
- agentOsActorConfigSchema,
399
- buildConfigJson,
400
- defineSoftware,
401
- getPluginPath,
402
- nativeAgentOsOptionsSchema,
403
- nodeModulesMount,
1926
+ createAgentOS as agentOS,
1927
+ createAgentOS,
1928
+ createAgentOsActions,
404
1929
  setup
405
1930
  };
406
1931
  //# sourceMappingURL=index.js.map