@rivet-dev/agentos 0.0.0-codex-actor-plugin-contract-coverage.c7d8f87 → 0.0.0-fix-main-wasm-ownership.150c49a

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