@rivet-dev/agentos 0.0.0-main.2f99c77 → 0.0.0-main.5ac5a14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/inspector-tabs-app/assets/__vite-browser-external-2447137e-BIHI7g3E.js +1 -0
- package/assets/inspector-tabs-app/assets/agentos-hero-logo-E3fapwXM.svg +74 -0
- package/assets/inspector-tabs-app/assets/filesystem-C-x0K5sy.js +1 -0
- package/assets/inspector-tabs-app/assets/hooks-DU8a-cwM.js +1 -0
- package/assets/inspector-tabs-app/assets/index-7G_DbdZ6.js +110 -0
- package/assets/inspector-tabs-app/assets/index-DG_s1YoH.css +1 -0
- package/assets/inspector-tabs-app/assets/scroll-area-kPbv4IGy.js +1 -0
- package/assets/inspector-tabs-app/assets/sed-BwsOyU9v.svg +1 -0
- package/assets/inspector-tabs-app/assets/system-D98yBhMj.js +2 -0
- package/assets/inspector-tabs-app/assets/terminal-Bv9GKv4q.js +13 -0
- package/assets/inspector-tabs-app/assets/transcript-kMbm_tF8.js +1 -0
- package/assets/inspector-tabs-app/assets/useSuspenseQuery-ChN8rnBd.js +1 -0
- package/assets/inspector-tabs-app/assets/vm-boot-gate-rpuO0b5W.js +1 -0
- package/assets/inspector-tabs-app/assets/vm-status-badges-09qyfN_A.js +5 -0
- package/assets/inspector-tabs-app/index.html +2 -2
- package/dist/chunk-V6TY7KAL.js +8 -0
- package/dist/chunk-V6TY7KAL.js.map +1 -0
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +403 -712
- package/dist/index.js +1835 -310
- package/dist/index.js.map +1 -1
- package/dist/node.d.ts +67 -0
- package/dist/node.js +275 -0
- package/dist/node.js.map +1 -0
- package/package.json +26 -15
- package/assets/inspector-tabs-app/assets/badge-Coq9s9H6.js +0 -1
- package/assets/inspector-tabs-app/assets/filesystem-_yeTmDH7.js +0 -1
- package/assets/inspector-tabs-app/assets/index-C50G2vhD.js +0 -125
- package/assets/inspector-tabs-app/assets/index-Dt5XhJ9h.css +0 -1
- package/assets/inspector-tabs-app/assets/mounts-C0eJmxpt.js +0 -1
- package/assets/inspector-tabs-app/assets/processes-CvN1MFLy.js +0 -1
- package/assets/inspector-tabs-app/assets/scroll-area-DzL-iGyn.js +0 -1
- package/assets/inspector-tabs-app/assets/software-BjGEcqMs.js +0 -1
- package/assets/inspector-tabs-app/assets/transcript-BKLxbOF5.js +0 -1
- package/assets/inspector-tabs-app/assets/useQuery-RSkOi56s.js +0 -1
- package/assets/inspector-tabs-app/assets/useSuspenseQuery-CpwiXRj_.js +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/actor.ts","../src/config.ts","../src/plugin-binary.ts"],"sourcesContent":["// Rust-backed agent-os actor surface (native actor plugin / cdylib).\n//\n// Only the `agentOS()` definition function, the config schema, the\n// `nodeModulesMount` helper, the plugin-path resolver, and the public domain\n// types are exported. All actor lifecycle + action dispatch live in the Rust\n// plugin (`crates/agentos-actor-plugin`), loaded by RivetKit via the generic\n// native-plugin ABI.\n\nimport type {\n\tAgentOsOptions,\n\tJsonRpcNotification,\n\tPermissionRequest,\n} from \"@rivet-dev/agentos-core\";\nimport { setup as rivetkitSetup } from \"rivetkit\";\nimport { type AgentOsActorDefinition, createAgentOS } from \"./actor.js\";\nimport type {\n\tAgentOsActorConfigInput,\n\tNativeAgentOsOptions,\n} from \"./config.js\";\n\n// 512 MiB — large agent prompts/results cross the actor websocket transport as\n// single messages; RivetKit's registry-level defaults (maxIncomingMessageSize\n// 64 KiB, maxOutgoingMessageSize 1 MiB) truncate real payloads. Still a finite\n// bound per the limits-and-observability policy.\nconst AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT = 512 * 1024 * 1024;\n\n/**\n * `setup()` wrapper that defaults the registry transport message-size caps to\n * never-hit-by-normal-use values for AgentOS apps, mirroring the per-actor crank\n * in `DEFAULT_AGENTOS_ACTOR_OPTIONS`. Any caller-supplied value wins, so an app\n * can still tighten the bound when it wants one.\n */\nexport const setup: typeof rivetkitSetup = ((\n\tinput: Parameters<typeof rivetkitSetup>[0],\n) =>\n\trivetkitSetup({\n\t\tmaxIncomingMessageSize: AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT,\n\t\tmaxOutgoingMessageSize: AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT,\n\t\t...input,\n\t})) as typeof rivetkitSetup;\n\n// Re-export the software-definition helper so custom agents/tools/commands can\n// be defined without importing @rivet-dev/agentos-core directly.\nexport { defineSoftware } from \"@rivet-dev/agentos-core\";\nexport {\n\tbuildConfigJson,\n\ttype NodeModulesMountConfig,\n\tnodeModulesMount,\n} from \"./actor.js\";\nexport {\n\ttype AgentOsActorConfig,\n\ttype AgentOsActorConfigInput,\n\tagentOsActorConfigSchema,\n\ttype NativeAgentOsOptions,\n\tnativeAgentOsOptionsSchema,\n} from \"./config.js\";\nexport type {\n\tAgentOsActions,\n\tCreateSessionOptions,\n\tDirEntry,\n\tReadFileResult,\n\tScheduledCronJob,\n\tSignedPreviewUrl,\n\tSpawnedProcess,\n\tVmFetchOptions,\n\tVmFetchResponse,\n\tWriteFileResult,\n} from \"./generated/actor-actions.generated.js\";\nexport { getPluginPath } from \"./plugin-binary.js\";\nexport type {\n\tAgentCrashedPayload,\n\tAgentOsActionContext,\n\tAgentOsActorState,\n\tAgentOsActorVars,\n\tAgentOsEvents,\n\tCronEventPayload,\n\tPermissionRequestPayload,\n\tPersistedSessionEvent,\n\tPersistedSessionRecord,\n\tProcessExitPayload,\n\tProcessOutputPayload,\n\tPromptResult,\n\tSerializableCronAction,\n\tSerializableCronEvent,\n\tSerializableCronJobInfo,\n\tSerializableCronJobOptions,\n\tSessionEventPayload,\n\tSessionRecord,\n\tShellDataPayload,\n\tVmBootedPayload,\n\tVmShutdownPayload,\n} from \"./types.js\";\n\nexport type AgentOSActorConfigInput<TConnParams = undefined> =\n\tNativeAgentOsOptions & Omit<AgentOsActorConfigInput<TConnParams>, \"options\">;\n\nexport type AgentOSConfigInput<TConnParams = undefined> = AgentOsOptions & {\n\tpreview?: AgentOsActorConfigInput<TConnParams>[\"preview\"];\n\tactorOptions?: AgentOsActorConfigInput<TConnParams>[\"actorOptions\"];\n\tonBeforeConnect?: AgentOsActorConfigInput<TConnParams>[\"onBeforeConnect\"];\n\tonSessionEvent?: (\n\t\tsessionId: string,\n\t\tevent: JsonRpcNotification,\n\t) => void | Promise<void>;\n\tonPermissionRequest?: (\n\t\tsessionId: string,\n\t\trequest: PermissionRequest,\n\t) => void | Promise<void>;\n};\n\nexport function agentOS<TConnParams = undefined>(\n\tconfig: AgentOSConfigInput<TConnParams> = {},\n): AgentOsActorDefinition<TConnParams> {\n\tconst {\n\t\tpreview,\n\t\tactorOptions,\n\t\tonBeforeConnect,\n\t\tonSessionEvent,\n\t\tonPermissionRequest,\n\t\t...options\n\t} = config;\n\n\treturn createAgentOS({\n\t\toptions,\n\t\tactorOptions,\n\t\tpreview,\n\t\tonBeforeConnect,\n\t\tonSessionEvent: onSessionEvent\n\t\t\t? (_ctx, sessionId, event) => onSessionEvent(sessionId, event)\n\t\t\t: undefined,\n\t\tonPermissionRequest: onPermissionRequest\n\t\t\t? (_ctx, sessionId, request) => onPermissionRequest(sessionId, request)\n\t\t\t: undefined,\n\t} as AgentOsActorConfigInput<TConnParams>);\n}\n","/**\n * Rust-backed `agentOS(...)` definition.\n *\n * Produces an `ActorDefinition` whose `nativeFactoryBuilder` constructs a\n * native-actor-plugin factory through `runtime.createNativePluginFactory(...)`\n * (NAPI → `dlopen` of the agent-os actor plugin cdylib, the inverse of the\n * generic host loader). All lifecycle, state, and action dispatch live in the\n * Rust plugin (`crates/agentos-actor-plugin`). This JS shim only validates\n * configuration, resolves the plugin + sidecar binaries, and hands the opaque\n * config envelope across the bridge — it owns no agent-os runtime logic.\n */\n\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport common from \"@agentos-software/common\";\nimport { OPT_AGENTOS_ROOT } from \"@rivet-dev/agentos-core\";\nimport { getSidecarPath } from \"@rivet-dev/agentos-sidecar\";\nimport {\n\ttype ActorDefinition,\n\ttype ActorFactoryHandle,\n\tactor,\n\ttype CoreRuntime,\n\ttype DatabaseProvider,\n\ttype NapiNativePluginOptions,\n\ttype RawAccess,\n} from \"rivetkit\";\nimport {\n\ttype AgentOsActorConfig,\n\ttype AgentOsActorConfigInput,\n\tagentOsActorConfigSchema,\n\tnativeAgentOsOptionsSchema,\n} from \"./config.js\";\nimport type { AgentOsActions } from \"./generated/actor-actions.generated.js\";\nimport { getPluginPath } from \"./plugin-binary.js\";\nimport type { AgentOsActorState, AgentOsActorVars } from \"./types.js\";\n\n/**\n * Build the JSON envelope the Rust plugin consumes. The Rust deserializer\n * uses `deny_unknown_fields`, so the envelope must stay in lock-step with\n * `crates/agentos-actor-plugin/src/config.rs::AgentOsConfigJson`.\n *\n * Software threading: each software ref is flattened (meta packages such as\n * `common` are arrays of refs), normalized to a package dir, and forwarded as\n * `{ dir }` so the sidecar owns the `/opt/agentos` projection. Agent configs\n * are derived from each package's `agentos-package.json`, mirroring\n * `packages/core/src/agent-os.ts`.\n */\ninterface NativeMountLike {\n\tpath: string;\n\tplugin: {\n\t\tid: string;\n\t\tconfig?: unknown;\n\t};\n\treadOnly?: boolean;\n}\n\ninterface NormalizedPackageRef {\n\tpath: string;\n}\n\n/**\n * A native `host_dir` mount of a host `node_modules` directory at\n * `/root/node_modules`, the serializable form `agentOS({ options: { mounts } })`\n * accepts across the NAPI boundary.\n */\nexport interface NodeModulesMountConfig {\n\tpath: \"/root/node_modules\";\n\tplugin: { id: \"host_dir\"; config: { hostPath: string; readOnly: boolean } };\n\treadOnly: boolean;\n}\n\n/**\n * Mount a host `node_modules` directory into the VM at `/root/node_modules`.\n *\n * This is the explicit, mount-based replacement for the removed `moduleAccessCwd`\n * mechanism: the VM module resolver reads the mounted tree through the kernel\n * VFS, so the caller supplies exactly the `node_modules` directory whose\n * packages should resolve in the guest.\n *\n * @param hostNodeModulesDir Absolute host path to a `node_modules` directory.\n * @param opts.readOnly Defaults to `true`; the mount is read-only.\n */\nexport function nodeModulesMount(\n\thostNodeModulesDir: string,\n\topts?: { readOnly?: boolean },\n): NodeModulesMountConfig {\n\tconst readOnly = opts?.readOnly ?? true;\n\treturn {\n\t\tpath: \"/root/node_modules\",\n\t\tplugin: {\n\t\t\tid: \"host_dir\",\n\t\t\tconfig: { hostPath: hostNodeModulesDir, readOnly },\n\t\t},\n\t\treadOnly,\n\t};\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n\treturn value && typeof value === \"object\" && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: {};\n}\n\nfunction normalizePackageRef(value: unknown): NormalizedPackageRef | undefined {\n\t// Single package reference: `packagePath` (packed `.aospkg` file, or a\n\t// transition package dir); a raw string is shorthand for the same path.\n\tif (typeof value === \"string\") {\n\t\treturn { path: value };\n\t}\n\tconst record = toRecord(value);\n\tif (typeof record.packagePath === \"string\") {\n\t\treturn { path: record.packagePath };\n\t}\n\t// Recognizably-legacy shapes fail loudly instead of silently dropping the\n\t// package from the VM.\n\tfor (const legacy of [\"packageTar\", \"packageDir\", \"commandDir\", \"dir\"]) {\n\t\tif (typeof record[legacy] === \"string\") {\n\t\t\tthrow new Error(\n\t\t\t\t`agentOS package ref uses removed field \"${legacy}\"; packages are referenced ` +\n\t\t\t\t\t\"by a single `packagePath` — rebuild @agentos-software/* dependencies or pass { packagePath }\",\n\t\t\t);\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction normalizedPackageRefs(software: unknown[]): NormalizedPackageRef[] {\n\tconst refs: NormalizedPackageRef[] = [];\n\tconst seen = new Set<string>();\n\tfor (const entry of software.flat()) {\n\t\tconst ref = normalizePackageRef(entry);\n\t\tif (!ref || seen.has(ref.path)) continue;\n\t\tseen.add(ref.path);\n\t\trefs.push(ref);\n\t}\n\treturn refs;\n}\n\nexport function buildConfigJson<TConnParams>(\n\tparsed: AgentOsActorConfig<TConnParams>,\n): string {\n\tconst options = nativeAgentOsOptionsSchema.parse(\n\t\tparsed.options ?? {},\n\t) as Record<string, unknown>;\n\tconst softwareInput = Array.isArray(options.software) ? options.software : [];\n\tconst defaultSoftwareEnabled = options.defaultSoftware !== false;\n\tconst packageRefs = normalizedPackageRefs(\n\t\tdefaultSoftwareEnabled ? [common, ...softwareInput] : softwareInput,\n\t);\n\tconst packages = packageRefs.map((ref) => ({ packagePath: ref.path }));\n\tconst mounts = serializeNativeMounts(options.mounts);\n\tconst sidecar = serializeSidecar(options.sidecar);\n\treturn JSON.stringify({\n\t\t// The actor forwards ONLY package dirs; the sidecar resolves each agent from\n\t\t// the projected `/opt/agentos/<name>/current/agentos-package.json` (no\n\t\t// client-side adapter-entrypoint resolution — see root CLAUDE.md).\n\t\tpackages,\n\t\tpackagesMountAt: OPT_AGENTOS_ROOT,\n\t\tadditionalInstructions: options.additionalInstructions,\n\t\tloopbackExemptPorts: options.loopbackExemptPorts,\n\t\tallowedNodeBuiltins: options.allowedNodeBuiltins,\n\t\tpermissions: options.permissions,\n\t\trootFilesystem: options.rootFilesystem,\n\t\tmounts,\n\t\tlimits: options.limits,\n\t\tsidecar,\n\t});\n}\n\nfunction serializeNativeMounts(input: unknown): NativeMountLike[] | undefined {\n\tif (input == null) return undefined;\n\tif (!Array.isArray(input)) {\n\t\tthrow new Error(\"agentOS() options.mounts must be an array\");\n\t}\n\treturn input.map((mount, index) => {\n\t\tif (!mount || typeof mount !== \"object\") {\n\t\t\tthrow new Error(`agentOS() options.mounts[${index}] must be an object`);\n\t\t}\n\t\tconst record = mount as Record<string, unknown>;\n\t\tif (record.driver !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t\"agentOS() only supports Native mounts across the NAPI boundary; Plain mounts with driver callbacks are not serializable\",\n\t\t\t);\n\t\t}\n\t\tif (record.filesystem !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t\"agentOS() only supports Native mounts across the NAPI boundary; Overlay mounts are not serializable\",\n\t\t\t);\n\t\t}\n\t\tconst plugin = record.plugin;\n\t\tif (\n\t\t\ttypeof record.path !== \"string\" ||\n\t\t\t!plugin ||\n\t\t\ttypeof plugin !== \"object\" ||\n\t\t\ttypeof (plugin as Record<string, unknown>).id !== \"string\"\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`agentOS() options.mounts[${index}] must be a Native mount with { path, plugin: { id, config? } }`,\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tpath: record.path,\n\t\t\tplugin: {\n\t\t\t\tid: (plugin as Record<string, unknown>).id as string,\n\t\t\t\tconfig: (plugin as Record<string, unknown>).config,\n\t\t\t},\n\t\t\treadOnly:\n\t\t\t\ttypeof record.readOnly === \"boolean\" ? record.readOnly : undefined,\n\t\t};\n\t});\n}\n\nfunction serializeSidecar(input: unknown): { pool?: string } | undefined {\n\tif (input == null) return undefined;\n\tif (!input || typeof input !== \"object\") {\n\t\tthrow new Error(\"agentOS() options.sidecar must be an object\");\n\t}\n\tconst record = input as Record<string, unknown>;\n\tif (record.kind === \"explicit\" || record.handle !== undefined) {\n\t\tthrow new Error(\n\t\t\t\"agentOS() only supports sidecar shared pool configuration across the NAPI boundary; explicit sidecar handles are not serializable\",\n\t\t);\n\t}\n\tif (record.kind !== undefined && record.kind !== \"shared\") {\n\t\tthrow new Error('agentOS() options.sidecar.kind must be \"shared\"');\n\t}\n\treturn typeof record.pool === \"string\" ? { pool: record.pool } : {};\n}\n\nfunction buildNativeFactoryBuilder<TConnParams>(\n\tparsed: AgentOsActorConfig<TConnParams>,\n\tactorOptions: Record<string, unknown>,\n): (runtime: CoreRuntime) => ActorFactoryHandle {\n\treturn (runtime) => {\n\t\tif (runtime.kind !== \"napi\") {\n\t\t\tthrow new Error(\n\t\t\t\t`agentOS() is only supported on the native NAPI runtime (current runtime kind: ${runtime.kind})`,\n\t\t\t);\n\t\t}\n\t\tif (!runtime.createNativePluginFactory) {\n\t\t\tthrow new Error(\n\t\t\t\t\"runtime.createNativePluginFactory is not implemented on the active CoreRuntime\",\n\t\t\t);\n\t\t}\n\t\tconst options: NapiNativePluginOptions = {\n\t\t\t// Resolve the prebuilt agent-os actor plugin cdylib; RivetKit `dlopen`s\n\t\t\t// it through the generic native-plugin ABI.\n\t\t\tpluginPath: getPluginPath(),\n\t\t\t// Opaque config envelope the plugin parses (config.rs::AgentOsConfigJson).\n\t\t\tconfigJson: buildConfigJson(parsed),\n\t\t\t// RivetKit's native-plugin bridge owns the runtime ActorConfig for\n\t\t\t// cdylib actors, so forward the merged per-actor lifecycle options too.\n\t\t\tactorOptions,\n\t\t\t// Resolve the prebuilt sidecar binary from the npm package so the plugin\n\t\t\t// spawns the bundled binary rather than relying on `agentos-sidecar`\n\t\t\t// being on PATH.\n\t\t\tsidecarPath: getSidecarPath(),\n\t\t\t// Custom inspector tabs. The native-plugin path bypasses the normal\n\t\t\t// actor-config assembly (`buildActorConfig`/`inspectorTabs`), so the\n\t\t\t// tabs MUST ride on the plugin options: the Rust NAPI binding\n\t\t\t// `from_native_plugin` forwards `inspectorTabs` into the actor config so\n\t\t\t// the dashboard serves `/inspector/custom-tabs/<id>/` and advertises them\n\t\t\t// in `tab-config`. (Setting `actor({ inspector })` alone does nothing for\n\t\t\t// native-plugin actors.)\n\t\t\tinspectorTabs: AGENTOS_INSPECTOR_CONFIG.tabs,\n\t\t} as NapiNativePluginOptions & {\n\t\t\tactorOptions?: Record<string, unknown>;\n\t\t\tinspectorTabs: typeof AGENTOS_INSPECTOR_CONFIG.tabs;\n\t\t};\n\t\treturn runtime.createNativePluginFactory(options);\n\t};\n}\n\n/**\n * Type alias for the `agentOS(...)` return type. Events are not typed at the TS\n * surface because the Rust plugin owns the broadcast set, but the ACTIONS are\n * typed via {@link AgentOsActions} — generated from the Rust dispatch contract\n * table in `crates/agentos-actor-plugin/src/actions/contract_surface.rs`.\n * That is what gives `createClient<typeof registry>()` a fully-typed handle\n * (e.g. `handle.exec()` returns `ExecResult`, not `unknown`).\n */\nexport type AgentOsActorDefinition<TConnParams> = ActorDefinition<\n\tAgentOsActorState,\n\tTConnParams,\n\tundefined,\n\tAgentOsActorVars,\n\tundefined,\n\tDatabaseProvider<RawAccess>,\n\tRecord<never, never>,\n\tRecord<never, never>,\n\tAgentOsActions\n>;\n\n// One hour — far past any normal agent turn, connection setup, or idle gap, but\n// still a finite bound (never `0`/Infinity) per the limits-and-observability\n// policy. Agent turns routinely run minutes; the stock RivetKit defaults\n// (actionTimeout 60s, on{Before,}ConnectTimeout 5s, sleepTimeout 30s) cut them\n// off mid-flight and broke live `sessionEvent` streaming with\n// \"actor websocket connection setup timed out after 5000 ms\".\nconst ACTOR_NEVER_HIT_MS = 60 * 60 * 1000;\n// 512 MiB — large prompts/results stream as single actor messages; the stock\n// 64 KiB incoming / 1 MiB outgoing caps truncate real agent payloads.\nconst ACTOR_NEVER_HIT_MESSAGE_BYTES = 512 * 1024 * 1024;\n\n/**\n * Never-hit-by-normal-use defaults for the AgentOS actor. Every value is a high\n * but finite bound so a long multi-step agent turn, a slow connection setup, a\n * large prompt/result, and live `sessionEvent` streaming all complete without\n * tripping a RivetKit actor default. Callers can still override any single knob\n * via `actorOptions` (their value wins over these defaults).\n */\nexport const DEFAULT_AGENTOS_ACTOR_OPTIONS = {\n\t// Connection/setup lifecycle (stock 5s each) — the websocket setup path that\n\t// was timing out at 5000ms and dropping all streamed events.\n\tonBeforeConnectTimeout: ACTOR_NEVER_HIT_MS,\n\tonConnectTimeout: ACTOR_NEVER_HIT_MS,\n\tcreateVarsTimeout: ACTOR_NEVER_HIT_MS,\n\tcreateConnStateTimeout: ACTOR_NEVER_HIT_MS,\n\tonMigrateTimeout: ACTOR_NEVER_HIT_MS,\n\t// Action/RPC lifecycle (stock 60s) — long multi-step prompt turns.\n\tactionTimeout: ACTOR_NEVER_HIT_MS,\n\t// Idle/keepalive — don't reap a live session or sleep mid-turn (stock\n\t// connectionLivenessTimeout 2.5s, sleepTimeout 30s). The liveness *interval*\n\t// (ping cadence) is intentionally left at its small default.\n\tconnectionLivenessTimeout: ACTOR_NEVER_HIT_MS,\n\tsleepTimeout: ACTOR_NEVER_HIT_MS,\n\t// Payload sizes — large prompts/results. `maxQueueMessageSize` is the\n\t// per-actor message cap (stock 64 KiB); the transport-level\n\t// max{Incoming,Outgoing}MessageSize live on the registry/setup config (see\n\t// AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULTS), not on per-actor options.\n\tmaxQueueSize: 1_000_000,\n\tmaxQueueMessageSize: ACTOR_NEVER_HIT_MESSAGE_BYTES,\n} as const;\n\n// Absolute path to the built inspector-tabs app (the shared Vite bundle). All\n// custom tabs share this one `source` dir; the app routes on the\n// `/inspector/custom-tabs/<id>/` URL segment. Resolves from both `src/` (tsx dev\n// / the demo) and the published `dist/`, since `assets/` sits at the package\n// root in both layouts.\nconst INSPECTOR_TABS_ASSET_DIR = join(\n\tdirname(fileURLToPath(import.meta.url)),\n\t\"..\",\n\t\"assets\",\n\t\"inspector-tabs-app\",\n);\n\n// Custom inspector tabs shipped by agent-os. Ids MUST match the `TABS` registry\n// in `src/inspector-tabs/main.tsx`. The built-in rivetkit tabs are hidden so the\n// dashboard shows only the agent-os tabs.\nconst AGENTOS_INSPECTOR_CONFIG = {\n\ttabs: [\n\t\t{\n\t\t\tid: \"transcript\",\n\t\t\tlabel: \"Transcript\",\n\t\t\tsource: INSPECTOR_TABS_ASSET_DIR,\n\t\t\ticon: \"comments\",\n\t\t},\n\t\t{\n\t\t\tid: \"filesystem\",\n\t\t\tlabel: \"Filesystem\",\n\t\t\tsource: INSPECTOR_TABS_ASSET_DIR,\n\t\t\ticon: \"folder-tree\",\n\t\t},\n\t\t{\n\t\t\tid: \"processes\",\n\t\t\tlabel: \"Processes\",\n\t\t\tsource: INSPECTOR_TABS_ASSET_DIR,\n\t\t\ticon: \"microchip\",\n\t\t},\n\t\t{\n\t\t\tid: \"software\",\n\t\t\tlabel: \"Software\",\n\t\t\tsource: INSPECTOR_TABS_ASSET_DIR,\n\t\t\ticon: \"box-archive\",\n\t\t},\n\t\t{\n\t\t\tid: \"mounts\",\n\t\t\tlabel: \"Mounts\",\n\t\t\tsource: INSPECTOR_TABS_ASSET_DIR,\n\t\t\ticon: \"hard-drive\",\n\t\t},\n\t\t...[\"workflow\", \"database\", \"state\", \"queue\", \"connections\", \"console\"].map(\n\t\t\t(id) => ({ id, hidden: true as const }),\n\t\t),\n\t],\n};\n\nexport function createAgentOS<TConnParams = undefined>(\n\tconfig: AgentOsActorConfigInput<TConnParams>,\n): AgentOsActorDefinition<TConnParams> {\n\tconst parsed = agentOsActorConfigSchema.parse(\n\t\tconfig,\n\t) as AgentOsActorConfig<TConnParams>;\n\n\t// Construct a minimal definition through the existing actor() helper, then\n\t// attach the Rust factory builder marker. The actions block stays empty\n\t// because no JS-side action ever runs: the engine driver branches on\n\t// `nativeFactoryBuilder` before reaching the JS dispatch path.\n\tconst userActorOptions = (\n\t\tparsed as { actorOptions?: Record<string, unknown> }\n\t).actorOptions;\n\t// High never-hit defaults, with any caller-supplied option winning.\n\tconst actorOptions = {\n\t\t...DEFAULT_AGENTOS_ACTOR_OPTIONS,\n\t\t...(userActorOptions ?? {}),\n\t};\n\tconst definition = actor({\n\t\tactions: {},\n\t\toptions: actorOptions,\n\t\t// Register the custom agent-os inspector tabs (and hide the built-in\n\t\t// rivetkit tabs) so the dashboard renders the agent-os UI. Without this\n\t\t// the shipped tab assets are never surfaced.\n\t\tinspector: AGENTOS_INSPECTOR_CONFIG,\n\t} as Parameters<\n\t\ttypeof actor\n\t>[0]) as unknown as AgentOsActorDefinition<TConnParams>;\n\tdefinition.nativeFactoryBuilder = buildNativeFactoryBuilder(\n\t\tparsed,\n\t\tactorOptions,\n\t);\n\treturn definition;\n}\n","import type {\n\tAgentOsOptions,\n\tJsonRpcNotification,\n\tNativeMountConfig,\n\tPermissionRequest,\n} from \"@rivet-dev/agentos-core\";\nimport {\n\tagentOsOptionFieldSchemas,\n\tnativeMountConfigSchema,\n\tsharedSidecarConfigSchema,\n} from \"@rivet-dev/agentos-core\";\nimport type { ActorContext, BeforeConnectContext } from \"rivetkit\";\nimport { z } from \"zod/v4\";\nimport type { AgentOsActorState, AgentOsActorVars } from \"./types.js\";\n\nconst zFunction = <\n\tT extends (...args: any[]) => any = (...args: unknown[]) => unknown,\n>() => z.custom<T>((val) => typeof val === \"function\");\n\nexport const nativeAgentOsOptionsSchema = z\n\t// Native actor options are a JSON-serializable subset of AgentOsOptions.\n\t// Keep this allow-list in sync with buildConfigJson() and\n\t// crates/agentos-actor-plugin/src/config.rs::AgentOsConfigJson.\n\t.object({\n\t\tsoftware: agentOsOptionFieldSchemas.software,\n\t\tdefaultSoftware: agentOsOptionFieldSchemas.defaultSoftware,\n\t\tloopbackExemptPorts: agentOsOptionFieldSchemas.loopbackExemptPorts,\n\t\tallowedNodeBuiltins: agentOsOptionFieldSchemas.allowedNodeBuiltins,\n\t\trootFilesystem: agentOsOptionFieldSchemas.rootFilesystem,\n\t\tmounts: z.array(nativeMountConfigSchema).optional(),\n\t\tadditionalInstructions: agentOsOptionFieldSchemas.additionalInstructions,\n\t\tpermissions: agentOsOptionFieldSchemas.permissions,\n\t\tsidecar: sharedSidecarConfigSchema.optional(),\n\t\tlimits: agentOsOptionFieldSchemas.limits,\n\t})\n\t.strict();\n\n/**\n * RivetKit actor lifecycle/transport options forwarded to `actor({ options })`.\n *\n * Validated downstream by RivetKit's own actor config schema, so this stays a\n * permissive pass-through allow-list. `agentOS()` overlays the never-hit\n * defaults in `DEFAULT_AGENTOS_ACTOR_OPTIONS` (see actor.ts) and lets any value\n * here win, so callers can still tighten a bound when they want one.\n */\nexport const agentOsActorOptionsSchema = z\n\t.record(z.string(), z.unknown())\n\t.optional();\n\nexport const agentOsActorConfigSchema = z\n\t.object({\n\t\toptions: nativeAgentOsOptionsSchema.optional(),\n\t\tactorOptions: agentOsActorOptionsSchema,\n\t\tpreview: z\n\t\t\t.object({\n\t\t\t\tdefaultExpiresInSeconds: z.number().positive().default(3600),\n\t\t\t\tmaxExpiresInSeconds: z.number().positive().default(86400),\n\t\t\t})\n\t\t\t.strict()\n\t\t\t.prefault(() => ({})),\n\t\tonBeforeConnect: zFunction().optional(),\n\t\tonSessionEvent: zFunction().optional(),\n\t\tonPermissionRequest: zFunction().optional(),\n\t})\n\t.strict();\n\n// --- Typed config types (generic callbacks overlaid on the Zod schema) ---\n\n/**\n * Type mirror of `nativeAgentOsOptionsSchema`.\n *\n * Keep this in sync with the schema above and the Rust serde mirror at\n * `crates/agentos-actor-plugin/src/config.rs::AgentOsConfigJson`.\n */\nexport type NativeAgentOsOptions = Pick<\n\tAgentOsOptions,\n\t| \"software\"\n\t| \"defaultSoftware\"\n\t| \"loopbackExemptPorts\"\n\t| \"allowedNodeBuiltins\"\n\t| \"rootFilesystem\"\n\t| \"additionalInstructions\"\n\t| \"permissions\"\n\t| \"limits\"\n> & {\n\tmounts?: NativeMountConfig[];\n\tsidecar?: { kind: \"shared\"; pool?: string };\n};\n\ntype AgentOsActorContext<TConnParams> = ActorContext<\n\tAgentOsActorState,\n\tTConnParams,\n\tundefined,\n\tAgentOsActorVars,\n\tundefined,\n\tany\n>;\n\ninterface AgentOsActorConfigCallbacks<TConnParams> {\n\tonBeforeConnect?: (\n\t\tc: BeforeConnectContext<\n\t\t\tAgentOsActorState,\n\t\t\tAgentOsActorVars,\n\t\t\tundefined,\n\t\t\tany\n\t\t>,\n\t\tparams: TConnParams,\n\t) => void | Promise<void>;\n\tonSessionEvent?: (\n\t\tc: AgentOsActorContext<TConnParams>,\n\t\tsessionId: string,\n\t\tevent: JsonRpcNotification,\n\t) => void | Promise<void>;\n\tonPermissionRequest?: (\n\t\tc: AgentOsActorContext<TConnParams>,\n\t\tsessionId: string,\n\t\trequest: PermissionRequest,\n\t) => void | Promise<void>;\n}\n\n// Parsed config (after Zod defaults/transforms applied).\nexport type AgentOsActorConfig<TConnParams = undefined> = Omit<\n\tz.infer<typeof agentOsActorConfigSchema>,\n\t\"options\" | \"onBeforeConnect\" | \"onSessionEvent\" | \"onPermissionRequest\"\n> &\n\t{ options?: NativeAgentOsOptions } &\n\tAgentOsActorConfigCallbacks<TConnParams>;\n\n// Input config (what users pass in before Zod transforms).\nexport type AgentOsActorConfigInput<TConnParams = undefined> = Omit<\n\tz.input<typeof agentOsActorConfigSchema>,\n\t\"options\" | \"onBeforeConnect\" | \"onSessionEvent\" | \"onPermissionRequest\"\n> &\n\t{ options?: NativeAgentOsOptions } &\n\tAgentOsActorConfigCallbacks<TConnParams>;\n","// Platform-specific resolver for the prebuilt agent-os actor plugin cdylib\n// (`libagentos_actor_plugin.{so,dylib,dll}`). Mirrors the sidecar-binary\n// resolver (`@rivet-dev/agentos-sidecar`): the library ships inside one of the\n// `@rivet-dev/agentos-plugin-<platform>` packages, declared as\n// optionalDependencies so npm installs only the one matching the current\n// `os`/`cpu`/`libc` at install time (spec phase 6).\n//\n// Resolution priority:\n// 1. `AGENTOS_PLUGIN_BIN` env var (absolute path override).\n// 2. A cargo build output under the repo `target/{release,debug}/` (dev).\n// 3. The platform-specific `@rivet-dev/agentos-plugin-<platform>` package.\n\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst PLUGIN_BIN_ENV = \"AGENTOS_PLUGIN_BIN\";\n\n/** The cdylib filename for the current platform. */\nfunction libraryName(): string {\n\tswitch (process.platform) {\n\t\tcase \"darwin\":\n\t\t\treturn \"libagentos_actor_plugin.dylib\";\n\t\tcase \"win32\":\n\t\t\treturn \"agentos_actor_plugin.dll\";\n\t\tdefault:\n\t\t\treturn \"libagentos_actor_plugin.so\";\n\t}\n}\n\nfunction getPlatformPackageName(): string | null {\n\tconst { platform, arch } = process;\n\tswitch (platform) {\n\t\tcase \"linux\":\n\t\t\tif (arch === \"x64\") return \"@rivet-dev/agentos-plugin-linux-x64-gnu\";\n\t\t\tif (arch === \"arm64\") return \"@rivet-dev/agentos-plugin-linux-arm64-gnu\";\n\t\t\tbreak;\n\t\tcase \"darwin\":\n\t\t\tif (arch === \"x64\") return \"@rivet-dev/agentos-plugin-darwin-x64\";\n\t\t\tif (arch === \"arm64\") return \"@rivet-dev/agentos-plugin-darwin-arm64\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\treturn null;\n}\n\n/**\n * Resolve the absolute path to the agent-os actor plugin cdylib. RivetKit\n * `dlopen`s this path through the generic native-plugin ABI.\n */\nexport function getPluginPath(): string {\n\tconst override = process.env[PLUGIN_BIN_ENV];\n\tif (override) {\n\t\tif (!existsSync(override)) {\n\t\t\tthrow new Error(\n\t\t\t\t`${PLUGIN_BIN_ENV} is set to ${override} but the file does not exist`,\n\t\t\t);\n\t\t}\n\t\treturn override;\n\t}\n\n\tconst lib = libraryName();\n\n\t// Dev: a cargo build output under the repo `target/`. `import.meta.url` is\n\t// `packages/agentos/dist/plugin-binary.js`, so the repo root is three levels up.\n\tconst here = dirname(fileURLToPath(import.meta.url));\n\tfor (const profile of [\"release\", \"debug\"]) {\n\t\tconst candidate = join(here, \"..\", \"..\", \"..\", \"target\", profile, lib);\n\t\tif (existsSync(candidate)) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\t// Prod: the platform-specific package.\n\tconst platformPkg = getPlatformPackageName();\n\tif (!platformPkg) {\n\t\tthrow new Error(\n\t\t\t`@rivet-dev/agentos: unsupported platform ${process.platform}/${process.arch}. ` +\n\t\t\t\t\"The Agent OS actor plugin currently supports linux and darwin on x64 and arm64. \" +\n\t\t\t\t`Set ${PLUGIN_BIN_ENV} to a local cdylib to override.`,\n\t\t);\n\t}\n\n\tconst require = createRequire(import.meta.url);\n\tlet pkgJsonPath: string;\n\ttry {\n\t\tpkgJsonPath = require.resolve(`${platformPkg}/package.json`);\n\t} catch {\n\t\tthrow new Error(\n\t\t\t`@rivet-dev/agentos: platform package ${platformPkg} is not installed.\\n` +\n\t\t\t\t\"This usually means the platform is unsupported or optionalDependencies\\n\" +\n\t\t\t\t`were skipped during install. Try: npm install --include=optional ${platformPkg}\\n` +\n\t\t\t\t`Or set ${PLUGIN_BIN_ENV} to a local cdylib, or build it with\\n` +\n\t\t\t\t\"`cargo build -p agentos-actor-plugin`.\",\n\t\t);\n\t}\n\n\treturn join(dirname(pkgJsonPath), lib);\n}\n"],"mappings":";AAaA,SAAS,SAAS,qBAAqB;;;ACDvC,SAAS,WAAAA,UAAS,QAAAC,aAAY;AAC9B,SAAS,iBAAAC,sBAAqB;AAC9B,OAAO,YAAY;AACnB,SAAS,wBAAwB;AACjC,SAAS,sBAAsB;AAC/B;AAAA,EAGC;AAAA,OAKM;;;ACnBP;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAEP,SAAS,SAAS;AAGlB,IAAM,YAAY,MAEX,EAAE,OAAU,CAAC,QAAQ,OAAO,QAAQ,UAAU;AAE9C,IAAM,6BAA6B,EAIxC,OAAO;AAAA,EACP,UAAU,0BAA0B;AAAA,EACpC,iBAAiB,0BAA0B;AAAA,EAC3C,qBAAqB,0BAA0B;AAAA,EAC/C,qBAAqB,0BAA0B;AAAA,EAC/C,gBAAgB,0BAA0B;AAAA,EAC1C,QAAQ,EAAE,MAAM,uBAAuB,EAAE,SAAS;AAAA,EAClD,wBAAwB,0BAA0B;AAAA,EAClD,aAAa,0BAA0B;AAAA,EACvC,SAAS,0BAA0B,SAAS;AAAA,EAC5C,QAAQ,0BAA0B;AACnC,CAAC,EACA,OAAO;AAUF,IAAM,4BAA4B,EACvC,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAC9B,SAAS;AAEJ,IAAM,2BAA2B,EACtC,OAAO;AAAA,EACP,SAAS,2BAA2B,SAAS;AAAA,EAC7C,cAAc;AAAA,EACd,SAAS,EACP,OAAO;AAAA,IACP,yBAAyB,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,IAC3D,qBAAqB,EAAE,OAAO,EAAE,SAAS,EAA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QAAQ;AAAA,MACR,MAAM;AAAA,IACP;AAAA,IACA,GAAG,CAAC,YAAY,YAAY,SAAS,SAAS,eAAe,SAAS,EAAE;AAAA,MACvE,CAAC,QAAQ,EAAE,IAAI,QAAQ,KAAc;AAAA,IACtC;AAAA,EACD;AACD;AAEO,SAAS,cACf,QACsC;AACtC,QAAM,SAAS,yBAAyB;AAAA,IACvC;AAAA,EACD;AAMA,QAAM,mBACL,OACC;AAEF,QAAM,eAAe;AAAA,IACpB,GAAG;AAAA,IACH,GAAI,oBAAoB,CAAC;AAAA,EAC1B;AACA,QAAM,aAAa,MAAM;AAAA,IACxB,SAAS,CAAC;AAAA,IACV,SAAS;AAAA;AAAA;AAAA;AAAA,IAIT,WAAW;AAAA,EACZ,CAEI;AACJ,aAAW,uBAAuB;AAAA,IACjC;AAAA,IACA;AAAA,EACD;AACA,SAAO;AACR;;;AD1XA,SAAS,sBAAsB;AAnB/B,IAAM,wCAAwC,MAAM,OAAO;AAQpD,IAAM,SAA+B,CAC3C,UAEA,cAAc;AAAA,EACb,wBAAwB;AAAA,EACxB,wBAAwB;AAAA,EACxB,GAAG;AACJ,CAAC;AAuEK,SAAS,QACf,SAA0C,CAAC,GACL;AACtC,QAAM;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACJ,IAAI;AAEJ,SAAO,cAAc;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB,iBACb,CAAC,MAAM,WAAW,UAAU,eAAe,WAAW,KAAK,IAC3D;AAAA,IACH,qBAAqB,sBAClB,CAAC,MAAM,WAAW,YAAY,oBAAoB,WAAW,OAAO,IACpE;AAAA,EACJ,CAAyC;AAC1C;","names":["dirname","join","fileURLToPath","require","join","dirname","fileURLToPath"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/actor.ts","../src/shell-replay.ts"],"sourcesContent":["import { setup as rivetkitSetup } from \"rivetkit\";\n\nexport type { Registry } from \"rivetkit\";\n\nconst AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT = 512 * 1024 * 1024;\n\n/**\n * RivetKit setup with the direct actor SQLite UDS enabled. The UDS is consumed\n * by the AgentOS sidecar; filesystem SQL never crosses the JavaScript layer.\n */\nexport const setup: typeof rivetkitSetup = ((\n\tinput: Parameters<typeof rivetkitSetup>[0],\n) =>\n\trivetkitSetup({\n\t\t...input,\n\t\tmaxIncomingMessageSize: AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT,\n\t\tmaxOutgoingMessageSize: AGENTOS_REGISTRY_MESSAGE_SIZE_DEFAULT,\n\t\texperimentalActorUds: true,\n\t} as Parameters<typeof rivetkitSetup>[0])) as typeof rivetkitSetup;\n\nexport * from \"@rivet-dev/agentos-core\";\nexport type {\n\tAgentOsActorConfigInput as AgentOSActorConfigInput,\n\tAgentOsActorConfigInput as AgentOSConfigInput,\n} from \"./actor.js\";\nexport {\n\ttype AgentOsActions,\n\ttype AgentOsActorConfigInput,\n\ttype AgentOsActorExtras,\n\ttype AgentOsEventHooks,\n\tcreateAgentOS,\n\tcreateAgentOS as agentOS,\n\tcreateAgentOsActions,\n\ttype VmFetchOptions,\n\ttype VmFetchResponse,\n\ttype VmFetchStreamChunk,\n\ttype VmFetchStreamHead,\n} from \"./actor.js\";\nexport type {\n\tActorData,\n\tActorLanguageSpawnOptions,\n\tActorSpawnOptions,\n\tAgentOsEvents,\n\tProcessExitPayload,\n\tProcessOutputPayload,\n\tRuntimeAgentExit,\n\tRuntimeHealth,\n\tRuntimeLimitWarning,\n\tRuntimeSidecarInfo,\n\tRuntimeStderrLine,\n\tSerializableCronAction,\n\tSerializableCronEvent,\n\tSerializableCronJobInfo,\n\tSerializableCronJobOptions,\n\tShellDataPayload,\n\tShellExitPayload,\n\tShellInfo,\n\tShellReplayMode,\n\tShellSnapshot,\n\tVmBootedPayload,\n\tVmShutdownPayload,\n} from \"./types.js\";\n","import crypto from \"node:crypto\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n\ttype AgentExitEvent,\n\tAgentOs,\n\ttype AgentOsOptions,\n\ttype CodeExecutionResult,\n\ttype CronEvent,\n\ttype DynamicMountDescriptor,\n\ttype OpenSessionInput,\n\ttype PackageDescriptor,\n\ttype ProcessDescriptor,\n\ttype PromptInput,\n\ttype SessionStreamEntry,\n} from \"@rivet-dev/agentos-core\";\nimport {\n\ttype Actions,\n\ttype ActorConfigInput,\n\ttype ActorContext,\n\ttype ActorDefinition,\n\tactor,\n\tevent,\n\ttype Type,\n\tUserError,\n} from \"rivetkit\";\nimport { type DatabaseProvider, db, type RawAccess } from \"rivetkit/db\";\nimport { migrations } from \"rivetkit/unstable/migrations\";\nimport { ShellReplayStore } from \"./shell-replay.js\";\nimport type {\n\tActorData,\n\tActorInlineExecutionOptions,\n\tActorJavaScriptExecutionOptions,\n\tActorLanguageExecutionOptions,\n\tActorLanguageSpawnOptions,\n\tActorNpmPackageInstallOptions,\n\tActorNpmProjectInstallOptions,\n\tActorPythonInstallOptions,\n\tActorSpawnOptions,\n\tActorTypeScriptCheckOptions,\n\tActorTypeScriptExecutionOptions,\n\tActorTypeScriptFileExecutionOptions,\n\tAgentOsEvents,\n\tProcessExitPayload,\n\tProcessOutputPayload,\n\tRuntimeAgentExit,\n\tRuntimeHealth,\n\tRuntimeLimitWarning,\n\tSerializableCronJobOptions,\n\tShellDataPayload,\n\tShellExitPayload,\n\tShellInfo,\n\tShellReplayMode,\n\tShellSnapshot,\n\tVmBootedPayload,\n\tVmShutdownPayload,\n} from \"./types.js\";\n\n// Prompts may remain paused at a permission request for a long human review.\n// RivetKit currently exposes only one actor-wide action timeout, so use the\n// largest value Node timers can represent safely (~24.8 days). Callers may\n// still opt into a shorter timeout through actor options.\nconst DEFAULT_ACTION_TIMEOUT_MS = 2_147_483_647;\nconst DEFAULT_SLEEP_GRACE_PERIOD_MS = 15 * 60_000;\nconst DEFAULT_PREVIEW_TTL_SECONDS = 3_600;\nconst MAX_PREVIEW_TTL_SECONDS = 86_400;\nconst DEFAULT_MAX_ACTIVE_PREVIEW_TOKENS = 1_024;\nconst DEFAULT_MAX_SESSION_SUBSCRIPTIONS = 10_000;\nconst DEFAULT_MAX_DYNAMIC_MOUNTS = 10_000;\nconst DEFAULT_MAX_LINKED_SOFTWARE = 10_000;\nconst ACTOR_SQLITE_CHUNK_SIZE = 512 * 1024;\nconst ACTOR_SQLITE_INLINE_THRESHOLD = 64 * 1024;\nconst ROOT_NAMESPACE = \"agentos-root\";\nconst PREVIEW_PATH_PATTERN = /^\\/fetch\\/([a-f0-9]{48})(\\/.*)?$/;\nconst MAX_SQLITE_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;\n// Each open shell holds the VM awake, so this bounds an unbounded wake-lock.\nconst MAX_OPEN_SHELLS = 32;\n\ninterface ActorSqliteMigration {\n\treadonly version: number;\n\treadonly sql: string;\n}\n\nconst ACTOR_SQLITE_MIGRATIONS = [\n\t{\n\t\tversion: 1,\n\t\tsql: `\n\t\t\tCREATE TABLE agentos_actor_preview_tokens (\n\t\t\t\ttoken TEXT PRIMARY KEY CHECK (length(token) = 48 AND token NOT GLOB '*[^0-9a-f]*'),\n\t\t\t\tport INTEGER NOT NULL CHECK (port BETWEEN 1 AND 65535),\n\t\t\t\tcreated_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND ${MAX_SQLITE_SAFE_INTEGER}),\n\t\t\t\texpires_at_ms INTEGER NOT NULL CHECK (expires_at_ms > created_at_ms AND expires_at_ms <= ${MAX_SQLITE_SAFE_INTEGER})\n\t\t\t) STRICT;\n\t\t\tCREATE INDEX agentos_actor_preview_tokens_by_expiry\n\t\t\t\tON agentos_actor_preview_tokens(expires_at_ms);\n\t\t\tCREATE TABLE agentos_actor_dynamic_mounts (\n\t\t\t\tpath TEXT PRIMARY KEY CHECK (substr(path, 1, 1) = '/' AND instr(path, char(0)) = 0),\n\t\t\t\tdescriptor_json TEXT NOT NULL CHECK (json_valid(descriptor_json) AND json_type(descriptor_json) = 'object')\n\t\t\t) STRICT;\n\t\t\tCREATE TABLE agentos_actor_linked_software (\n\t\t\t\tpath TEXT PRIMARY KEY CHECK (length(path) > 0 AND instr(path, char(0)) = 0),\n\t\t\t\tdescriptor_json TEXT NOT NULL CHECK (json_valid(descriptor_json) AND json_type(descriptor_json) = 'object')\n\t\t\t) STRICT;\n\t\t`,\n\t},\n] as const satisfies readonly ActorSqliteMigration[];\n\ntype BuiltInEvents = {\n\t[K in keyof AgentOsEvents]: Type<AgentOsEvents[K]>;\n};\n\nconst builtInEvents: BuiltInEvents = {\n\tsessionEvent: event<SessionStreamEntry>(),\n\tvmBooted: event<VmBootedPayload>(),\n\tvmShutdown: event<VmShutdownPayload>(),\n\tprocessOutput: event<ProcessOutputPayload>(),\n\tprocessExit: event<ProcessExitPayload>(),\n\tshellData: event<ShellDataPayload>(),\n\tcronEvent: event<CronEvent>(),\n\tagentExit: event<AgentExitEvent>(),\n\tshellStderr: event<ShellDataPayload>(),\n\tshellExit: event<ShellExitPayload>(),\n};\ntype ActorDb = DatabaseProvider<RawAccess>;\ntype EventSchemaConfig = Record<string, any>;\ntype QueueSchemaConfig = Record<string, any>;\ntype AnyContext = ActorContext<any, any, any, any, any, ActorDb, any, any>;\n\ninterface RuntimeState {\n\tvm: Promise<AgentOs> | null;\n\t/** Set once `vm` resolves, cleared when it stops. Observe-only callers must\n\t * read this instead of sampling `vm`: any `.then`/`.catch` on a settled\n\t * promise still needs a microtask, so racing one against an immediate value\n\t * always loses and reports a booted VM as not booted. */\n\tbootedVm: AgentOs | null;\n\t/** Shells opened through this actor, in open order. Enumeration is\n\t * server-owned: a client that lost its page (or never had one) must be able\n\t * to find shells it is still keeping the VM awake for. Entries die with the\n\t * VM, so this is deliberately in-memory. */\n\topenShells: Map<string, { openedAt: number }>;\n\t/** Headless emulator per live shell, fed the same chunks this actor\n\t * broadcasts, so a reattaching client can be repainted. */\n\tshellReplay: ShellReplayStore;\n\tsubscribedSessions: Map<string, readonly (() => void)[]>;\n\tonVmStop?: (\n\t\tc: AnyContext,\n\t\tvm: AgentOs,\n\t\treason: \"sleep\" | \"destroy\" | \"error\",\n\t) => void | Promise<void>;\n\tonVmDisposed?: (\n\t\tc: AnyContext,\n\t\treason: \"sleep\" | \"destroy\" | \"error\",\n\t) => void | Promise<void>;\n\tvmCleanupRan: boolean;\n\tfetchStreamHolds: Map<string, () => void>;\n}\n\nconst runtimes = new Map<string, RuntimeState>();\nconst optionResolvers = new WeakMap<\n\tAgentOsOptions,\n\t(c: AnyContext) => AgentOsOptions | Promise<AgentOsOptions>\n>();\nconst vmStartResolvers = new WeakMap<\n\tAgentOsOptions,\n\t(c: AnyContext, vm: AgentOs) => void | Promise<void>\n>();\nconst vmStopResolvers = new WeakMap<\n\tAgentOsOptions,\n\t(\n\t\tc: AnyContext,\n\t\tvm: AgentOs,\n\t\treason: \"sleep\" | \"destroy\" | \"error\",\n\t) => void | Promise<void>\n>();\nconst vmDisposedResolvers = new WeakMap<\n\tAgentOsOptions,\n\t(c: AnyContext, reason: \"sleep\" | \"destroy\" | \"error\") => void | Promise<void>\n>();\n\n// Bounded post-mortem buffers for the observe-only `health` action. Kept in\n// their own map — not on RuntimeState — because `disposeVm` drops the runtime\n// entry on sleep while these must stay readable while `booted` is false. They\n// are cleared only when the actor is destroyed.\nconst HEALTH_WARNINGS_CAP = 50;\nconst HEALTH_AGENT_EXITS_CAP = 50;\n\ninterface HealthBuffers {\n\twarnings: RuntimeLimitWarning[];\n\tagentExits: RuntimeAgentExit[];\n}\n\nconst healthBuffers = new Map<string, HealthBuffers>();\n\nfunction healthBuffersFor(actorId: string): HealthBuffers {\n\tlet buffers = healthBuffers.get(actorId);\n\tif (!buffers) {\n\t\tbuffers = { warnings: [], agentExits: [] };\n\t\thealthBuffers.set(actorId, buffers);\n\t}\n\treturn buffers;\n}\n\nfunction pushCapped<T>(buffer: T[], item: T, cap: number): void {\n\tbuffer.push(item);\n\twhile (buffer.length > cap) buffer.shift();\n}\n\nfunction runtimeFor(c: AnyContext): RuntimeState {\n\tlet runtime = runtimes.get(c.actorId);\n\tif (!runtime) {\n\t\truntime = {\n\t\t\tvm: null,\n\t\t\tbootedVm: null,\n\t\t\topenShells: new Map(),\n\t\t\tshellReplay: new ShellReplayStore(),\n\t\t\tsubscribedSessions: new Map(),\n\t\t\tvmCleanupRan: false,\n\t\t\tfetchStreamHolds: new Map(),\n\t\t};\n\t\truntimes.set(c.actorId, runtime);\n\t}\n\treturn runtime;\n}\n\nasync function runVmDisposedHook(\n\truntime: RuntimeState,\n\tc: AnyContext,\n\treason: \"sleep\" | \"destroy\" | \"error\",\n): Promise<void> {\n\tif (runtime.vmCleanupRan) return;\n\truntime.vmCleanupRan = true;\n\tawait runtime.onVmDisposed?.(c, reason);\n}\n\nasync function ensureVm(\n\tc: AnyContext,\n\toptions?: AgentOsOptions,\n): Promise<AgentOs> {\n\tconst runtime = runtimeFor(c);\n\tif (runtime.vm !== null) return runtime.vm;\n\n\tconst startedAt = Date.now();\n\truntime.vmCleanupRan = false;\n\truntime.vm = (async () => {\n\t\truntime.onVmStop = options ? vmStopResolvers.get(options) : undefined;\n\t\truntime.onVmDisposed = options\n\t\t\t? vmDisposedResolvers.get(options)\n\t\t\t: undefined;\n\t\tconst resolvedOptions = {\n\t\t\t...options,\n\t\t\t...(options && optionResolvers.has(options)\n\t\t\t\t? await optionResolvers.get(options)?.(c)\n\t\t\t\t: undefined),\n\t\t};\n\t\tif (resolvedOptions.rootFilesystem) {\n\t\t\tthrow new Error(\n\t\t\t\t\"agentOS() owns rootFilesystem so it can persist directly through the actor SQLite UDS; resolveOptions may configure mounts but not rootFilesystem\",\n\t\t\t);\n\t\t}\n\t\tif (resolvedOptions.database) {\n\t\t\tthrow new Error(\n\t\t\t\t\"agentOS() owns database and injects the actor SQLite UDS descriptor; resolveOptions cannot replace it\",\n\t\t\t);\n\t\t}\n\t\tif (resolvedOptions.sandbox && \"client\" in resolvedOptions.sandbox) {\n\t\t\tthrow new Error(\n\t\t\t\t\"agentOS() cannot share sandbox: { client } across actor instances; resolveOptions must use sandbox: { provider }\",\n\t\t\t);\n\t\t}\n\t\tconst actorRuntimeSocket = (\n\t\t\tc as AnyContext & {\n\t\t\t\tactorRuntimeSocket(): Promise<{ path: string }>;\n\t\t\t}\n\t\t).actorRuntimeSocket;\n\t\tif (typeof actorRuntimeSocket !== \"function\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"AgentOS actors require a RivetKit runtime with Actor Runtime Socket support\",\n\t\t\t);\n\t\t}\n\t\tconst { path } = await actorRuntimeSocket.call(c);\n\t\tconst mountRows = await c.db.execute<{ descriptor_json: string }>(\n\t\t\t\"SELECT descriptor_json FROM agentos_actor_dynamic_mounts ORDER BY path\",\n\t\t);\n\t\tconst softwareRows = await c.db.execute<{ descriptor_json: string }>(\n\t\t\t\"SELECT descriptor_json FROM agentos_actor_linked_software ORDER BY path\",\n\t\t);\n\t\tconst vm = await AgentOs.create({\n\t\t\t...resolvedOptions,\n\t\t\tdatabase: { type: \"actor_uds\", path },\n\t\t\tonAgentExit: (event) => {\n\t\t\t\tc.log.error({\n\t\t\t\t\tmsg: \"agent-os agent adapter exited unexpectedly\",\n\t\t\t\t\t...event,\n\t\t\t\t});\n\t\t\t\tpushCapped(\n\t\t\t\t\thealthBuffersFor(c.actorId).agentExits,\n\t\t\t\t\t{\n\t\t\t\t\t\tts: Date.now(),\n\t\t\t\t\t\tsessionId: event.sessionId,\n\t\t\t\t\t\tagentType: event.agentType,\n\t\t\t\t\t\texitCode: event.exitCode,\n\t\t\t\t\t\trestart: event.restart,\n\t\t\t\t\t\trestartCount: event.restartCount,\n\t\t\t\t\t},\n\t\t\t\t\tHEALTH_AGENT_EXITS_CAP,\n\t\t\t\t);\n\t\t\t\tc.broadcast(\"agentExit\", event);\n\t\t\t\ttry {\n\t\t\t\t\tresolvedOptions.onAgentExit?.(event);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tc.log.error({\n\t\t\t\t\t\tmsg: \"agent-os onAgentExit hook failed\",\n\t\t\t\t\t\tsessionId: event.sessionId,\n\t\t\t\t\t\terror,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t},\n\t\t\tonLimitWarning: (warning) => {\n\t\t\t\tc.log.warn({\n\t\t\t\t\tmsg: \"agent-os runtime limit is near capacity\",\n\t\t\t\t\t...warning,\n\t\t\t\t});\n\t\t\t\tpushCapped(\n\t\t\t\t\thealthBuffersFor(c.actorId).warnings,\n\t\t\t\t\t{ ts: Date.now(), ...warning },\n\t\t\t\t\tHEALTH_WARNINGS_CAP,\n\t\t\t\t);\n\t\t\t\ttry {\n\t\t\t\t\toptions?.onLimitWarning?.(warning);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tc.log.error({\n\t\t\t\t\t\tmsg: \"agent-os onLimitWarning hook failed\",\n\t\t\t\t\t\tlimit: warning.limit,\n\t\t\t\t\t\terror,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t},\n\t\t\trootFilesystem: {\n\t\t\t\ttype: \"native\",\n\t\t\t\tplugin: {\n\t\t\t\t\tid: \"chunked_actor_sqlite\",\n\t\t\t\t\tconfig: {\n\t\t\t\t\t\tnamespace: ROOT_NAMESPACE,\n\t\t\t\t\t\tchunkSize: ACTOR_SQLITE_CHUNK_SIZE,\n\t\t\t\t\t\tinlineThreshold: ACTOR_SQLITE_INLINE_THRESHOLD,\n\t\t\t\t\t\tuid:\n\t\t\t\t\t\t\tresolvedOptions.user?.euid ?? resolvedOptions.user?.uid ?? 1000,\n\t\t\t\t\t\tgid:\n\t\t\t\t\t\t\tresolvedOptions.user?.egid ?? resolvedOptions.user?.gid ?? 1000,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t\ttry {\n\t\t\tfor (const row of mountRows) {\n\t\t\t\tawait vm.filesystem.mount(\n\t\t\t\t\tJSON.parse(row.descriptor_json) as DynamicMountDescriptor,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const row of softwareRows) {\n\t\t\t\tawait vm.software.link(\n\t\t\t\t\tJSON.parse(row.descriptor_json) as PackageDescriptor,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tawait vm.dispose();\n\t\t\tthrow error;\n\t\t}\n\t\tconst onVmStart = options ? vmStartResolvers.get(options) : undefined;\n\t\tif (onVmStart) {\n\t\t\ttry {\n\t\t\t\tawait onVmStart(c, vm);\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait vm.dispose();\n\t\t\t\t} catch (disposeError) {\n\t\t\t\t\tc.log.error({\n\t\t\t\t\t\tmsg: \"failed to dispose AgentOS VM after start hook failure\",\n\t\t\t\t\t\tdisposeError,\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\tawait runVmDisposedHook(runtime, c, \"error\");\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tvm.onCronEvent((cronEvent) => c.broadcast(\"cronEvent\", cronEvent));\n\t\truntime.bootedVm = vm;\n\t\tc.broadcast(\"vmBooted\", {});\n\t\tc.log.info({\n\t\t\tmsg: \"agent-os vm booted\",\n\t\t\tbootDurationMs: Date.now() - startedAt,\n\t\t});\n\t\treturn vm;\n\t})();\n\n\ttry {\n\t\treturn await runtime.vm;\n\t} catch (error) {\n\t\truntime.vm = null;\n\t\truntime.bootedVm = null;\n\t\tc.log.error({\n\t\t\tmsg: \"agent-os vm bootstrap failed\",\n\t\t\tactorId: c.actorId,\n\t\t\terror,\n\t\t});\n\t\tawait runVmDisposedHook(runtime, c, \"error\");\n\t\tthrow error;\n\t}\n}\n\nasync function disposeVm(c: AnyContext, reason: \"sleep\" | \"destroy\" | \"error\") {\n\t// Post-mortem health buffers survive sleep and error by design; only a\n\t// destroyed actor drops them.\n\tif (reason === \"destroy\") healthBuffers.delete(c.actorId);\n\tconst runtime = runtimes.get(c.actorId);\n\tif (!runtime) return;\n\tconst vm = runtime.vm;\n\truntime.bootedVm = null;\n\truntimes.delete(c.actorId);\n\tfor (const unsubscribers of runtime.subscribedSessions.values()) {\n\t\tfor (const unsubscribe of unsubscribers) unsubscribe();\n\t}\n\truntime.subscribedSessions.clear();\n\tfor (const release of runtime.fetchStreamHolds.values()) release();\n\truntime.fetchStreamHolds.clear();\n\tif (vm) {\n\t\tconst failures: unknown[] = [];\n\t\ttry {\n\t\t\tconst resolvedVm = await vm;\n\t\t\ttry {\n\t\t\t\tawait runtime.onVmStop?.(c, resolvedVm, reason);\n\t\t\t} catch (error) {\n\t\t\t\tfailures.push(error);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait resolvedVm.dispose();\n\t\t\t} catch (error) {\n\t\t\t\tfailures.push(error);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t\ttry {\n\t\t\tawait runVmDisposedHook(runtime, c, reason);\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t\tif (failures.length === 1) throw failures[0];\n\t\tif (failures.length > 1) {\n\t\t\tconst aggregate = new Error(\n\t\t\t\t\"failed to stop, dispose, or clean up AgentOS VM\",\n\t\t\t);\n\t\t\t(aggregate as Error & { errors: unknown[] }).errors = failures;\n\t\t\tthrow aggregate;\n\t\t}\n\t}\n\tc.broadcast(\"vmShutdown\", { reason });\n}\n\nfunction matchPreviewPath(pathname: string): RegExpMatchArray | null {\n\treturn pathname.match(PREVIEW_PATH_PATTERN);\n}\n\n/** @internal Exported only for focused migration-ladder tests. */\nexport function validateAgentOsActorMigrationLadder(\n\tmigrations: readonly ActorSqliteMigration[],\n): void {\n\tif (migrations.length === 0) {\n\t\tthrow new Error(\"AgentOS actor SQLite migration ladder must not be empty\");\n\t}\n\tfor (const [index, migration] of migrations.entries()) {\n\t\tconst expectedVersion = index + 1;\n\t\tif (migration.version !== expectedVersion) {\n\t\t\tthrow new Error(\n\t\t\t\t`invalid AgentOS actor SQLite migration ladder: expected version ${expectedVersion}, received ${migration.version}`,\n\t\t\t);\n\t\t}\n\t\tif (migration.sql.trim().length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`invalid AgentOS actor SQLite migration ${migration.version}: SQL is empty`,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t/(?:^|;)\\s*(?:BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\\b/im.test(\n\t\t\t\tmigration.sql,\n\t\t\t)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`invalid AgentOS actor SQLite migration ${migration.version}: transaction control belongs to the migration provider`,\n\t\t\t);\n\t\t}\n\t\tif (/\\b(?:FOREIGN\\s+KEY|REFERENCES)\\b/i.test(migration.sql)) {\n\t\t\tthrow new Error(\n\t\t\t\t`invalid AgentOS actor SQLite migration ${migration.version}: foreign keys are not used in the actor-owned schema`,\n\t\t\t);\n\t\t}\n\t\tfor (const statement of migration.sql.split(\";\")) {\n\t\t\tif (\n\t\t\t\t/^\\s*CREATE\\s+TABLE\\b/i.test(statement) &&\n\t\t\t\t!/[)]\\s*STRICT\\s*$/i.test(statement)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`invalid AgentOS actor SQLite migration ${migration.version}: every actor-owned table must be STRICT`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tconst ownedIdentifiers = migration.sql.match(/\\bagentos_[a-z0-9_]+\\b/gi);\n\t\tif (\n\t\t\t!ownedIdentifiers ||\n\t\t\townedIdentifiers.some(\n\t\t\t\t(identifier) => !identifier.startsWith(\"agentos_actor_\"),\n\t\t\t)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`invalid AgentOS actor SQLite migration ${migration.version}: migrations may reference only agentos_actor_* tables and indexes`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** @internal Exported only for focused migration tests. */\nexport async function migrateAgentOsActorTables(\n\tdatabase: RawAccess,\n): Promise<void> {\n\tvalidateAgentOsActorMigrationLadder(ACTOR_SQLITE_MIGRATIONS);\n\tawait runAgentOsActorMigrations(database);\n}\n\nconst runAgentOsActorMigrations = migrations({\n\ttableName: \"agentos_actor_schema_version\",\n\tmigrations: ACTOR_SQLITE_MIGRATIONS,\n});\n\nasync function assertActorCollectionCapacity(\n\tc: AnyContext,\n\ttable: \"agentos_actor_dynamic_mounts\" | \"agentos_actor_linked_software\",\n\tkey: string,\n\tlimit: number,\n\tlabel: \"dynamic mounts\" | \"linked software packages\",\n\tconfigKey: \"maxDynamicMounts\" | \"maxLinkedSoftware\",\n): Promise<void> {\n\tconst existing = await c.db.execute<{ present: number }>(\n\t\t`SELECT 1 AS present FROM ${table} WHERE path = ? LIMIT 1`,\n\t\tkey,\n\t);\n\tif (existing.length > 0) return;\n\tconst rows = await c.db.execute<{ count: number }>(\n\t\t`SELECT COUNT(*) AS count FROM ${table}`,\n\t);\n\tconst count = Number(rows[0]?.count ?? 0);\n\tif (count >= limit) {\n\t\tthrow new UserError(\n\t\t\t`${label} limit ${limit} reached; raise ${configKey} to persist more`,\n\t\t\t{\n\t\t\t\tcode: `agentos_${configKey === \"maxDynamicMounts\" ? \"dynamic_mount\" : \"linked_software\"}_limit`,\n\t\t\t\tmetadata: { limit },\n\t\t\t},\n\t\t);\n\t}\n\tif (count + 1 === Math.ceil(limit * 0.8)) {\n\t\tc.log.warn({\n\t\t\tmsg: `${label} are near the limit of ${limit}; raise ${configKey} to persist more`,\n\t\t\tcount: count + 1,\n\t\t\tlimit,\n\t\t});\n\t}\n}\n\nexport interface VmFetchOptions {\n\tmethod?: string;\n\theaders?: Record<string, string>;\n\tbody?: string | Uint8Array;\n}\n\nexport interface VmFetchResponse {\n\tstatus: number;\n\tstatusText: string;\n\theaders: Record<string, string>;\n\trawHeaders?: Array<[string, string]>;\n\tbody: Uint8Array;\n}\n\nexport interface VmFetchStreamHead {\n\tstreamId: string;\n\tstatus: number;\n\tstatusText: string;\n\theaders: Record<string, string>;\n\trawHeaders?: Array<[string, string]>;\n}\n\nexport interface VmFetchStreamChunk {\n\tbody: Uint8Array;\n\tdone: boolean;\n}\n\nexport interface AgentOsEventHooks<TContext = AnyContext> {\n\tonSessionEvent?: (\n\t\tc: TContext,\n\t\tsessionId: string,\n\t\tevent: SessionStreamEntry,\n\t) => void | Promise<void>;\n}\n\nfunction trackSessionEvents(\n\tc: AnyContext,\n\tvm: AgentOs,\n\tsessionId: string,\n\thooks: AgentOsEventHooks,\n\tmaxSessionSubscriptions: number,\n): void {\n\tconst runtime = runtimeFor(c);\n\tif (runtime.subscribedSessions.has(sessionId)) return;\n\tif (runtime.subscribedSessions.size >= maxSessionSubscriptions) {\n\t\tthrow new UserError(\n\t\t\t`session subscription limit ${maxSessionSubscriptions} reached; raise maxSessionSubscriptions to observe more sessions`,\n\t\t\t{\n\t\t\t\tcode: \"agentos_session_subscription_limit\",\n\t\t\t\tmetadata: { limit: maxSessionSubscriptions },\n\t\t\t},\n\t\t);\n\t}\n\tconst nextCount = runtime.subscribedSessions.size + 1;\n\tif (nextCount === Math.ceil(maxSessionSubscriptions * 0.8)) {\n\t\tc.log.warn({\n\t\t\tmsg: `session subscriptions are near the limit of ${maxSessionSubscriptions}; raise maxSessionSubscriptions to observe more sessions`,\n\t\t\tsubscriptionCount: nextCount,\n\t\t\tlimit: maxSessionSubscriptions,\n\t\t});\n\t}\n\tconst unsubscribeSession = vm.onSessionEvent(\n\t\tsessionId,\n\t\t(notification: SessionStreamEntry) => {\n\t\t\tconst serialized = JSON.parse(\n\t\t\t\tJSON.stringify(notification),\n\t\t\t) as SessionStreamEntry;\n\t\t\tc.broadcast(\"sessionEvent\", serialized);\n\t\t\tif (hooks.onSessionEvent) {\n\t\t\t\tvoid c.keepAwake(\n\t\t\t\t\tPromise.resolve()\n\t\t\t\t\t\t.then(() => hooks.onSessionEvent?.(c, sessionId, serialized))\n\t\t\t\t\t\t.catch((error) =>\n\t\t\t\t\t\t\tc.log.error({\n\t\t\t\t\t\t\t\tmsg: \"agent-os session event hook failed\",\n\t\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t);\n\truntime.subscribedSessions.set(sessionId, [unsubscribeSession]);\n}\n\nfunction untrackSessionEvents(c: AnyContext, sessionId: string): void {\n\tconst unsubscribers = runtimeFor(c).subscribedSessions.get(sessionId);\n\tif (!unsubscribers) return;\n\tfor (const unsubscribe of unsubscribers) unsubscribe();\n\truntimeFor(c).subscribedSessions.delete(sessionId);\n}\n\nfunction trackFetchStream(c: AnyContext, streamId: string): void {\n\tconst runtime = runtimeFor(c);\n\tif (runtime.fetchStreamHolds.has(streamId)) return;\n\tconst hold = new Promise<void>((resolve) => {\n\t\truntime.fetchStreamHolds.set(streamId, resolve);\n\t});\n\tvoid c.keepAwake(hold).catch((error) =>\n\t\tc.log.error({\n\t\t\tmsg: \"agent-os fetch stream hold failed\",\n\t\t\tstreamId,\n\t\t\terror,\n\t\t}),\n\t);\n}\n\nfunction releaseFetchStream(c: AnyContext, streamId: string): void {\n\tconst runtime = runtimeFor(c);\n\truntime.fetchStreamHolds.get(streamId)?.();\n\truntime.fetchStreamHolds.delete(streamId);\n}\n\nfunction decodeActorData(value: ActorData): string | Uint8Array;\nfunction decodeActorData(value: unknown): string | Uint8Array | undefined;\nfunction decodeActorData(value: unknown): string | Uint8Array | undefined {\n\tif (value === undefined) return undefined;\n\tif (\n\t\ttypeof value !== \"object\" ||\n\t\tvalue === null ||\n\t\t!(\"encoding\" in value) ||\n\t\t!(\"data\" in value)\n\t) {\n\t\tthrow new UserError(\"stdin must be tagged UTF-8 or base64 actor data\", {\n\t\t\tcode: \"agentos_execution_invalid_actor_data\",\n\t\t});\n\t}\n\tconst input = value as { encoding: unknown; data: unknown };\n\tif (typeof input.data !== \"string\") {\n\t\tthrow new UserError(\"actor data must contain a string\", {\n\t\t\tcode: \"agentos_execution_invalid_actor_data\",\n\t\t});\n\t}\n\tif (input.encoding === \"utf8\") return input.data;\n\tif (input.encoding === \"base64\")\n\t\treturn new Uint8Array(Buffer.from(input.data, \"base64\"));\n\tthrow new UserError(\"actor data encoding must be utf8 or base64\", {\n\t\tcode: \"agentos_execution_invalid_actor_data\",\n\t});\n}\n\nfunction actorExecutionArgs(args: readonly unknown[]): unknown[] {\n\treturn args.map((arg) => {\n\t\tif (typeof arg !== \"object\" || arg === null || Array.isArray(arg))\n\t\t\treturn arg;\n\t\tconst options = arg as Record<string, unknown>;\n\t\tfor (const field of [\"signal\", \"onStdout\", \"onStderr\"] as const) {\n\t\t\tif (options[field] !== undefined) {\n\t\t\t\tthrow new UserError(`${field} is not available on actor actions`, {\n\t\t\t\t\tcode: \"agentos_execution_non_serializable_option\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst normalized = { ...options };\n\t\tif (\"stdin\" in normalized)\n\t\t\tnormalized.stdin = decodeActorData(normalized.stdin);\n\t\treturn normalized;\n\t});\n}\n\nfunction actorSpawnArgs(options: unknown): unknown[] {\n\treturn options === undefined ? [] : actorExecutionArgs([options]);\n}\n\nasync function runActorExecution<T>(\n\tc: AnyContext,\n\toperation: (vm: AgentOs) => Promise<T>,\n\toptions?: AgentOsOptions,\n): Promise<T> {\n\tconst vm = await ensureVm(c, options);\n\treturn c.keepAwake(operation(vm));\n}\n\nasync function runActorSpawn(\n\tc: AnyContext,\n\toperation: (vm: AgentOs) => Promise<ProcessDescriptor>,\n\toptions?: AgentOsOptions,\n): Promise<ProcessDescriptor> {\n\tconst vm = await ensureVm(c, options);\n\tconst process = await operation(vm);\n\tconst unsubscribeOutput = vm.onProcessOutput(process.pid, (event) =>\n\t\tc.broadcast(\"processOutput\", event),\n\t);\n\tconst unsubscribeExit = vm.onProcessExit(process.pid, (event) =>\n\t\tc.broadcast(\"processExit\", event),\n\t);\n\tvoid c\n\t\t.keepAwake(\n\t\t\tvm.process.wait(process.pid).finally(() => {\n\t\t\t\tunsubscribeOutput();\n\t\t\t\tunsubscribeExit();\n\t\t\t}),\n\t\t)\n\t\t.catch((error) =>\n\t\t\tc.log.error({\n\t\t\t\tmsg: \"agent-os process wait failed\",\n\t\t\t\tpid: process.pid,\n\t\t\t\terror,\n\t\t\t}),\n\t\t);\n\treturn process;\n}\n\nexport function createAgentOsActions(\n\toptions?: AgentOsOptions,\n\thooks: AgentOsEventHooks = {},\n\tpreview: AgentOsActorExtras[\"preview\"] = {},\n\tmaxSessionSubscriptions = DEFAULT_MAX_SESSION_SUBSCRIPTIONS,\n\tmaxDynamicMounts = DEFAULT_MAX_DYNAMIC_MOUNTS,\n\tmaxLinkedSoftware = DEFAULT_MAX_LINKED_SOFTWARE,\n) {\n\tconst defaultPreviewTtlSeconds =\n\t\tpreview.defaultExpiresInSeconds ?? DEFAULT_PREVIEW_TTL_SECONDS;\n\tconst maxPreviewTtlSeconds =\n\t\tpreview.maxExpiresInSeconds ?? MAX_PREVIEW_TTL_SECONDS;\n\tconst maxActivePreviewTokens =\n\t\tpreview.maxActiveTokens ?? DEFAULT_MAX_ACTIVE_PREVIEW_TOKENS;\n\tif (\n\t\t!Number.isFinite(defaultPreviewTtlSeconds) ||\n\t\tdefaultPreviewTtlSeconds <= 0 ||\n\t\t!Number.isFinite(maxPreviewTtlSeconds) ||\n\t\tmaxPreviewTtlSeconds <= 0 ||\n\t\tdefaultPreviewTtlSeconds > maxPreviewTtlSeconds\n\t) {\n\t\tthrow new UserError(\n\t\t\t\"preview expiry bounds must be positive and the default cannot exceed the maximum\",\n\t\t\t{ code: \"agentos_preview_invalid_config\" },\n\t\t);\n\t}\n\tif (!Number.isInteger(maxActivePreviewTokens) || maxActivePreviewTokens < 1) {\n\t\tthrow new UserError(\"preview.maxActiveTokens must be a positive integer\", {\n\t\t\tcode: \"agentos_preview_invalid_config\",\n\t\t});\n\t}\n\tif (\n\t\t!Number.isInteger(maxSessionSubscriptions) ||\n\t\tmaxSessionSubscriptions < 1\n\t) {\n\t\tthrow new UserError(\"maxSessionSubscriptions must be a positive integer\", {\n\t\t\tcode: \"agentos_session_subscription_invalid_config\",\n\t\t});\n\t}\n\tif (!Number.isInteger(maxDynamicMounts) || maxDynamicMounts < 1) {\n\t\tthrow new UserError(\"maxDynamicMounts must be a positive integer\", {\n\t\t\tcode: \"agentos_dynamic_mount_invalid_config\",\n\t\t});\n\t}\n\tif (!Number.isInteger(maxLinkedSoftware) || maxLinkedSoftware < 1) {\n\t\tthrow new UserError(\"maxLinkedSoftware must be a positive integer\", {\n\t\t\tcode: \"agentos_linked_software_invalid_config\",\n\t\t});\n\t}\n\tconst flat = {\n\t\treadFile: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"readFile\"]>\n\t\t) => {\n\t\t\ttry {\n\t\t\t\treturn await (await ensureVm(c, options)).filesystem.readFile(...args);\n\t\t\t} catch (error) {\n\t\t\t\tc.log.error({\n\t\t\t\t\tmsg: \"agent-os readFile action failed\",\n\t\t\t\t\tpath: args[0],\n\t\t\t\t\terror,\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\twriteFile: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"writeFile\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.writeFile(...args),\n\t\treadFiles: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"readFiles\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.readFiles(...args),\n\t\twriteFiles: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"writeFiles\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.writeFiles(...args),\n\t\tstat: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"stat\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.stat(...args),\n\t\tmkdir: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"mkdir\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.mkdir(...args),\n\t\treaddir: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"readdir\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.readdir(...args),\n\t\treaddirEntries: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"readdirEntries\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.readdirEntries(...args),\n\t\treaddirRecursive: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"readdirRecursive\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.readdirRecursive(...args),\n\t\texists: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"exists\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.exists(...args),\n\t\tmove: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"move\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.move(...args),\n\t\tremove: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"remove\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.remove(...args),\n\t\texec: async (\n\t\t\tc: AnyContext,\n\t\t\tcommand: string,\n\t\t\tactorOptions?: ActorLanguageExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.process.exec(\n\t\t\t\t\t\tcommand,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\texecArgv: async (\n\t\t\tc: AnyContext,\n\t\t\tcommand: string,\n\t\t\targs: readonly string[] = [],\n\t\t\tactorOptions?: Omit<ActorLanguageExecutionOptions, \"args\">,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.process.execFile(\n\t\t\t\t\t\tcommand,\n\t\t\t\t\t\targs,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tspawn: async (\n\t\t\tc: AnyContext,\n\t\t\tcommand: string,\n\t\t\targs: string[] = [],\n\t\t\tactorOptions?: ActorSpawnOptions,\n\t\t) =>\n\t\t\trunActorSpawn(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.process.spawn(\n\t\t\t\t\t\tcommand,\n\t\t\t\t\t\targs,\n\t\t\t\t\t\t...(actorSpawnArgs(actorOptions) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tcreateContext: async (c: AnyContext, contextId: string) =>\n\t\t\t(await ensureVm(c, options)).createContext(contextId),\n\t\texecuteJavaScript: async (\n\t\t\tc: AnyContext,\n\t\t\tsource: string,\n\t\t\tactorOptions?: ActorJavaScriptExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.javascript.execute(\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tevaluateJavaScript: async (\n\t\t\tc: AnyContext,\n\t\t\texpression: string,\n\t\t\tactorOptions?: ActorJavaScriptExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.javascript.evaluate(\n\t\t\t\t\t\texpression,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\texecuteJavaScriptFile: async (\n\t\t\tc: AnyContext,\n\t\t\tpath: string,\n\t\t\tactorOptions?: ActorLanguageExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.javascript.executeFile(\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tspawnJavaScript: async (\n\t\t\tc: AnyContext,\n\t\t\tsource: string,\n\t\t\tactorOptions?: ActorLanguageSpawnOptions,\n\t\t) =>\n\t\t\trunActorSpawn(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.javascript.spawn(\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\t...(actorSpawnArgs(actorOptions) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tspawnJavaScriptFile: async (\n\t\t\tc: AnyContext,\n\t\t\tpath: string,\n\t\t\tactorOptions?: ActorLanguageSpawnOptions,\n\t\t) =>\n\t\t\trunActorSpawn(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.javascript.spawnFile(\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\t...(actorSpawnArgs(actorOptions) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\texecuteTypeScript: async (\n\t\t\tc: AnyContext,\n\t\t\tsource: string,\n\t\t\tactorOptions?: ActorTypeScriptExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.typescript.execute(\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tevaluateTypeScript: async (\n\t\t\tc: AnyContext,\n\t\t\texpression: string,\n\t\t\tactorOptions?: ActorTypeScriptExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.typescript.evaluate(\n\t\t\t\t\t\texpression,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\texecuteTypeScriptFile: async (\n\t\t\tc: AnyContext,\n\t\t\tpath: string,\n\t\t\tactorOptions?: ActorTypeScriptFileExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.typescript.executeFile(\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tspawnTypeScript: async (\n\t\t\tc: AnyContext,\n\t\t\tsource: string,\n\t\t\tactorOptions?: ActorLanguageSpawnOptions,\n\t\t) =>\n\t\t\trunActorSpawn(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.typescript.spawn(\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\t...(actorSpawnArgs(actorOptions) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tspawnTypeScriptFile: async (\n\t\t\tc: AnyContext,\n\t\t\tpath: string,\n\t\t\tactorOptions?: ActorLanguageSpawnOptions,\n\t\t) =>\n\t\t\trunActorSpawn(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.typescript.spawnFile(\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\t...(actorSpawnArgs(actorOptions) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tcheckTypeScript: async (\n\t\t\tc: AnyContext,\n\t\t\tsource: string,\n\t\t\tactorOptions?: ActorTypeScriptCheckOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.typescript.check(\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tcheckTypeScriptProject: async (\n\t\t\tc: AnyContext,\n\t\t\tactorOptions?: Omit<\n\t\t\t\tActorTypeScriptCheckOptions,\n\t\t\t\t\"filePath\" | \"compilerOptions\"\n\t\t\t>,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.typescript.checkProject(\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tinstallNpmPackages: async (\n\t\t\tc: AnyContext,\n\t\t\t...args:\n\t\t\t\t| [options?: ActorNpmProjectInstallOptions]\n\t\t\t\t| [packages: string | string[], options?: ActorNpmPackageInstallOptions]\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\t(\n\t\t\t\t\t\tvm.javascript.npm.install as (\n\t\t\t\t\t\t\t...callArgs: unknown[]\n\t\t\t\t\t\t) => Promise<CodeExecutionResult>\n\t\t\t\t\t)(...actorExecutionArgs(args)),\n\t\t\t\toptions,\n\t\t\t),\n\t\texecuteNpmScript: async (\n\t\t\tc: AnyContext,\n\t\t\tscript: string,\n\t\t\tactorOptions?: ActorLanguageExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.javascript.npm.runScript(\n\t\t\t\t\t\tscript,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\texecuteNpmPackage: async (\n\t\t\tc: AnyContext,\n\t\t\tpackageSpec: string,\n\t\t\tactorOptions?: ActorLanguageExecutionOptions & { binary?: string },\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.javascript.npm.runPackage(\n\t\t\t\t\t\tpackageSpec,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\texecutePython: async (\n\t\t\tc: AnyContext,\n\t\t\tsource: string,\n\t\t\tactorOptions?: ActorInlineExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.python.execute(\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tevaluatePython: async (\n\t\t\tc: AnyContext,\n\t\t\texpression: string,\n\t\t\tactorOptions?: ActorInlineExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.python.evaluate(\n\t\t\t\t\t\texpression,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\texecutePythonFile: async (\n\t\t\tc: AnyContext,\n\t\t\tpath: string,\n\t\t\tactorOptions?: ActorLanguageExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.python.executeFile(\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\texecutePythonModule: async (\n\t\t\tc: AnyContext,\n\t\t\tmodule: string,\n\t\t\tactorOptions?: ActorLanguageExecutionOptions,\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.python.executeModule(\n\t\t\t\t\t\tmodule,\n\t\t\t\t\t\t...(actorExecutionArgs([actorOptions]) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tspawnPython: async (\n\t\t\tc: AnyContext,\n\t\t\tsource: string,\n\t\t\tactorOptions?: ActorLanguageSpawnOptions,\n\t\t) =>\n\t\t\trunActorSpawn(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.python.spawn(source, ...(actorSpawnArgs(actorOptions) as [never])),\n\t\t\t\toptions,\n\t\t\t),\n\t\tspawnPythonFile: async (\n\t\t\tc: AnyContext,\n\t\t\tpath: string,\n\t\t\tactorOptions?: ActorLanguageSpawnOptions,\n\t\t) =>\n\t\t\trunActorSpawn(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.python.spawnFile(\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\t...(actorSpawnArgs(actorOptions) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tspawnPythonModule: async (\n\t\t\tc: AnyContext,\n\t\t\tmodule: string,\n\t\t\tactorOptions?: ActorLanguageSpawnOptions,\n\t\t) =>\n\t\t\trunActorSpawn(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\tvm.python.spawnModule(\n\t\t\t\t\t\tmodule,\n\t\t\t\t\t\t...(actorSpawnArgs(actorOptions) as [never]),\n\t\t\t\t\t),\n\t\t\t\toptions,\n\t\t\t),\n\t\tinstallPythonPackages: async (\n\t\t\tc: AnyContext,\n\t\t\t...args:\n\t\t\t\t| [options?: ActorPythonInstallOptions]\n\t\t\t\t| [packages: string | string[], options?: ActorPythonInstallOptions]\n\t\t) =>\n\t\t\trunActorExecution(\n\t\t\t\tc,\n\t\t\t\t(vm) =>\n\t\t\t\t\t(\n\t\t\t\t\t\tvm.python.install as (\n\t\t\t\t\t\t\t...callArgs: unknown[]\n\t\t\t\t\t\t) => Promise<CodeExecutionResult>\n\t\t\t\t\t)(...actorExecutionArgs(args)),\n\t\t\t\toptions,\n\t\t\t),\n\t\tgetContext: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"contexts\"][\"get\"]>\n\t\t) => (await ensureVm(c, options)).contexts.get(...args),\n\t\tlistContexts: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).contexts.list(),\n\t\tresetContext: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"contexts\"][\"reset\"]>\n\t\t) => (await ensureVm(c, options)).contexts.reset(...args),\n\t\tdeleteContext: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"contexts\"][\"delete\"]>\n\t\t) => (await ensureVm(c, options)).contexts.delete(...args),\n\t\twaitProcess: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"process\"][\"wait\"]>\n\t\t) => (await ensureVm(c, options)).process.wait(...args),\n\t\tkillProcess: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"process\"][\"kill\"]>\n\t\t) => (await ensureVm(c, options)).process.kill(...args),\n\t\tsignalProcess: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"process\"][\"signal\"]>\n\t\t) => (await ensureVm(c, options)).process.signal(...args),\n\t\tlistProcesses: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).process.list(),\n\t\tprocessTree: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).process.tree(),\n\t\tgetProcess: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"process\"][\"get\"]>\n\t\t) => (await ensureVm(c, options)).process.get(...args),\n\t\twriteProcessStdin: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"process\"][\"writeStdin\"]>\n\t\t) => (await ensureVm(c, options)).process.writeStdin(...args),\n\t\tcloseProcessStdin: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"process\"][\"closeStdin\"]>\n\t\t) => (await ensureVm(c, options)).process.closeStdin(...args),\n\t\tresizeProcessPty: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"process\"][\"resizePty\"]>\n\t\t) => (await ensureVm(c, options)).process.resizePty(...args),\n\t\treadProcessOutput: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"process\"][\"readOutput\"]>\n\t\t) => {\n\t\t\tconst replay = await (await ensureVm(c, options)).process.readOutput(\n\t\t\t\t...args,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\t...replay,\n\t\t\t\tevents: replay.events.map((event) => ({\n\t\t\t\t\t...event,\n\t\t\t\t\tchunk: {\n\t\t\t\t\t\tencoding: \"base64\" as const,\n\t\t\t\t\t\tdata: Buffer.from(event.chunk).toString(\"base64\"),\n\t\t\t\t\t},\n\t\t\t\t})),\n\t\t\t};\n\t\t},\n\t\topenShell: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"terminal\"][\"open\"]>\n\t\t) => {\n\t\t\tconst vm = await ensureVm(c, options);\n\t\t\tconst runtime = runtimeFor(c);\n\t\t\tif (runtime.openShells.size >= MAX_OPEN_SHELLS) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`agent-os shell limit reached (${MAX_OPEN_SHELLS} open); close a shell or raise MAX_OPEN_SHELLS`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Warm the emulator module before the PTY exists: from `terminal.open`\n\t\t\t// to the subscription below, nothing may await, or the output produced\n\t\t\t// in that window is lost to every consumer.\n\t\t\tawait runtime.shellReplay.warm();\n\t\t\tconst shell = vm.terminal.open(...args);\n\t\t\truntime.openShells.set(shell.shellId, { openedAt: Date.now() });\n\t\t\truntime.shellReplay.open(shell.shellId, args[0]?.cols, args[0]?.rows);\n\t\t\tconst unsubscribeData = vm.onShellData(shell.shellId, (event) =>\n\t\t\t\tc.broadcast(\"shellData\", {\n\t\t\t\t\t...event,\n\t\t\t\t\tseq: runtime.shellReplay.feed(event.shellId, event.data),\n\t\t\t\t}),\n\t\t\t);\n\t\t\tconst unsubscribeStderr = vm.onShellStderr(shell.shellId, (event) =>\n\t\t\t\t// A diagnostic tap carrying bytes `shellData` already delivered, so\n\t\t\t\t// it is never folded into replay and carries no sequence.\n\t\t\t\tc.broadcast(\"shellStderr\", { ...event, seq: 0 }),\n\t\t\t);\n\t\t\tconst unsubscribeExit = vm.onShellExit(shell.shellId, (event) =>\n\t\t\t\tc.broadcast(\"shellExit\", event),\n\t\t\t);\n\t\t\tvoid c\n\t\t\t\t.keepAwake(\n\t\t\t\t\tvm.terminal.wait(shell.shellId).finally(() => {\n\t\t\t\t\t\truntime.openShells.delete(shell.shellId);\n\t\t\t\t\t\truntime.shellReplay.close(shell.shellId);\n\t\t\t\t\t\tunsubscribeData();\n\t\t\t\t\t\tunsubscribeStderr();\n\t\t\t\t\t\tunsubscribeExit();\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.catch((error) =>\n\t\t\t\t\tc.log.error({\n\t\t\t\t\t\tmsg: \"agent-os shell wait failed\",\n\t\t\t\t\t\tshellId: shell.shellId,\n\t\t\t\t\t\terror,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\treturn shell;\n\t\t},\n\t\t// Observe-only: enumerates shells this actor opened without booting a\n\t\t// sleeping VM (a sleeping VM has none). Clients must not track shell ids\n\t\t// themselves — a shell outlives the page that opened it and keeps the VM\n\t\t// awake, so it has to stay discoverable.\n\t\tlistShells: async (c: AnyContext): Promise<ShellInfo[]> => {\n\t\t\tconst runtime = runtimes.get(c.actorId);\n\t\t\tif (!runtime?.bootedVm) return [];\n\t\t\treturn [...runtime.openShells.entries()]\n\t\t\t\t.map(([shellId, entry]) => ({ shellId, openedAt: entry.openedAt }))\n\t\t\t\t.sort((a, b) => a.openedAt - b.openedAt);\n\t\t},\n\t\twriteShell: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"terminal\"][\"write\"]>\n\t\t) => (await ensureVm(c, options)).terminal.write(...args),\n\t\tresizeShell: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"terminal\"][\"resize\"]>\n\t\t) => {\n\t\t\tconst result = (await ensureVm(c, options)).terminal.resize(...args);\n\t\t\truntimeFor(c).shellReplay.resize(args[0], args[1], args[2]);\n\t\t\treturn result;\n\t\t},\n\t\t// Observe-only, like `listShells`: repainting a shell must never boot a\n\t\t// VM, and a sleeping VM has no live shells to repaint. Returns `null`\n\t\t// for an unknown shell so a client falls back to no replay.\n\t\tshellSnapshot: async (\n\t\t\tc: AnyContext,\n\t\t\tshellId: string,\n\t\t\tmode: ShellReplayMode = \"screen\",\n\t\t): Promise<ShellSnapshot | null> => {\n\t\t\tconst runtime = runtimes.get(c.actorId);\n\t\t\tif (!runtime?.bootedVm) return null;\n\t\t\treturn runtime.shellReplay.snapshot(shellId, mode);\n\t\t},\n\t\tcloseShell: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"terminal\"][\"close\"]>\n\t\t) => (await ensureVm(c, options)).terminal.close(...args),\n\t\twaitShell: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"terminal\"][\"wait\"]>\n\t\t) => (await ensureVm(c, options)).terminal.wait(...args),\n\t\thttpRequest: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"network\"][\"httpRequest\"]>\n\t\t) => (await ensureVm(c, options)).network.httpRequest(...args),\n\t\tvmFetch: async (\n\t\t\tc: AnyContext,\n\t\t\tport: number,\n\t\t\turl: string,\n\t\t\trequestOptions?: VmFetchOptions,\n\t\t): Promise<VmFetchResponse> => {\n\t\t\tconst vm = await ensureVm(c, options);\n\t\t\tconst body =\n\t\t\t\trequestOptions?.body instanceof Uint8Array\n\t\t\t\t\t? Buffer.from(requestOptions.body)\n\t\t\t\t\t: requestOptions?.body;\n\t\t\tconst response = await vm.fetch(\n\t\t\t\tport,\n\t\t\t\tnew Request(url, {\n\t\t\t\t\tmethod: requestOptions?.method ?? \"GET\",\n\t\t\t\t\theaders: requestOptions?.headers,\n\t\t\t\t\tbody,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tconst headers: Record<string, string> = {};\n\t\t\tconst rawHeaders: Array<[string, string]> = [];\n\t\t\tresponse.headers.forEach((value, key) => {\n\t\t\t\theaders[key] = value;\n\t\t\t\tif (key !== \"set-cookie\") rawHeaders.push([key, value]);\n\t\t\t});\n\t\t\tfor (const value of response.headers.getSetCookie?.() ?? []) {\n\t\t\t\trawHeaders.push([\"set-cookie\", value]);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstatus: response.status,\n\t\t\t\tstatusText: response.statusText,\n\t\t\t\theaders,\n\t\t\t\trawHeaders,\n\t\t\t\tbody: new Uint8Array(await response.arrayBuffer()),\n\t\t\t};\n\t\t},\n\t\tvmFetchStreamStart: async (\n\t\t\tc: AnyContext,\n\t\t\tport: number,\n\t\t\turl: string,\n\t\t\trequestOptions?: VmFetchOptions,\n\t\t): Promise<VmFetchStreamHead> => {\n\t\t\tconst vm = await ensureVm(c, options);\n\t\t\tconst body =\n\t\t\t\trequestOptions?.body instanceof Uint8Array\n\t\t\t\t\t? Buffer.from(requestOptions.body)\n\t\t\t\t\t: requestOptions?.body;\n\t\t\tconst head = await vm.fetchStreamStart(\n\t\t\t\tport,\n\t\t\t\tnew Request(url, {\n\t\t\t\t\tmethod: requestOptions?.method ?? \"GET\",\n\t\t\t\t\theaders: requestOptions?.headers,\n\t\t\t\t\tbody,\n\t\t\t\t}),\n\t\t\t);\n\t\t\ttrackFetchStream(c, head.streamId);\n\t\t\tconst headers: Record<string, string> = {};\n\t\t\tfor (const [name, value] of head.headers) headers[name] = value;\n\t\t\treturn { ...head, headers, rawHeaders: head.headers };\n\t\t},\n\t\tvmFetchStreamRead: async (\n\t\t\tc: AnyContext,\n\t\t\tstreamId: string,\n\t\t\tmaxBytes?: number,\n\t\t): Promise<VmFetchStreamChunk> => {\n\t\t\ttry {\n\t\t\t\tconst chunk = await (await ensureVm(c, options)).fetchStreamRead(\n\t\t\t\t\tstreamId,\n\t\t\t\t\tmaxBytes,\n\t\t\t\t);\n\t\t\t\tif (chunk.done) releaseFetchStream(c, streamId);\n\t\t\t\treturn chunk;\n\t\t\t} catch (error) {\n\t\t\t\treleaseFetchStream(c, streamId);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tvmFetchStreamCancel: async (c: AnyContext, streamId: string) => {\n\t\t\ttry {\n\t\t\t\tawait (await ensureVm(c, options)).fetchStreamCancel(streamId);\n\t\t\t} finally {\n\t\t\t\treleaseFetchStream(c, streamId);\n\t\t\t}\n\t\t},\n\t\tscheduleCron: async (\n\t\t\tc: AnyContext,\n\t\t\tcronOptions: SerializableCronJobOptions,\n\t\t) => {\n\t\t\tconst job = (await ensureVm(c, options)).cron.schedule(\n\t\t\t\tcronOptions as Parameters<AgentOs[\"cron\"][\"schedule\"]>[0],\n\t\t\t);\n\t\t\treturn { id: job.id };\n\t\t},\n\t\tlistCronJobs: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).cron.list(),\n\t\tcancelCronJob: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"cron\"][\"cancel\"]>\n\t\t) => (await ensureVm(c, options)).cron.cancel(...args),\n\t\tlistAgents: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).agents.list(),\n\t\t// Observe-only: reports VM liveness and the post-mortem buffers without\n\t\t// ever booting the VM (deliberately no ensureVm).\n\t\thealth: async (c: AnyContext): Promise<RuntimeHealth> => {\n\t\t\tconst runtime = runtimes.get(c.actorId);\n\t\t\tconst buffers = healthBuffersFor(c.actorId);\n\t\t\tlet booted = false;\n\t\t\tlet sessions: number | null = null;\n\t\t\tlet sidecar: RuntimeHealth[\"sidecar\"] = null;\n\t\t\t// Read the settled VM synchronously: a VM still booting (or one whose\n\t\t\t// boot failed) reports not-booted rather than blocking the\n\t\t\t// observe-only action.\n\t\t\tconst vm = runtime?.bootedVm;\n\t\t\tif (runtime && vm) {\n\t\t\t\tbooted = true;\n\t\t\t\tsessions = runtime.subscribedSessions.size;\n\t\t\t\tconst description = vm.sidecar.describe();\n\t\t\t\tsidecar = {\n\t\t\t\t\tstate: description.state,\n\t\t\t\t\tactiveVmCount: description.activeVmCount,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tbooted,\n\t\t\t\tsessions,\n\t\t\t\tsidecar,\n\t\t\t\twarnings: [...buffers.warnings],\n\t\t\t\tagentExits: [...buffers.agentExits],\n\t\t\t\tstderrTail: [],\n\t\t\t};\n\t\t},\n\t\topenSession: async (c: AnyContext, input: OpenSessionInput) => {\n\t\t\tconst vm = await ensureVm(c, options);\n\t\t\ttry {\n\t\t\t\tawait vm.sessions.open(input);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tconst causeCode =\n\t\t\t\t\ttypeof (error as { code?: unknown })?.code === \"string\"\n\t\t\t\t\t\t? (error as { code: string }).code\n\t\t\t\t\t\t: undefined;\n\t\t\t\tc.log.error({\n\t\t\t\t\tmsg: \"agent-os openSession action failed\",\n\t\t\t\t\tsessionId: input.sessionId ?? \"main\",\n\t\t\t\t\tagent: input.agent,\n\t\t\t\t\tcauseCode,\n\t\t\t\t\terror,\n\t\t\t\t});\n\t\t\t\tthrow new UserError(`AgentOS openSession failed: ${message}`, {\n\t\t\t\t\tcode: \"agentos_session_open_failed\",\n\t\t\t\t\tmetadata: causeCode ? { causeCode } : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t\ttrackSessionEvents(\n\t\t\t\tc,\n\t\t\t\tvm,\n\t\t\t\tinput.sessionId ?? \"main\",\n\t\t\t\thooks,\n\t\t\t\tmaxSessionSubscriptions,\n\t\t\t);\n\t\t},\n\t\tgetSession: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"sessions\"][\"get\"]>\n\t\t) => (await ensureVm(c, options)).sessions.get(...args),\n\t\tlistSessions: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"sessions\"][\"list\"]>\n\t\t) => (await ensureVm(c, options)).sessions.list(...args),\n\t\tdeleteSession: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"sessions\"][\"delete\"]>\n\t\t) => {\n\t\t\tconst result = await (await ensureVm(c, options)).sessions.delete(\n\t\t\t\t...args,\n\t\t\t);\n\t\t\tuntrackSessionEvents(c, args[0]?.sessionId ?? \"main\");\n\t\t\treturn result;\n\t\t},\n\t\tunloadSession: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"sessions\"][\"unload\"]>\n\t\t) => {\n\t\t\tconst result = await (await ensureVm(c, options)).sessions.unload(\n\t\t\t\t...args,\n\t\t\t);\n\t\t\tuntrackSessionEvents(c, args[0]?.sessionId ?? \"main\");\n\t\t\treturn result;\n\t\t},\n\t\tprompt: async (c: AnyContext, input: PromptInput) => {\n\t\t\tconst vm = await ensureVm(c, options);\n\t\t\tconst sessionId = input.sessionId ?? \"main\";\n\t\t\ttrackSessionEvents(c, vm, sessionId, hooks, maxSessionSubscriptions);\n\t\t\t// The actor is held only through the terminal SQLite commit for this\n\t\t\t// active turn. Merely having an idle durable session holds nothing.\n\t\t\ttry {\n\t\t\t\treturn await c.keepAwake(vm.sessions.prompt(input));\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tconst causeCode =\n\t\t\t\t\ttypeof (error as { code?: unknown })?.code === \"string\"\n\t\t\t\t\t\t? (error as { code: string }).code\n\t\t\t\t\t\t: undefined;\n\t\t\t\tc.log.error({\n\t\t\t\t\tmsg: \"agent-os prompt action failed\",\n\t\t\t\t\tsessionId,\n\t\t\t\t\tcauseCode,\n\t\t\t\t\terror,\n\t\t\t\t});\n\t\t\t\tthrow new UserError(`AgentOS prompt failed: ${message}`, {\n\t\t\t\t\tcode: \"agentos_prompt_failed\",\n\t\t\t\t\tmetadata: causeCode ? { causeCode } : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\tcancelPrompt: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"sessions\"][\"cancelPrompt\"]>\n\t\t) => (await ensureVm(c, options)).sessions.cancelPrompt(...args),\n\t\trespondPermission: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"sessions\"][\"respondPermission\"]>\n\t\t) => (await ensureVm(c, options)).sessions.respondPermission(...args),\n\t\treadHistory: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"sessions\"][\"readHistory\"]>\n\t\t) => (await ensureVm(c, options)).sessions.readHistory(...args),\n\t\tgetSessionConfig: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"sessions\"][\"getConfig\"]>\n\t\t) => (await ensureVm(c, options)).sessions.getConfig(...args),\n\t\tsetSessionConfigOption: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"sessions\"][\"setConfigOption\"]>\n\t\t) => (await ensureVm(c, options)).sessions.setConfigOption(...args),\n\t\tgetSessionCapabilities: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"sessions\"][\"getCapabilities\"]>\n\t\t) => (await ensureVm(c, options)).sessions.getCapabilities(...args),\n\t\tgetSessionAgentInfo: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"sessions\"][\"getAgentInfo\"]>\n\t\t) => (await ensureVm(c, options)).sessions.getAgentInfo(...args),\n\t\tcreatePreviewUrl: async (\n\t\t\tc: AnyContext,\n\t\t\tport: number,\n\t\t\tttlSeconds = defaultPreviewTtlSeconds,\n\t\t) => {\n\t\t\tif (!Number.isInteger(port) || port < 1 || port > 65_535)\n\t\t\t\tthrow new UserError(\n\t\t\t\t\t\"port must be an integer between 1 and 65535; pass a valid VM listener port\",\n\t\t\t\t\t{ code: \"agentos_preview_invalid_port\" },\n\t\t\t\t);\n\t\t\tif (\n\t\t\t\t!Number.isFinite(ttlSeconds) ||\n\t\t\t\tttlSeconds <= 0 ||\n\t\t\t\tttlSeconds > maxPreviewTtlSeconds\n\t\t\t)\n\t\t\t\tthrow new UserError(\n\t\t\t\t\t`ttlSeconds must be greater than 0 and at most ${maxPreviewTtlSeconds}; raise preview.maxExpiresInSeconds to allow a longer lifetime`,\n\t\t\t\t\t{ code: \"agentos_preview_invalid_ttl\" },\n\t\t\t\t);\n\t\t\tconst token = crypto.randomBytes(24).toString(\"hex\");\n\t\t\tconst createdAt = Date.now();\n\t\t\tconst expiresAt = createdAt + ttlSeconds * 1_000;\n\t\t\tawait c.db.execute(\n\t\t\t\t\"DELETE FROM agentos_actor_preview_tokens WHERE expires_at_ms <= ?\",\n\t\t\t\tcreatedAt,\n\t\t\t);\n\t\t\tconst counts = await c.db.execute<{ count: number }>(\n\t\t\t\t\"SELECT COUNT(*) AS count FROM agentos_actor_preview_tokens\",\n\t\t\t);\n\t\t\tconst activeTokenCount = Number(counts[0]?.count ?? 0);\n\t\t\tif (activeTokenCount >= maxActivePreviewTokens) {\n\t\t\t\tthrow new UserError(\n\t\t\t\t\t`preview token limit ${maxActivePreviewTokens} reached; raise preview.maxActiveTokens to allow more`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"agentos_preview_token_limit\",\n\t\t\t\t\t\tmetadata: { limit: maxActivePreviewTokens },\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst nextActiveTokenCount = activeTokenCount + 1;\n\t\t\tconst warningThreshold = Math.ceil(maxActivePreviewTokens * 0.8);\n\t\t\tif (nextActiveTokenCount === warningThreshold) {\n\t\t\t\tc.log.warn({\n\t\t\t\t\tmsg: `preview tokens are near the limit of ${maxActivePreviewTokens}; raise preview.maxActiveTokens to allow more`,\n\t\t\t\t\tactiveTokenCount: nextActiveTokenCount,\n\t\t\t\t\tlimit: maxActivePreviewTokens,\n\t\t\t\t});\n\t\t\t}\n\t\t\tawait c.db.execute(\n\t\t\t\t\"INSERT INTO agentos_actor_preview_tokens (token, port, created_at_ms, expires_at_ms) VALUES (?, ?, ?, ?)\",\n\t\t\t\ttoken,\n\t\t\t\tport,\n\t\t\t\tcreatedAt,\n\t\t\t\texpiresAt,\n\t\t\t);\n\t\t\treturn { path: `/fetch/${token}`, token, port, expiresAt };\n\t\t},\n\t\texpirePreviewUrl: async (c: AnyContext, token: string) => {\n\t\t\tawait c.db.execute(\n\t\t\t\t\"DELETE FROM agentos_actor_preview_tokens WHERE token = ?\",\n\t\t\t\ttoken,\n\t\t\t);\n\t\t},\n\t\texportRootFilesystem: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"filesystem\"][\"export\"]>\n\t\t) => (await ensureVm(c, options)).filesystem.export(...args),\n\t\tmountFs: async (c: AnyContext, descriptor: DynamicMountDescriptor) => {\n\t\t\tawait assertActorCollectionCapacity(\n\t\t\t\tc,\n\t\t\t\t\"agentos_actor_dynamic_mounts\",\n\t\t\t\tdescriptor.path,\n\t\t\t\tmaxDynamicMounts,\n\t\t\t\t\"dynamic mounts\",\n\t\t\t\t\"maxDynamicMounts\",\n\t\t\t);\n\t\t\tconst vm = await ensureVm(c, options);\n\t\t\tawait vm.filesystem.mount(descriptor);\n\t\t\ttry {\n\t\t\t\tawait c.db.execute(\n\t\t\t\t\t\"INSERT INTO agentos_actor_dynamic_mounts (path, descriptor_json) VALUES (?, ?) ON CONFLICT(path) DO UPDATE SET descriptor_json = excluded.descriptor_json\",\n\t\t\t\t\tdescriptor.path,\n\t\t\t\t\tJSON.stringify(descriptor),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait vm.filesystem.unmount(descriptor.path);\n\t\t\t\t} catch (rollbackError) {\n\t\t\t\t\tc.log.error({\n\t\t\t\t\t\tmsg: \"agent-os dynamic mount rollback failed\",\n\t\t\t\t\t\tpath: descriptor.path,\n\t\t\t\t\t\terror: rollbackError,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tunmountFs: async (c: AnyContext, path: string) => {\n\t\t\tconst rows = await c.db.execute<{ descriptor_json: string }>(\n\t\t\t\t\"SELECT descriptor_json FROM agentos_actor_dynamic_mounts WHERE path = ?\",\n\t\t\t\tpath,\n\t\t\t);\n\t\t\tconst vm = await ensureVm(c, options);\n\t\t\tawait vm.filesystem.unmount(path);\n\t\t\ttry {\n\t\t\t\tawait c.db.execute(\n\t\t\t\t\t\"DELETE FROM agentos_actor_dynamic_mounts WHERE path = ?\",\n\t\t\t\t\tpath,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (rows[0]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait vm.filesystem.mount(\n\t\t\t\t\t\t\tJSON.parse(rows[0].descriptor_json) as DynamicMountDescriptor,\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (rollbackError) {\n\t\t\t\t\t\tc.log.error({\n\t\t\t\t\t\t\tmsg: \"agent-os dynamic unmount rollback failed\",\n\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\terror: rollbackError,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tlistMounts: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).filesystem.listMounts(),\n\t\tlistSoftware: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).software.list(),\n\t\tlinkSoftware: async (c: AnyContext, descriptor: PackageDescriptor) => {\n\t\t\tawait assertActorCollectionCapacity(\n\t\t\t\tc,\n\t\t\t\t\"agentos_actor_linked_software\",\n\t\t\t\tdescriptor.path,\n\t\t\t\tmaxLinkedSoftware,\n\t\t\t\t\"linked software packages\",\n\t\t\t\t\"maxLinkedSoftware\",\n\t\t\t);\n\t\t\tawait c.db.execute(\n\t\t\t\t\"INSERT INTO agentos_actor_linked_software (path, descriptor_json) VALUES (?, ?) ON CONFLICT(path) DO UPDATE SET descriptor_json = excluded.descriptor_json\",\n\t\t\t\tdescriptor.path,\n\t\t\t\tJSON.stringify(descriptor),\n\t\t\t);\n\t\t\ttry {\n\t\t\t\tawait (await ensureVm(c, options)).software.link(descriptor);\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait c.db.execute(\n\t\t\t\t\t\t\"DELETE FROM agentos_actor_linked_software WHERE path = ?\",\n\t\t\t\t\t\tdescriptor.path,\n\t\t\t\t\t);\n\t\t\t\t} catch (rollbackError) {\n\t\t\t\t\tc.log.error({\n\t\t\t\t\t\tmsg: \"agent-os linked software rollback failed\",\n\t\t\t\t\t\tpath: descriptor.path,\n\t\t\t\t\t\terror: rollbackError,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n\n\tconst nested = {\n\t\tcreateContext: flat.createContext,\n\t\tprocess: {\n\t\t\texec: flat.exec,\n\t\t\texecFile: flat.execArgv,\n\t\t\tspawn: flat.spawn,\n\t\t\tget: flat.getProcess,\n\t\t\tlist: flat.listProcesses,\n\t\t\ttree: flat.processTree,\n\t\t\twait: flat.waitProcess,\n\t\t\tsignal: flat.signalProcess,\n\t\t\tkill: flat.killProcess,\n\t\t\twriteStdin: flat.writeProcessStdin,\n\t\t\tcloseStdin: flat.closeProcessStdin,\n\t\t\tresizePty: flat.resizeProcessPty,\n\t\t\treadOutput: flat.readProcessOutput,\n\t\t},\n\t\tjavascript: {\n\t\t\texecute: flat.executeJavaScript,\n\t\t\tevaluate: flat.evaluateJavaScript,\n\t\t\texecuteFile: flat.executeJavaScriptFile,\n\t\t\tspawn: flat.spawnJavaScript,\n\t\t\tspawnFile: flat.spawnJavaScriptFile,\n\t\t\tnpm: {\n\t\t\t\tinstall: flat.installNpmPackages,\n\t\t\t\trunScript: flat.executeNpmScript,\n\t\t\t\trunPackage: flat.executeNpmPackage,\n\t\t\t},\n\t\t},\n\t\ttypescript: {\n\t\t\texecute: flat.executeTypeScript,\n\t\t\tevaluate: flat.evaluateTypeScript,\n\t\t\texecuteFile: flat.executeTypeScriptFile,\n\t\t\tspawn: flat.spawnTypeScript,\n\t\t\tspawnFile: flat.spawnTypeScriptFile,\n\t\t\tcheck: flat.checkTypeScript,\n\t\t\tcheckProject: flat.checkTypeScriptProject,\n\t\t},\n\t\tpython: {\n\t\t\texecute: flat.executePython,\n\t\t\tevaluate: flat.evaluatePython,\n\t\t\texecuteFile: flat.executePythonFile,\n\t\t\texecuteModule: flat.executePythonModule,\n\t\t\tspawn: flat.spawnPython,\n\t\t\tspawnFile: flat.spawnPythonFile,\n\t\t\tspawnModule: flat.spawnPythonModule,\n\t\t\tinstall: flat.installPythonPackages,\n\t\t},\n\t\tcontexts: {\n\t\t\tget: flat.getContext,\n\t\t\tlist: flat.listContexts,\n\t\t\treset: flat.resetContext,\n\t\t\tdelete: flat.deleteContext,\n\t\t},\n\t\tterminal: {\n\t\t\topen: flat.openShell,\n\t\t\tlist: flat.listShells,\n\t\t\tsnapshot: flat.shellSnapshot,\n\t\t\twrite: flat.writeShell,\n\t\t\tresize: flat.resizeShell,\n\t\t\twait: flat.waitShell,\n\t\t\tclose: flat.closeShell,\n\t\t},\n\t\tfilesystem: {\n\t\t\treadFile: flat.readFile,\n\t\t\twriteFile: flat.writeFile,\n\t\t\treadFiles: flat.readFiles,\n\t\t\twriteFiles: flat.writeFiles,\n\t\t\tstat: flat.stat,\n\t\t\tmkdir: flat.mkdir,\n\t\t\treaddir: flat.readdir,\n\t\t\treaddirEntries: flat.readdirEntries,\n\t\t\treaddirRecursive: flat.readdirRecursive,\n\t\t\texists: flat.exists,\n\t\t\tmove: flat.move,\n\t\t\tremove: flat.remove,\n\t\t\texport: flat.exportRootFilesystem,\n\t\t\tmount: flat.mountFs,\n\t\t\tunmount: flat.unmountFs,\n\t\t\tlistMounts: flat.listMounts,\n\t\t},\n\t\tnetwork: {\n\t\t\thttpRequest: flat.httpRequest,\n\t\t},\n\t\tsoftware: {\n\t\t\tlist: flat.listSoftware,\n\t\t\tlink: flat.linkSoftware,\n\t\t},\n\t\tagents: {\n\t\t\tlist: flat.listAgents,\n\t\t},\n\t\tsessions: {\n\t\t\topen: flat.openSession,\n\t\t\tget: flat.getSession,\n\t\t\tlist: flat.listSessions,\n\t\t\tdelete: flat.deleteSession,\n\t\t\tunload: flat.unloadSession,\n\t\t\tprompt: flat.prompt,\n\t\t\tcancelPrompt: flat.cancelPrompt,\n\t\t\trespondPermission: flat.respondPermission,\n\t\t\treadHistory: flat.readHistory,\n\t\t\tgetConfig: flat.getSessionConfig,\n\t\t\tsetConfigOption: flat.setSessionConfigOption,\n\t\t\tgetCapabilities: flat.getSessionCapabilities,\n\t\t\tgetAgentInfo: flat.getSessionAgentInfo,\n\t\t},\n\t\tcron: {\n\t\t\tschedule: flat.scheduleCron,\n\t\t\tlist: flat.listCronJobs,\n\t\t\tcancel: flat.cancelCronJob,\n\t\t},\n\t};\n\n\treturn {\n\t\t...nested,\n\n\t\t// Legacy flat actions from the pre-language-execution API. Keep these\n\t\t// as aliases to the canonical nested handlers.\n\t\treadFile: nested.filesystem.readFile,\n\t\twriteFile: nested.filesystem.writeFile,\n\t\treadFiles: nested.filesystem.readFiles,\n\t\twriteFiles: nested.filesystem.writeFiles,\n\t\tstat: nested.filesystem.stat,\n\t\tmkdir: nested.filesystem.mkdir,\n\t\treaddir: nested.filesystem.readdir,\n\t\treaddirEntries: nested.filesystem.readdirEntries,\n\t\treaddirRecursive: nested.filesystem.readdirRecursive,\n\t\texists: nested.filesystem.exists,\n\t\tmove: nested.filesystem.move,\n\t\tremove: nested.filesystem.remove,\n\t\texportRootFilesystem: nested.filesystem.export,\n\t\tmountFs: nested.filesystem.mount,\n\t\tunmountFs: nested.filesystem.unmount,\n\t\tlistMounts: nested.filesystem.listMounts,\n\t\texec: async (c: AnyContext, ...args: Parameters<AgentOs[\"exec\"]>) =>\n\t\t\t(await ensureVm(c, options)).exec(...args),\n\t\texecArgv: async (c: AnyContext, ...args: Parameters<AgentOs[\"execArgv\"]>) =>\n\t\t\t(await ensureVm(c, options)).execArgv(...args),\n\t\tspawn: nested.process.spawn,\n\t\twaitProcess: nested.process.wait,\n\t\tkillProcess: nested.process.kill,\n\t\tlistProcesses: nested.process.list,\n\t\tprocessTree: nested.process.tree,\n\t\tgetProcess: nested.process.get,\n\t\twriteProcessStdin: nested.process.writeStdin,\n\t\tcloseProcessStdin: nested.process.closeStdin,\n\t\topenShell: nested.terminal.open,\n\t\tlistShells: nested.terminal.list,\n\t\tshellSnapshot: nested.terminal.snapshot,\n\t\twriteShell: nested.terminal.write,\n\t\tresizeShell: nested.terminal.resize,\n\t\tcloseShell: nested.terminal.close,\n\t\twaitShell: nested.terminal.wait,\n\t\thttpRequest: nested.network.httpRequest,\n\t\tvmFetch: flat.vmFetch,\n\t\tvmFetchStreamStart: flat.vmFetchStreamStart,\n\t\tvmFetchStreamRead: flat.vmFetchStreamRead,\n\t\tvmFetchStreamCancel: flat.vmFetchStreamCancel,\n\t\tscheduleCron: nested.cron.schedule,\n\t\tlistCronJobs: nested.cron.list,\n\t\tcancelCronJob: nested.cron.cancel,\n\t\tlistAgents: nested.agents.list,\n\t\topenSession: nested.sessions.open,\n\t\tgetSession: nested.sessions.get,\n\t\tlistSessions: nested.sessions.list,\n\t\tdeleteSession: nested.sessions.delete,\n\t\tunloadSession: nested.sessions.unload,\n\t\tprompt: nested.sessions.prompt,\n\t\tcancelPrompt: nested.sessions.cancelPrompt,\n\t\trespondPermission: nested.sessions.respondPermission,\n\t\treadHistory: nested.sessions.readHistory,\n\t\tgetSessionConfig: nested.sessions.getConfig,\n\t\tsetSessionConfigOption: nested.sessions.setConfigOption,\n\t\tgetSessionCapabilities: nested.sessions.getCapabilities,\n\t\tgetSessionAgentInfo: nested.sessions.getAgentInfo,\n\t\tlistSoftware: nested.software.list,\n\t\tlinkSoftware: nested.software.link,\n\n\t\t// Preview URLs are RivetKit-specific and intentionally stay flat.\n\t\tcreatePreviewUrl: flat.createPreviewUrl,\n\t\texpirePreviewUrl: flat.expirePreviewUrl,\n\t\t// Observe-only runtime health, also RivetKit-specific.\n\t\thealth: flat.health,\n\t};\n}\n\nexport type AgentOsActions = ReturnType<typeof createAgentOsActions>;\nexport type AgentOsActorDefinition<TConnParams = undefined> = ActorDefinition<\n\tundefined,\n\tTConnParams,\n\tundefined,\n\tundefined,\n\tundefined,\n\tActorDb,\n\tBuiltInEvents,\n\tRecord<never, never>,\n\tAgentOsActions\n>;\n\nexport interface AgentOsActorExtras extends AgentOsOptions {\n\t/**\n\t * Resolve trusted VM options from actor state immediately before the VM's\n\t * first boot. Evaluated once per wake. The actor-owned root filesystem and\n\t * database cannot be replaced.\n\t */\n\tresolveOptions?: (c: AnyContext) => AgentOsOptions | Promise<AgentOsOptions>;\n\t/** Start long-lived processes after each VM boot. Trusted host code only. */\n\tonVmStart?: (c: AnyContext, vm: AgentOs) => void | Promise<void>;\n\t/** Gracefully stop long-lived processes before the VM is disposed. */\n\tonVmStop?: (\n\t\tc: AnyContext,\n\t\tvm: AgentOs,\n\t\treason: \"sleep\" | \"destroy\" | \"error\",\n\t) => void | Promise<void>;\n\t/** Clean up host resources after the VM and lazy mount readers close. */\n\tonVmDisposed?: (\n\t\tc: AnyContext,\n\t\treason: \"sleep\" | \"destroy\" | \"error\",\n\t) => void | Promise<void>;\n\t/** Maximum live session event subscriptions per actor VM. Default: 10,000. */\n\tmaxSessionSubscriptions?: number;\n\t/** Maximum durable dynamic mount descriptors per actor. Default: 10,000. */\n\tmaxDynamicMounts?: number;\n\t/** Maximum durable linked software descriptors per actor. Default: 10,000. */\n\tmaxLinkedSoftware?: number;\n\tpreview?: {\n\t\tdefaultExpiresInSeconds?: number;\n\t\tmaxExpiresInSeconds?: number;\n\t\tmaxActiveTokens?: number;\n\t};\n}\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n\t? Omit<T, K>\n\t: never;\n\nexport type AgentOsActorConfigInput<\n\tTState = undefined,\n\tTConnParams = undefined,\n\tTConnState = undefined,\n\tTVars = undefined,\n\tTInput = undefined,\n\tTEvents extends EventSchemaConfig = Record<never, never>,\n\tTQueues extends QueueSchemaConfig = Record<never, never>,\n\tTUserActions extends Actions<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tActorDb,\n\t\tTEvents,\n\t\tTQueues\n\t> = Record<never, never>,\n> = DistributiveOmit<\n\tActorConfigInput<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tActorDb,\n\t\tTEvents,\n\t\tTQueues,\n\t\tTUserActions\n\t>,\n\t\"db\"\n> &\n\tAgentOsActorExtras &\n\tAgentOsEventHooks<\n\t\tActorContext<\n\t\t\tTState,\n\t\t\tTConnParams,\n\t\t\tTConnState,\n\t\t\tTVars,\n\t\t\tTInput,\n\t\t\tActorDb,\n\t\t\tTEvents,\n\t\t\tTQueues\n\t\t>\n\t>;\n\nconst agentOsOptionKeys = [\n\t\"software\",\n\t\"defaultSoftware\",\n\t\"loopbackExemptPorts\",\n\t\"allowedNodeBuiltins\",\n\t\"highResolutionTime\",\n\t\"database\",\n\t\"rootFilesystem\",\n\t\"mounts\",\n\t\"sandbox\",\n\t\"scheduleDriver\",\n\t\"bindings\",\n\t\"permissions\",\n\t\"sidecar\",\n\t\"limits\",\n\t\"onAgentStderr\",\n\t\"onAgentExit\",\n\t\"onLimitWarning\",\n] as const satisfies readonly (keyof AgentOsOptions)[];\n\nfunction splitConfig(\n\tconfig: AgentOsActorConfigInput<any, any, any, any, any, any, any, any>,\n) {\n\tconst actorConfig = { ...config } as Record<string, unknown>;\n\tconst agentOsOptions: AgentOsOptions = {};\n\tfor (const key of agentOsOptionKeys) {\n\t\tif (key in actorConfig) {\n\t\t\t(agentOsOptions as Record<string, unknown>)[key] = actorConfig[key];\n\t\t\tdelete actorConfig[key];\n\t\t}\n\t}\n\tconst onSessionEvent =\n\t\tactorConfig.onSessionEvent as AgentOsEventHooks<AnyContext>[\"onSessionEvent\"];\n\tconst preview = actorConfig.preview as AgentOsActorExtras[\"preview\"];\n\tconst resolveOptions = actorConfig.resolveOptions as\n\t\t| AgentOsActorExtras[\"resolveOptions\"]\n\t\t| undefined;\n\tconst onVmStart = actorConfig.onVmStart as AgentOsActorExtras[\"onVmStart\"];\n\tconst onVmStop = actorConfig.onVmStop as AgentOsActorExtras[\"onVmStop\"];\n\tconst onVmDisposed =\n\t\tactorConfig.onVmDisposed as AgentOsActorExtras[\"onVmDisposed\"];\n\tconst maxSessionSubscriptions = actorConfig.maxSessionSubscriptions as\n\t\t| number\n\t\t| undefined;\n\tconst maxDynamicMounts = actorConfig.maxDynamicMounts as number | undefined;\n\tconst maxLinkedSoftware = actorConfig.maxLinkedSoftware as number | undefined;\n\tdelete actorConfig.onSessionEvent;\n\tdelete actorConfig.preview;\n\tdelete actorConfig.resolveOptions;\n\tdelete actorConfig.onVmStart;\n\tdelete actorConfig.onVmStop;\n\tdelete actorConfig.onVmDisposed;\n\tdelete actorConfig.maxSessionSubscriptions;\n\tdelete actorConfig.maxDynamicMounts;\n\tdelete actorConfig.maxLinkedSoftware;\n\treturn {\n\t\tactorConfig,\n\t\tagentOsOptions,\n\t\thooks: { onSessionEvent },\n\t\tpreview,\n\t\tresolveOptions,\n\t\tonVmStart,\n\t\tonVmStop,\n\t\tonVmDisposed,\n\t\tmaxSessionSubscriptions,\n\t\tmaxDynamicMounts,\n\t\tmaxLinkedSoftware,\n\t};\n}\n\nfunction assertNoReservedKeys(\n\tkind: string,\n\tcustom: object | undefined,\n\tbuiltIns: object,\n) {\n\tfor (const key of Object.keys(custom ?? {})) {\n\t\tif (key in builtIns)\n\t\t\tthrow new Error(`agentOS() ${kind} name is reserved: ${key}`);\n\t}\n}\n\n// Absolute path to the built inspector-tabs app (the shared Vite bundle). All\n// custom tabs share this one `source` dir; the app routes on the\n// `/inspector/custom-tabs/<id>/` URL segment. Resolves from both `src/` (tsx\n// dev) and the published `dist/`, since `assets/` sits at the package root in\n// both layouts.\nconst INSPECTOR_TABS_ASSET_DIR = join(\n\tdirname(fileURLToPath(import.meta.url)),\n\t\"..\",\n\t\"assets\",\n\t\"inspector-tabs-app\",\n);\n\n// Custom inspector tabs shipped by agent-os. Ids MUST match the `TABS`\n// registry in `src/inspector-tabs/main.tsx`. The built-in rivetkit tabs are\n// hidden so the dashboard shows only the agent-os tabs.\nconst AGENTOS_INSPECTOR_CONFIG = {\n\ttabs: [\n\t\t{\n\t\t\tid: \"transcript\",\n\t\t\tlabel: \"Transcript\",\n\t\t\tsource: INSPECTOR_TABS_ASSET_DIR,\n\t\t\ticon: \"comments\",\n\t\t},\n\t\t{\n\t\t\tid: \"filesystem\",\n\t\t\tlabel: \"Filesystem\",\n\t\t\tsource: INSPECTOR_TABS_ASSET_DIR,\n\t\t\ticon: \"folder-tree\",\n\t\t},\n\t\t{\n\t\t\tid: \"terminal\",\n\t\t\tlabel: \"Terminal\",\n\t\t\tsource: INSPECTOR_TABS_ASSET_DIR,\n\t\t\ticon: \"terminal\",\n\t\t},\n\t\t{\n\t\t\tid: \"system\",\n\t\t\tlabel: \"System\",\n\t\t\tsource: INSPECTOR_TABS_ASSET_DIR,\n\t\t\ticon: \"layer-group\",\n\t\t},\n\t\t// Processes/software/mounts live as sections inside the System tab.\n\t\t// `metadata` is dashboard-owned and not hideable (the schema only\n\t\t// accepts the six built-in ids below), so it stays.\n\t\t...[\"workflow\", \"database\", \"state\", \"queue\", \"connections\", \"console\"].map(\n\t\t\t(id) => ({ id, hidden: true as const }),\n\t\t),\n\t],\n};\n\nexport function createAgentOS<\n\tTState = undefined,\n\tTConnParams = undefined,\n\tTConnState = undefined,\n\tTVars = undefined,\n\tTInput = undefined,\n\tTEvents extends EventSchemaConfig = Record<never, never>,\n\tTQueues extends QueueSchemaConfig = Record<never, never>,\n\tTUserActions extends Actions<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tActorDb,\n\t\tTEvents,\n\t\tTQueues\n\t> = Record<never, never>,\n>(\n\tconfig: AgentOsActorConfigInput<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTEvents,\n\t\tTQueues,\n\t\tTUserActions\n\t> = {} as AgentOsActorConfigInput<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTEvents,\n\t\tTQueues,\n\t\tTUserActions\n\t>,\n): ActorDefinition<\n\tTState,\n\tTConnParams,\n\tTConnState,\n\tTVars,\n\tTInput,\n\tActorDb,\n\tTEvents & BuiltInEvents,\n\tTQueues,\n\tTUserActions & AgentOsActions\n> {\n\tconst split = splitConfig(config);\n\tconst actorConfig = split.actorConfig as Omit<\n\t\ttypeof config,\n\t\tkeyof AgentOsActorExtras\n\t>;\n\tconst {\n\t\tagentOsOptions,\n\t\thooks,\n\t\tpreview,\n\t\tmaxSessionSubscriptions,\n\t\tmaxDynamicMounts,\n\t\tmaxLinkedSoftware,\n\t} = split;\n\tif (split.resolveOptions)\n\t\toptionResolvers.set(agentOsOptions, split.resolveOptions);\n\tif (split.onVmStart) vmStartResolvers.set(agentOsOptions, split.onVmStart);\n\tif (split.onVmStop) vmStopResolvers.set(agentOsOptions, split.onVmStop);\n\tif (split.onVmDisposed)\n\t\tvmDisposedResolvers.set(agentOsOptions, split.onVmDisposed);\n\tif (agentOsOptions.sandbox && \"client\" in agentOsOptions.sandbox) {\n\t\tthrow new Error(\n\t\t\t\"agentOS() cannot share sandbox: { client } across actor instances; use sandbox: { provider } so each actor VM starts its own client\",\n\t\t);\n\t}\n\tif (agentOsOptions.rootFilesystem) {\n\t\tthrow new Error(\n\t\t\t\"agentOS() owns rootFilesystem so it can persist directly through the actor SQLite UDS; use mounts for additional filesystems\",\n\t\t);\n\t}\n\tif (agentOsOptions.database) {\n\t\tthrow new Error(\n\t\t\t\"agentOS() owns database and injects the actor SQLite UDS descriptor; standalone AgentOs clients may choose a SQLite file\",\n\t\t);\n\t}\n\tconst actions = createAgentOsActions(\n\t\tagentOsOptions,\n\t\thooks,\n\t\tpreview,\n\t\tmaxSessionSubscriptions,\n\t\tmaxDynamicMounts,\n\t\tmaxLinkedSoftware,\n\t);\n\tassertNoReservedKeys(\"action\", actorConfig.actions, actions);\n\tassertNoReservedKeys(\"event\", actorConfig.events, builtInEvents);\n\n\tconst userOnWake = actorConfig.onWake;\n\tconst userOnSleep = actorConfig.onSleep;\n\tconst userOnDestroy = actorConfig.onDestroy;\n\tconst userOnRequest = actorConfig.onRequest;\n\tconst userOnBeforeConnect = actorConfig.onBeforeConnect;\n\n\treturn actor({\n\t\t...actorConfig,\n\t\toptions: {\n\t\t\tactionTimeout: DEFAULT_ACTION_TIMEOUT_MS,\n\t\t\tsleepGracePeriod: DEFAULT_SLEEP_GRACE_PERIOD_MS,\n\t\t\t...actorConfig.options,\n\t\t\tenableActorRuntimeSocket: true,\n\t\t},\n\t\t// Register the custom agent-os inspector tabs (and hide the built-in\n\t\t// rivetkit tabs) so the dashboard renders the agent-os UI. Without\n\t\t// this the shipped tab assets are never surfaced. A caller-supplied\n\t\t// inspector config wins.\n\t\tinspector:\n\t\t\t(actorConfig as { inspector?: unknown }).inspector ??\n\t\t\tAGENTOS_INSPECTOR_CONFIG,\n\t\tdb: db({ onMigrate: migrateAgentOsActorTables }),\n\t\tevents: { ...(actorConfig.events ?? {}), ...builtInEvents },\n\t\tactions: { ...(actorConfig.actions ?? {}), ...actions },\n\t\tonBeforeConnect: async (\n\t\t\tc: Parameters<NonNullable<typeof userOnBeforeConnect>>[0],\n\t\t\tparams: Parameters<NonNullable<typeof userOnBeforeConnect>>[1],\n\t\t) => {\n\t\t\tif (\n\t\t\t\tc.request &&\n\t\t\t\tmatchPreviewPath(new URL(c.request.url).pathname) !== null\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait userOnBeforeConnect?.(c, params);\n\t\t},\n\t\tonWake: async (c: AnyContext) => {\n\t\t\ttry {\n\t\t\t\tawait userOnWake?.(c);\n\t\t\t} catch (error) {\n\t\t\t\tawait disposeVm(c as AnyContext, \"error\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tonSleep: async (c: AnyContext) => {\n\t\t\ttry {\n\t\t\t\tawait userOnSleep?.(c);\n\t\t\t} finally {\n\t\t\t\tawait disposeVm(c as AnyContext, \"sleep\");\n\t\t\t}\n\t\t},\n\t\tonDestroy: async (c: AnyContext) => {\n\t\t\ttry {\n\t\t\t\tawait userOnDestroy?.(c);\n\t\t\t} finally {\n\t\t\t\tawait disposeVm(c as AnyContext, \"destroy\");\n\t\t\t}\n\t\t},\n\t\tonRequest: async (c: AnyContext, request: Request) => {\n\t\t\tconst url = new URL(request.url);\n\t\t\tconst match = matchPreviewPath(url.pathname);\n\t\t\tif (!match) {\n\t\t\t\tconst response = await userOnRequest?.(c as never, request);\n\t\t\t\treturn response ?? new Response(\"Not Found\", { status: 404 });\n\t\t\t}\n\t\t\tif (request.method === \"OPTIONS\")\n\t\t\t\treturn new Response(null, {\n\t\t\t\t\tstatus: 204,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"access-control-allow-origin\": \"*\",\n\t\t\t\t\t\t\"access-control-allow-methods\":\n\t\t\t\t\t\t\t\"GET, POST, PUT, PATCH, DELETE, OPTIONS\",\n\t\t\t\t\t\t\"access-control-allow-headers\": \"*\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\tconst now = Date.now();\n\t\t\tawait c.db.execute(\n\t\t\t\t\"DELETE FROM agentos_actor_preview_tokens WHERE expires_at_ms <= ?\",\n\t\t\t\tnow,\n\t\t\t);\n\t\t\tconst rows = await c.db.execute<{ port: number }>(\n\t\t\t\t\"SELECT port FROM agentos_actor_preview_tokens WHERE token = ? AND expires_at_ms > ?\",\n\t\t\t\tmatch[1],\n\t\t\t\tnow,\n\t\t\t);\n\t\t\tif (!rows[0])\n\t\t\t\treturn new Response(\"Preview URL expired or invalid\", { status: 403 });\n\t\t\tconst target = new URL(request.url);\n\t\t\ttarget.pathname = match[2] ?? \"/\";\n\t\t\tconst vm = await ensureVm(c as AnyContext, agentOsOptions);\n\t\t\tconst requestHeaders: Record<string, string> = {};\n\t\t\trequest.headers.forEach((value, key) => {\n\t\t\t\trequestHeaders[key] = value;\n\t\t\t});\n\t\t\tconst response = await vm.network.httpRequest({\n\t\t\t\tport: rows[0].port,\n\t\t\t\tpath: `${target.pathname}${target.search}`,\n\t\t\t\tmethod: request.method,\n\t\t\t\theaders: requestHeaders,\n\t\t\t\t...(request.method === \"GET\" || request.method === \"HEAD\"\n\t\t\t\t\t? {}\n\t\t\t\t\t: { body: new Uint8Array(await request.arrayBuffer()) }),\n\t\t\t});\n\t\t\tconst headers = new Headers(response.headers);\n\t\t\theaders.set(\"access-control-allow-origin\", \"*\");\n\t\t\treturn new Response(Buffer.from(response.body), {\n\t\t\t\tstatus: response.status,\n\t\t\t\tstatusText: response.statusText,\n\t\t\t\theaders,\n\t\t\t});\n\t\t},\n\t} as any) as ActorDefinition<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tActorDb,\n\t\tTEvents & BuiltInEvents,\n\t\tTQueues,\n\t\tTUserActions & AgentOsActions\n\t>;\n}\n","// Server-side terminal state for shell replay.\n//\n// A shell outlives the page that opened it, and the dashboard reboots the tab\n// iframe on every tab switch. Without state on this side, a reattaching client\n// sees a blank pane until the guest happens to repaint — which a full-screen\n// program (vim, less) never does unprompted. So the actor keeps a headless\n// Ghostty emulator per shell, fed from the same chunks it broadcasts, and\n// serializes it back to ANSI on demand.\nimport { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport type { ShellReplayMode, ShellSnapshot } from \"./types.js\";\n\n/** Emulators alive at once. Matches the actor's open-shell ceiling. */\nconst MAX_REPLAY_SHELLS = 32;\n/** Scrollback retained per shell. Bounds the `scrollback` snapshot mode and\n * the emulator's own memory; the screen itself is bounded by cols × rows. */\nconst MAX_SCROLLBACK_LINES = 1_000;\n/** Rejects an absurd resize before it becomes a cols × rows allocation. */\nconst MAX_COLS = 1_000;\nconst MAX_ROWS = 1_000;\n\nconst DEFAULT_COLS = 80;\nconst DEFAULT_ROWS = 24;\n\n// ── WASM loading ───────────────────────────────────────────────────────────\n// ghostty-web's own loader resolves its inlined wasm against `self.location`,\n// which does not exist outside a browser. Instantiating the shipped .wasm\n// directly avoids both the missing global and a multi-megabyte base64 decode.\ninterface GhosttyModule {\n\tcreateTerminal(\n\t\tcols: number,\n\t\trows: number,\n\t\tconfig?: { scrollbackLimit?: number },\n\t): HeadlessTerminal;\n}\n\ninterface WebAssemblyRuntime {\n\tinstantiate(\n\t\tbytes: Uint8Array,\n\t\timports: Record<string, Record<string, () => void>>,\n\t): Promise<{ instance: object }>;\n}\n\ninterface GhosttyCell {\n\tcodepoint: number;\n\tfg_r: number;\n\tfg_g: number;\n\tfg_b: number;\n\tbg_r: number;\n\tbg_g: number;\n\tbg_b: number;\n\tflags: number;\n\twidth: number;\n\tgrapheme_len: number;\n}\n\ninterface HeadlessTerminal {\n\twrite(data: string | Uint8Array): void;\n\tresize(cols: number, rows: number): void;\n\tfree(): void;\n\tupdate(): number;\n\tgetViewport(): GhosttyCell[];\n\tgetCursor(): { viewportX: number; viewportY: number; visible: number };\n\tgetColors(): {\n\t\tforeground: { r: number; g: number; b: number };\n\t\tbackground: { r: number; g: number; b: number };\n\t};\n\tgetGraphemeString(row: number, col: number): string;\n\tgetScrollbackLength(): number;\n\tgetScrollbackLine(offset: number): GhosttyCell[] | null;\n\tgetScrollbackGraphemeString(offset: number, col: number): string;\n\tisAlternateScreen(): boolean;\n\tgetMode(mode: number, isAnsi?: boolean): boolean;\n}\n\nlet ghosttyPromise: Promise<GhosttyModule> | undefined;\n\nasync function loadGhostty(): Promise<GhosttyModule> {\n\tghosttyPromise ??= (async () => {\n\t\tconst require = createRequire(import.meta.url);\n\t\tconst { Ghostty } = await import(\"ghostty-web\");\n\t\tconst bytes = await readFile(\n\t\t\trequire.resolve(\"ghostty-web/ghostty-vt.wasm\"),\n\t\t);\n\t\tconst webAssembly = Reflect.get(globalThis, \"WebAssembly\") as\n\t\t\t| WebAssemblyRuntime\n\t\t\t| undefined;\n\t\tif (!webAssembly) {\n\t\t\tthrow new Error(\"WebAssembly is unavailable in this runtime\");\n\t\t}\n\t\tconst { instance } = await webAssembly.instantiate(bytes, {\n\t\t\tenv: { log: () => {} },\n\t\t});\n\t\tconst GhosttyConstructor = Ghostty as unknown as new (\n\t\t\tinstance: object,\n\t\t) => GhosttyModule;\n\t\treturn new GhosttyConstructor(instance);\n\t})();\n\treturn ghosttyPromise;\n}\n\n// ── ANSI serialization ─────────────────────────────────────────────────────\nconst CELL_BOLD = 1;\nconst CELL_ITALIC = 2;\nconst CELL_UNDERLINE = 4;\nconst CELL_STRIKETHROUGH = 8;\nconst CELL_INVERSE = 16;\nconst CELL_INVISIBLE = 32;\nconst CELL_BLINK = 64;\nconst CELL_FAINT = 128;\n\n/** DEC private modes worth restoring: getting these wrong strands the guest in\n * a state its client no longer agrees with — arrow keys emitting the wrong\n * prefix, or a paste arriving unbracketed and executing as commands. Each is\n * read back individually rather than inferred, so the exact mouse protocol\n * survives too. Alt-screen (1049) and cursor visibility (25) are restored\n * separately, in a fixed order relative to the repaint. */\nconst RESTORED_DEC_MODES = [\n\t1, // DECCKM — application cursor keys\n\t7, // DECAWM — autowrap\n\t1000, // mouse: click tracking\n\t1002, // mouse: button-event tracking\n\t1003, // mouse: any-event tracking\n\t1004, // focus in/out reporting\n\t1005, // mouse: UTF-8 coordinates\n\t1006, // mouse: SGR coordinates\n\t1015, // mouse: urxvt coordinates\n\t2004, // bracketed paste\n];\n\ninterface CellStyle {\n\tfg: number | null;\n\tbg: number | null;\n\tflags: number;\n}\n\nconst DEFAULT_STYLE: CellStyle = { fg: null, bg: null, flags: 0 };\n\nfunction rgb(r: number, g: number, b: number): number {\n\treturn (r << 16) | (g << 8) | b;\n}\n\nfunction styleOf(\n\tcell: GhosttyCell,\n\tdefaultFg: number,\n\tdefaultBg: number,\n): CellStyle {\n\tconst fg = rgb(cell.fg_r, cell.fg_g, cell.fg_b);\n\tconst bg = rgb(cell.bg_r, cell.bg_g, cell.bg_b);\n\treturn {\n\t\tfg: fg === defaultFg ? null : fg,\n\t\tbg: bg === defaultBg ? null : bg,\n\t\tflags: cell.flags,\n\t};\n}\n\nfunction sameStyle(a: CellStyle, b: CellStyle): boolean {\n\treturn a.fg === b.fg && a.bg === b.bg && a.flags === b.flags;\n}\n\n/** Full SGR for a style, always prefixed with a reset so it never inherits\n * attributes from whatever the client last rendered. */\nfunction sgr(style: CellStyle): string {\n\tconst params: number[] = [0];\n\tif (style.flags & CELL_BOLD) params.push(1);\n\tif (style.flags & CELL_FAINT) params.push(2);\n\tif (style.flags & CELL_ITALIC) params.push(3);\n\tif (style.flags & CELL_UNDERLINE) params.push(4);\n\tif (style.flags & CELL_BLINK) params.push(5);\n\tif (style.flags & CELL_INVERSE) params.push(7);\n\tif (style.flags & CELL_INVISIBLE) params.push(8);\n\tif (style.flags & CELL_STRIKETHROUGH) params.push(9);\n\tif (style.fg !== null) {\n\t\tparams.push(\n\t\t\t38,\n\t\t\t2,\n\t\t\t(style.fg >> 16) & 0xff,\n\t\t\t(style.fg >> 8) & 0xff,\n\t\t\tstyle.fg & 0xff,\n\t\t);\n\t}\n\tif (style.bg !== null) {\n\t\tparams.push(\n\t\t\t48,\n\t\t\t2,\n\t\t\t(style.bg >> 16) & 0xff,\n\t\t\t(style.bg >> 8) & 0xff,\n\t\t\tstyle.bg & 0xff,\n\t\t);\n\t}\n\treturn `\\x1b[${params.join(\";\")}m`;\n}\n\n/** One row of cells → text plus SGR changes. `graphemeAt` supplies the full\n * cluster for cells that carry combining marks. Trailing default-styled blanks\n * are dropped in favour of an erase-to-end-of-line. */\nfunction serializeRow(\n\tcells: GhosttyCell[],\n\tcols: number,\n\tdefaultFg: number,\n\tdefaultBg: number,\n\tgraphemeAt: (col: number) => string,\n): string {\n\tlet lastMeaningful = -1;\n\tfor (let x = 0; x < cols; x++) {\n\t\tconst cell = cells[x];\n\t\tif (!cell) continue;\n\t\tconst blank = cell.codepoint === 0 || cell.codepoint === 32;\n\t\tif (\n\t\t\t!blank ||\n\t\t\t!sameStyle(styleOf(cell, defaultFg, defaultBg), DEFAULT_STYLE)\n\t\t) {\n\t\t\tlastMeaningful = x;\n\t\t}\n\t}\n\tif (lastMeaningful < 0) return \"\\x1b[0m\\x1b[K\";\n\n\tlet out = \"\";\n\tlet current = DEFAULT_STYLE;\n\tout += sgr(current);\n\tfor (let x = 0; x <= lastMeaningful; x++) {\n\t\tconst cell = cells[x];\n\t\tif (!cell) {\n\t\t\tout += \" \";\n\t\t\tcontinue;\n\t\t}\n\t\t// Width 0 is the trailing half of a wide character; the preceding cell\n\t\t// already emitted the whole glyph.\n\t\tif (cell.width === 0) continue;\n\t\tconst style = styleOf(cell, defaultFg, defaultBg);\n\t\tif (!sameStyle(style, current)) {\n\t\t\tout += sgr(style);\n\t\t\tcurrent = style;\n\t\t}\n\t\tif (cell.grapheme_len > 0) {\n\t\t\tout += graphemeAt(x);\n\t\t} else if (cell.codepoint === 0) {\n\t\t\tout += \" \";\n\t\t} else {\n\t\t\tout += String.fromCodePoint(cell.codepoint);\n\t\t}\n\t}\n\treturn `${out}\\x1b[0m\\x1b[K`;\n}\n\n// ── Store ──────────────────────────────────────────────────────────────────\ninterface ReplayEntry {\n\tterm: HeadlessTerminal;\n\tcols: number;\n\trows: number;\n\tseq: number;\n}\n\nfunction clamp(\n\tvalue: number | undefined,\n\tfallback: number,\n\tmax: number,\n): number {\n\tif (!Number.isFinite(value) || value === undefined || value <= 0)\n\t\treturn fallback;\n\treturn Math.min(Math.floor(value), max);\n}\n\n/**\n * One headless emulator per live shell, fed the same bytes the actor\n * broadcasts. All methods are no-ops for unknown shell ids so a shell opened\n * before replay existed (or one whose emulator failed to start) degrades to\n * the previous behaviour instead of failing the write path.\n */\nexport class ShellReplayStore {\n\tprivate entries = new Map<string, ReplayEntry>();\n\tprivate ghostty: GhosttyModule | null = null;\n\n\t/** Instantiates the WASM module. Callers must await this before opening a\n\t * shell so that `open` itself can be synchronous: a PTY starts producing\n\t * output the moment it exists, and any await between opening it and\n\t * subscribing is a window where output is lost to every consumer. */\n\tasync warm(): Promise<void> {\n\t\tthis.ghostty ??= await loadGhostty();\n\t}\n\n\topen(shellId: string, cols?: number, rows?: number): void {\n\t\tif (this.entries.has(shellId)) return;\n\t\tif (this.entries.size >= MAX_REPLAY_SHELLS) {\n\t\t\tthrow new Error(\n\t\t\t\t`agent-os shell replay limit reached (${MAX_REPLAY_SHELLS} emulators); close a shell or raise MAX_REPLAY_SHELLS in shell-replay.ts`,\n\t\t\t);\n\t\t}\n\t\tif (!this.ghostty) {\n\t\t\tthrow new Error(\"agent-os shell replay used before warm() resolved\");\n\t\t}\n\t\tconst width = clamp(cols, DEFAULT_COLS, MAX_COLS);\n\t\tconst height = clamp(rows, DEFAULT_ROWS, MAX_ROWS);\n\t\tconst term = this.ghostty.createTerminal(width, height, {\n\t\t\tscrollbackLimit: MAX_SCROLLBACK_LINES,\n\t\t});\n\t\t// A freed terminal's handle is recycled without its screen being cleared,\n\t\t// so a new emulator can start holding the previous shell's contents — and\n\t\t// serve them to whoever attaches next. Reset before anything is fed in.\n\t\tterm.write(\"\\x1bc\");\n\t\tthis.entries.set(shellId, { term, cols: width, rows: height, seq: 0 });\n\t}\n\n\t/** Feeds one broadcast chunk and returns its sequence number. Clients use\n\t * it to drop chunks a snapshot already contains. Returns 0 when this shell\n\t * has no emulator, which clients read as \"no replay available\". */\n\tfeed(shellId: string, data: Uint8Array): number {\n\t\tconst entry = this.entries.get(shellId);\n\t\tif (!entry) return 0;\n\t\tentry.term.write(data);\n\t\treturn ++entry.seq;\n\t}\n\n\tresize(shellId: string, cols: number, rows: number): void {\n\t\tconst entry = this.entries.get(shellId);\n\t\tif (!entry) return;\n\t\tentry.cols = clamp(cols, entry.cols, MAX_COLS);\n\t\tentry.rows = clamp(rows, entry.rows, MAX_ROWS);\n\t\tentry.term.resize(entry.cols, entry.rows);\n\t}\n\n\tclose(shellId: string): void {\n\t\tconst entry = this.entries.get(shellId);\n\t\tif (!entry) return;\n\t\tthis.entries.delete(shellId);\n\t\tentry.term.free();\n\t}\n\n\thas(shellId: string): boolean {\n\t\treturn this.entries.has(shellId);\n\t}\n\n\tsnapshot(shellId: string, mode: ShellReplayMode): ShellSnapshot | null {\n\t\tconst entry = this.entries.get(shellId);\n\t\tif (!entry) return null;\n\t\tconst { term, cols, rows, seq } = entry;\n\t\tconst base = { shellId, seq, cols, rows };\n\t\tif (mode === \"none\") return { ...base, mode, data: \"\" };\n\n\t\tterm.update();\n\t\tconst colors = term.getColors();\n\t\tconst defaultFg = rgb(\n\t\t\tcolors.foreground.r,\n\t\t\tcolors.foreground.g,\n\t\t\tcolors.foreground.b,\n\t\t);\n\t\tconst defaultBg = rgb(\n\t\t\tcolors.background.r,\n\t\t\tcolors.background.g,\n\t\t\tcolors.background.b,\n\t\t);\n\t\tconst alternate = term.isAlternateScreen();\n\n\t\t// RIS first: the client pane may be reused, and a repaint that inherits\n\t\t// stale modes or attributes is worse than no repaint at all.\n\t\tlet out = \"\\x1bc\";\n\n\t\t// Scrollback is written first and scrolled off by the screen paint that\n\t\t// follows, so it lands in the client's scrollback rather than on screen.\n\t\t// It belongs to the primary screen, so it precedes the alt-screen switch.\n\t\tif (mode === \"scrollback\" && !alternate) {\n\t\t\tconst available = Math.min(\n\t\t\t\tterm.getScrollbackLength(),\n\t\t\t\tMAX_SCROLLBACK_LINES,\n\t\t\t);\n\t\t\tfor (let i = available; i > 0; i--) {\n\t\t\t\tconst offset = i - 1;\n\t\t\t\tconst line = term.getScrollbackLine(offset);\n\t\t\t\tif (!line) continue;\n\t\t\t\tout += serializeRow(line, cols, defaultFg, defaultBg, (col) =>\n\t\t\t\t\tterm.getScrollbackGraphemeString(offset, col),\n\t\t\t\t);\n\t\t\t\tout += \"\\r\\n\";\n\t\t\t}\n\t\t}\n\n\t\t// Modes go on before the repaint so the client is already in the right\n\t\t// screen when cells land; 1049 also clears, which would undo the paint.\n\t\tif (alternate) out += \"\\x1b[?1049h\";\n\t\tfor (const decMode of RESTORED_DEC_MODES) {\n\t\t\tout += term.getMode(decMode) ? `\\x1b[?${decMode}h` : `\\x1b[?${decMode}l`;\n\t\t}\n\n\t\t// Rows are painted sequentially from home rather than by absolute\n\t\t// address: each `\\r\\n` scrolls whatever preceded it into scrollback,\n\t\t// which is what carries the dump above off-screen intact.\n\t\tconst viewport = term.getViewport();\n\t\tout += \"\\x1b[H\";\n\t\tfor (let y = 0; y < rows; y++) {\n\t\t\tif (y > 0) out += \"\\r\\n\";\n\t\t\tconst row = viewport.slice(y * cols, (y + 1) * cols);\n\t\t\tout += serializeRow(row, cols, defaultFg, defaultBg, (col) =>\n\t\t\t\tterm.getGraphemeString(y, col),\n\t\t\t);\n\t\t}\n\n\t\tconst cursor = term.getCursor();\n\t\tconst cy = Math.min(Math.max(cursor.viewportY, 0), rows - 1) + 1;\n\t\tconst cx = Math.min(Math.max(cursor.viewportX, 0), cols - 1) + 1;\n\t\tout += `\\x1b[0m\\x1b[${cy};${cx}H`;\n\t\tout += cursor.visible ? \"\\x1b[?25h\" : \"\\x1b[?25l\";\n\n\t\treturn { ...base, mode, data: out };\n\t}\n}\n"],"mappings":";;;;;AAAA,SAAS,SAAS,qBAAqB;AAoBvC,cAAc;;;ACpBd,OAAO,YAAY;AACnB,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAC9B;AAAA,EAEC;AAAA,OAUM;AACP;AAAA,EAKC;AAAA,EACA;AAAA,EAEA;AAAA,OACM;AACP,SAAgC,UAA0B;AAC1D,SAAS,kBAAkB;;;ACnB3B,S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,SAAS,GAAiB,cAAc;AACzD,YAAM,iBAAyC,CAAC;AAChD,cAAQ,QAAQ,QAAQ,CAAC,OAAO,QAAQ;AACvC,uBAAe,GAAG,IAAI;AAAA,MACvB,CAAC;AACD,YAAM,WAAW,MAAM,GAAG,QAAQ,YAAY;AAAA,QAC7C,MAAM,KAAK,CAAC,EAAE;AAAA,QACd,MAAM,GAAG,OAAO,QAAQ,GAAG,OAAO,MAAM;AAAA,QACxC,QAAQ,QAAQ;AAAA,QAChB,SAAS;AAAA,QACT,GAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,SAChD,CAAC,IACD,EAAE,MAAM,IAAI,WAAW,MAAM,QAAQ,YAAY,CAAC,EAAE;AAAA,MACxD,CAAC;AACD,YAAM,UAAU,IAAI,QAAQ,SAAS,OAAO;AAC5C,cAAQ,IAAI,+BAA+B,GAAG;AAC9C,aAAO,IAAI,SAAS,OAAO,KAAK,SAAS,IAAI,GAAG;AAAA,QAC/C,QAAQ,SAAS;AAAA,QACjB,YAAY,SAAS;AAAA,QACrB;AAAA,MACD,CAAC;AAAA,IACF;AAAA,EACD,CAAQ;AAWT;;;ADh5EA,IAAM,wCAAwC,MAAM,OAAO;AAMpD,IAAM,SAA+B,CAC3C,UAEA,cAAc;AAAA,EACb,GAAG;AAAA,EACH,wBAAwB;AAAA,EACxB,wBAAwB;AAAA,EACxB,sBAAsB;AACvB,CAAwC;","names":["require","event","migrations","response"]}
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
interface NodeShellOpenOptions {
|
|
2
|
+
command?: string;
|
|
3
|
+
args?: string[];
|
|
4
|
+
env?: Record<string, string>;
|
|
5
|
+
cwd?: string;
|
|
6
|
+
cols?: number;
|
|
7
|
+
rows?: number;
|
|
8
|
+
}
|
|
9
|
+
interface NodeShellConnection {
|
|
10
|
+
openShell(options?: NodeShellOpenOptions): Promise<{
|
|
11
|
+
shellId: string;
|
|
12
|
+
}>;
|
|
13
|
+
writeShell(shellId: string, data: string | Uint8Array): Promise<void>;
|
|
14
|
+
resizeShell(shellId: string, cols: number, rows: number): Promise<void>;
|
|
15
|
+
closeShell(shellId: string): Promise<void>;
|
|
16
|
+
waitShell(shellId: string): Promise<number>;
|
|
17
|
+
}
|
|
18
|
+
interface NodeShellInput {
|
|
19
|
+
isTTY?: boolean;
|
|
20
|
+
isRaw?: boolean;
|
|
21
|
+
setRawMode?(enabled: boolean): unknown;
|
|
22
|
+
on(event: "data", listener: (data: string | Uint8Array) => void): unknown;
|
|
23
|
+
on(event: "end", listener: () => void): unknown;
|
|
24
|
+
on(event: "error", listener: (error: Error) => void): unknown;
|
|
25
|
+
removeListener(event: "data", listener: (data: string | Uint8Array) => void): unknown;
|
|
26
|
+
removeListener(event: "end", listener: () => void): unknown;
|
|
27
|
+
removeListener(event: "error", listener: (error: Error) => void): unknown;
|
|
28
|
+
pause(): unknown;
|
|
29
|
+
resume(): unknown;
|
|
30
|
+
}
|
|
31
|
+
interface NodeShellOutput {
|
|
32
|
+
isTTY?: boolean;
|
|
33
|
+
columns?: number;
|
|
34
|
+
rows?: number;
|
|
35
|
+
write(data: string | Uint8Array): boolean;
|
|
36
|
+
on(event: "resize", listener: () => void): unknown;
|
|
37
|
+
removeListener(event: "resize", listener: () => void): unknown;
|
|
38
|
+
}
|
|
39
|
+
type NodeShellSignal = "SIGINT" | "SIGHUP" | "SIGTERM";
|
|
40
|
+
interface AttachShellOptions extends NodeShellOpenOptions {
|
|
41
|
+
stdin?: NodeShellInput;
|
|
42
|
+
stdout?: NodeShellOutput;
|
|
43
|
+
stderr?: NodeShellOutput;
|
|
44
|
+
rawMode?: boolean;
|
|
45
|
+
resize?: boolean;
|
|
46
|
+
signals?: readonly NodeShellSignal[];
|
|
47
|
+
maxPendingOutputBytes?: number;
|
|
48
|
+
onWarning?: (message: string) => void;
|
|
49
|
+
}
|
|
50
|
+
declare class NodeShellOutputLimitError extends Error {
|
|
51
|
+
readonly limitBytes: number;
|
|
52
|
+
readonly pendingBytes: number;
|
|
53
|
+
readonly code = "AGENTOS_NODE_SHELL_OUTPUT_LIMIT";
|
|
54
|
+
constructor(limitBytes: number, pendingBytes: number);
|
|
55
|
+
}
|
|
56
|
+
declare class NodeShellCleanupError extends Error {
|
|
57
|
+
readonly errors: readonly Error[];
|
|
58
|
+
readonly code = "AGENTOS_NODE_SHELL_CLEANUP_FAILED";
|
|
59
|
+
constructor(errors: readonly Error[]);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Open an AgentOS PTY shell and attach it to the current Node process terminal.
|
|
63
|
+
* The connection must expose AgentOS shell actions and its broadcast `on()` API.
|
|
64
|
+
*/
|
|
65
|
+
declare function attachShell(connection: NodeShellConnection, options?: AttachShellOptions): Promise<number>;
|
|
66
|
+
|
|
67
|
+
export { type AttachShellOptions, NodeShellCleanupError, type NodeShellConnection, type NodeShellInput, type NodeShellOpenOptions, type NodeShellOutput, NodeShellOutputLimitError, type NodeShellSignal, attachShell };
|