3467 lines · 88.2 KB · TypeScript
RawDownload
import { execFileSync } from "node:child_process";import * as fsSync from "node:fs";import * as fs from "node:fs/promises";import { tmpdir } from "node:os";import * as path from "node:path";import * as posixPath from "node:path/posix";import { fileURLToPath } from "node:url";import "./native-client.js";import { resolvePublishedSidecarBinary } from "./binary.js";import { findCargoBinary, resolveCargoBinary } from "./cargo.js";import type { JsRuntimeConfig } from "./generated/JsRuntimeConfig.js";import type { PermissionsPolicy } from "./generated/PermissionsPolicy.js";import type { VmLimitsConfig } from "./generated/VmLimitsConfig.js";import type { VmUserConfig } from "./generated/VmUserConfig.js";import {	type AuthenticatedSession,	type CreatedVm,	type LocalCompatMount,	NativeSidecarKernelProxy,	type RootFilesystemEntry,	SidecarProcess,	type SidecarRegisteredHostCallbackDefinition,	type SidecarRequestFrame,	type SidecarResponsePayload,	serializeMountConfigForSidecar,} from "./kernel-proxy.js"; export const AF_INET = 2;export const AF_UNIX = 1;export const SOCK_STREAM = 1;export const SOCK_DGRAM = 2;export const SIGTERM = 15; const S_IFREG = 0o100000;const S_IFDIR = 0o040000;const S_IFLNK = 0o120000;const MAX_SYMLINK_DEPTH = 40;const KERNEL_COMMAND_STUB = "#!/bin/sh\n# kernel command stub\n";const NODE_RUNTIME_BOOTSTRAP_COMMANDS = ["node", "npm", "npx"] as const;const KERNEL_POSIX_BOOTSTRAP_DIRS = [	"/dev",	"/proc",	"/tmp",	"/bin",	"/lib",	"/sbin",	"/boot",	"/etc",	"/root",	"/run",	"/srv",	"/sys",	"/opt",	"/opt/agentos",	"/opt/agentos/bin",	"/mnt",	"/media",	"/home",	"/home/agentos",	"/workspace",	"/usr",	"/usr/bin",	"/usr/games",	"/usr/include",	"/usr/lib",	"/usr/libexec",	"/usr/man",	"/usr/local",	"/usr/local/bin",	"/usr/sbin",	"/usr/share",	"/usr/share/man",	"/var",	"/var/cache",	"/var/empty",	"/var/lib",	"/var/lock",	"/var/log",	"/var/run",	"/var/spool",	"/var/tmp",] as const;const REPO_ROOT = fileURLToPath(new URL("../../..", import.meta.url));const SIDECAR_BINARY = path.join(	REPO_ROOT,	"target/debug/agentos-native-sidecar",);const SIDECAR_BUILD_INPUTS = [	path.join(REPO_ROOT, "Cargo.toml"),	path.join(REPO_ROOT, "Cargo.lock"),	path.join(REPO_ROOT, "crates/bridge"),	path.join(REPO_ROOT, "crates/build-support"),	path.join(REPO_ROOT, "crates/execution"),	path.join(REPO_ROOT, "crates/kernel"),	path.join(REPO_ROOT, "crates/native-sidecar"),	path.join(REPO_ROOT, "crates/native-sidecar-core"),	path.join(REPO_ROOT, "crates/sidecar-protocol"),	path.join(REPO_ROOT, "crates/v8-runtime"),	path.join(REPO_ROOT, "crates/vfs"),	path.join(REPO_ROOT, "crates/vm-config"),	path.join(REPO_ROOT, "packages/build-tools/bridge-src"),	path.join(REPO_ROOT, "packages/build-tools/package.json"),	path.join(REPO_ROOT, "packages/build-tools/scripts/build-v8-bridge.mjs"),	path.join(REPO_ROOT, "packages/core/fixtures/base-filesystem.json"),	path.join(REPO_ROOT, "packages/runtime-core/fixtures/base-filesystem.json"),	path.join(REPO_ROOT, "pnpm-lock.yaml"),] as const; export type KernelBootTimingPhase =	| "filesystem_snapshot"	| "sidecar_spawn"	| "session_open"	| "vm_create"	| "vm_ready"	| "vm_configure"; export interface KernelBootTiming {	phase: KernelBootTimingPhase;	durationMs: number;}let ensuredSidecarBinary: string | null = null; export type StdioChannel = "stdout" | "stderr";export type TimingMitigation = "off" | "freeze";export type PermissionMode = "allow" | "deny";export type PermissionDecision = PermissionMode; export interface VirtualDirEntry {	name: string;	isDirectory: boolean;	isSymbolicLink?: boolean;} export interface VirtualStat {	mode: number;	size: number;	sizeExact?: bigint;	blocks: number;	dev: number;	rdev: number;	isDirectory: boolean;	isSymbolicLink: boolean;	atimeMs: number;	mtimeMs: number;	ctimeMs: number;	birthtimeMs: number;	ino: number;	inoExact?: bigint;	nlink: number;	nlinkExact?: bigint;	uid: number;	gid: number;} export interface VirtualFileSystem {	readFile(path: string): Promise<Uint8Array>;	readTextFile(path: string): Promise<string>;	readDir(path: string): Promise<string[]>;	readDirWithTypes(path: string): Promise<VirtualDirEntry[]>;	writeFile(path: string, content: string | Uint8Array): Promise<void>;	createDir(path: string): Promise<void>;	mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;	exists(path: string): Promise<boolean>;	stat(path: string): Promise<VirtualStat>;	removeFile(path: string): Promise<void>;	removeDir(path: string): Promise<void>;	rename(oldPath: string, newPath: string): Promise<void>;	realpath(path: string): Promise<string>;	symlink(target: string, linkPath: string): Promise<void>;	readlink(path: string): Promise<string>;	lstat(path: string): Promise<VirtualStat>;	link(oldPath: string, newPath: string): Promise<void>;	chmod(path: string, mode: number): Promise<void>;	chown(		path: string,		uid: number,		gid: number,		options?: { followSymlinks?: boolean },	): Promise<void>;	utimes(path: string, atime: number, mtime: number): Promise<void>;	truncate(path: string, length: number): Promise<void>;	pread(path: string, offset: number, length: number): Promise<Uint8Array>;	pwrite(path: string, offset: number, data: Uint8Array): Promise<void>;} export interface NetworkAccessRequest {	url?: string;	host?: string;	port?: number;	protocol?: string;} export interface FsPermissionRule {	mode: PermissionMode;	operations?: string[];	paths?: string[];} export interface PatternPermissionRule {	mode: PermissionMode;	operations?: string[];	patterns?: string[];} export interface RulePermissions<TRule> {	default?: PermissionMode;	rules: TRule[];} export type FsPermissions = PermissionMode | RulePermissions<FsPermissionRule>;export type NetworkPermissions =	| PermissionMode	| RulePermissions<PatternPermissionRule>;export type ChildProcessPermissions =	| PermissionMode	| RulePermissions<PatternPermissionRule>;export type ProcessPermissions =	| PermissionMode	| RulePermissions<PatternPermissionRule>;export type EnvPermissions =	| PermissionMode	| RulePermissions<PatternPermissionRule>;export type BindingPermissions =	| PermissionMode	| RulePermissions<PatternPermissionRule>; export interface ProcessInfo {	pid: number;	ppid: number;	pgid: number;	sid: number;	driver: string;	command: string;	args: string[];	cwd: string;	status: "running" | "exited";	exitCode: number | null;	startTime: number;	exitTime: number | null;} export interface ManagedProcess {	pid: number;	writeStdin(data: Uint8Array | string): void;	closeStdin(): void;	kill(signal?: number): void;	wait(): Promise<number>;	readonly exitCode: number | null;} export interface ShellHandle {	pid: number;	write(data: Uint8Array | string): void;	/** Ordered PTY output containing stdout and stderr exactly once. */	onData: ((data: Uint8Array) => void) | null;	resize(cols: number, rows: number): void;	kill(signal?: number): void;	wait(): Promise<number>;} export interface OpenShellOptions {	command?: string;	args?: string[];	env?: Record<string, string>;	cwd?: string;	cols?: number;	rows?: number;	/** Optional stderr-only diagnostic tap; do not render it alongside `onData`. */	onStderr?: (data: Uint8Array) => void;} export interface ConnectTerminalOptions extends OpenShellOptions {	onData?: (data: Uint8Array) => void;} export interface ExecOptions {	env?: Record<string, string>;	cwd?: string;	stdin?: string | Uint8Array;	timeout?: number;	onStdout?: (data: Uint8Array) => void;	onStderr?: (data: Uint8Array) => void;	captureStdio?: boolean;	filePath?: string;	cpuTimeLimitMs?: number;	timingMitigation?: TimingMitigation;} export interface ExecResult {	exitCode: number;	stdout: string;	stderr: string;} export interface RunResult<T = unknown> {	value?: T;	code: number;	errorMessage?: string;} export interface KernelSpawnOptions extends ExecOptions {	stdio?: "pipe" | "inherit";	stdinFd?: number;	stdoutFd?: number;	stderrFd?: number;	streamStdin?: boolean;} export type KernelExecOptions = ExecOptions;export type KernelExecResult = ExecResult;export type StatInfo = VirtualStat;export type DirEntry = VirtualDirEntry;export type StdioEvent = { channel: StdioChannel; message: string };export type StdioHook = (event: StdioEvent) => void; export interface Permissions {	fs?: FsPermissions;	network?: NetworkPermissions;	childProcess?: ChildProcessPermissions;	process?: ProcessPermissions;	env?: EnvPermissions;	binding?: BindingPermissions;} /** A worked example shown alongside a registered binding. */export interface BindingExample {	/** What this example demonstrates. */	description: string;	/** Example input matching the binding's input schema. */	input: unknown;} /** * A host-side binding that guest code can invoke as a shell command. The guest * runs the binding by name and the invocation round-trips back to the host JS * `handler`, whose return value is passed back to the guest. Bindings never run * inside the guest: they execute on the host, so they are the bridge for giving * sandboxed guest code controlled, named capabilities (the kind AI agents call * as tools). */export interface BindingDefinition {	/** Human-readable description of what the binding does. */	description: string;	/** JSON Schema describing the binding's input. */	inputSchema: object;	/** Abort the invocation after this many milliseconds. */	timeoutMs?: number;	/** Worked examples shown alongside the binding. */	examples?: BindingExample[];	/**	 * Extra command names the guest can use to invoke this binding, in addition	 * to the key it is registered under.	 */	commandAliases?: string[];	/**	 * Host handler invoked when guest code runs the binding. Receives the parsed	 * input and returns a JSON-serializable result delivered back to the guest.	 */	handler: (input: unknown) => unknown | Promise<unknown>;} export interface ResourceBudgets {	maxOutputBytes?: number;	maxBridgeCalls?: number;	maxTimers?: number;	maxChildProcesses?: number;	maxHandles?: number;} export interface ProcessConfig {	cwd?: string;	env?: Record<string, string>;	argv?: string[];	stdinIsTTY?: boolean;	stdoutIsTTY?: boolean;	stderrIsTTY?: boolean;} export interface OSConfig {	homedir?: string;	tmpdir?: string;} export interface CommandExecutor {	spawn(		command: string,		args: string[],		options?: KernelSpawnOptions,	): ManagedProcess;} export interface NetworkAdapter {	fetch(		url: string,		options?: {			method?: string;			headers?: Record<string, string>;			body?: unknown;		},	): Promise<{		ok: boolean;		status: number;		statusText: string;		headers: Record<string, string>;		body: string;		url: string;		redirected: boolean;	}>;	dnsLookup(hostname: string): Promise<{		address?: string;		family?: number;		error?: string;		code?: string;	}>;	httpRequest(		url: string,		options?: {			method?: string;			headers?: Record<string, string>;			body?: unknown;		},	): Promise<{		status: number;		statusText: string;		headers: Record<string, string>;		body: string;		url: string;	}>;} export interface SystemDriver {	filesystem?: VirtualFileSystem;	network?: NetworkAdapter;	commandExecutor?: CommandExecutor;	permissions?: Permissions;	runtime: {		process: ProcessConfig;		os: OSConfig;	};} export interface RuntimeDriverOptions {	system: SystemDriver;	runtime: {		process: ProcessConfig;		os: OSConfig;	};	memoryLimit?: number;	cpuTimeLimitMs?: number;	timingMitigation?: TimingMitigation;	onStdio?: StdioHook;	payloadLimits?: {		base64TransferBytes?: number;		jsonPayloadBytes?: number;	};	resourceBudgets?: ResourceBudgets;} export interface NodeRuntimeDriver {	exec(code: string, options?: ExecOptions): Promise<ExecResult>;	run<T = unknown>(code: string, filePath?: string): Promise<RunResult<T>>;	dispose(): void;	terminate?(): Promise<void>;	readonly network?: Pick<		NetworkAdapter,		"fetch" | "dnsLookup" | "httpRequest"	>;} export interface NodeRuntimeDriverFactory {	createRuntimeDriver(options: RuntimeDriverOptions): NodeRuntimeDriver;} export interface KernelInterface {	vfs: VirtualFileSystem;} export interface Kernel extends KernelInterface {	mount(driver: KernelRuntimeDriver): Promise<void>;	dispose(): Promise<void>;	exec(command: string, options?: KernelExecOptions): Promise<KernelExecResult>;	spawn(		command: string,		args: string[],		options?: KernelSpawnOptions,	): ManagedProcess;	openShell(options?: OpenShellOptions): ShellHandle;	connectTerminal(options?: ConnectTerminalOptions): Promise<number>;	mountFs(		path: string,		fs: VirtualFileSystem,		options?: { readOnly?: boolean },	): void;	unmountFs(path: string): void;	readFile(path: string): Promise<Uint8Array>;	writeFile(path: string, content: string | Uint8Array): Promise<void>;	mkdir(path: string): Promise<void>;	readdir(path: string): Promise<string[]>;	stat(path: string): Promise<VirtualStat>;	exists(path: string): Promise<boolean>;

Lines 1–500 of 3467.