@rivet-dev/agentos 0.0.0-codex-actor-plugin-contract-coverage.115ca8a → 0.0.0-eve-integration.9df6f34
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/badge-CkqYPoD9.js +1 -0
- package/assets/inspector-tabs-app/assets/filesystem-DbXxNt-B.js +1 -0
- package/assets/inspector-tabs-app/assets/{index-C50G2vhD.js → index-nTg2hrne.js} +22 -22
- package/assets/inspector-tabs-app/assets/{mounts-C0eJmxpt.js → mounts-BlNRslup.js} +1 -1
- package/assets/inspector-tabs-app/assets/{processes-CvN1MFLy.js → processes-CjHQ_o8t.js} +1 -1
- package/assets/inspector-tabs-app/assets/scroll-area-DE-oi7a2.js +1 -0
- package/assets/inspector-tabs-app/assets/{software-BjGEcqMs.js → software-2sjLheLb.js} +1 -1
- package/assets/inspector-tabs-app/assets/transcript-Cz9DrFWK.js +1 -0
- package/assets/inspector-tabs-app/assets/{useSuspenseQuery-CpwiXRj_.js → useSuspenseQuery-V0HYenB_.js} +1 -1
- package/assets/inspector-tabs-app/index.html +1 -1
- 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 +116 -731
- package/dist/index.js +818 -341
- 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 +23 -18
- 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/scroll-area-DzL-iGyn.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/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,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;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"],"sourcesContent":["import { setup as rivetkitSetup } 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 type {\n\tAgentOsOptions,\n\tDirEntry,\n\tDynamicMountDescriptor,\n\tExportRootFilesystemOptions,\n\tHttpRequest,\n\tHttpResponse,\n\tMountInfo,\n\tNodeModulesMountConfig,\n\tPackageDescriptor,\n\tProcessExit,\n\tProcessOutput,\n\tPromptResult,\n\tReaddirEntry,\n\tRootSnapshotExport,\n\tSessionInfo,\n\tShellData,\n\tShellExit,\n} from \"@rivet-dev/agentos-core\";\nexport { defineSoftware, nodeModulesMount } 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} from \"./actor.js\";\nexport type {\n\tAgentOsEvents,\n\tProcessExitPayload,\n\tProcessOutputPayload,\n\tSerializableCronAction,\n\tSerializableCronEvent,\n\tSerializableCronJobInfo,\n\tSerializableCronJobOptions,\n\tShellDataPayload,\n\tShellExitPayload,\n\tVmBootedPayload,\n\tVmShutdownPayload,\n} from \"./types.js\";\n","import crypto from \"node:crypto\";\nimport {\n\ttype AgentExitEvent,\n\tAgentOs,\n\ttype AgentOsOptions,\n\ttype CronEvent,\n\ttype DynamicMountDescriptor,\n\ttype OpenSessionInput,\n\ttype PackageDescriptor,\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 type {\n\tAgentOsEvents,\n\tProcessExitPayload,\n\tProcessOutputPayload,\n\tSerializableCronJobOptions,\n\tShellDataPayload,\n\tShellExitPayload,\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\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\tsubscribedSessions: Map<string, readonly (() => void)[]>;\n}\n\nconst runtimes = new Map<string, RuntimeState>();\n\nfunction runtimeFor(c: AnyContext): RuntimeState {\n\tlet runtime = runtimes.get(c.actorId);\n\tif (!runtime) {\n\t\truntime = { vm: null, subscribedSessions: new Map() };\n\t\truntimes.set(c.actorId, runtime);\n\t}\n\treturn runtime;\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.vm = (async () => {\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...options,\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\tc.broadcast(\"agentExit\", event);\n\t\t\t\ttry {\n\t\t\t\t\toptions?.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\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: options?.user?.euid ?? options?.user?.uid ?? 1000,\n\t\t\t\t\t\tgid: options?.user?.egid ?? options?.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.mountFs(\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.linkSoftware(\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\tvm.onCronEvent((cronEvent) => c.broadcast(\"cronEvent\", cronEvent));\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\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\tthrow error;\n\t}\n}\n\nasync function disposeVm(c: AnyContext, reason: \"sleep\" | \"destroy\" | \"error\") {\n\tconst runtime = runtimes.get(c.actorId);\n\tif (!runtime) return;\n\tconst vm = runtime.vm;\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\tif (vm) await (await vm).dispose();\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 database.execute(`\n\t\tCREATE TABLE IF NOT EXISTS agentos_actor_schema_version (\n\t\t\tsingleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n\t\t\tschema_version INTEGER NOT NULL CHECK (schema_version BETWEEN 0 AND ${MAX_SQLITE_SAFE_INTEGER})\n\t\t) STRICT;\n\t`);\n\tconst rows = await database.execute<{ schema_version: unknown }>(\n\t\t\"SELECT schema_version FROM agentos_actor_schema_version WHERE singleton = 1\",\n\t);\n\tif (rows.length > 1) {\n\t\tthrow new Error(\n\t\t\t`invalid AgentOS actor SQLite schema version table: expected at most one row, received ${rows.length}`,\n\t\t);\n\t}\n\tconst rawCurrent = rows[0]?.schema_version;\n\tconst current = rows.length === 0 ? 0 : rawCurrent;\n\tif (\n\t\ttypeof current !== \"number\" ||\n\t\t!Number.isSafeInteger(current) ||\n\t\tcurrent < 0\n\t) {\n\t\tthrow new Error(\n\t\t\t`invalid AgentOS actor SQLite schema version ${String(rawCurrent)}`,\n\t\t);\n\t}\n\tif (current > ACTOR_SQLITE_MIGRATIONS.length) {\n\t\tthrow new Error(\n\t\t\t`AgentOS actor SQLite schema version ${current} is newer than supported version ${ACTOR_SQLITE_MIGRATIONS.length}`,\n\t\t);\n\t}\n\tfor (const migration of ACTOR_SQLITE_MIGRATIONS.slice(current)) {\n\t\tawait database.execute(migration.sql);\n\t\tawait database.execute(\n\t\t\t`INSERT INTO agentos_actor_schema_version (singleton, schema_version)\n\t\t\t VALUES (1, ?)\n\t\t\t ON CONFLICT(singleton) DO UPDATE SET schema_version = excluded.schema_version`,\n\t\t\tmigration.version,\n\t\t);\n\t}\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 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\tc.waitUntil(\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\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\treturn {\n\t\treadFile: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"readFile\"]>\n\t\t) => {\n\t\t\ttry {\n\t\t\t\treturn await (await ensureVm(c, options)).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[\"writeFile\"]>\n\t\t) => (await ensureVm(c, options)).writeFile(...args),\n\t\treadFiles: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"readFiles\"]>\n\t\t) => (await ensureVm(c, options)).readFiles(...args),\n\t\twriteFiles: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"writeFiles\"]>\n\t\t) => (await ensureVm(c, options)).writeFiles(...args),\n\t\tstat: async (c: AnyContext, ...args: Parameters<AgentOs[\"stat\"]>) =>\n\t\t\t(await ensureVm(c, options)).stat(...args),\n\t\tmkdir: async (c: AnyContext, ...args: Parameters<AgentOs[\"mkdir\"]>) =>\n\t\t\t(await ensureVm(c, options)).mkdir(...args),\n\t\treaddir: async (c: AnyContext, ...args: Parameters<AgentOs[\"readdir\"]>) =>\n\t\t\t(await ensureVm(c, options)).readdir(...args),\n\t\treaddirEntries: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"readdirEntries\"]>\n\t\t) => (await ensureVm(c, options)).readdirEntries(...args),\n\t\treaddirRecursive: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"readdirRecursive\"]>\n\t\t) => (await ensureVm(c, options)).readdirRecursive(...args),\n\t\texists: async (c: AnyContext, ...args: Parameters<AgentOs[\"exists\"]>) =>\n\t\t\t(await ensureVm(c, options)).exists(...args),\n\t\tmove: async (c: AnyContext, ...args: Parameters<AgentOs[\"move\"]>) =>\n\t\t\t(await ensureVm(c, options)).move(...args),\n\t\tremove: async (c: AnyContext, ...args: Parameters<AgentOs[\"remove\"]>) =>\n\t\t\t(await ensureVm(c, options)).remove(...args),\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: async (c: AnyContext, ...args: Parameters<AgentOs[\"spawn\"]>) => {\n\t\t\tconst vm = await ensureVm(c, options);\n\t\t\tconst process = vm.spawn(...args);\n\t\t\tconst unsubscribeOutput = vm.onProcessOutput(process.pid, (event) =>\n\t\t\t\tc.broadcast(\"processOutput\", event),\n\t\t\t);\n\t\t\tconst unsubscribeExit = vm.onProcessExit(process.pid, (event) =>\n\t\t\t\tc.broadcast(\"processExit\", event),\n\t\t\t);\n\t\t\tvoid c\n\t\t\t\t.keepAwake(\n\t\t\t\t\tvm.waitProcess(process.pid).finally(() => {\n\t\t\t\t\t\tunsubscribeOutput();\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 process wait failed\",\n\t\t\t\t\t\tpid: process.pid,\n\t\t\t\t\t\terror,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\treturn process;\n\t\t},\n\t\twaitProcess: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"waitProcess\"]>\n\t\t) => (await ensureVm(c, options)).waitProcess(...args),\n\t\tkillProcess: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"killProcess\"]>\n\t\t) => (await ensureVm(c, options)).killProcess(...args),\n\t\tstopProcess: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"stopProcess\"]>\n\t\t) => (await ensureVm(c, options)).stopProcess(...args),\n\t\tlistProcesses: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).listProcesses(),\n\t\tallProcesses: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).allProcesses(),\n\t\tprocessTree: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).processTree(),\n\t\tgetProcess: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"getProcess\"]>\n\t\t) => (await ensureVm(c, options)).getProcess(...args),\n\t\twriteProcessStdin: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"writeProcessStdin\"]>\n\t\t) => (await ensureVm(c, options)).writeProcessStdin(...args),\n\t\tcloseProcessStdin: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"closeProcessStdin\"]>\n\t\t) => (await ensureVm(c, options)).closeProcessStdin(...args),\n\t\topenShell: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"openShell\"]>\n\t\t) => {\n\t\t\tconst vm = await ensureVm(c, options);\n\t\t\tconst shell = vm.openShell(...args);\n\t\t\tconst unsubscribeData = vm.onShellData(shell.shellId, (event) =>\n\t\t\t\tc.broadcast(\"shellData\", event),\n\t\t\t);\n\t\t\tconst unsubscribeStderr = vm.onShellStderr(shell.shellId, (event) =>\n\t\t\t\tc.broadcast(\"shellStderr\", event),\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.waitShell(shell.shellId).finally(() => {\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\twriteShell: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"writeShell\"]>\n\t\t) => (await ensureVm(c, options)).writeShell(...args),\n\t\tresizeShell: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"resizeShell\"]>\n\t\t) => (await ensureVm(c, options)).resizeShell(...args),\n\t\tcloseShell: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"closeShell\"]>\n\t\t) => (await ensureVm(c, options)).closeShell(...args),\n\t\twaitShell: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"waitShell\"]>\n\t\t) => (await ensureVm(c, options)).waitShell(...args),\n\t\thttpRequest: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"httpRequest\"]>\n\t\t) => (await ensureVm(c, options)).httpRequest(...args),\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)).scheduleCron(\n\t\t\t\tcronOptions as Parameters<AgentOs[\"scheduleCron\"]>[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)).listCronJobs(),\n\t\tcancelCronJob: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"cancelCronJob\"]>\n\t\t) => (await ensureVm(c, options)).cancelCronJob(...args),\n\t\tlistAgents: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).listAgents(),\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.openSession(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[\"getSession\"]>\n\t\t) => (await ensureVm(c, options)).getSession(...args),\n\t\tlistSessions: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"listSessions\"]>\n\t\t) => (await ensureVm(c, options)).listSessions(...args),\n\t\tdeleteSession: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"deleteSession\"]>\n\t\t) => {\n\t\t\tconst result = await (await ensureVm(c, options)).deleteSession(...args);\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[\"unloadSession\"]>\n\t\t) => {\n\t\t\tconst result = await (await ensureVm(c, options)).unloadSession(...args);\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.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[\"cancelPrompt\"]>\n\t\t) => (await ensureVm(c, options)).cancelPrompt(...args),\n\t\trespondPermission: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"respondPermission\"]>\n\t\t) => (await ensureVm(c, options)).respondPermission(...args),\n\t\treadHistory: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"readHistory\"]>\n\t\t) => (await ensureVm(c, options)).readHistory(...args),\n\t\tgetSessionConfig: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"getSessionConfig\"]>\n\t\t) => (await ensureVm(c, options)).getSessionConfig(...args),\n\t\tsetSessionConfigOption: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"setSessionConfigOption\"]>\n\t\t) => (await ensureVm(c, options)).setSessionConfigOption(...args),\n\t\tgetSessionCapabilities: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"getSessionCapabilities\"]>\n\t\t) => (await ensureVm(c, options)).getSessionCapabilities(...args),\n\t\tgetSessionAgentInfo: async (\n\t\t\tc: AnyContext,\n\t\t\t...args: Parameters<AgentOs[\"getSessionAgentInfo\"]>\n\t\t) => (await ensureVm(c, options)).getSessionAgentInfo(...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[\"exportRootFilesystem\"]>\n\t\t) => (await ensureVm(c, options)).exportRootFilesystem(...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.mountFs(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.unmountFs(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.unmountFs(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.mountFs(\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)).listMounts(),\n\t\tlistSoftware: async (c: AnyContext) =>\n\t\t\t(await ensureVm(c, options)).listSoftware(),\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)).linkSoftware(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\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/** 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\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> = Omit<\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\"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 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.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\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\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 (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\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.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"],"mappings":";;;AAAA,SAAS,SAAS,qBAAqB;AAqCvC,SAAS,gBAAgB,wBAAwB;;;ACrCjD,OAAO,YAAY;AACnB;AAAA,EAEC;AAAA,OAQM;AACP;AAAA,EAKC;AAAA,EACA;AAAA,EAEA;AAAA,OACM;AACP,SAAgC,UAA0B;AAgB1D,IAAM,4BAA4B;AAClC,IAAM,gCAAgC,KAAK;AAC3C,IAAM,8BAA8B;AACpC,IAAM,0BAA0B;AAChC,IAAM,oCAAoC;AAC1C,IAAM,oCAAoC;AAC1C,IAAM,6BAA6B;AACnC,IAAM,8BAA8B;AACpC,IAAM,0BAA0B,MAAM;AACtC,IAAM,gCAAgC,KAAK;AAC3C,IAAM,iBAAiB;AACvB,IAAM,uBAAuB;AAC7B,IAAM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AQ,QAAQ,CAAC,OAAO,QAAQ;AACvC,uBAAe,GAAG,IAAI;AAAA,MACvB,CAAC;AACD,YAAM,WAAW,MAAM,GAAG,YAAY;AAAA,QACrC,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;;;ADnvCA,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":["event","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 };
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__publicField
|
|
3
|
+
} from "./chunk-V6TY7KAL.js";
|
|
4
|
+
|
|
5
|
+
// src/node.ts
|
|
6
|
+
import { Buffer } from "buffer";
|
|
7
|
+
var DEFAULT_MAX_PENDING_OUTPUT_BYTES = 8 * 1024 * 1024;
|
|
8
|
+
var OUTPUT_LIMIT_WARNING_RATIO = 0.8;
|
|
9
|
+
var TRAILING_OUTPUT_GRACE_MS = 250;
|
|
10
|
+
var NodeShellOutputLimitError = class extends Error {
|
|
11
|
+
constructor(limitBytes, pendingBytes) {
|
|
12
|
+
super(
|
|
13
|
+
`AgentOS Node shell pending output exceeded ${limitBytes} bytes (${pendingBytes} bytes pending); raise AttachShellOptions.maxPendingOutputBytes to allow more`
|
|
14
|
+
);
|
|
15
|
+
this.limitBytes = limitBytes;
|
|
16
|
+
this.pendingBytes = pendingBytes;
|
|
17
|
+
__publicField(this, "code", "AGENTOS_NODE_SHELL_OUTPUT_LIMIT");
|
|
18
|
+
this.name = "NodeShellOutputLimitError";
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var NodeShellCleanupError = class extends Error {
|
|
22
|
+
constructor(errors) {
|
|
23
|
+
super("AgentOS Node shell and cleanup both failed");
|
|
24
|
+
this.errors = errors;
|
|
25
|
+
__publicField(this, "code", "AGENTOS_NODE_SHELL_CLEANUP_FAILED");
|
|
26
|
+
this.name = "NodeShellCleanupError";
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
async function attachShell(connection, options = {}) {
|
|
30
|
+
const stdin = options.stdin ?? process.stdin;
|
|
31
|
+
const stdout = options.stdout ?? process.stdout;
|
|
32
|
+
const stderr = options.stderr ?? process.stderr;
|
|
33
|
+
const events = connection;
|
|
34
|
+
if (typeof events.on !== "function") {
|
|
35
|
+
throw new TypeError("attachShell requires an AgentOS connection with on()");
|
|
36
|
+
}
|
|
37
|
+
const maxPendingOutputBytes = options.maxPendingOutputBytes ?? DEFAULT_MAX_PENDING_OUTPUT_BYTES;
|
|
38
|
+
if (!Number.isSafeInteger(maxPendingOutputBytes) || maxPendingOutputBytes <= 0) {
|
|
39
|
+
throw new RangeError(
|
|
40
|
+
"AttachShellOptions.maxPendingOutputBytes must be a positive safe integer"
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
const warn = options.onWarning ?? ((message) => stderr.write(`${message}
|
|
44
|
+
`));
|
|
45
|
+
let shellId;
|
|
46
|
+
let shellClosed = false;
|
|
47
|
+
let failure;
|
|
48
|
+
let resolveFailure;
|
|
49
|
+
const failurePromise = new Promise((resolve) => {
|
|
50
|
+
resolveFailure = resolve;
|
|
51
|
+
});
|
|
52
|
+
const fail = (error) => {
|
|
53
|
+
if (failure) return;
|
|
54
|
+
failure = error;
|
|
55
|
+
resolveFailure?.({ kind: "failure", error });
|
|
56
|
+
};
|
|
57
|
+
const earlyOutput = [];
|
|
58
|
+
let earlyOutputBytes = 0;
|
|
59
|
+
let earlyOutputWarned = false;
|
|
60
|
+
let resolveShellExit;
|
|
61
|
+
const shellExitPromise = new Promise((resolve) => {
|
|
62
|
+
resolveShellExit = resolve;
|
|
63
|
+
});
|
|
64
|
+
const onShellData = (payload) => {
|
|
65
|
+
routeOutput("stdout", payload);
|
|
66
|
+
};
|
|
67
|
+
const onShellStderr = (payload) => {
|
|
68
|
+
routeOutput("stderr", payload);
|
|
69
|
+
};
|
|
70
|
+
const onShellExit = (payload) => {
|
|
71
|
+
if (shellId && payload.shellId === shellId) resolveShellExit?.();
|
|
72
|
+
};
|
|
73
|
+
const unsubscribers = [
|
|
74
|
+
subscribe(events, "shellData", onShellData),
|
|
75
|
+
subscribe(events, "shellStderr", onShellStderr),
|
|
76
|
+
subscribe(events, "shellExit", onShellExit)
|
|
77
|
+
];
|
|
78
|
+
function routeOutput(stream, payload) {
|
|
79
|
+
try {
|
|
80
|
+
const bytes = toBytes(payload.data);
|
|
81
|
+
if (bytes.byteLength === 0) return;
|
|
82
|
+
if (!shellId) {
|
|
83
|
+
const nextBytes = earlyOutputBytes + bytes.byteLength;
|
|
84
|
+
if (nextBytes > maxPendingOutputBytes) {
|
|
85
|
+
fail(new NodeShellOutputLimitError(maxPendingOutputBytes, nextBytes));
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
earlyOutputBytes = nextBytes;
|
|
89
|
+
earlyOutput.push({ stream, payload, bytes });
|
|
90
|
+
if (!earlyOutputWarned && nextBytes >= Math.floor(maxPendingOutputBytes * OUTPUT_LIMIT_WARNING_RATIO)) {
|
|
91
|
+
earlyOutputWarned = true;
|
|
92
|
+
warn(
|
|
93
|
+
`AgentOS Node shell pending output is near its ${maxPendingOutputBytes}-byte limit (${nextBytes} bytes pending)`
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (payload.shellId !== shellId) return;
|
|
99
|
+
(stream === "stdout" ? stdout : stderr).write(bytes);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
fail(asError(error));
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
let inputAttached = false;
|
|
105
|
+
let rawModeChanged = false;
|
|
106
|
+
let previousRawMode = false;
|
|
107
|
+
let inputWrite = Promise.resolve();
|
|
108
|
+
let inputEnded = false;
|
|
109
|
+
let resizeAttached = false;
|
|
110
|
+
let signalOutcomeResolve;
|
|
111
|
+
const signalPromise = new Promise((resolve) => {
|
|
112
|
+
signalOutcomeResolve = resolve;
|
|
113
|
+
});
|
|
114
|
+
const signalHandlers = /* @__PURE__ */ new Map();
|
|
115
|
+
const onInputData = (data) => {
|
|
116
|
+
stdin.pause();
|
|
117
|
+
inputWrite = inputWrite.then(async () => {
|
|
118
|
+
if (shellId) await connection.writeShell(shellId, data);
|
|
119
|
+
}).then(() => {
|
|
120
|
+
if (!inputEnded) stdin.resume();
|
|
121
|
+
}).catch((error) => fail(asError(error)));
|
|
122
|
+
};
|
|
123
|
+
const onInputEnd = () => {
|
|
124
|
+
inputEnded = true;
|
|
125
|
+
stdin.pause();
|
|
126
|
+
inputWrite = inputWrite.then(async () => {
|
|
127
|
+
if (shellId) await connection.writeShell(shellId, "");
|
|
128
|
+
}).catch((error) => fail(asError(error)));
|
|
129
|
+
};
|
|
130
|
+
const onInputError = (error) => fail(error);
|
|
131
|
+
const onResize = () => {
|
|
132
|
+
if (!shellId) return;
|
|
133
|
+
const cols = stdout.columns;
|
|
134
|
+
const rows = stdout.rows;
|
|
135
|
+
if (!positiveInteger(cols) || !positiveInteger(rows)) return;
|
|
136
|
+
void connection.resizeShell(shellId, cols, rows).catch((error) => {
|
|
137
|
+
fail(asError(error));
|
|
138
|
+
});
|
|
139
|
+
};
|
|
140
|
+
try {
|
|
141
|
+
const opened = await connection.openShell({
|
|
142
|
+
command: options.command,
|
|
143
|
+
args: options.args,
|
|
144
|
+
env: options.env,
|
|
145
|
+
cwd: options.cwd,
|
|
146
|
+
cols: options.cols ?? stdout.columns,
|
|
147
|
+
rows: options.rows ?? stdout.rows
|
|
148
|
+
});
|
|
149
|
+
shellId = opened.shellId;
|
|
150
|
+
for (const item of earlyOutput) {
|
|
151
|
+
if (item.payload.shellId !== shellId) continue;
|
|
152
|
+
(item.stream === "stdout" ? stdout : stderr).write(item.bytes);
|
|
153
|
+
}
|
|
154
|
+
earlyOutput.length = 0;
|
|
155
|
+
earlyOutputBytes = 0;
|
|
156
|
+
if (failure) throw failure;
|
|
157
|
+
previousRawMode = Boolean(stdin.isRaw);
|
|
158
|
+
if ((options.rawMode ?? true) && stdin.isTTY && typeof stdin.setRawMode === "function" && !previousRawMode) {
|
|
159
|
+
stdin.setRawMode(true);
|
|
160
|
+
rawModeChanged = true;
|
|
161
|
+
}
|
|
162
|
+
stdin.on("data", onInputData);
|
|
163
|
+
stdin.on("end", onInputEnd);
|
|
164
|
+
stdin.on("error", onInputError);
|
|
165
|
+
stdin.resume();
|
|
166
|
+
inputAttached = true;
|
|
167
|
+
if ((options.resize ?? true) && stdout.isTTY) {
|
|
168
|
+
stdout.on("resize", onResize);
|
|
169
|
+
resizeAttached = true;
|
|
170
|
+
onResize();
|
|
171
|
+
}
|
|
172
|
+
for (const signal of options.signals ?? ["SIGINT", "SIGHUP", "SIGTERM"]) {
|
|
173
|
+
const handler = () => {
|
|
174
|
+
signalOutcomeResolve?.({
|
|
175
|
+
kind: "signal",
|
|
176
|
+
signal,
|
|
177
|
+
exitCode: signalExitCode(signal)
|
|
178
|
+
});
|
|
179
|
+
};
|
|
180
|
+
signalHandlers.set(signal, handler);
|
|
181
|
+
process.once(signal, handler);
|
|
182
|
+
}
|
|
183
|
+
const outcome = await Promise.race([
|
|
184
|
+
connection.waitShell(shellId).then((exitCode) => ({
|
|
185
|
+
kind: "exit",
|
|
186
|
+
exitCode
|
|
187
|
+
})),
|
|
188
|
+
failurePromise,
|
|
189
|
+
signalPromise
|
|
190
|
+
]);
|
|
191
|
+
if (outcome.kind === "failure") {
|
|
192
|
+
await connection.closeShell(shellId);
|
|
193
|
+
shellClosed = true;
|
|
194
|
+
throw outcome.error;
|
|
195
|
+
}
|
|
196
|
+
if (outcome.kind === "signal") {
|
|
197
|
+
await connection.closeShell(shellId);
|
|
198
|
+
shellClosed = true;
|
|
199
|
+
return outcome.exitCode;
|
|
200
|
+
}
|
|
201
|
+
await Promise.race([
|
|
202
|
+
shellExitPromise,
|
|
203
|
+
new Promise(
|
|
204
|
+
(resolve) => setTimeout(resolve, TRAILING_OUTPUT_GRACE_MS)
|
|
205
|
+
)
|
|
206
|
+
]);
|
|
207
|
+
await inputWrite;
|
|
208
|
+
if (failure) throw failure;
|
|
209
|
+
return outcome.exitCode;
|
|
210
|
+
} catch (error) {
|
|
211
|
+
if (shellId && !shellClosed) {
|
|
212
|
+
try {
|
|
213
|
+
await connection.closeShell(shellId);
|
|
214
|
+
shellClosed = true;
|
|
215
|
+
} catch (closeError) {
|
|
216
|
+
throw new NodeShellCleanupError([asError(error), asError(closeError)]);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
throw error;
|
|
220
|
+
} finally {
|
|
221
|
+
for (const unsubscribe of unsubscribers) unsubscribe();
|
|
222
|
+
if (inputAttached) {
|
|
223
|
+
stdin.removeListener("data", onInputData);
|
|
224
|
+
stdin.removeListener("end", onInputEnd);
|
|
225
|
+
stdin.removeListener("error", onInputError);
|
|
226
|
+
stdin.pause();
|
|
227
|
+
}
|
|
228
|
+
if (resizeAttached) stdout.removeListener("resize", onResize);
|
|
229
|
+
if (rawModeChanged) stdin.setRawMode?.(previousRawMode);
|
|
230
|
+
for (const [signal, handler] of signalHandlers) {
|
|
231
|
+
process.removeListener(signal, handler);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
function subscribe(events, event, listener) {
|
|
236
|
+
const untypedListener = listener;
|
|
237
|
+
const result = events.on(event, untypedListener);
|
|
238
|
+
if (typeof result === "function") return result;
|
|
239
|
+
return () => {
|
|
240
|
+
if (events.off) events.off(event, untypedListener);
|
|
241
|
+
else events.removeListener?.(event, untypedListener);
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
function toBytes(data) {
|
|
245
|
+
if (data instanceof Uint8Array) return data;
|
|
246
|
+
if (Array.isArray(data) && data.length === 2 && data[0] === "$Uint8Array" && typeof data[1] === "string") {
|
|
247
|
+
return Buffer.from(data[1], "base64");
|
|
248
|
+
}
|
|
249
|
+
if (typeof data === "string") return Buffer.from(data, "utf8");
|
|
250
|
+
throw new TypeError(
|
|
251
|
+
`Unsupported AgentOS shell data payload: ${String(data)}`
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
function positiveInteger(value) {
|
|
255
|
+
return Number.isInteger(value) && (value ?? 0) > 0;
|
|
256
|
+
}
|
|
257
|
+
function signalExitCode(signal) {
|
|
258
|
+
switch (signal) {
|
|
259
|
+
case "SIGHUP":
|
|
260
|
+
return 129;
|
|
261
|
+
case "SIGINT":
|
|
262
|
+
return 130;
|
|
263
|
+
case "SIGTERM":
|
|
264
|
+
return 143;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
function asError(error) {
|
|
268
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
269
|
+
}
|
|
270
|
+
export {
|
|
271
|
+
NodeShellCleanupError,
|
|
272
|
+
NodeShellOutputLimitError,
|
|
273
|
+
attachShell
|
|
274
|
+
};
|
|
275
|
+
//# sourceMappingURL=node.js.map
|
package/dist/node.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/node.ts"],"sourcesContent":["import { Buffer } from \"node:buffer\";\n\nconst DEFAULT_MAX_PENDING_OUTPUT_BYTES = 8 * 1024 * 1024;\nconst OUTPUT_LIMIT_WARNING_RATIO = 0.8;\nconst TRAILING_OUTPUT_GRACE_MS = 250;\n\nexport interface NodeShellOpenOptions {\n\tcommand?: string;\n\targs?: string[];\n\tenv?: Record<string, string>;\n\tcwd?: string;\n\tcols?: number;\n\trows?: number;\n}\n\nexport interface NodeShellConnection {\n\topenShell(options?: NodeShellOpenOptions): Promise<{ shellId: string }>;\n\twriteShell(shellId: string, data: string | Uint8Array): Promise<void>;\n\tresizeShell(shellId: string, cols: number, rows: number): Promise<void>;\n\tcloseShell(shellId: string): Promise<void>;\n\twaitShell(shellId: string): Promise<number>;\n}\n\nexport interface NodeShellInput {\n\tisTTY?: boolean;\n\tisRaw?: boolean;\n\tsetRawMode?(enabled: boolean): unknown;\n\ton(event: \"data\", listener: (data: string | Uint8Array) => void): unknown;\n\ton(event: \"end\", listener: () => void): unknown;\n\ton(event: \"error\", listener: (error: Error) => void): unknown;\n\tremoveListener(\n\t\tevent: \"data\",\n\t\tlistener: (data: string | Uint8Array) => void,\n\t): unknown;\n\tremoveListener(event: \"end\", listener: () => void): unknown;\n\tremoveListener(event: \"error\", listener: (error: Error) => void): unknown;\n\tpause(): unknown;\n\tresume(): unknown;\n}\n\nexport interface NodeShellOutput {\n\tisTTY?: boolean;\n\tcolumns?: number;\n\trows?: number;\n\twrite(data: string | Uint8Array): boolean;\n\ton(event: \"resize\", listener: () => void): unknown;\n\tremoveListener(event: \"resize\", listener: () => void): unknown;\n}\n\nexport type NodeShellSignal = \"SIGINT\" | \"SIGHUP\" | \"SIGTERM\";\n\nexport interface AttachShellOptions extends NodeShellOpenOptions {\n\tstdin?: NodeShellInput;\n\tstdout?: NodeShellOutput;\n\tstderr?: NodeShellOutput;\n\trawMode?: boolean;\n\tresize?: boolean;\n\tsignals?: readonly NodeShellSignal[];\n\tmaxPendingOutputBytes?: number;\n\tonWarning?: (message: string) => void;\n}\n\ninterface ShellDataPayload {\n\tshellId: string;\n\tdata: unknown;\n}\n\ninterface ShellExitPayload {\n\tshellId: string;\n\texitCode: number;\n}\n\ninterface ShellEventSource {\n\ton(event: string, listener: (payload: never) => void): unknown;\n\toff?(event: string, listener: (payload: never) => void): unknown;\n\tremoveListener?(event: string, listener: (payload: never) => void): unknown;\n}\n\ntype EarlyOutput = {\n\tstream: \"stdout\" | \"stderr\";\n\tpayload: ShellDataPayload;\n\tbytes: Uint8Array;\n};\n\ntype AttachOutcome =\n\t| { kind: \"exit\"; exitCode: number }\n\t| { kind: \"failure\"; error: Error }\n\t| { kind: \"signal\"; signal: NodeShellSignal; exitCode: number };\n\nexport class NodeShellOutputLimitError extends Error {\n\treadonly code = \"AGENTOS_NODE_SHELL_OUTPUT_LIMIT\";\n\n\tconstructor(\n\t\treadonly limitBytes: number,\n\t\treadonly pendingBytes: number,\n\t) {\n\t\tsuper(\n\t\t\t`AgentOS Node shell pending output exceeded ${limitBytes} bytes ` +\n\t\t\t\t`(${pendingBytes} bytes pending); raise AttachShellOptions.maxPendingOutputBytes to allow more`,\n\t\t);\n\t\tthis.name = \"NodeShellOutputLimitError\";\n\t}\n}\n\nexport class NodeShellCleanupError extends Error {\n\treadonly code = \"AGENTOS_NODE_SHELL_CLEANUP_FAILED\";\n\n\tconstructor(readonly errors: readonly Error[]) {\n\t\tsuper(\"AgentOS Node shell and cleanup both failed\");\n\t\tthis.name = \"NodeShellCleanupError\";\n\t}\n}\n\n/**\n * Open an AgentOS PTY shell and attach it to the current Node process terminal.\n * The connection must expose AgentOS shell actions and its broadcast `on()` API.\n */\nexport async function attachShell(\n\tconnection: NodeShellConnection,\n\toptions: AttachShellOptions = {},\n): Promise<number> {\n\tconst stdin = options.stdin ?? process.stdin;\n\tconst stdout = options.stdout ?? process.stdout;\n\tconst stderr = options.stderr ?? process.stderr;\n\tconst events = connection as unknown as ShellEventSource;\n\tif (typeof events.on !== \"function\") {\n\t\tthrow new TypeError(\"attachShell requires an AgentOS connection with on()\");\n\t}\n\n\tconst maxPendingOutputBytes =\n\t\toptions.maxPendingOutputBytes ?? DEFAULT_MAX_PENDING_OUTPUT_BYTES;\n\tif (\n\t\t!Number.isSafeInteger(maxPendingOutputBytes) ||\n\t\tmaxPendingOutputBytes <= 0\n\t) {\n\t\tthrow new RangeError(\n\t\t\t\"AttachShellOptions.maxPendingOutputBytes must be a positive safe integer\",\n\t\t);\n\t}\n\n\tconst warn =\n\t\toptions.onWarning ?? ((message: string) => stderr.write(`${message}\\n`));\n\tlet shellId: string | undefined;\n\tlet shellClosed = false;\n\tlet failure: Error | undefined;\n\tlet resolveFailure: ((outcome: AttachOutcome) => void) | undefined;\n\tconst failurePromise = new Promise<AttachOutcome>((resolve) => {\n\t\tresolveFailure = resolve;\n\t});\n\tconst fail = (error: Error) => {\n\t\tif (failure) return;\n\t\tfailure = error;\n\t\tresolveFailure?.({ kind: \"failure\", error });\n\t};\n\tconst earlyOutput: EarlyOutput[] = [];\n\tlet earlyOutputBytes = 0;\n\tlet earlyOutputWarned = false;\n\tlet resolveShellExit: (() => void) | undefined;\n\tconst shellExitPromise = new Promise<void>((resolve) => {\n\t\tresolveShellExit = resolve;\n\t});\n\n\tconst onShellData = (payload: ShellDataPayload) => {\n\t\trouteOutput(\"stdout\", payload);\n\t};\n\tconst onShellStderr = (payload: ShellDataPayload) => {\n\t\trouteOutput(\"stderr\", payload);\n\t};\n\tconst onShellExit = (payload: ShellExitPayload) => {\n\t\tif (shellId && payload.shellId === shellId) resolveShellExit?.();\n\t};\n\tconst unsubscribers = [\n\t\tsubscribe(events, \"shellData\", onShellData),\n\t\tsubscribe(events, \"shellStderr\", onShellStderr),\n\t\tsubscribe(events, \"shellExit\", onShellExit),\n\t];\n\n\tfunction routeOutput(\n\t\tstream: \"stdout\" | \"stderr\",\n\t\tpayload: ShellDataPayload,\n\t): void {\n\t\ttry {\n\t\t\tconst bytes = toBytes(payload.data);\n\t\t\tif (bytes.byteLength === 0) return;\n\t\t\tif (!shellId) {\n\t\t\t\tconst nextBytes = earlyOutputBytes + bytes.byteLength;\n\t\t\t\tif (nextBytes > maxPendingOutputBytes) {\n\t\t\t\t\tfail(new NodeShellOutputLimitError(maxPendingOutputBytes, nextBytes));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tearlyOutputBytes = nextBytes;\n\t\t\t\tearlyOutput.push({ stream, payload, bytes });\n\t\t\t\tif (\n\t\t\t\t\t!earlyOutputWarned &&\n\t\t\t\t\tnextBytes >=\n\t\t\t\t\t\tMath.floor(maxPendingOutputBytes * OUTPUT_LIMIT_WARNING_RATIO)\n\t\t\t\t) {\n\t\t\t\t\tearlyOutputWarned = true;\n\t\t\t\t\twarn(\n\t\t\t\t\t\t`AgentOS Node shell pending output is near its ${maxPendingOutputBytes}-byte limit ` +\n\t\t\t\t\t\t\t`(${nextBytes} bytes pending)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (payload.shellId !== shellId) return;\n\t\t\t(stream === \"stdout\" ? stdout : stderr).write(bytes);\n\t\t} catch (error) {\n\t\t\tfail(asError(error));\n\t\t}\n\t}\n\n\tlet inputAttached = false;\n\tlet rawModeChanged = false;\n\tlet previousRawMode = false;\n\tlet inputWrite = Promise.resolve();\n\tlet inputEnded = false;\n\tlet resizeAttached = false;\n\tlet signalOutcomeResolve: ((outcome: AttachOutcome) => void) | undefined;\n\tconst signalPromise = new Promise<AttachOutcome>((resolve) => {\n\t\tsignalOutcomeResolve = resolve;\n\t});\n\tconst signalHandlers = new Map<NodeShellSignal, () => void>();\n\n\tconst onInputData = (data: string | Uint8Array) => {\n\t\tstdin.pause();\n\t\tinputWrite = inputWrite\n\t\t\t.then(async () => {\n\t\t\t\tif (shellId) await connection.writeShell(shellId, data);\n\t\t\t})\n\t\t\t.then(() => {\n\t\t\t\tif (!inputEnded) stdin.resume();\n\t\t\t})\n\t\t\t.catch((error) => fail(asError(error)));\n\t};\n\tconst onInputEnd = () => {\n\t\tinputEnded = true;\n\t\tstdin.pause();\n\t\tinputWrite = inputWrite\n\t\t\t.then(async () => {\n\t\t\t\tif (shellId) await connection.writeShell(shellId, \"\\u0004\");\n\t\t\t})\n\t\t\t.catch((error) => fail(asError(error)));\n\t};\n\tconst onInputError = (error: Error) => fail(error);\n\tconst onResize = () => {\n\t\tif (!shellId) return;\n\t\tconst cols = stdout.columns;\n\t\tconst rows = stdout.rows;\n\t\tif (!positiveInteger(cols) || !positiveInteger(rows)) return;\n\t\tvoid connection.resizeShell(shellId, cols, rows).catch((error) => {\n\t\t\tfail(asError(error));\n\t\t});\n\t};\n\n\ttry {\n\t\tconst opened = await connection.openShell({\n\t\t\tcommand: options.command,\n\t\t\targs: options.args,\n\t\t\tenv: options.env,\n\t\t\tcwd: options.cwd,\n\t\t\tcols: options.cols ?? stdout.columns,\n\t\t\trows: options.rows ?? stdout.rows,\n\t\t});\n\t\tshellId = opened.shellId;\n\t\tfor (const item of earlyOutput) {\n\t\t\tif (item.payload.shellId !== shellId) continue;\n\t\t\t(item.stream === \"stdout\" ? stdout : stderr).write(item.bytes);\n\t\t}\n\t\tearlyOutput.length = 0;\n\t\tearlyOutputBytes = 0;\n\t\tif (failure) throw failure;\n\n\t\tpreviousRawMode = Boolean(stdin.isRaw);\n\t\tif (\n\t\t\t(options.rawMode ?? true) &&\n\t\t\tstdin.isTTY &&\n\t\t\ttypeof stdin.setRawMode === \"function\" &&\n\t\t\t!previousRawMode\n\t\t) {\n\t\t\tstdin.setRawMode(true);\n\t\t\trawModeChanged = true;\n\t\t}\n\t\tstdin.on(\"data\", onInputData);\n\t\tstdin.on(\"end\", onInputEnd);\n\t\tstdin.on(\"error\", onInputError);\n\t\tstdin.resume();\n\t\tinputAttached = true;\n\n\t\tif ((options.resize ?? true) && stdout.isTTY) {\n\t\t\tstdout.on(\"resize\", onResize);\n\t\t\tresizeAttached = true;\n\t\t\tonResize();\n\t\t}\n\n\t\tfor (const signal of options.signals ?? [\"SIGINT\", \"SIGHUP\", \"SIGTERM\"]) {\n\t\t\tconst handler = () => {\n\t\t\t\tsignalOutcomeResolve?.({\n\t\t\t\t\tkind: \"signal\",\n\t\t\t\t\tsignal,\n\t\t\t\t\texitCode: signalExitCode(signal),\n\t\t\t\t});\n\t\t\t};\n\t\t\tsignalHandlers.set(signal, handler);\n\t\t\tprocess.once(signal, handler);\n\t\t}\n\n\t\tconst outcome = await Promise.race<AttachOutcome>([\n\t\t\tconnection.waitShell(shellId).then((exitCode) => ({\n\t\t\t\tkind: \"exit\" as const,\n\t\t\t\texitCode,\n\t\t\t})),\n\t\t\tfailurePromise,\n\t\t\tsignalPromise,\n\t\t]);\n\t\tif (outcome.kind === \"failure\") {\n\t\t\tawait connection.closeShell(shellId);\n\t\t\tshellClosed = true;\n\t\t\tthrow outcome.error;\n\t\t}\n\t\tif (outcome.kind === \"signal\") {\n\t\t\tawait connection.closeShell(shellId);\n\t\t\tshellClosed = true;\n\t\t\treturn outcome.exitCode;\n\t\t}\n\n\t\tawait Promise.race([\n\t\t\tshellExitPromise,\n\t\t\tnew Promise<void>((resolve) =>\n\t\t\t\tsetTimeout(resolve, TRAILING_OUTPUT_GRACE_MS),\n\t\t\t),\n\t\t]);\n\t\tawait inputWrite;\n\t\tif (failure) throw failure;\n\t\treturn outcome.exitCode;\n\t} catch (error) {\n\t\tif (shellId && !shellClosed) {\n\t\t\ttry {\n\t\t\t\tawait connection.closeShell(shellId);\n\t\t\t\tshellClosed = true;\n\t\t\t} catch (closeError) {\n\t\t\t\tthrow new NodeShellCleanupError([asError(error), asError(closeError)]);\n\t\t\t}\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\tfor (const unsubscribe of unsubscribers) unsubscribe();\n\t\tif (inputAttached) {\n\t\t\tstdin.removeListener(\"data\", onInputData);\n\t\t\tstdin.removeListener(\"end\", onInputEnd);\n\t\t\tstdin.removeListener(\"error\", onInputError);\n\t\t\tstdin.pause();\n\t\t}\n\t\tif (resizeAttached) stdout.removeListener(\"resize\", onResize);\n\t\tif (rawModeChanged) stdin.setRawMode?.(previousRawMode);\n\t\tfor (const [signal, handler] of signalHandlers) {\n\t\t\tprocess.removeListener(signal, handler);\n\t\t}\n\t}\n}\n\nfunction subscribe<TPayload>(\n\tevents: ShellEventSource,\n\tevent: string,\n\tlistener: (payload: TPayload) => void,\n): () => void {\n\tconst untypedListener = listener as (payload: never) => void;\n\tconst result = events.on(event, untypedListener);\n\tif (typeof result === \"function\") return result as () => void;\n\treturn () => {\n\t\tif (events.off) events.off(event, untypedListener);\n\t\telse events.removeListener?.(event, untypedListener);\n\t};\n}\n\nfunction toBytes(data: unknown): Uint8Array {\n\tif (data instanceof Uint8Array) return data;\n\tif (\n\t\tArray.isArray(data) &&\n\t\tdata.length === 2 &&\n\t\tdata[0] === \"$Uint8Array\" &&\n\t\ttypeof data[1] === \"string\"\n\t) {\n\t\treturn Buffer.from(data[1], \"base64\");\n\t}\n\tif (typeof data === \"string\") return Buffer.from(data, \"utf8\");\n\tthrow new TypeError(\n\t\t`Unsupported AgentOS shell data payload: ${String(data)}`,\n\t);\n}\n\nfunction positiveInteger(value: number | undefined): value is number {\n\treturn Number.isInteger(value) && (value ?? 0) > 0;\n}\n\nfunction signalExitCode(signal: NodeShellSignal): number {\n\tswitch (signal) {\n\t\tcase \"SIGHUP\":\n\t\t\treturn 129;\n\t\tcase \"SIGINT\":\n\t\t\treturn 130;\n\t\tcase \"SIGTERM\":\n\t\t\treturn 143;\n\t}\n}\n\nfunction asError(error: unknown): Error {\n\treturn error instanceof Error ? error : new Error(String(error));\n}\n"],"mappings":";;;;;AAAA,SAAS,cAAc;AAEvB,IAAM,mCAAmC,IAAI,OAAO;AACpD,IAAM,6BAA6B;AACnC,IAAM,2BAA2B;AAqF1B,IAAM,4BAAN,cAAwC,MAAM;AAAA,EAGpD,YACU,YACA,cACR;AACD;AAAA,MACC,8CAA8C,UAAU,WACnD,YAAY;AAAA,IAClB;AANS;AACA;AAJV,wBAAS,QAAO;AAUf,SAAK,OAAO;AAAA,EACb;AACD;AAEO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAGhD,YAAqB,QAA0B;AAC9C,UAAM,4CAA4C;AAD9B;AAFrB,wBAAS,QAAO;AAIf,SAAK,OAAO;AAAA,EACb;AACD;AAMA,eAAsB,YACrB,YACA,UAA8B,CAAC,GACb;AAClB,QAAM,QAAQ,QAAQ,SAAS,QAAQ;AACvC,QAAM,SAAS,QAAQ,UAAU,QAAQ;AACzC,QAAM,SAAS,QAAQ,UAAU,QAAQ;AACzC,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