@rivet-dev/agentos 0.0.0-glibc.9438c58 → 0.0.0-main.29b0797

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,370 +1,830 @@
1
- // src/actor.ts
2
- import { dirname as dirname2, join as join2 } from "path";
3
- import { fileURLToPath as fileURLToPath2 } from "url";
4
- import common from "@agentos-software/common";
5
- import { OPT_AGENTOS_ROOT } from "@rivet-dev/agentos-core";
6
- import { getSidecarPath } from "@rivet-dev/agentos-sidecar";
7
- import {
8
- actor
9
- } from "rivetkit";
1
+ // src/index.ts
2
+ import { setup as rivetkitSetup } from "rivetkit";
3
+ import { defineSoftware, nodeModulesMount } from "@rivet-dev/agentos-core";
10
4
 
11
- // src/config.ts
5
+ // src/actor.ts
6
+ import crypto from "crypto";
12
7
  import {
13
- agentOsOptionFieldSchemas,
14
- nativeMountConfigSchema,
15
- sharedSidecarConfigSchema
8
+ AgentOs
16
9
  } from "@rivet-dev/agentos-core";
17
- import { z } from "zod/v4";
18
- var zFunction = () => z.custom((val) => typeof val === "function");
19
- var nativeAgentOsOptionsSchema = z.object({
20
- software: agentOsOptionFieldSchemas.software,
21
- defaultSoftware: agentOsOptionFieldSchemas.defaultSoftware,
22
- loopbackExemptPorts: agentOsOptionFieldSchemas.loopbackExemptPorts,
23
- allowedNodeBuiltins: agentOsOptionFieldSchemas.allowedNodeBuiltins,
24
- rootFilesystem: agentOsOptionFieldSchemas.rootFilesystem,
25
- mounts: z.array(nativeMountConfigSchema).optional(),
26
- additionalInstructions: agentOsOptionFieldSchemas.additionalInstructions,
27
- permissions: agentOsOptionFieldSchemas.permissions,
28
- sidecar: sharedSidecarConfigSchema.optional(),
29
- limits: agentOsOptionFieldSchemas.limits
30
- }).strict();
31
- var agentOsActorOptionsSchema = z.record(z.string(), z.unknown()).optional();
32
- var agentOsActorConfigSchema = z.object({
33
- options: nativeAgentOsOptionsSchema.optional(),
34
- actorOptions: agentOsActorOptionsSchema,
35
- preview: z.object({
36
- defaultExpiresInSeconds: z.number().positive().default(3600),
37
- maxExpiresInSeconds: z.number().positive().default(86400)
38
- }).strict().prefault(() => ({})),
39
- onBeforeConnect: zFunction().optional(),
40
- onSessionEvent: zFunction().optional(),
41
- onPermissionRequest: zFunction().optional()
42
- }).strict();
43
-
44
- // src/plugin-binary.ts
45
- import { existsSync } from "fs";
46
- import { createRequire } from "module";
47
- import { dirname, join } from "path";
48
- import { fileURLToPath } from "url";
49
- var PLUGIN_BIN_ENV = "AGENTOS_PLUGIN_BIN";
50
- function libraryName() {
51
- switch (process.platform) {
52
- case "darwin":
53
- return "libagentos_actor_plugin.dylib";
54
- case "win32":
55
- return "agentos_actor_plugin.dll";
56
- default:
57
- 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
+ `
58
50
  }
59
- }
60
- function getPlatformPackageName() {
61
- const { platform, arch } = process;
62
- switch (platform) {
63
- case "linux":
64
- if (arch === "x64") return "@rivet-dev/agentos-plugin-linux-x64-gnu";
65
- if (arch === "arm64") return "@rivet-dev/agentos-plugin-linux-arm64-gnu";
66
- break;
67
- case "darwin":
68
- if (arch === "x64") return "@rivet-dev/agentos-plugin-darwin-x64";
69
- if (arch === "arm64") return "@rivet-dev/agentos-plugin-darwin-arm64";
70
- break;
71
- default:
72
- 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);
73
70
  }
74
- return null;
71
+ return runtime;
75
72
  }
76
- function getPluginPath() {
77
- const override = process.env[PLUGIN_BIN_ENV];
78
- if (override) {
79
- 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") {
80
80
  throw new Error(
81
- `${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"
82
82
  );
83
83
  }
84
- return override;
85
- }
86
- const lib = libraryName();
87
- const here = dirname(fileURLToPath(import.meta.url));
88
- for (const profile of ["release", "debug"]) {
89
- const candidate = join(here, "..", "..", "..", "target", profile, lib);
90
- if (existsSync(candidate)) {
91
- return candidate;
92
- }
93
- }
94
- const platformPkg = getPlatformPackageName();
95
- if (!platformPkg) {
96
- throw new Error(
97
- `@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"
98
87
  );
99
- }
100
- const require2 = createRequire(import.meta.url);
101
- let pkgJsonPath;
102
- try {
103
- pkgJsonPath = require2.resolve(`${platformPkg}/package.json`);
104
- } catch {
105
- throw new Error(
106
- `@rivet-dev/agentos: platform package ${platformPkg} is not installed.
107
- This usually means the platform is unsupported or optionalDependencies
108
- were skipped during install. Try: npm install --include=optional ${platformPkg}
109
- Or set ${PLUGIN_BIN_ENV} to a local cdylib, or build it with
110
- \`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"
111
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;
112
150
  }
113
- return join(dirname(pkgJsonPath), lib);
114
151
  }
115
-
116
- // src/actor.ts
117
- function nodeModulesMount(hostNodeModulesDir, opts) {
118
- const readOnly = opts?.readOnly ?? true;
119
- return {
120
- path: "/root/node_modules",
121
- plugin: {
122
- id: "host_dir",
123
- config: { hostPath: hostNodeModulesDir, readOnly }
124
- },
125
- readOnly
126
- };
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 });
127
163
  }
128
- function toRecord(value) {
129
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
164
+ function matchPreviewPath(pathname) {
165
+ return pathname.match(PREVIEW_PATH_PATTERN);
130
166
  }
131
- function normalizePackageRef(value) {
132
- if (typeof value === "string") {
133
- 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");
134
170
  }
135
- const record = toRecord(value);
136
- if (typeof record.packagePath === "string") {
137
- return { path: record.packagePath };
138
- }
139
- for (const legacy of ["packageTar", "packageDir", "commandDir", "dir"]) {
140
- if (typeof record[legacy] === "string") {
171
+ for (const [index, migration] of migrations.entries()) {
172
+ const expectedVersion = index + 1;
173
+ if (migration.version !== expectedVersion) {
141
174
  throw new Error(
142
- `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}`
143
176
  );
144
177
  }
145
- }
146
- return void 0;
147
- }
148
- function normalizedPackageRefs(software) {
149
- const refs = [];
150
- const seen = /* @__PURE__ */ new Set();
151
- for (const entry of software.flat()) {
152
- const ref = normalizePackageRef(entry);
153
- if (!ref || seen.has(ref.path)) continue;
154
- seen.add(ref.path);
155
- refs.push(ref);
156
- }
157
- return refs;
158
- }
159
- function buildConfigJson(parsed) {
160
- const options = nativeAgentOsOptionsSchema.parse(
161
- parsed.options ?? {}
162
- );
163
- const softwareInput = Array.isArray(options.software) ? options.software : [];
164
- const defaultSoftwareEnabled = options.defaultSoftware !== false;
165
- const packageRefs = normalizedPackageRefs(
166
- defaultSoftwareEnabled ? [common, ...softwareInput] : softwareInput
167
- );
168
- const packages = packageRefs.map((ref) => ({ packagePath: ref.path }));
169
- const mounts = serializeNativeMounts(options.mounts);
170
- const sidecar = serializeSidecar(options.sidecar);
171
- return JSON.stringify({
172
- // The actor forwards ONLY package dirs; the sidecar resolves each agent from
173
- // the projected `/opt/agentos/<name>/current/agentos-package.json` (no
174
- // client-side adapter-entrypoint resolution — see root CLAUDE.md).
175
- packages,
176
- packagesMountAt: OPT_AGENTOS_ROOT,
177
- additionalInstructions: options.additionalInstructions,
178
- loopbackExemptPorts: options.loopbackExemptPorts,
179
- allowedNodeBuiltins: options.allowedNodeBuiltins,
180
- permissions: options.permissions,
181
- rootFilesystem: options.rootFilesystem,
182
- mounts,
183
- limits: options.limits,
184
- sidecar
185
- });
186
- }
187
- function serializeNativeMounts(input) {
188
- if (input == null) return void 0;
189
- if (!Array.isArray(input)) {
190
- throw new Error("agentOS() options.mounts must be an array");
191
- }
192
- return input.map((mount, index) => {
193
- if (!mount || typeof mount !== "object") {
194
- 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
+ );
195
182
  }
196
- const record = mount;
197
- if (record.driver !== void 0) {
183
+ if (/(?:^|;)\s*(?:BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\b/im.test(
184
+ migration.sql
185
+ )) {
198
186
  throw new Error(
199
- "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`
200
188
  );
201
189
  }
202
- if (record.filesystem !== void 0) {
190
+ if (/\b(?:FOREIGN\s+KEY|REFERENCES)\b/i.test(migration.sql)) {
203
191
  throw new Error(
204
- "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`
205
193
  );
206
194
  }
207
- const plugin = record.plugin;
208
- 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
+ )) {
209
206
  throw new Error(
210
- `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`
211
208
  );
212
209
  }
213
- return {
214
- path: record.path,
215
- plugin: {
216
- id: plugin.id,
217
- config: plugin.config
218
- },
219
- readOnly: typeof record.readOnly === "boolean" ? record.readOnly : void 0
220
- };
221
- });
210
+ }
222
211
  }
223
- function serializeSidecar(input) {
224
- if (input == null) return void 0;
225
- if (!input || typeof input !== "object") {
226
- 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
227
  }
228
- const record = input;
229
- if (record.kind === "explicit" || record.handle !== void 0) {
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) {
230
231
  throw new Error(
231
- "agentOS() only supports sidecar shared pool configuration across the NAPI boundary; explicit sidecar handles are not serializable"
232
+ `invalid AgentOS actor SQLite schema version ${String(rawCurrent)}`
232
233
  );
233
234
  }
234
- if (record.kind !== void 0 && record.kind !== "shared") {
235
- throw new Error('agentOS() options.sidecar.kind must be "shared"');
235
+ if (current > ACTOR_SQLITE_MIGRATIONS.length) {
236
+ throw new Error(
237
+ `AgentOS actor SQLite schema version ${current} is newer than supported version ${ACTOR_SQLITE_MIGRATIONS.length}`
238
+ );
239
+ }
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
+ );
236
248
  }
237
- return typeof record.pool === "string" ? { pool: record.pool } : {};
238
249
  }
239
- function buildNativeFactoryBuilder(parsed) {
240
- return (runtime) => {
241
- if (runtime.kind !== "napi") {
242
- throw new Error(
243
- `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)
244
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
+ }
245
315
  }
246
- if (!runtime.createNativePluginFactory) {
247
- throw new Error(
248
- "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)
249
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)
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
+ }
250
632
  }
251
- const options = {
252
- // Resolve the prebuilt agent-os actor plugin cdylib; RivetKit `dlopen`s
253
- // it through the generic native-plugin ABI.
254
- pluginPath: getPluginPath(),
255
- // Opaque config envelope the plugin parses (config.rs::AgentOsConfigJson).
256
- configJson: buildConfigJson(parsed),
257
- // Resolve the prebuilt sidecar binary from the npm package so the plugin
258
- // spawns the bundled binary rather than relying on `agentos-sidecar`
259
- // being on PATH.
260
- sidecarPath: getSidecarPath(),
261
- // Custom inspector tabs. The native-plugin path bypasses the normal
262
- // actor-config assembly (`buildActorConfig`/`inspectorTabs`), so the
263
- // tabs MUST ride on the plugin options: the Rust NAPI binding
264
- // `from_native_plugin` forwards `inspectorTabs` into the actor config so
265
- // the dashboard serves `/inspector/custom-tabs/<id>/` and advertises them
266
- // in `tab-config`. (Setting `actor({ inspector })` alone does nothing for
267
- // native-plugin actors.)
268
- inspectorTabs: AGENTOS_INSPECTOR_CONFIG.tabs
269
- };
270
- return runtime.createNativePluginFactory(options);
271
633
  };
272
634
  }
273
- var ACTOR_NEVER_HIT_MS = 60 * 60 * 1e3;
274
- var ACTOR_NEVER_HIT_MESSAGE_BYTES = 512 * 1024 * 1024;
275
- var DEFAULT_AGENTOS_ACTOR_OPTIONS = {
276
- // Connection/setup lifecycle (stock 5s each) — the websocket setup path that
277
- // was timing out at 5000ms and dropping all streamed events.
278
- onBeforeConnectTimeout: ACTOR_NEVER_HIT_MS,
279
- onConnectTimeout: ACTOR_NEVER_HIT_MS,
280
- createVarsTimeout: ACTOR_NEVER_HIT_MS,
281
- createConnStateTimeout: ACTOR_NEVER_HIT_MS,
282
- onMigrateTimeout: ACTOR_NEVER_HIT_MS,
283
- // Action/RPC lifecycle (stock 60s) — long multi-step prompt turns.
284
- actionTimeout: ACTOR_NEVER_HIT_MS,
285
- // Idle/keepalive — don't reap a live session or sleep mid-turn (stock
286
- // connectionLivenessTimeout 2.5s, sleepTimeout 30s). The liveness *interval*
287
- // (ping cadence) is intentionally left at its small default.
288
- connectionLivenessTimeout: ACTOR_NEVER_HIT_MS,
289
- sleepTimeout: ACTOR_NEVER_HIT_MS,
290
- // Payload sizes — large prompts/results. `maxQueueMessageSize` is the
291
- // per-actor message cap (stock 64 KiB); the transport-level
292
- // max{Incoming,Outgoing}MessageSize live on the registry/setup config (see
293
- // AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULTS), not on per-actor options.
294
- maxQueueSize: 1e6,
295
- maxQueueMessageSize: ACTOR_NEVER_HIT_MESSAGE_BYTES
296
- };
297
- var INSPECTOR_TABS_ASSET_DIR = join2(
298
- dirname2(fileURLToPath2(import.meta.url)),
299
- "..",
300
- "assets",
301
- "inspector-tabs-app"
302
- );
303
- var AGENTOS_INSPECTOR_CONFIG = {
304
- tabs: [
305
- { id: "transcript", label: "Transcript", source: INSPECTOR_TABS_ASSET_DIR, icon: "comments" },
306
- { id: "filesystem", label: "Filesystem", source: INSPECTOR_TABS_ASSET_DIR, icon: "folder-tree" },
307
- { id: "processes", label: "Processes", source: INSPECTOR_TABS_ASSET_DIR, icon: "microchip" },
308
- { id: "software", label: "Software", source: INSPECTOR_TABS_ASSET_DIR, icon: "box-archive" },
309
- { id: "mounts", label: "Mounts", source: INSPECTOR_TABS_ASSET_DIR, icon: "hard-drive" },
310
- ...["workflow", "database", "state", "queue", "connections", "console"].map(
311
- (id) => ({ id, hidden: true })
312
- )
313
- ]
314
- };
315
- function createAgentOS(config) {
316
- const parsed = agentOsActorConfigSchema.parse(
317
- config
318
- );
319
- const userActorOptions = parsed.actorOptions;
320
- const actorOptions = {
321
- ...DEFAULT_AGENTOS_ACTOR_OPTIONS,
322
- ...userActorOptions ?? {}
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
323
680
  };
324
- const definition = actor({
325
- actions: {},
326
- options: actorOptions,
327
- // Register the custom agent-os inspector tabs (and hide the built-in
328
- // rivetkit tabs) so the dashboard renders the agent-os UI. Without this
329
- // the shipped tab assets are never surfaced.
330
- inspector: AGENTOS_INSPECTOR_CONFIG
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
730
+ },
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);
739
+ },
740
+ onWake: async (c) => {
741
+ try {
742
+ await userOnWake?.(c);
743
+ } catch (error) {
744
+ await disposeVm(c, "error");
745
+ throw error;
746
+ }
747
+ },
748
+ onSleep: async (c) => {
749
+ try {
750
+ await userOnSleep?.(c);
751
+ } finally {
752
+ await disposeVm(c, "sleep");
753
+ }
754
+ },
755
+ onDestroy: async (c) => {
756
+ try {
757
+ await userOnDestroy?.(c);
758
+ } finally {
759
+ await disposeVm(c, "destroy");
760
+ }
761
+ },
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
+ }
331
812
  });
332
- definition.nativeFactoryBuilder = buildNativeFactoryBuilder(parsed);
333
- return definition;
334
813
  }
335
814
 
336
815
  // src/index.ts
337
- import { setup as rivetkitSetup } from "rivetkit";
338
- import { defineSoftware } from "@rivet-dev/agentos-core";
339
816
  var AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT = 512 * 1024 * 1024;
340
817
  var setup = ((input) => rivetkitSetup({
818
+ ...input,
341
819
  maxIncomingMessageSize: AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT,
342
820
  maxOutgoingMessageSize: AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT,
343
- ...input
821
+ experimentalActorUds: true
344
822
  }));
345
- function agentOS(config = {}) {
346
- const {
347
- preview,
348
- onBeforeConnect,
349
- onSessionEvent,
350
- onPermissionRequest,
351
- ...options
352
- } = config;
353
- return createAgentOS({
354
- options,
355
- preview,
356
- onBeforeConnect,
357
- onSessionEvent: onSessionEvent ? (_ctx, sessionId, event) => onSessionEvent(sessionId, event) : void 0,
358
- onPermissionRequest: onPermissionRequest ? (_ctx, sessionId, request) => onPermissionRequest(sessionId, request) : void 0
359
- });
360
- }
361
823
  export {
362
- agentOS,
363
- agentOsActorConfigSchema,
364
- buildConfigJson,
824
+ createAgentOS as agentOS,
825
+ createAgentOS,
826
+ createAgentOsActions,
365
827
  defineSoftware,
366
- getPluginPath,
367
- nativeAgentOsOptionsSchema,
368
828
  nodeModulesMount,
369
829
  setup
370
830
  };