@rivet-dev/agentos-runtime-core0.4.949.5 kB
import { decodeGuestFilesystemContent, encodeGuestFilesystemContent, } from "./filesystem.js";
import { SIDECAR_PROTOCOL_SCHEMA } from "./protocol-schema.js";
export { SidecarEventBufferOverflow } from "./event-buffer.js";
export { SidecarFrameTooLarge, SidecarProcessError, SidecarProcessExited, SidecarSilenceTimeout, } from "./sidecar-errors.js";
// `Sidecar` is the public name for the native sidecar process client. The class
// is `SidecarProcess` internally; consumers import it as `Sidecar` via the
// `@rivet-dev/agentos-runtime-core/sidecar-client` subpath and the package root.
export { SidecarProcess as Sidecar };
const BRIDGE_CONTRACT_VERSION = 1;
const DEFAULT_SIDECAR_EVENT_BUFFER_CAPACITY = 4_096;
const DEFAULT_SIDECAR_GRACEFUL_EXIT_MS = 5_000;
const DEFAULT_SIDECAR_FORCE_EXIT_MS = 2_000;
// Room for the frame envelope and per-entry length prefixes.
const WRITE_FILES_FRAME_OVERHEAD_BYTES = 64 * 1024;
const WRITE_FILES_ENTRY_OVERHEAD_BYTES = 16;
let sidecarProcessSpawnFactory = null;
export function registerSidecarProcessSpawnFactory(factory) {
sidecarProcessSpawnFactory = factory;
}
export class SidecarProcess {
protocolClient;
/** Set once the transport fails for good; no request can succeed after it. */
lost = false;
nonVmRequestHandler = null;
/** One entry per VM this process admitted, so VM admission bounds its size. */
vmRequestHandlers = new Map();
/** `onEvent` subscribers, which also receive a dispose's completions. */
eventListeners = new Set();
constructor(protocolClient) {
this.protocolClient = protocolClient;
protocolClient.onClose(() => {
this.lost = true;
});
protocolClient.setSidecarRequestHandler((request) => {
const owner = request.ownership;
const handler = owner.scope === "vm"
? this.vmRequestHandlers.get(owner.vm_id)
: this.nonVmRequestHandler;
// Never fall back to another handler: it would run a sibling VM's code.
if (!handler) {
const scope = owner.scope === "vm" ? `VM ${owner.vm_id}` : owner.scope;
throw new Error(`no sidecar request handler registered for ${request.payload.type} in ${scope}`);
}
return handler(request);
});
}
static fromClient(protocolClient) {
return new SidecarProcess(protocolClient);
}
static spawn(options = {}) {
if (!sidecarProcessSpawnFactory) {
throw new Error("native sidecar spawn is not registered; import @rivet-dev/agentos-runtime-core/native-client before calling SidecarProcess.spawn, or use SidecarProcess.fromClient");
}
const protocolClient = sidecarProcessSpawnFactory({
command: options.command,
args: options.args ?? [],
cwd: options.cwd,
silenceTimeoutMs: options.silenceTimeoutMs,
eventBufferCapacity: options.eventBufferCapacity ?? DEFAULT_SIDECAR_EVENT_BUFFER_CAPACITY,
gracefulExitMs: options.gracefulExitMs ?? DEFAULT_SIDECAR_GRACEFUL_EXIT_MS,
forceExitMs: options.forceExitMs ?? DEFAULT_SIDECAR_FORCE_EXIT_MS,
disposedErrorMessage: "native sidecar disposed",
payloadCodec: options.payloadCodec ?? "bare",
});
return SidecarProcess.fromClient(protocolClient);
}
/** Handles requests that have connection or session ownership. */
setSidecarRequestHandler(handler) {
this.nonVmRequestHandler = handler;
}
/** Handles requests owned by `vmId`. Pass `null` when the VM is gone. */
setVmSidecarRequestHandler(vmId, handler) {
if (handler) {
this.vmRequestHandlers.set(vmId, handler);
}
else {
this.vmRequestHandlers.delete(vmId);
}
}
onEvent(handler) {
this.eventListeners.add(handler);
const unsubscribe = this.protocolClient.onEvent(handler);
return () => {
this.eventListeners.delete(handler);
unsubscribe();
};
}
/** Runs `handler` once when the sidecar exits or its connection fails. */
onClose(handler) {
return this.protocolClient.onClose(handler);
}
async authenticateAndOpenSession(sessionMetadata = {}) {
const authenticated = await this.sendRequest({
ownership: {
scope: "connection",
connection_id: "client-hint",
},
payload: {
type: "authenticate",
client_name: "agentos-core-client",
auth_token: "agentos-core-client-token",
protocol_version: SIDECAR_PROTOCOL_SCHEMA.version,
bridge_version: BRIDGE_CONTRACT_VERSION,
},
});
if (authenticated.payload.type !== "authenticated") {
throw new Error(`unexpected authenticate response: ${authenticated.payload.type}`);
}
const opened = await this.sendRequest({
ownership: {
scope: "connection",
connection_id: authenticated.payload.connection_id,
},
payload: {
type: "open_session",
placement: {
kind: "shared",
pool: null,
},
metadata: sessionMetadata,
},
});
if (opened.payload.type !== "session_opened") {
throw new Error(`unexpected open_session response: ${opened.payload.type}`);
}
return {
connectionId: authenticated.payload.connection_id,
sessionId: opened.payload.session_id,
maxFrameBytes: authenticated.payload.max_frame_bytes,
maxWriteFilesEntries: authenticated.payload.max_write_files_entries,
};
}
/**
* Read-only VM-config comparison using this sidecar's defaults; no VM is allocated.
* Does not compare the runtime kind or fields supplied separately to configureVm.
*/
async compareVmConfig(session, before, after, options = {}) {
const response = await this.sendRequest({
ownership: {
scope: "session",
connection_id: session.connectionId,
session_id: session.sessionId,
},
payload: {
type: "compare_vm_config",
before,
after,
before_mounts: options.beforeMounts ?? [],
after_mounts: options.afterMounts ?? [],
before_restart_identity: options.beforeRestartIdentity ?? [],
after_restart_identity: options.afterRestartIdentity ?? [],
},
});
if (response.payload.type !== "vm_config_compared") {
throw new Error(`unexpected compare_vm_config response: ${response.payload.type}`);
}
return response.payload.equivalent;
}
/**
* Acquire verified metadata/warm cache without a VM. Does not pin an artifact
* for later installation. The sidecar clamps timeout_ms to its operator cap;
* dropping the client waiter does not immediately cancel server acquisition.
*/
async acquirePackage(session, options) {
const response = await this.sendRequest({
ownership: {
scope: "session",
connection_id: session.connectionId,
session_id: session.sessionId,
},
payload: { ...options, type: "acquire_package" },
});
if (response.payload.type !== "package_acquired") {
throw new Error(`unexpected acquire_package response: ${response.payload.type}`);
}
const { type: _type, ...metadata } = response.payload;
return metadata;
}
async getPackageCacheStats(session) {
const response = await this.sendRequest({
ownership: {
scope: "session",
connection_id: session.connectionId,
session_id: session.sessionId,
},
payload: { type: "get_package_cache_stats" },
});
if (response.payload.type !== "package_cache_stats") {
throw new Error(`unexpected get_package_cache_stats response: ${response.payload.type}`);
}
const { type: _type, ...stats } = response.payload;
return stats;
}
async createVm(session, options) {
const response = await this.sendRequest({
ownership: {
scope: "session",
connection_id: session.connectionId,
session_id: session.sessionId,
},
payload: {
type: "create_vm",
runtime: options.runtime,
config: options.config,
},
});
if (response.payload.type !== "vm_created") {
throw new Error(`unexpected create_vm response: ${response.payload.type}`);
}
return {
vmId: response.payload.vm_id,
};
}
async extensionRequest(session, vm, envelope) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "ext",
envelope,
},
});
if (response.payload.type !== "ext_result") {
throw new Error(`unexpected ext response: ${response.payload.type}`);
}
return response.payload.envelope;
}
async configureVm(session, vm, options) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "configure_vm",
mounts: (options.mounts ?? []).map(toWireMountDescriptor),
software: (options.software ?? []).map(toWireSoftwareDescriptor),
permissions: toWirePermissionsPolicy(options.permissions),
module_access_cwd: options.moduleAccessCwd,
instructions: options.instructions ?? [],
projected_modules: (options.projectedModules ?? []).map(toWireProjectedModuleDescriptor),
command_permissions: options.commandPermissions ?? {},
...(options.loopbackExemptPorts
? { loopback_exempt_ports: options.loopbackExemptPorts }
: {}),
packages: (options.packages ?? []).map(toWirePackageDescriptor),
...(options.packagesMountAt
? { packages_mount_at: options.packagesMountAt }
: {}),
bootstrap_commands: options.bootstrapCommands ?? [],
host_function_shim_commands: options.hostFunctionShimCommands ?? [],
},
});
if (response.payload.type !== "vm_configured") {
throw new Error(`unexpected configure_vm response: ${response.payload.type}`);
}
return {
appliedMounts: response.payload.applied_mounts,
appliedSoftware: response.payload.applied_software,
projectedCommands: response.payload.projected_commands.map((command) => ({
name: command.name,
guestPath: command.guest_path,
})),
};
}
/**
* Runtime dynamic `linkSoftware`: project one package into the live
* `/opt/agentos` tree. Returns projected command entrypoints.
*/
async linkPackage(session, vm, descriptor, packageId = `path:${descriptor.path}`) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "link_package",
package: toWirePackageDescriptor(descriptor),
package_id: packageId,
},
});
if (response.payload.type !== "package_linked") {
throw new Error(`unexpected link_package response: ${response.payload.type}`);
}
return {
projectedCommands: response.payload.projected_commands.map((command) => ({
name: command.name,
guestPath: command.guest_path,
})),
};
}
/** Resolve, verify, and pin one artifact in the sidecar before projection. */
async installPackage(session, vm, acquisition) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: { type: "install_package", acquisition },
});
if (response.payload.type !== "package_installed") {
throw new Error(`unexpected install_package response: ${response.payload.type}`);
}
const { type: _type, ...installed } = response.payload;
return installed;
}
async unlinkPackage(session, vm, packageId) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: { type: "unlink_package", package_id: packageId },
});
if (response.payload.type !== "package_unlinked") {
throw new Error(`unexpected unlink_package response: ${response.payload.type}`);
}
return response.payload.removed_commands;
}
async providedCommands(session, vm) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "provided_commands",
},
});
if (response.payload.type !== "provided_commands_response") {
throw new Error(`unexpected provided_commands response: ${response.payload.type}`);
}
return response.payload.packages.map((pkg) => ({
packageName: pkg.package_name,
commands: [...pkg.commands],
}));
}
async registerHostCallbacks(session, vm, registration) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "register_host_callbacks",
name: registration.name,
description: registration.description,
command_aliases: registration.commandAliases ?? [],
registry_command_aliases: registration.registryCommandAliases ?? [],
callbacks: Object.fromEntries(Object.entries(registration.callbacks).map(([callbackName, callback]) => [
callbackName,
{
description: callback.description,
input_schema: callback.inputSchema,
...(callback.timeoutMs !== undefined
? { timeout_ms: callback.timeoutMs }
: {}),
...(callback.examples && callback.examples.length > 0
? {
examples: callback.examples.map((example) => ({
description: example.description,
input: example.input,
})),
}
: {}),
},
])),
},
});
if (response.payload.type !== "host_callbacks_registered") {
throw new Error(`unexpected register_host_callbacks response: ${response.payload.type}`);
}
return {
registration: response.payload.registration,
commandCount: response.payload.command_count,
};
}
async createLayer(session, vm) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "create_layer",
},
});
if (response.payload.type !== "layer_created") {
throw new Error(`unexpected create_layer response: ${response.payload.type}`);
}
return response.payload.layer_id;
}
async sealLayer(session, vm, layerId) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "seal_layer",
layer_id: layerId,
},
});
if (response.payload.type !== "layer_sealed") {
throw new Error(`unexpected seal_layer response: ${response.payload.type}`);
}
return response.payload.layer_id;
}
async importSnapshot(session, vm, entries) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "import_snapshot",
entries,
},
});
if (response.payload.type !== "snapshot_imported") {
throw new Error(`unexpected import_snapshot response: ${response.payload.type}`);
}
return response.payload.layer_id;
}
async exportSnapshot(session, vm, layerId) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "export_snapshot",
layer_id: layerId,
},
});
if (response.payload.type !== "snapshot_exported") {
throw new Error(`unexpected export_snapshot response: ${response.payload.type}`);
}
return response.payload.entries;
}
async createOverlay(session, vm, options) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "create_overlay",
mode: options.mode,
upper_layer_id: options.upperLayerId,
lower_layer_ids: options.lowerLayerIds,
},
});
if (response.payload.type !== "overlay_created") {
throw new Error(`unexpected create_overlay response: ${response.payload.type}`);
}
return response.payload.layer_id;
}
async bootstrapRootFilesystem(session, vm, entries) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "bootstrap_root_filesystem",
entries,
},
});
if (response.payload.type !== "root_filesystem_bootstrapped") {
throw new Error(`unexpected bootstrap_root_filesystem response: ${response.payload.type}`);
}
}
async snapshotRootFilesystem(session, vm, maxBytes) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "snapshot_root_filesystem",
max_bytes: maxBytes,
},
});
if (response.payload.type !== "root_filesystem_snapshot") {
throw new Error(`unexpected snapshot_root_filesystem response: ${response.payload.type}`);
}
return response.payload.entries;
}
async listMounts(session, vm) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: { type: "list_mounts" },
});
if (response.payload.type !== "mounts_listed") {
throw new Error(`unexpected list_mounts response: ${response.payload.type}`);
}
return response.payload.mounts.map((mount) => ({
path: mount.path,
kind: mount.kind,
readOnly: mount.read_only,
}));
}
async readFile(session, vm, path) {
const response = await this.guestFilesystemCall(session, vm, {
operation: "read_file",
path,
});
return decodeGuestFilesystemContent(response);
}
async pread(session, vm, path, offset, length) {
const response = await this.guestFilesystemCall(session, vm, {
operation: "pread",
path,
offset,
len: length,
});
return decodeGuestFilesystemContent(response);
}
async writeFile(session, vm, path, content) {
const encoded = encodeGuestFilesystemContent(content);
await this.guestFilesystemCall(session, vm, {
operation: "write_file",
path,
content: encoded.content,
encoding: encoded.encoding,
});
}
/**
* Writes each file after creating its missing parent directories. Returns
* one error message (or `null` on success) per entry, in input order. A
* failed entry does not stop later entries. Sends as few requests as the
* entry-count and frame-size limits from the handshake allow.
*/
async writeFiles(session, vm, entries) {
const encoder = new TextEncoder();
const encoded = entries.map((entry) => ({
path: entry.path,
content: typeof entry.content === "string"
? encoder.encode(entry.content)
: entry.content,
}));
const errors = new Array(entries.length).fill(null);
const maxEntries = Math.max(1, session.maxWriteFilesEntries);
let start = 0;
while (start < encoded.length) {
let end = start;
let bytes = WRITE_FILES_FRAME_OVERHEAD_BYTES;
while (end < encoded.length &&
end - start < maxEntries) {
const entryBytes = Buffer.byteLength(encoded[end].path) +
encoded[end].content.byteLength +
WRITE_FILES_ENTRY_OVERHEAD_BYTES;
if (end > start && bytes + entryBytes > session.maxFrameBytes) {
break;
}
bytes += entryBytes;
end += 1;
}
const chunk = encoded.slice(start, end);
try {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: { type: "guest_filesystem_write_files", entries: chunk },
});
if (response.payload.type !== "guest_filesystem_write_files_result" ||
response.payload.response.results.length !== chunk.length) {
throw new Error(`unexpected guest_filesystem_write_files response: ${response.payload.type}`);
}
response.payload.response.results.forEach((result, index) => {
if (result.error) {
const { code, message } = result.error;
errors[start + index] = message.startsWith(`${code}:`)
? message
: `${code}: ${message}`;
}
});
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
for (let index = start; index < end; index += 1) {
errors[index] = message;
}
}
start = end;
}
return errors;
}
async pwrite(session, vm, path, offset, content) {
const encoded = encodeGuestFilesystemContent(content);
await this.guestFilesystemCall(session, vm, {
operation: "pwrite",
path,
offset,
content: encoded.content,
encoding: encoded.encoding,
});
}
async mkdir(session, vm, path, options) {
await this.guestFilesystemCall(session, vm, {
operation: options?.recursive ? "mkdir" : "create_dir",
path,
recursive: options?.recursive ?? false,
});
}
async readdir(session, vm, path) {
const response = await this.guestFilesystemCall(session, vm, {
operation: "read_dir",
path,
});
return (response.entries ?? []).map((entry) => entry.name);
}
async readdirRecursive(session, vm, path, options) {
const response = await this.guestFilesystemCall(session, vm, {
operation: "read_dir_recursive",
path,
max_depth: options?.maxDepth,
});
return response.entries ?? [];
}
async exists(session, vm, path) {
const response = await this.guestFilesystemCall(session, vm, {
operation: "exists",
path,
});
return response.exists ?? false;
}
async stat(session, vm, path, options) {
const response = await this.guestFilesystemCall(session, vm, {
operation: options?.dereference === false ? "lstat" : "stat",
path,
});
if (!response.stat) {
throw new Error(`sidecar returned no stat payload for ${path}`);
}
return response.stat;
}
async lstat(session, vm, path) {
return this.stat(session, vm, path, { dereference: false });
}
async rename(session, vm, fromPath, toPath) {
await this.guestFilesystemCall(session, vm, {
operation: "rename",
path: fromPath,
destination_path: toPath,
});
}
async realpath(session, vm, path) {
const response = await this.guestFilesystemCall(session, vm, {
operation: "realpath",
path,
});
if (response.target === undefined) {
throw new Error(`sidecar returned no realpath payload for ${path}`);
}
return response.target;
}
async removeFile(session, vm, path) {
await this.guestFilesystemCall(session, vm, {
operation: "remove_file",
path,
});
}
async removeDir(session, vm, path) {
await this.guestFilesystemCall(session, vm, {
operation: "remove_dir",
path,
});
}
async removePath(session, vm, path, options) {
await this.guestFilesystemCall(session, vm, {
operation: "remove",
path,
recursive: options?.recursive ?? false,
});
}
async copyPath(session, vm, fromPath, toPath, options) {
await this.guestFilesystemCall(session, vm, {
operation: "copy",
path: fromPath,
destination_path: toPath,
recursive: options?.recursive ?? false,
});
}
async movePath(session, vm, fromPath, toPath) {
await this.guestFilesystemCall(session, vm, {
operation: "move",
path: fromPath,
destination_path: toPath,
recursive: true,
});
}
async symlink(session, vm, target, linkPath) {
await this.guestFilesystemCall(session, vm, {
operation: "symlink",
path: linkPath,
target,
});
}
async readLink(session, vm, path) {
const response = await this.guestFilesystemCall(session, vm, {
operation: "read_link",
path,
});
if (response.target === undefined) {
throw new Error(`sidecar returned no symlink target for ${path}`);
}
return response.target;
}
async link(session, vm, fromPath, toPath) {
await this.guestFilesystemCall(session, vm, {
operation: "link",
path: fromPath,
destination_path: toPath,
});
}
async chmod(session, vm, path, mode) {
await this.guestFilesystemCall(session, vm, {
operation: "chmod",
path,
mode,
});
}
async chown(session, vm, path, uid, gid) {
await this.guestFilesystemCall(session, vm, {
operation: "chown",
path,
uid,
gid,
});
}
async utimes(session, vm, path, atimeMs, mtimeMs) {
await this.guestFilesystemCall(session, vm, {
operation: "utimes",
path,
atime_ms: atimeMs,
mtime_ms: mtimeMs,
});
}
async truncate(session, vm, path, length) {
await this.guestFilesystemCall(session, vm, {
operation: "truncate",
path,
len: length,
});
}
async disposeVm(session, vm) {
// A VM dies with its sidecar process, so a lost transport leaves nothing
// to dispose. Matches the Rust client.
if (this.lost) {
return;
}
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "dispose_vm",
reason: "requested",
},
});
if (response.payload.type !== "vm_disposed") {
throw new Error(`unexpected dispose_vm response: ${response.payload.type}`);
}
// An execution can finish just before the dispose while its completion
// event is still on the event lane. The response lists every execution
// that had finished; deliver each as the completion event it stands
// for, before the dispose resolves. A listener that already saw the
// event ignores the repeat.
for (const completed of response.payload.completed_executions) {
const event = {
frame_type: "event",
schema: SIDECAR_PROTOCOL_SCHEMA,
ownership: response.ownership,
payload: { type: "execution_completed", event: completed },
};
for (const listener of this.eventListeners) {
try {
listener(event);
}
catch (error) {
console.error("[agentOS] dispose completion listener failed", error);
}
}
}
}
async execute(session, vm, options) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "execute",
process_id: options.processId,
args: options.args ?? [],
...(options.command ? { command: options.command } : {}),
...(options.runtime ? { runtime: options.runtime } : {}),
...(options.entrypoint ? { entrypoint: options.entrypoint } : {}),
...(options.env ? { env: options.env } : {}),
...(options.cwd ? { cwd: options.cwd } : {}),
...(options.wasmPermissionTier
? { wasm_permission_tier: options.wasmPermissionTier }
: {}),
retain_output: options.retainOutput ?? false,
},
});
if (response.payload.type !== "process_started") {
throw new Error(`unexpected execute response: ${response.payload.type}`);
}
return {
pid: response.payload.pid ?? null,
};
}
async writeStdin(session, vm, processId, chunk) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "write_stdin",
process_id: processId,
chunk: typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk,
},
});
if (response.payload.type !== "stdin_written") {
throw new Error(`unexpected write_stdin response: ${response.payload.type}`);
}
}
async resizePty(session, vm, processId, cols, rows) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "resize_pty",
process_id: processId,
cols,
rows,
},
});
if (response.payload.type !== "pty_resized") {
throw new Error(`unexpected resize_pty response: ${response.payload.type}`);
}
}
async closeStdin(session, vm, processId) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "close_stdin",
process_id: processId,
},
});
if (response.payload.type !== "stdin_closed") {
throw new Error(`unexpected close_stdin response: ${response.payload.type}`);
}
}
async killProcess(session, vm, processId, signal = "SIGTERM") {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "kill_process",
process_id: processId,
signal,
},
});
if (response.payload.type !== "process_killed") {
throw new Error(`unexpected kill_process response: ${response.payload.type}`);
}
}
async findListener(session, vm, request) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "find_listener",
...(request.host !== undefined ? { host: request.host } : {}),
...(request.port !== undefined ? { port: request.port } : {}),
...(request.path !== undefined ? { path: request.path } : {}),
},
});
if (response.payload.type !== "listener_snapshot") {
throw new Error(`unexpected find_listener response: ${response.payload.type}`);
}
return response.payload.listener
? toSidecarSocketStateEntry(response.payload.listener)
: null;
}
async getProcessSnapshot(session, vm) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "get_process_snapshot",
},
});
if (response.payload.type !== "process_snapshot") {
throw new Error(`unexpected get_process_snapshot response: ${response.payload.type}`);
}
return response.payload.processes.map(toSidecarProcessSnapshotEntry);
}
async getResourceSnapshot(session, vm) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "get_resource_snapshot",
},
});
if (response.payload.type !== "resource_snapshot") {
throw new Error(`unexpected get_resource_snapshot response: ${response.payload.type}`);
}
return {
runningProcesses: response.payload.running_processes,
exitedProcesses: response.payload.exited_processes,
fdTables: response.payload.fd_tables,
openFds: response.payload.open_fds,
pipes: response.payload.pipes,
pipeBufferedBytes: response.payload.pipe_buffered_bytes,
ptys: response.payload.ptys,
ptyBufferedInputBytes: response.payload.pty_buffered_input_bytes,
ptyBufferedOutputBytes: response.payload.pty_buffered_output_bytes,
sockets: response.payload.sockets,
socketListeners: response.payload.socket_listeners,
socketConnections: response.payload.socket_connections,
socketBufferedBytes: response.payload.socket_buffered_bytes,
socketDatagramQueueLen: response.payload.socket_datagram_queue_len,
queueSnapshots: response.payload.queue_snapshots.map((queue) => ({
name: queue.name,
category: queue.category,
depth: queue.depth,
highWater: queue.high_water,
capacity: queue.capacity,
fillPercent: queue.fill_percent,
})),
};
}
async findBoundUdp(session, vm, request) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "find_bound_udp",
...(request.host !== undefined ? { host: request.host } : {}),
...(request.port !== undefined ? { port: request.port } : {}),
},
});
if (response.payload.type !== "bound_udp_snapshot") {
throw new Error(`unexpected find_bound_udp response: ${response.payload.type}`);
}
return response.payload.socket
? toSidecarSocketStateEntry(response.payload.socket)
: null;
}
async vmFetch(session, vm, request) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "vm_fetch",
port: request.port,
method: request.method,
path: request.path,
headers_json: request.headersJson,
...(request.body !== undefined ? { body: request.body } : {}),
...(request.bodyBase64 !== undefined
? { body_base64: request.bodyBase64 }
: {}),
...(request.streamOperation !== undefined
? { stream_operation: request.streamOperation }
: {}),
...(request.streamId !== undefined
? { stream_id: request.streamId }
: {}),
...(request.maxBytes !== undefined
? { max_bytes: request.maxBytes }
: {}),
},
});
if (response.payload.type !== "vm_fetch_result") {
throw new Error(`unexpected vm_fetch response: ${response.payload.type}`);
}
return response.payload.response_json;
}
async getSignalState(session, vm, processId) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "get_signal_state",
process_id: processId,
},
});
if (response.payload.type !== "signal_state") {
throw new Error(`unexpected get_signal_state response: ${response.payload.type}`);
}
return {
processId: response.payload.process_id,
handlers: new Map(Object.entries(response.payload.handlers).map(([signal, registration]) => [
Number(signal),
{
action: registration.action,
mask: [...registration.mask],
flags: registration.flags,
},
])),
};
}
async getZombieTimerCount(session, vm) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "get_zombie_timer_count",
},
});
if (response.payload.type !== "zombie_timer_count") {
throw new Error(`unexpected get_zombie_timer_count response: ${response.payload.type}`);
}
return {
count: response.payload.count,
};
}
async hostFilesystemCall(session, vm, request) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "host_filesystem_call",
operation: request.operation,
path: request.path,
payload_size_bytes: request.payloadSizeBytes,
},
});
if (response.payload.type !== "filesystem_result") {
throw new Error(`unexpected host_filesystem_call response: ${response.payload.type}`);
}
return {
operation: response.payload.operation,
status: response.payload.status,
payloadSizeBytes: response.payload.payload_size_bytes,
};
}
async persistenceLoad(session, key) {
const response = await this.sendRequest({
ownership: {
scope: "session",
connection_id: session.connectionId,
session_id: session.sessionId,
},
payload: { type: "persistence_load", key },
});
if (response.payload.type !== "persistence_state") {
throw new Error(`unexpected persistence_load response: ${response.payload.type}`);
}
return {
key: response.payload.key,
found: response.payload.found,
payloadSizeBytes: response.payload.payload_size_bytes,
};
}
async persistenceFlush(session, request) {
const response = await this.sendRequest({
ownership: {
scope: "session",
connection_id: session.connectionId,
session_id: session.sessionId,
},
payload: {
type: "persistence_flush",
key: request.key,
payload_size_bytes: request.payloadSizeBytes,
},
});
if (response.payload.type !== "persistence_flushed") {
throw new Error(`unexpected persistence_flush response: ${response.payload.type}`);
}
return {
key: response.payload.key,
committedBytes: response.payload.committed_bytes,
};
}
async waitForEvent(matcher, timeoutMs, options) {
return await this.protocolClient.waitForEvent(matcher, timeoutMs, options);
}
/** Internal semantic request entrypoint used by the AgentOS client surface. */
async sendVmRequest(session, vm, payload) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload,
});
return response.payload;
}
async dispose() {
await this.protocolClient.dispose();
}
async sendRequest(input) {
return await this.protocolClient.sendRequest(input);
}
async guestFilesystemCall(session, vm, payload) {
const response = await this.sendRequest({
ownership: {
scope: "vm",
connection_id: session.connectionId,
session_id: session.sessionId,
vm_id: vm.vmId,
},
payload: {
type: "guest_filesystem_call",
...payload,
},
});
if (response.payload.type !== "guest_filesystem_result") {
throw new Error(`unexpected guest_filesystem_call response: ${response.payload.type}`);
}
return response.payload;
}
}
function toSidecarSocketStateEntry(entry) {
return {
processId: entry.process_id,
...(entry.host !== undefined ? { host: entry.host } : {}),
...(entry.port !== undefined ? { port: entry.port } : {}),
...(entry.path !== undefined ? { path: entry.path } : {}),
};
}
function toSidecarProcessSnapshotEntry(entry) {
return {
processId: entry.process_id,
pid: entry.pid,
ppid: entry.ppid,
pgid: entry.pgid,
sid: entry.sid,
driver: entry.driver,
command: entry.command,
args: [...(entry.args ?? [])],
cwd: entry.cwd,
status: entry.status,
exitCode: entry.exit_code ?? null,
};
}
function toWireRootFilesystemDescriptor(descriptor) {
if (!descriptor) {
return {};
}
return {
...(descriptor.mode ? { mode: descriptor.mode } : {}),
...(descriptor.disableDefaultBaseLayer !== undefined
? { disable_default_base_layer: descriptor.disableDefaultBaseLayer }
: {}),
...(descriptor.lowers
? {
lowers: descriptor.lowers.map((lower) => lower.kind === "bundled_base_filesystem"
? { kind: "bundled_base_filesystem" }
: {
kind: "snapshot",
entries: (lower.entries ?? []).map(toWireRootFilesystemEntry),
}),
}
: {}),
...(descriptor.bootstrapEntries
? {
bootstrap_entries: descriptor.bootstrapEntries.map(toWireRootFilesystemEntry),
}
: {}),
};
}
function toWireRootFilesystemEntry(entry) {
return {
path: entry.path,
kind: entry.kind,
...(entry.mode !== undefined ? { mode: entry.mode } : {}),
...(entry.uid !== undefined ? { uid: entry.uid } : {}),
...(entry.gid !== undefined ? { gid: entry.gid } : {}),
...(entry.content !== undefined ? { content: entry.content } : {}),
...(entry.encoding !== undefined ? { encoding: entry.encoding } : {}),
...(entry.target !== undefined ? { target: entry.target } : {}),
...(entry.executable !== undefined ? { executable: entry.executable } : {}),
};
}
function toWireMountDescriptor(descriptor) {
return {
guest_path: descriptor.guestPath,
guest_source: descriptor.guestSource ?? descriptor.plugin.id,
guest_fstype: descriptor.guestFstype ?? descriptor.plugin.id,
read_only: descriptor.readOnly,
plugin: {
id: descriptor.plugin.id,
config: descriptor.plugin.config ?? {},
},
};
}
function toWireSoftwareDescriptor(descriptor) {
return {
package_name: descriptor.packageName,
root: descriptor.root,
};
}
function toWirePermissionsPolicy(policy) {
if (!policy) {
return undefined;
}
return {
fs: policy.fs,
network: policy.network,
child_process: policy.childProcess,
process: policy.process,
env: policy.env,
host_function: policy.hostFunction,
};
}
function toWireProjectedModuleDescriptor(descriptor) {
return {
package_name: descriptor.packageName,
entrypoint: descriptor.entrypoint,
};
}
function toWirePackageDescriptor(descriptor) {
return {
path: descriptor.path,
};
}
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.