@rivet-dev/agentos 0.2.8-rc.1 → 0.2.8-rc.3

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 (25) hide show
  1. package/assets/inspector-tabs-app/assets/badge-CkqYPoD9.js +1 -0
  2. package/assets/inspector-tabs-app/assets/filesystem-DbXxNt-B.js +1 -0
  3. package/assets/inspector-tabs-app/assets/{index-C50G2vhD.js → index-nTg2hrne.js} +22 -22
  4. package/assets/inspector-tabs-app/assets/{mounts-C0eJmxpt.js → mounts-BlNRslup.js} +1 -1
  5. package/assets/inspector-tabs-app/assets/{processes-CvN1MFLy.js → processes-CjHQ_o8t.js} +1 -1
  6. package/assets/inspector-tabs-app/assets/scroll-area-DE-oi7a2.js +1 -0
  7. package/assets/inspector-tabs-app/assets/{software-BjGEcqMs.js → software-2sjLheLb.js} +1 -1
  8. package/assets/inspector-tabs-app/assets/transcript-Cz9DrFWK.js +1 -0
  9. package/assets/inspector-tabs-app/assets/{useSuspenseQuery-CpwiXRj_.js → useSuspenseQuery-V0HYenB_.js} +1 -1
  10. package/assets/inspector-tabs-app/index.html +1 -1
  11. package/dist/chunk-V6TY7KAL.js +8 -0
  12. package/dist/chunk-V6TY7KAL.js.map +1 -0
  13. package/dist/client.js.map +1 -1
  14. package/dist/index.d.ts +116 -731
  15. package/dist/index.js +818 -341
  16. package/dist/index.js.map +1 -1
  17. package/dist/node.d.ts +67 -0
  18. package/dist/node.js +275 -0
  19. package/dist/node.js.map +1 -0
  20. package/package.json +21 -16
  21. package/assets/inspector-tabs-app/assets/badge-Coq9s9H6.js +0 -1
  22. package/assets/inspector-tabs-app/assets/filesystem-_yeTmDH7.js +0 -1
  23. package/assets/inspector-tabs-app/assets/scroll-area-DzL-iGyn.js +0 -1
  24. package/assets/inspector-tabs-app/assets/transcript-BKLxbOF5.js +0 -1
  25. package/assets/inspector-tabs-app/assets/useQuery-RSkOi56s.js +0 -1
package/dist/index.js CHANGED
@@ -1,405 +1,882 @@
1
+ import "./chunk-V6TY7KAL.js";
2
+
1
3
  // src/index.ts
2
4
  import { setup as rivetkitSetup } from "rivetkit";
5
+ import { defineSoftware, nodeModulesMount } from "@rivet-dev/agentos-core";
3
6
 
4
7
  // 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
8
+ import crypto from "crypto";
15
9
  import {
16
- agentOsOptionFieldSchemas,
17
- nativeMountConfigSchema,
18
- sharedSidecarConfigSchema
10
+ AgentOs
19
11
  } 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();
46
-
47
- // src/plugin-binary.ts
48
- import { existsSync } from "fs";
49
- 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";
12
+ import {
13
+ actor,
14
+ event,
15
+ UserError
16
+ } from "rivetkit";
17
+ import { db } from "rivetkit/db";
18
+ var DEFAULT_ACTION_TIMEOUT_MS = 2147483647;
19
+ var DEFAULT_SLEEP_GRACE_PERIOD_MS = 15 * 6e4;
20
+ var DEFAULT_PREVIEW_TTL_SECONDS = 3600;
21
+ var MAX_PREVIEW_TTL_SECONDS = 86400;
22
+ var DEFAULT_MAX_ACTIVE_PREVIEW_TOKENS = 1024;
23
+ var DEFAULT_MAX_SESSION_SUBSCRIPTIONS = 1e4;
24
+ var DEFAULT_MAX_DYNAMIC_MOUNTS = 1e4;
25
+ var DEFAULT_MAX_LINKED_SOFTWARE = 1e4;
26
+ var ACTOR_SQLITE_CHUNK_SIZE = 512 * 1024;
27
+ var ACTOR_SQLITE_INLINE_THRESHOLD = 64 * 1024;
28
+ var ROOT_NAMESPACE = "agentos-root";
29
+ var PREVIEW_PATH_PATTERN = /^\/fetch\/([a-f0-9]{48})(\/.*)?$/;
30
+ var MAX_SQLITE_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
31
+ var ACTOR_SQLITE_MIGRATIONS = [
32
+ {
33
+ version: 1,
34
+ sql: `
35
+ CREATE TABLE agentos_actor_preview_tokens (
36
+ token TEXT PRIMARY KEY CHECK (length(token) = 48 AND token NOT GLOB '*[^0-9a-f]*'),
37
+ port INTEGER NOT NULL CHECK (port BETWEEN 1 AND 65535),
38
+ created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND ${MAX_SQLITE_SAFE_INTEGER}),
39
+ expires_at_ms INTEGER NOT NULL CHECK (expires_at_ms > created_at_ms AND expires_at_ms <= ${MAX_SQLITE_SAFE_INTEGER})
40
+ ) STRICT;
41
+ CREATE INDEX agentos_actor_preview_tokens_by_expiry
42
+ ON agentos_actor_preview_tokens(expires_at_ms);
43
+ CREATE TABLE agentos_actor_dynamic_mounts (
44
+ path TEXT PRIMARY KEY CHECK (substr(path, 1, 1) = '/' AND instr(path, char(0)) = 0),
45
+ descriptor_json TEXT NOT NULL CHECK (json_valid(descriptor_json) AND json_type(descriptor_json) = 'object')
46
+ ) STRICT;
47
+ CREATE TABLE agentos_actor_linked_software (
48
+ path TEXT PRIMARY KEY CHECK (length(path) > 0 AND instr(path, char(0)) = 0),
49
+ descriptor_json TEXT NOT NULL CHECK (json_valid(descriptor_json) AND json_type(descriptor_json) = 'object')
50
+ ) STRICT;
51
+ `
61
52
  }
62
- }
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;
53
+ ];
54
+ var builtInEvents = {
55
+ sessionEvent: event(),
56
+ vmBooted: event(),
57
+ vmShutdown: event(),
58
+ processOutput: event(),
59
+ processExit: event(),
60
+ shellData: event(),
61
+ cronEvent: event(),
62
+ agentExit: event(),
63
+ shellStderr: event(),
64
+ shellExit: event()
65
+ };
66
+ var runtimes = /* @__PURE__ */ new Map();
67
+ function runtimeFor(c) {
68
+ let runtime = runtimes.get(c.actorId);
69
+ if (!runtime) {
70
+ runtime = { vm: null, subscribedSessions: /* @__PURE__ */ new Map() };
71
+ runtimes.set(c.actorId, runtime);
76
72
  }
77
- return null;
73
+ return runtime;
78
74
  }
79
- function getPluginPath() {
80
- const override = process.env[PLUGIN_BIN_ENV];
81
- if (override) {
82
- if (!existsSync(override)) {
75
+ async function ensureVm(c, options) {
76
+ const runtime = runtimeFor(c);
77
+ if (runtime.vm !== null) return runtime.vm;
78
+ const startedAt = Date.now();
79
+ runtime.vm = (async () => {
80
+ const actorRuntimeSocket = c.actorRuntimeSocket;
81
+ if (typeof actorRuntimeSocket !== "function") {
83
82
  throw new Error(
84
- `${PLUGIN_BIN_ENV} is set to ${override} but the file does not exist`
83
+ "AgentOS actors require a RivetKit runtime with Actor Runtime Socket support"
85
84
  );
86
85
  }
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;
95
- }
96
- }
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.`
86
+ const { path } = await actorRuntimeSocket.call(c);
87
+ const mountRows = await c.db.execute(
88
+ "SELECT descriptor_json FROM agentos_actor_dynamic_mounts ORDER BY path"
101
89
  );
102
- }
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\`.`
90
+ const softwareRows = await c.db.execute(
91
+ "SELECT descriptor_json FROM agentos_actor_linked_software ORDER BY path"
114
92
  );
93
+ const vm = await AgentOs.create({
94
+ ...options,
95
+ database: { type: "actor_uds", path },
96
+ onAgentExit: (event2) => {
97
+ c.log.error({
98
+ msg: "agent-os agent adapter exited unexpectedly",
99
+ ...event2
100
+ });
101
+ c.broadcast("agentExit", event2);
102
+ try {
103
+ options?.onAgentExit?.(event2);
104
+ } catch (error) {
105
+ c.log.error({
106
+ msg: "agent-os onAgentExit hook failed",
107
+ sessionId: event2.sessionId,
108
+ error
109
+ });
110
+ }
111
+ },
112
+ rootFilesystem: {
113
+ type: "native",
114
+ plugin: {
115
+ id: "chunked_actor_sqlite",
116
+ config: {
117
+ namespace: ROOT_NAMESPACE,
118
+ chunkSize: ACTOR_SQLITE_CHUNK_SIZE,
119
+ inlineThreshold: ACTOR_SQLITE_INLINE_THRESHOLD,
120
+ uid: options?.user?.euid ?? options?.user?.uid ?? 1e3,
121
+ gid: options?.user?.egid ?? options?.user?.gid ?? 1e3
122
+ }
123
+ }
124
+ }
125
+ });
126
+ try {
127
+ for (const row of mountRows) {
128
+ await vm.mountFs(
129
+ JSON.parse(row.descriptor_json)
130
+ );
131
+ }
132
+ for (const row of softwareRows) {
133
+ await vm.linkSoftware(
134
+ JSON.parse(row.descriptor_json)
135
+ );
136
+ }
137
+ } catch (error) {
138
+ await vm.dispose();
139
+ throw error;
140
+ }
141
+ vm.onCronEvent((cronEvent) => c.broadcast("cronEvent", cronEvent));
142
+ c.broadcast("vmBooted", {});
143
+ c.log.info({
144
+ msg: "agent-os vm booted",
145
+ bootDurationMs: Date.now() - startedAt
146
+ });
147
+ return vm;
148
+ })();
149
+ try {
150
+ return await runtime.vm;
151
+ } catch (error) {
152
+ runtime.vm = null;
153
+ c.log.error({
154
+ msg: "agent-os vm bootstrap failed",
155
+ actorId: c.actorId,
156
+ error
157
+ });
158
+ throw error;
115
159
  }
116
- return join(dirname(pkgJsonPath), lib);
117
160
  }
118
-
119
- // 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
- };
161
+ async function disposeVm(c, reason) {
162
+ const runtime = runtimes.get(c.actorId);
163
+ if (!runtime) return;
164
+ const vm = runtime.vm;
165
+ runtimes.delete(c.actorId);
166
+ for (const unsubscribers of runtime.subscribedSessions.values()) {
167
+ for (const unsubscribe of unsubscribers) unsubscribe();
168
+ }
169
+ runtime.subscribedSessions.clear();
170
+ if (vm) await (await vm).dispose();
171
+ c.broadcast("vmShutdown", { reason });
130
172
  }
131
- function toRecord(value) {
132
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
173
+ function matchPreviewPath(pathname) {
174
+ return pathname.match(PREVIEW_PATH_PATTERN);
133
175
  }
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 };
176
+ function validateAgentOsActorMigrationLadder(migrations) {
177
+ if (migrations.length === 0) {
178
+ throw new Error("AgentOS actor SQLite migration ladder must not be empty");
141
179
  }
142
- for (const legacy of ["packageTar", "packageDir", "commandDir", "dir"]) {
143
- if (typeof record[legacy] === "string") {
180
+ for (const [index, migration] of migrations.entries()) {
181
+ const expectedVersion = index + 1;
182
+ if (migration.version !== expectedVersion) {
144
183
  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 }`
184
+ `invalid AgentOS actor SQLite migration ladder: expected version ${expectedVersion}, received ${migration.version}`
146
185
  );
147
186
  }
148
- }
149
- return void 0;
150
- }
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;
161
- }
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
- });
189
- }
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`);
187
+ if (migration.sql.trim().length === 0) {
188
+ throw new Error(
189
+ `invalid AgentOS actor SQLite migration ${migration.version}: SQL is empty`
190
+ );
198
191
  }
199
- const record = mount;
200
- if (record.driver !== void 0) {
192
+ if (/(?:^|;)\s*(?:BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\b/im.test(
193
+ migration.sql
194
+ )) {
201
195
  throw new Error(
202
- "agentOS() only supports Native mounts across the NAPI boundary; Plain mounts with driver callbacks are not serializable"
196
+ `invalid AgentOS actor SQLite migration ${migration.version}: transaction control belongs to the migration provider`
203
197
  );
204
198
  }
205
- if (record.filesystem !== void 0) {
199
+ if (/\b(?:FOREIGN\s+KEY|REFERENCES)\b/i.test(migration.sql)) {
206
200
  throw new Error(
207
- "agentOS() only supports Native mounts across the NAPI boundary; Overlay mounts are not serializable"
201
+ `invalid AgentOS actor SQLite migration ${migration.version}: foreign keys are not used in the actor-owned schema`
208
202
  );
209
203
  }
210
- const plugin = record.plugin;
211
- if (typeof record.path !== "string" || !plugin || typeof plugin !== "object" || typeof plugin.id !== "string") {
204
+ for (const statement of migration.sql.split(";")) {
205
+ if (/^\s*CREATE\s+TABLE\b/i.test(statement) && !/[)]\s*STRICT\s*$/i.test(statement)) {
206
+ throw new Error(
207
+ `invalid AgentOS actor SQLite migration ${migration.version}: every actor-owned table must be STRICT`
208
+ );
209
+ }
210
+ }
211
+ const ownedIdentifiers = migration.sql.match(/\bagentos_[a-z0-9_]+\b/gi);
212
+ if (!ownedIdentifiers || ownedIdentifiers.some(
213
+ (identifier) => !identifier.startsWith("agentos_actor_")
214
+ )) {
212
215
  throw new Error(
213
- `agentOS() options.mounts[${index}] must be a Native mount with { path, plugin: { id, config? } }`
216
+ `invalid AgentOS actor SQLite migration ${migration.version}: migrations may reference only agentos_actor_* tables and indexes`
214
217
  );
215
218
  }
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
- });
219
+ }
225
220
  }
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");
221
+ async function migrateAgentOsActorTables(database) {
222
+ validateAgentOsActorMigrationLadder(ACTOR_SQLITE_MIGRATIONS);
223
+ await database.execute(`
224
+ CREATE TABLE IF NOT EXISTS agentos_actor_schema_version (
225
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
226
+ schema_version INTEGER NOT NULL CHECK (schema_version BETWEEN 0 AND ${MAX_SQLITE_SAFE_INTEGER})
227
+ ) STRICT;
228
+ `);
229
+ const rows = await database.execute(
230
+ "SELECT schema_version FROM agentos_actor_schema_version WHERE singleton = 1"
231
+ );
232
+ if (rows.length > 1) {
233
+ throw new Error(
234
+ `invalid AgentOS actor SQLite schema version table: expected at most one row, received ${rows.length}`
235
+ );
230
236
  }
231
- const record = input;
232
- if (record.kind === "explicit" || record.handle !== void 0) {
237
+ const rawCurrent = rows[0]?.schema_version;
238
+ const current = rows.length === 0 ? 0 : rawCurrent;
239
+ if (typeof current !== "number" || !Number.isSafeInteger(current) || current < 0) {
233
240
  throw new Error(
234
- "agentOS() only supports sidecar shared pool configuration across the NAPI boundary; explicit sidecar handles are not serializable"
241
+ `invalid AgentOS actor SQLite schema version ${String(rawCurrent)}`
242
+ );
243
+ }
244
+ if (current > ACTOR_SQLITE_MIGRATIONS.length) {
245
+ throw new Error(
246
+ `AgentOS actor SQLite schema version ${current} is newer than supported version ${ACTOR_SQLITE_MIGRATIONS.length}`
247
+ );
248
+ }
249
+ for (const migration of ACTOR_SQLITE_MIGRATIONS.slice(current)) {
250
+ await database.execute(migration.sql);
251
+ await database.execute(
252
+ `INSERT INTO agentos_actor_schema_version (singleton, schema_version)
253
+ VALUES (1, ?)
254
+ ON CONFLICT(singleton) DO UPDATE SET schema_version = excluded.schema_version`,
255
+ migration.version
256
+ );
257
+ }
258
+ }
259
+ async function assertActorCollectionCapacity(c, table, key, limit, label, configKey) {
260
+ const existing = await c.db.execute(
261
+ `SELECT 1 AS present FROM ${table} WHERE path = ? LIMIT 1`,
262
+ key
263
+ );
264
+ if (existing.length > 0) return;
265
+ const rows = await c.db.execute(
266
+ `SELECT COUNT(*) AS count FROM ${table}`
267
+ );
268
+ const count = Number(rows[0]?.count ?? 0);
269
+ if (count >= limit) {
270
+ throw new UserError(
271
+ `${label} limit ${limit} reached; raise ${configKey} to persist more`,
272
+ {
273
+ code: `agentos_${configKey === "maxDynamicMounts" ? "dynamic_mount" : "linked_software"}_limit`,
274
+ metadata: { limit }
275
+ }
235
276
  );
236
277
  }
237
- if (record.kind !== void 0 && record.kind !== "shared") {
238
- throw new Error('agentOS() options.sidecar.kind must be "shared"');
278
+ if (count + 1 === Math.ceil(limit * 0.8)) {
279
+ c.log.warn({
280
+ msg: `${label} are near the limit of ${limit}; raise ${configKey} to persist more`,
281
+ count: count + 1,
282
+ limit
283
+ });
239
284
  }
240
- return typeof record.pool === "string" ? { pool: record.pool } : {};
241
285
  }
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})`
286
+ function trackSessionEvents(c, vm, sessionId, hooks, maxSessionSubscriptions) {
287
+ const runtime = runtimeFor(c);
288
+ if (runtime.subscribedSessions.has(sessionId)) return;
289
+ if (runtime.subscribedSessions.size >= maxSessionSubscriptions) {
290
+ throw new UserError(
291
+ `session subscription limit ${maxSessionSubscriptions} reached; raise maxSessionSubscriptions to observe more sessions`,
292
+ {
293
+ code: "agentos_session_subscription_limit",
294
+ metadata: { limit: maxSessionSubscriptions }
295
+ }
296
+ );
297
+ }
298
+ const nextCount = runtime.subscribedSessions.size + 1;
299
+ if (nextCount === Math.ceil(maxSessionSubscriptions * 0.8)) {
300
+ c.log.warn({
301
+ msg: `session subscriptions are near the limit of ${maxSessionSubscriptions}; raise maxSessionSubscriptions to observe more sessions`,
302
+ subscriptionCount: nextCount,
303
+ limit: maxSessionSubscriptions
304
+ });
305
+ }
306
+ const unsubscribeSession = vm.onSessionEvent(
307
+ sessionId,
308
+ (notification) => {
309
+ const serialized = JSON.parse(
310
+ JSON.stringify(notification)
247
311
  );
312
+ c.broadcast("sessionEvent", serialized);
313
+ if (hooks.onSessionEvent) {
314
+ c.waitUntil(
315
+ Promise.resolve().then(() => hooks.onSessionEvent?.(c, sessionId, serialized)).catch(
316
+ (error) => c.log.error({
317
+ msg: "agent-os session event hook failed",
318
+ sessionId,
319
+ error
320
+ })
321
+ )
322
+ );
323
+ }
248
324
  }
249
- if (!runtime.createNativePluginFactory) {
250
- throw new Error(
251
- "runtime.createNativePluginFactory is not implemented on the active CoreRuntime"
325
+ );
326
+ runtime.subscribedSessions.set(sessionId, [unsubscribeSession]);
327
+ }
328
+ function untrackSessionEvents(c, sessionId) {
329
+ const unsubscribers = runtimeFor(c).subscribedSessions.get(sessionId);
330
+ if (!unsubscribers) return;
331
+ for (const unsubscribe of unsubscribers) unsubscribe();
332
+ runtimeFor(c).subscribedSessions.delete(sessionId);
333
+ }
334
+ function createAgentOsActions(options, hooks = {}, preview = {}, maxSessionSubscriptions = DEFAULT_MAX_SESSION_SUBSCRIPTIONS, maxDynamicMounts = DEFAULT_MAX_DYNAMIC_MOUNTS, maxLinkedSoftware = DEFAULT_MAX_LINKED_SOFTWARE) {
335
+ const defaultPreviewTtlSeconds = preview.defaultExpiresInSeconds ?? DEFAULT_PREVIEW_TTL_SECONDS;
336
+ const maxPreviewTtlSeconds = preview.maxExpiresInSeconds ?? MAX_PREVIEW_TTL_SECONDS;
337
+ const maxActivePreviewTokens = preview.maxActiveTokens ?? DEFAULT_MAX_ACTIVE_PREVIEW_TOKENS;
338
+ if (!Number.isFinite(defaultPreviewTtlSeconds) || defaultPreviewTtlSeconds <= 0 || !Number.isFinite(maxPreviewTtlSeconds) || maxPreviewTtlSeconds <= 0 || defaultPreviewTtlSeconds > maxPreviewTtlSeconds) {
339
+ throw new UserError(
340
+ "preview expiry bounds must be positive and the default cannot exceed the maximum",
341
+ { code: "agentos_preview_invalid_config" }
342
+ );
343
+ }
344
+ if (!Number.isInteger(maxActivePreviewTokens) || maxActivePreviewTokens < 1) {
345
+ throw new UserError("preview.maxActiveTokens must be a positive integer", {
346
+ code: "agentos_preview_invalid_config"
347
+ });
348
+ }
349
+ if (!Number.isInteger(maxSessionSubscriptions) || maxSessionSubscriptions < 1) {
350
+ throw new UserError("maxSessionSubscriptions must be a positive integer", {
351
+ code: "agentos_session_subscription_invalid_config"
352
+ });
353
+ }
354
+ if (!Number.isInteger(maxDynamicMounts) || maxDynamicMounts < 1) {
355
+ throw new UserError("maxDynamicMounts must be a positive integer", {
356
+ code: "agentos_dynamic_mount_invalid_config"
357
+ });
358
+ }
359
+ if (!Number.isInteger(maxLinkedSoftware) || maxLinkedSoftware < 1) {
360
+ throw new UserError("maxLinkedSoftware must be a positive integer", {
361
+ code: "agentos_linked_software_invalid_config"
362
+ });
363
+ }
364
+ return {
365
+ readFile: async (c, ...args) => {
366
+ try {
367
+ return await (await ensureVm(c, options)).readFile(...args);
368
+ } catch (error) {
369
+ c.log.error({
370
+ msg: "agent-os readFile action failed",
371
+ path: args[0],
372
+ error
373
+ });
374
+ throw error;
375
+ }
376
+ },
377
+ writeFile: async (c, ...args) => (await ensureVm(c, options)).writeFile(...args),
378
+ readFiles: async (c, ...args) => (await ensureVm(c, options)).readFiles(...args),
379
+ writeFiles: async (c, ...args) => (await ensureVm(c, options)).writeFiles(...args),
380
+ stat: async (c, ...args) => (await ensureVm(c, options)).stat(...args),
381
+ mkdir: async (c, ...args) => (await ensureVm(c, options)).mkdir(...args),
382
+ readdir: async (c, ...args) => (await ensureVm(c, options)).readdir(...args),
383
+ readdirEntries: async (c, ...args) => (await ensureVm(c, options)).readdirEntries(...args),
384
+ readdirRecursive: async (c, ...args) => (await ensureVm(c, options)).readdirRecursive(...args),
385
+ exists: async (c, ...args) => (await ensureVm(c, options)).exists(...args),
386
+ move: async (c, ...args) => (await ensureVm(c, options)).move(...args),
387
+ remove: async (c, ...args) => (await ensureVm(c, options)).remove(...args),
388
+ exec: async (c, ...args) => (await ensureVm(c, options)).exec(...args),
389
+ execArgv: async (c, ...args) => (await ensureVm(c, options)).execArgv(...args),
390
+ spawn: async (c, ...args) => {
391
+ const vm = await ensureVm(c, options);
392
+ const process = vm.spawn(...args);
393
+ const unsubscribeOutput = vm.onProcessOutput(
394
+ process.pid,
395
+ (event2) => c.broadcast("processOutput", event2)
396
+ );
397
+ const unsubscribeExit = vm.onProcessExit(
398
+ process.pid,
399
+ (event2) => c.broadcast("processExit", event2)
400
+ );
401
+ void c.keepAwake(
402
+ vm.waitProcess(process.pid).finally(() => {
403
+ unsubscribeOutput();
404
+ unsubscribeExit();
405
+ })
406
+ ).catch(
407
+ (error) => c.log.error({
408
+ msg: "agent-os process wait failed",
409
+ pid: process.pid,
410
+ error
411
+ })
412
+ );
413
+ return process;
414
+ },
415
+ waitProcess: async (c, ...args) => (await ensureVm(c, options)).waitProcess(...args),
416
+ killProcess: async (c, ...args) => (await ensureVm(c, options)).killProcess(...args),
417
+ stopProcess: async (c, ...args) => (await ensureVm(c, options)).stopProcess(...args),
418
+ listProcesses: async (c) => (await ensureVm(c, options)).listProcesses(),
419
+ allProcesses: async (c) => (await ensureVm(c, options)).allProcesses(),
420
+ processTree: async (c) => (await ensureVm(c, options)).processTree(),
421
+ getProcess: async (c, ...args) => (await ensureVm(c, options)).getProcess(...args),
422
+ writeProcessStdin: async (c, ...args) => (await ensureVm(c, options)).writeProcessStdin(...args),
423
+ closeProcessStdin: async (c, ...args) => (await ensureVm(c, options)).closeProcessStdin(...args),
424
+ openShell: async (c, ...args) => {
425
+ const vm = await ensureVm(c, options);
426
+ const shell = vm.openShell(...args);
427
+ const unsubscribeData = vm.onShellData(
428
+ shell.shellId,
429
+ (event2) => c.broadcast("shellData", event2)
430
+ );
431
+ const unsubscribeStderr = vm.onShellStderr(
432
+ shell.shellId,
433
+ (event2) => c.broadcast("shellStderr", event2)
434
+ );
435
+ const unsubscribeExit = vm.onShellExit(
436
+ shell.shellId,
437
+ (event2) => c.broadcast("shellExit", event2)
438
+ );
439
+ void c.keepAwake(
440
+ vm.waitShell(shell.shellId).finally(() => {
441
+ unsubscribeData();
442
+ unsubscribeStderr();
443
+ unsubscribeExit();
444
+ })
445
+ ).catch(
446
+ (error) => c.log.error({
447
+ msg: "agent-os shell wait failed",
448
+ shellId: shell.shellId,
449
+ error
450
+ })
451
+ );
452
+ return shell;
453
+ },
454
+ writeShell: async (c, ...args) => (await ensureVm(c, options)).writeShell(...args),
455
+ resizeShell: async (c, ...args) => (await ensureVm(c, options)).resizeShell(...args),
456
+ closeShell: async (c, ...args) => (await ensureVm(c, options)).closeShell(...args),
457
+ waitShell: async (c, ...args) => (await ensureVm(c, options)).waitShell(...args),
458
+ httpRequest: async (c, ...args) => (await ensureVm(c, options)).httpRequest(...args),
459
+ scheduleCron: async (c, cronOptions) => {
460
+ const job = (await ensureVm(c, options)).scheduleCron(
461
+ cronOptions
462
+ );
463
+ return { id: job.id };
464
+ },
465
+ listCronJobs: async (c) => (await ensureVm(c, options)).listCronJobs(),
466
+ cancelCronJob: async (c, ...args) => (await ensureVm(c, options)).cancelCronJob(...args),
467
+ listAgents: async (c) => (await ensureVm(c, options)).listAgents(),
468
+ openSession: async (c, input) => {
469
+ const vm = await ensureVm(c, options);
470
+ try {
471
+ await vm.openSession(input);
472
+ } catch (error) {
473
+ const message = error instanceof Error ? error.message : String(error);
474
+ const causeCode = typeof error?.code === "string" ? error.code : void 0;
475
+ c.log.error({
476
+ msg: "agent-os openSession action failed",
477
+ sessionId: input.sessionId ?? "main",
478
+ agent: input.agent,
479
+ causeCode,
480
+ error
481
+ });
482
+ throw new UserError(`AgentOS openSession failed: ${message}`, {
483
+ code: "agentos_session_open_failed",
484
+ metadata: causeCode ? { causeCode } : void 0
485
+ });
486
+ }
487
+ trackSessionEvents(
488
+ c,
489
+ vm,
490
+ input.sessionId ?? "main",
491
+ hooks,
492
+ maxSessionSubscriptions
493
+ );
494
+ },
495
+ getSession: async (c, ...args) => (await ensureVm(c, options)).getSession(...args),
496
+ listSessions: async (c, ...args) => (await ensureVm(c, options)).listSessions(...args),
497
+ deleteSession: async (c, ...args) => {
498
+ const result = await (await ensureVm(c, options)).deleteSession(...args);
499
+ untrackSessionEvents(c, args[0]?.sessionId ?? "main");
500
+ return result;
501
+ },
502
+ unloadSession: async (c, ...args) => {
503
+ const result = await (await ensureVm(c, options)).unloadSession(...args);
504
+ untrackSessionEvents(c, args[0]?.sessionId ?? "main");
505
+ return result;
506
+ },
507
+ prompt: async (c, input) => {
508
+ const vm = await ensureVm(c, options);
509
+ const sessionId = input.sessionId ?? "main";
510
+ trackSessionEvents(c, vm, sessionId, hooks, maxSessionSubscriptions);
511
+ try {
512
+ return await c.keepAwake(vm.prompt(input));
513
+ } catch (error) {
514
+ const message = error instanceof Error ? error.message : String(error);
515
+ const causeCode = typeof error?.code === "string" ? error.code : void 0;
516
+ c.log.error({
517
+ msg: "agent-os prompt action failed",
518
+ sessionId,
519
+ causeCode,
520
+ error
521
+ });
522
+ throw new UserError(`AgentOS prompt failed: ${message}`, {
523
+ code: "agentos_prompt_failed",
524
+ metadata: causeCode ? { causeCode } : void 0
525
+ });
526
+ }
527
+ },
528
+ cancelPrompt: async (c, ...args) => (await ensureVm(c, options)).cancelPrompt(...args),
529
+ respondPermission: async (c, ...args) => (await ensureVm(c, options)).respondPermission(...args),
530
+ readHistory: async (c, ...args) => (await ensureVm(c, options)).readHistory(...args),
531
+ getSessionConfig: async (c, ...args) => (await ensureVm(c, options)).getSessionConfig(...args),
532
+ setSessionConfigOption: async (c, ...args) => (await ensureVm(c, options)).setSessionConfigOption(...args),
533
+ getSessionCapabilities: async (c, ...args) => (await ensureVm(c, options)).getSessionCapabilities(...args),
534
+ getSessionAgentInfo: async (c, ...args) => (await ensureVm(c, options)).getSessionAgentInfo(...args),
535
+ createPreviewUrl: async (c, port, ttlSeconds = defaultPreviewTtlSeconds) => {
536
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
537
+ throw new UserError(
538
+ "port must be an integer between 1 and 65535; pass a valid VM listener port",
539
+ { code: "agentos_preview_invalid_port" }
540
+ );
541
+ if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0 || ttlSeconds > maxPreviewTtlSeconds)
542
+ throw new UserError(
543
+ `ttlSeconds must be greater than 0 and at most ${maxPreviewTtlSeconds}; raise preview.maxExpiresInSeconds to allow a longer lifetime`,
544
+ { code: "agentos_preview_invalid_ttl" }
545
+ );
546
+ const token = crypto.randomBytes(24).toString("hex");
547
+ const createdAt = Date.now();
548
+ const expiresAt = createdAt + ttlSeconds * 1e3;
549
+ await c.db.execute(
550
+ "DELETE FROM agentos_actor_preview_tokens WHERE expires_at_ms <= ?",
551
+ createdAt
552
+ );
553
+ const counts = await c.db.execute(
554
+ "SELECT COUNT(*) AS count FROM agentos_actor_preview_tokens"
555
+ );
556
+ const activeTokenCount = Number(counts[0]?.count ?? 0);
557
+ if (activeTokenCount >= maxActivePreviewTokens) {
558
+ throw new UserError(
559
+ `preview token limit ${maxActivePreviewTokens} reached; raise preview.maxActiveTokens to allow more`,
560
+ {
561
+ code: "agentos_preview_token_limit",
562
+ metadata: { limit: maxActivePreviewTokens }
563
+ }
564
+ );
565
+ }
566
+ const nextActiveTokenCount = activeTokenCount + 1;
567
+ const warningThreshold = Math.ceil(maxActivePreviewTokens * 0.8);
568
+ if (nextActiveTokenCount === warningThreshold) {
569
+ c.log.warn({
570
+ msg: `preview tokens are near the limit of ${maxActivePreviewTokens}; raise preview.maxActiveTokens to allow more`,
571
+ activeTokenCount: nextActiveTokenCount,
572
+ limit: maxActivePreviewTokens
573
+ });
574
+ }
575
+ await c.db.execute(
576
+ "INSERT INTO agentos_actor_preview_tokens (token, port, created_at_ms, expires_at_ms) VALUES (?, ?, ?, ?)",
577
+ token,
578
+ port,
579
+ createdAt,
580
+ expiresAt
581
+ );
582
+ return { path: `/fetch/${token}`, token, port, expiresAt };
583
+ },
584
+ expirePreviewUrl: async (c, token) => {
585
+ await c.db.execute(
586
+ "DELETE FROM agentos_actor_preview_tokens WHERE token = ?",
587
+ token
588
+ );
589
+ },
590
+ exportRootFilesystem: async (c, ...args) => (await ensureVm(c, options)).exportRootFilesystem(...args),
591
+ mountFs: async (c, descriptor) => {
592
+ await assertActorCollectionCapacity(
593
+ c,
594
+ "agentos_actor_dynamic_mounts",
595
+ descriptor.path,
596
+ maxDynamicMounts,
597
+ "dynamic mounts",
598
+ "maxDynamicMounts"
599
+ );
600
+ const vm = await ensureVm(c, options);
601
+ await vm.mountFs(descriptor);
602
+ try {
603
+ await c.db.execute(
604
+ "INSERT INTO agentos_actor_dynamic_mounts (path, descriptor_json) VALUES (?, ?) ON CONFLICT(path) DO UPDATE SET descriptor_json = excluded.descriptor_json",
605
+ descriptor.path,
606
+ JSON.stringify(descriptor)
607
+ );
608
+ } catch (error) {
609
+ try {
610
+ await vm.unmountFs(descriptor.path);
611
+ } catch (rollbackError) {
612
+ c.log.error({
613
+ msg: "agent-os dynamic mount rollback failed",
614
+ path: descriptor.path,
615
+ error: rollbackError
616
+ });
617
+ }
618
+ throw error;
619
+ }
620
+ },
621
+ unmountFs: async (c, path) => {
622
+ const rows = await c.db.execute(
623
+ "SELECT descriptor_json FROM agentos_actor_dynamic_mounts WHERE path = ?",
624
+ path
625
+ );
626
+ const vm = await ensureVm(c, options);
627
+ await vm.unmountFs(path);
628
+ try {
629
+ await c.db.execute(
630
+ "DELETE FROM agentos_actor_dynamic_mounts WHERE path = ?",
631
+ path
632
+ );
633
+ } catch (error) {
634
+ if (rows[0]) {
635
+ try {
636
+ await vm.mountFs(
637
+ JSON.parse(rows[0].descriptor_json)
638
+ );
639
+ } catch (rollbackError) {
640
+ c.log.error({
641
+ msg: "agent-os dynamic unmount rollback failed",
642
+ path,
643
+ error: rollbackError
644
+ });
645
+ }
646
+ }
647
+ throw error;
648
+ }
649
+ },
650
+ listMounts: async (c) => (await ensureVm(c, options)).listMounts(),
651
+ listSoftware: async (c) => (await ensureVm(c, options)).listSoftware(),
652
+ linkSoftware: async (c, descriptor) => {
653
+ await assertActorCollectionCapacity(
654
+ c,
655
+ "agentos_actor_linked_software",
656
+ descriptor.path,
657
+ maxLinkedSoftware,
658
+ "linked software packages",
659
+ "maxLinkedSoftware"
252
660
  );
661
+ await c.db.execute(
662
+ "INSERT INTO agentos_actor_linked_software (path, descriptor_json) VALUES (?, ?) ON CONFLICT(path) DO UPDATE SET descriptor_json = excluded.descriptor_json",
663
+ descriptor.path,
664
+ JSON.stringify(descriptor)
665
+ );
666
+ try {
667
+ await (await ensureVm(c, options)).linkSoftware(descriptor);
668
+ } catch (error) {
669
+ try {
670
+ await c.db.execute(
671
+ "DELETE FROM agentos_actor_linked_software WHERE path = ?",
672
+ descriptor.path
673
+ );
674
+ } catch (rollbackError) {
675
+ c.log.error({
676
+ msg: "agent-os linked software rollback failed",
677
+ path: descriptor.path,
678
+ error: rollbackError
679
+ });
680
+ }
681
+ throw error;
682
+ }
253
683
  }
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);
277
684
  };
278
685
  }
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)),
305
- "..",
306
- "assets",
307
- "inspector-tabs-app"
308
- );
309
- var AGENTOS_INSPECTOR_CONFIG = {
310
- tabs: [
311
- {
312
- id: "transcript",
313
- label: "Transcript",
314
- source: INSPECTOR_TABS_ASSET_DIR,
315
- icon: "comments"
686
+ var agentOsOptionKeys = [
687
+ "software",
688
+ "defaultSoftware",
689
+ "loopbackExemptPorts",
690
+ "allowedNodeBuiltins",
691
+ "highResolutionTime",
692
+ "database",
693
+ "rootFilesystem",
694
+ "mounts",
695
+ "scheduleDriver",
696
+ "bindings",
697
+ "permissions",
698
+ "sidecar",
699
+ "limits",
700
+ "onAgentStderr",
701
+ "onAgentExit",
702
+ "onLimitWarning"
703
+ ];
704
+ function splitConfig(config) {
705
+ const actorConfig = { ...config };
706
+ const agentOsOptions = {};
707
+ for (const key of agentOsOptionKeys) {
708
+ if (key in actorConfig) {
709
+ agentOsOptions[key] = actorConfig[key];
710
+ delete actorConfig[key];
711
+ }
712
+ }
713
+ const onSessionEvent = actorConfig.onSessionEvent;
714
+ const preview = actorConfig.preview;
715
+ const maxSessionSubscriptions = actorConfig.maxSessionSubscriptions;
716
+ const maxDynamicMounts = actorConfig.maxDynamicMounts;
717
+ const maxLinkedSoftware = actorConfig.maxLinkedSoftware;
718
+ delete actorConfig.onSessionEvent;
719
+ delete actorConfig.preview;
720
+ delete actorConfig.maxSessionSubscriptions;
721
+ delete actorConfig.maxDynamicMounts;
722
+ delete actorConfig.maxLinkedSoftware;
723
+ return {
724
+ actorConfig,
725
+ agentOsOptions,
726
+ hooks: { onSessionEvent },
727
+ preview,
728
+ maxSessionSubscriptions,
729
+ maxDynamicMounts,
730
+ maxLinkedSoftware
731
+ };
732
+ }
733
+ function assertNoReservedKeys(kind, custom, builtIns) {
734
+ for (const key of Object.keys(custom ?? {})) {
735
+ if (key in builtIns)
736
+ throw new Error(`agentOS() ${kind} name is reserved: ${key}`);
737
+ }
738
+ }
739
+ function createAgentOS(config = {}) {
740
+ const split = splitConfig(config);
741
+ const actorConfig = split.actorConfig;
742
+ const {
743
+ agentOsOptions,
744
+ hooks,
745
+ preview,
746
+ maxSessionSubscriptions,
747
+ maxDynamicMounts,
748
+ maxLinkedSoftware
749
+ } = split;
750
+ if (agentOsOptions.rootFilesystem) {
751
+ throw new Error(
752
+ "agentOS() owns rootFilesystem so it can persist directly through the actor SQLite UDS; use mounts for additional filesystems"
753
+ );
754
+ }
755
+ if (agentOsOptions.database) {
756
+ throw new Error(
757
+ "agentOS() owns database and injects the actor SQLite UDS descriptor; standalone AgentOs clients may choose a SQLite file"
758
+ );
759
+ }
760
+ const actions = createAgentOsActions(
761
+ agentOsOptions,
762
+ hooks,
763
+ preview,
764
+ maxSessionSubscriptions,
765
+ maxDynamicMounts,
766
+ maxLinkedSoftware
767
+ );
768
+ assertNoReservedKeys("action", actorConfig.actions, actions);
769
+ assertNoReservedKeys("event", actorConfig.events, builtInEvents);
770
+ const userOnWake = actorConfig.onWake;
771
+ const userOnSleep = actorConfig.onSleep;
772
+ const userOnDestroy = actorConfig.onDestroy;
773
+ const userOnRequest = actorConfig.onRequest;
774
+ const userOnBeforeConnect = actorConfig.onBeforeConnect;
775
+ return actor({
776
+ ...actorConfig,
777
+ options: {
778
+ actionTimeout: DEFAULT_ACTION_TIMEOUT_MS,
779
+ sleepGracePeriod: DEFAULT_SLEEP_GRACE_PERIOD_MS,
780
+ ...actorConfig.options,
781
+ enableActorRuntimeSocket: true
316
782
  },
317
- {
318
- id: "filesystem",
319
- label: "Filesystem",
320
- source: INSPECTOR_TABS_ASSET_DIR,
321
- icon: "folder-tree"
783
+ db: db({ onMigrate: migrateAgentOsActorTables }),
784
+ events: { ...actorConfig.events ?? {}, ...builtInEvents },
785
+ actions: { ...actorConfig.actions ?? {}, ...actions },
786
+ onBeforeConnect: async (c, params) => {
787
+ if (c.request && matchPreviewPath(new URL(c.request.url).pathname) !== null) {
788
+ return;
789
+ }
790
+ await userOnBeforeConnect?.(c, params);
322
791
  },
323
- {
324
- id: "processes",
325
- label: "Processes",
326
- source: INSPECTOR_TABS_ASSET_DIR,
327
- icon: "microchip"
792
+ onWake: async (c) => {
793
+ try {
794
+ await userOnWake?.(c);
795
+ } catch (error) {
796
+ await disposeVm(c, "error");
797
+ throw error;
798
+ }
328
799
  },
329
- {
330
- id: "software",
331
- label: "Software",
332
- source: INSPECTOR_TABS_ASSET_DIR,
333
- icon: "box-archive"
800
+ onSleep: async (c) => {
801
+ try {
802
+ await userOnSleep?.(c);
803
+ } finally {
804
+ await disposeVm(c, "sleep");
805
+ }
334
806
  },
335
- {
336
- id: "mounts",
337
- label: "Mounts",
338
- source: INSPECTOR_TABS_ASSET_DIR,
339
- icon: "hard-drive"
807
+ onDestroy: async (c) => {
808
+ try {
809
+ await userOnDestroy?.(c);
810
+ } finally {
811
+ await disposeVm(c, "destroy");
812
+ }
340
813
  },
341
- ...["workflow", "database", "state", "queue", "connections", "console"].map(
342
- (id) => ({ id, hidden: true })
343
- )
344
- ]
345
- };
346
- function createAgentOS(config) {
347
- const parsed = agentOsActorConfigSchema.parse(
348
- config
349
- );
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,
358
- // 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
814
+ onRequest: async (c, request) => {
815
+ const url = new URL(request.url);
816
+ const match = matchPreviewPath(url.pathname);
817
+ if (!match) {
818
+ const response2 = await userOnRequest?.(c, request);
819
+ return response2 ?? new Response("Not Found", { status: 404 });
820
+ }
821
+ if (request.method === "OPTIONS")
822
+ return new Response(null, {
823
+ status: 204,
824
+ headers: {
825
+ "access-control-allow-origin": "*",
826
+ "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
827
+ "access-control-allow-headers": "*"
828
+ }
829
+ });
830
+ const now = Date.now();
831
+ await c.db.execute(
832
+ "DELETE FROM agentos_actor_preview_tokens WHERE expires_at_ms <= ?",
833
+ now
834
+ );
835
+ const rows = await c.db.execute(
836
+ "SELECT port FROM agentos_actor_preview_tokens WHERE token = ? AND expires_at_ms > ?",
837
+ match[1],
838
+ now
839
+ );
840
+ if (!rows[0])
841
+ return new Response("Preview URL expired or invalid", { status: 403 });
842
+ const target = new URL(request.url);
843
+ target.pathname = match[2] ?? "/";
844
+ const vm = await ensureVm(c, agentOsOptions);
845
+ const requestHeaders = {};
846
+ request.headers.forEach((value, key) => {
847
+ requestHeaders[key] = value;
848
+ });
849
+ const response = await vm.httpRequest({
850
+ port: rows[0].port,
851
+ path: `${target.pathname}${target.search}`,
852
+ method: request.method,
853
+ headers: requestHeaders,
854
+ ...request.method === "GET" || request.method === "HEAD" ? {} : { body: new Uint8Array(await request.arrayBuffer()) }
855
+ });
856
+ const headers = new Headers(response.headers);
857
+ headers.set("access-control-allow-origin", "*");
858
+ return new Response(Buffer.from(response.body), {
859
+ status: response.status,
860
+ statusText: response.statusText,
861
+ headers
862
+ });
863
+ }
362
864
  });
363
- definition.nativeFactoryBuilder = buildNativeFactoryBuilder(
364
- parsed,
365
- actorOptions
366
- );
367
- return definition;
368
865
  }
369
866
 
370
867
  // src/index.ts
371
- import { defineSoftware } from "@rivet-dev/agentos-core";
372
868
  var AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT = 512 * 1024 * 1024;
373
869
  var setup = ((input) => rivetkitSetup({
870
+ ...input,
374
871
  maxIncomingMessageSize: AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT,
375
872
  maxOutgoingMessageSize: AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT,
376
- ...input
873
+ experimentalActorUds: true
377
874
  }));
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
875
  export {
397
- agentOS,
398
- agentOsActorConfigSchema,
399
- buildConfigJson,
876
+ createAgentOS as agentOS,
877
+ createAgentOS,
878
+ createAgentOsActions,
400
879
  defineSoftware,
401
- getPluginPath,
402
- nativeAgentOsOptionsSchema,
403
880
  nodeModulesMount,
404
881
  setup
405
882
  };