/** * Agent Runtime — Sandboxed execution environment for AI agents * * Provides controlled access to shell commands, file system, and system * resources with policy enforcement, approval gates, and audit logging. * * Components: * - SandboxPolicy — defines what agents are allowed to do * - ShellExecutor — spawns child processes within policy constraints * - FileAccessor — scoped file read/write with traversal protection * - ApprovalGate — human-in-the-loop approval for sensitive operations * - AgentRuntime — unified facade combining all components * * @module AgentRuntime * @version 1.0.0 */ import { spawn } from 'child_process'; import type { ChildProcess } from 'child_process'; import { createHash } from 'crypto'; import { readFile, writeFile, readdir, stat, mkdir } from 'fs/promises'; import { join, normalize, isAbsolute, resolve, dirname, sep } from 'path'; import { EventEmitter } from 'events'; import type { ExecutionReceipt } from '../security'; import { SecureTokenManager } from '../security'; import { getAsiConfig, isAsiActive, isAsiEnforcing, AsiPolicyError } from './asi/config'; import type { ProofGate } from './asi/proof-gate'; import type { HaltCoordinator } from './asi/shutdown'; import type { AsiStrictConfig, FormalProof } from './asi/types'; import type { GuardedCheck, LeaseCheck } from './perpetual/types'; import type { ISandboxRunner, SandboxLimits, SandboxNetwork } from './perpetual/sandbox'; // ============================================================================ // ERRORS // ============================================================================ /** * Thrown when an agent attempts to access source code files or directories * while `sourceProtection` is enabled on the sandbox policy. */ export class SourceProtectionError extends Error { /** The path that was blocked */ readonly blockedPath: string; /** The agent that attempted access */ readonly agentId: string; constructor(blockedPath: string, agentId: string) { super(`Source protection: access to '${blockedPath}' is blocked for agent '${agentId}'`); this.name = 'SourceProtectionError'; this.blockedPath = blockedPath; this.agentId = agentId; } } // ============================================================================ // TYPES // ============================================================================ /** Result of a shell command execution */ export interface ShellResult { /** Exit code (0 = success) */ exitCode: number; /** Standard output */ stdout: string; /** Standard error output */ stderr: string; /** Execution time in milliseconds */ durationMs: number; /** Whether the command was terminated due to timeout */ timedOut: boolean; /** Whether the command was killed due to output limit */ truncated: boolean; /** Runtime-issued outcome-bound receipt (present when AgentRuntime executes via exec()) */ receipt?: ExecutionReceipt; } /** Options for shell execution */ export interface ShellOptions { /** Working directory (defaults to policy basePath) */ cwd?: string; /** Environment variables to merge with process.env */ env?: Record; /** Command timeout in milliseconds (default: 30000) */ timeoutMs?: number; /** Maximum output bytes (default: 1048576 = 1MB) */ maxOutputBytes?: number; /** Whether this command requires human approval (auto-detected from policy if not set) */ requiresApproval?: boolean; /** Agent ID requesting execution */ agentId?: string; /** ASI strict mode: proof for a gated `shell_exec` call (see `AgentRuntime.shellProofArgs`) */ proof?: FormalProof; } /** File operation result */ export interface FileResult { success: boolean; path: string; content?: string; entries?: string[]; error?: string; durationMs: number; /** Runtime-issued outcome-bound receipt (present on successful write operations) */ receipt?: ExecutionReceipt; } /** Sandbox policy configuration */ export interface SandboxPolicyConfig { /** Base directory agents are scoped to */ basePath: string; /** Allowed command patterns (globs). Empty = deny all. */ allowedCommands: string[]; /** Blocked command patterns (override allowed). Always enforced. */ blockedCommands: string[]; /** Allowed directory paths for file access (relative to basePath) */ allowedPaths: string[]; /** Blocked directory paths (override allowed) */ blockedPaths: string[]; /** Maximum concurrent processes (default: 5) */ maxConcurrentProcesses: number; /** Default command timeout in ms (default: 30000) */ defaultTimeoutMs: number; /** Default max output bytes (default: 1MB) */ defaultMaxOutputBytes: number; /** Commands that always require approval (patterns) */ approvalRequired: string[]; /** Whether read-only file operations auto-approve (default: true) */ autoApproveReads: boolean; /** * When true, agents cannot access source code files or directories * (lib/, adapters/, bin/, scripts/, *.ts, *.py, root *.json config files). * All access attempts outside `data//` are blocked and audited. * Default: false. */ sourceProtection?: boolean; /** * Active environment name. When set, file access is further restricted * to `data//` when sourceProtection is enabled. * Set this at construction time. Runtime changes to `NETWORK_AI_ENV` after * `SandboxPolicy` is created have no effect. */ env?: string; } /** Approval request passed to the approval callback */ export interface ApprovalRequest { /** Type of operation */ type: 'shell' | 'file_write' | 'file_read' | 'file_list'; /** The command or path being requested */ target: string; /** Agent ID making the request */ agentId: string; /** Why the agent needs this */ justification?: string; /** Risk assessment */ risk: 'low' | 'medium' | 'high'; /** Timestamp of request */ timestamp: number; } /** Approval decision from the human/callback */ export interface ApprovalDecision { approved: boolean; approvedBy?: string; reason?: string; } /** Callback function for approval decisions */ export type ApprovalCallback = (request: ApprovalRequest) => Promise; /** Audit entry for runtime operations */ export interface RuntimeAuditEntry { timestamp: string; action: 'shell_execute' | 'file_read' | 'file_write' | 'file_list' | 'approval_requested' | 'approval_granted' | 'approval_denied' | 'policy_violation'; agentId: string; target: string; result: 'success' | 'denied' | 'error' | 'timeout' | 'blocked'; details?: Record; durationMs?: number; } /** Events emitted by AgentRuntime */ export interface RuntimeEvents { 'approval:requested': (request: ApprovalRequest) => void; 'approval:decided': (request: ApprovalRequest, decision: ApprovalDecision) => void; 'command:start': (agentId: string, command: string) => void; 'command:complete': (agentId: string, command: string, result: ShellResult) => void; 'file:access': (agentId: string, path: string, mode: 'read' | 'write' | 'list') => void; 'policy:violation': (agentId: string, target: string, reason: string) => void; 'audit': (entry: RuntimeAuditEntry) => void; } /** Options for creating an AgentRuntime */ export interface AgentRuntimeOptions { policy: Partial & { basePath: string }; onApproval?: ApprovalCallback; autoApproveAll?: boolean; /** * ASI strict mode. Gated tools are `shell_exec` and `file_write`. In * `enforce` mode `sourceProtection` is forced on and secret-like * environment variables are withheld from child processes. */ asi?: { proofGate?: ProofGate; halt?: HaltCoordinator; config?: AsiStrictConfig; }; /** Perpetual runtime: every exec/writeFile needs a valid, in-scope lease (`LeaseGuard`). */ lease?: LeaseCheck; /** Perpetual runtime: writes to governance files need an operator-signed approval (`GuardedPaths`). */ guarded?: GuardedCheck; /** Perpetual runtime: run every `exec` inside a disposable sandbox instead of on the host. */ sandbox?: { runner: ISandboxRunner; network?: SandboxNetwork; limits?: Partial; }; } // ============================================================================ // COMMAND PARSING // ============================================================================ /** * Shell metacharacters that enable command chaining, substitution, or * redirection. Any of these appearing OUTSIDE of quotes turns a scoped * allowlist entry (e.g. `git *`) into arbitrary execution and must be * rejected (GHSA-qw6v-5fcf-5666). */ const SHELL_METACHARACTERS: ReadonlySet = new Set([ ';', '&', '|', '$', '`', '(', ')', '<', '>', '{', '}', '\n', '\r', ]); /** * Tokenize a command string into an argv array, honoring single and double * quotes, and report whether any shell metacharacter appears OUTSIDE of quotes. * * Commands are executed with `shell: false`, so no shell ever interprets the * result — quoted metacharacters are therefore safe, literal data. Unquoted * metacharacters indicate an attempt to chain, substitute, or redirect commands * and cause the command to be rejected before it can run. * * @param command - Raw command string to parse. * @returns Parsed argv plus flags for unquoted metacharacters and malformed quoting. */ function parseCommandLine(command: string): { argv: string[]; hasUnquotedMetacharacter: boolean; unterminatedQuote: boolean; } { const argv: string[] = []; let current = ''; let tokenOpen = false; let quote: '"' | "'" | null = null; let hasUnquotedMetacharacter = false; for (let i = 0; i < command.length; i++) { const ch = command[i]!; if (quote) { if (ch === quote) { quote = null; } else { current += ch; } tokenOpen = true; continue; } if (ch === '"' || ch === "'") { quote = ch; tokenOpen = true; continue; } if (ch === ' ' || ch === '\t') { if (tokenOpen) { argv.push(current); current = ''; tokenOpen = false; } continue; } if (SHELL_METACHARACTERS.has(ch)) { // Unquoted metacharacter — reject the whole command. Do not include it // in argv so the result can never be silently executed. hasUnquotedMetacharacter = true; continue; } current += ch; tokenOpen = true; } if (tokenOpen) argv.push(current); return { argv, hasUnquotedMetacharacter, unterminatedQuote: quote !== null }; } // ============================================================================ // SANDBOX POLICY // ============================================================================ const DEFAULT_POLICY: Omit = { allowedCommands: [], blockedCommands: [ 'rm -rf /', 'rm -rf /*', 'rmdir /s /q C:\\', 'format *', 'mkfs*', 'dd if=*', ':(){:|:&};:', // fork bomb 'shutdown*', 'reboot*', 'halt*', 'init 0', 'init 6', 'del /f /s /q C:\\*', 'reg delete*', 'net user*', 'net localgroup*', ], allowedPaths: ['.'], blockedPaths: [], maxConcurrentProcesses: 5, defaultTimeoutMs: 30_000, defaultMaxOutputBytes: 1_048_576, approvalRequired: [ 'rm *', 'del *', 'rmdir *', 'git push*', 'git reset --hard*', 'npm publish*', 'docker *', 'kubectl *', ], autoApproveReads: true, }; /** * Sandbox policy engine — determines what agents are allowed to do. * * @example * ```typescript * const policy = new SandboxPolicy({ * basePath: '/project', * allowedCommands: ['npm *', 'node *', 'git status'], * }); * policy.isCommandAllowed('npm test'); // true * policy.isCommandAllowed('rm -rf /'); // false * ``` */ export class SandboxPolicy { private readonly config: SandboxPolicyConfig; constructor(config: Partial & { basePath: string }) { this.config = { ...DEFAULT_POLICY, ...config }; this.config.basePath = resolve(this.config.basePath); } /** Check if a command matches the policy's allowed list and isn't blocked */ isCommandAllowed(command: string): boolean { const trimmed = command.trim(); if (!trimmed) return false; // Reject shell metacharacters and malformed quoting BEFORE pattern matching. // Commands run with `shell: false`, but a scoped allowlist entry such as // `git *` must never be escapable into arbitrary execution via `;`, `|`, // `&&`, `$(...)`, backticks, redirection, or newlines (GHSA-qw6v-5fcf-5666). const canonical = this.canonicalize(trimmed); if (canonical === null) return false; // Blocklist/allowlist matching operates on the CANONICAL (post-tokenize) // form — quotes stripped, whitespace collapsed — which is exactly what // the executor runs. Matching the raw string here let quoting or extra // whitespace evade both the blocklist and the allowlist while the // tokenized executor ran the identical unquoted command (GHSA-9v4f-j8cv-fhxw). if (this.matchesAny(canonical, this.config.blockedCommands)) return false; // If no allowedCommands, deny all if (this.config.allowedCommands.length === 0) return false; // Check allowed return this.matchesAny(canonical, this.config.allowedCommands); } /** * Tokenize a command into an argv array suitable for `shell: false` * execution. Returns `null` for any command that contains unquoted shell * metacharacters or malformed quoting — i.e. exactly the inputs that * {@link isCommandAllowed} rejects. Quoted metacharacters are preserved as * literal data within their token. * * @param command - Raw command string to tokenize. * @returns The argv array, or `null` if the command is unsafe to execute. */ tokenizeCommand(command: string): string[] | null { const parsed = parseCommandLine(command.trim()); if (parsed.hasUnquotedMetacharacter || parsed.unterminatedQuote || parsed.argv.length === 0) { return null; } return parsed.argv; } /** * Canonicalize a command into the exact representation the executor will * run: quotes stripped, whitespace collapsed to single spaces, using the * same tokenizer {@link tokenizeCommand} uses. Returns `null` when the * command contains unquoted shell metacharacters, unterminated quoting, or * no tokens at all. * * All security-relevant matching (blocklist, allowlist, approval * requirement, risk assessment) MUST operate on this canonical form, never * on the raw string — quotes and irregular whitespace are literal * characters to the glob matcher but semantically invisible to the * tokenizing executor, letting a crafted command evade blocklist/approval * matching while running identically to its unquoted equivalent * (GHSA-9v4f-j8cv-fhxw). */ private canonicalize(command: string): string | null { const parsed = parseCommandLine(command.trim()); if (parsed.hasUnquotedMetacharacter || parsed.unterminatedQuote || parsed.argv.length === 0) { return null; } return parsed.argv.join(' '); } /** * The canonical form of `command` (what the executor runs), or `null` if * it is unsafe. Proofs and approvals must bind to this, not the raw string. */ canonicalCommand(command: string): string | null { return this.canonicalize(command); } /** Check if a command requires human approval */ requiresApproval(command: string): boolean { const canonical = this.canonicalize(command); // Fail closed: a command that cannot be safely canonicalized will be // rejected by isCommandAllowed/tokenizeCommand regardless, but this // method must never silently answer "no approval needed" for input it // could not parse. if (canonical === null) return true; return this.matchesAny(canonical, this.config.approvalRequired); } /** Assess risk level of a command */ assessRisk(command: string): 'low' | 'medium' | 'high' { const canonical = this.canonicalize(command); if (canonical === null) return 'high'; // fail closed on unparseable input const trimmed = canonical.toLowerCase(); const highRisk = ['rm ', 'del ', 'format', 'drop ', 'delete ', 'truncate ', 'git push', 'git reset', 'docker', 'kubectl']; const medRisk = ['git ', 'npm ', 'pip ', 'mv ', 'move ', 'cp ', 'copy ', 'chmod ', 'chown ']; if (highRisk.some(p => trimmed.startsWith(p) || trimmed.includes(' ' + p))) return 'high'; if (medRisk.some(p => trimmed.startsWith(p) || trimmed.includes(' ' + p))) return 'medium'; return 'low'; } /** Validate that a file path is within allowed scope */ isPathAllowed(filePath: string): boolean { const normalized = this.resolvePath(filePath); if (!normalized) return false; // Check blocked paths (sep-anchored prefix — GHSA-jvcm-f35g-w78p) for (const blocked of this.config.blockedPaths) { const blockedAbs = resolve(this.config.basePath, blocked); if (normalized === blockedAbs || normalized.startsWith(blockedAbs + sep)) return false; } // Check allowed paths (sep-anchored prefix — GHSA-jvcm-f35g-w78p) for (const allowed of this.config.allowedPaths) { const allowedAbs = resolve(this.config.basePath, allowed); if (normalized === allowedAbs || normalized.startsWith(allowedAbs + sep)) return true; } return false; } /** Resolve and validate a path against basePath (returns null if traversal detected) */ resolvePath(filePath: string): string | null { const normalized = normalize(filePath); const absolute = isAbsolute(normalized) ? normalized : join(this.config.basePath, normalized); const resolved = resolve(absolute); // Traversal check — sep-anchored so '/foo/bar2' cannot match basePath '/foo/bar' // (GHSA-jvcm-f35g-w78p). if (resolved !== this.config.basePath && !resolved.startsWith(this.config.basePath + sep)) return null; return resolved; } /** Get a copy of the current policy config */ getConfig(): Readonly { return { ...this.config }; } /** Update allowed commands */ allowCommand(pattern: string): void { if (!this.config.allowedCommands.includes(pattern)) { this.config.allowedCommands.push(pattern); } } /** Remove an allowed command pattern */ disallowCommand(pattern: string): void { this.config.allowedCommands = this.config.allowedCommands.filter(c => c !== pattern); } /** Update allowed paths */ allowPath(path: string): void { if (!this.config.allowedPaths.includes(path)) { this.config.allowedPaths.push(path); } } /** Block a path */ blockPath(path: string): void { if (!this.config.blockedPaths.includes(path)) { this.config.blockedPaths.push(path); } } get basePath(): string { return this.config.basePath; } get maxConcurrentProcesses(): number { return this.config.maxConcurrentProcesses; } get defaultTimeoutMs(): number { return this.config.defaultTimeoutMs; } get defaultMaxOutputBytes(): number { return this.config.defaultMaxOutputBytes; } get autoApproveReads(): boolean { return this.config.autoApproveReads; } /** Simple glob matching: supports * as wildcard */ private matchesAny(value: string, patterns: string[]): boolean { return patterns.some(pattern => this.globMatch(pattern, value)); } /** Match a simple glob pattern against a string */ private globMatch(pattern: string, value: string): boolean { // Escape regex special chars except * const regexStr = pattern .replace(/[.+^${}()|[\]\\]/g, '\\$&') .replace(/\*/g, '.*'); return new RegExp(`^${regexStr}$`, 'i').test(value); } } // ============================================================================ // SHELL EXECUTOR // ============================================================================ /** * Sandboxed shell command executor with timeout, output limits, and * concurrent process tracking. * * @example * ```typescript * const executor = new ShellExecutor(policy); * const result = await executor.execute('npm test', { agentId: 'tester' }); * console.log(result.exitCode, result.stdout); * ``` */ export class ShellExecutor { private readonly policy: SandboxPolicy; private activeProcesses = 0; private readonly children = new Set(); private readonly scrubEnv: boolean; /** * @param policy Sandbox policy. * @param opts.scrubEnv Withhold secret-like environment variables from child processes. */ constructor(policy: SandboxPolicy, opts: { scrubEnv?: boolean } = {}) { this.policy = policy; this.scrubEnv = opts.scrubEnv ?? false; } /** Terminate every running child process. Returns how many were signalled. */ killAll(): number { let n = 0; for (const child of this.children) { if (child.kill('SIGKILL')) n++; } return n; } /** Execute a shell command within policy constraints */ async execute(command: string, opts: ShellOptions = {}): Promise { // Policy check if (!this.policy.isCommandAllowed(command)) { throw new RuntimePolicyError(`Command blocked by policy: ${command}`); } // Concurrency check if (this.activeProcesses >= this.policy.maxConcurrentProcesses) { throw new RuntimePolicyError( `Concurrency limit reached (${this.policy.maxConcurrentProcesses} max)`, ); } const cwd = opts.cwd ? (this.policy.resolvePath(opts.cwd) ?? this.policy.basePath) : this.policy.basePath; const timeoutMs = opts.timeoutMs ?? this.policy.defaultTimeoutMs; const maxBytes = opts.maxOutputBytes ?? this.policy.defaultMaxOutputBytes; this.activeProcesses++; try { return await this.spawnCommand(command, cwd, timeoutMs, maxBytes, opts.env); } finally { this.activeProcesses--; } } /** Get the number of currently running processes */ get running(): number { return this.activeProcesses; } private spawnCommand( command: string, cwd: string, timeoutMs: number, maxBytes: number, env?: Record, ): Promise { return new Promise((resolvePromise, reject) => { // Execute with `shell: false` using a parsed argv. The command was already // validated by `isCommandAllowed`, but we re-tokenize here as the single // source of truth for what actually runs — no string is ever handed to a // shell, so metacharacters cannot be interpreted (GHSA-qw6v-5fcf-5666). const argv = this.policy.tokenizeCommand(command); if (!argv || argv.length === 0) { reject(new RuntimePolicyError( `Command rejected — shell metacharacters are not permitted: ${command}`, )); return; } const file = argv[0]!; const args = argv.slice(1); const baseEnv = this.scrubEnv ? scrubSecretEnv(process.env) : process.env; const child = spawn(file, args, { cwd, env: env ? { ...baseEnv, ...env } : baseEnv, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, shell: false, }); this.children.add(child); let stdout = ''; let stderr = ''; let totalBytes = 0; let timedOut = false; let truncated = false; const timer = setTimeout(() => { timedOut = true; child.kill('SIGTERM'); setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); }, 2000); }, timeoutMs); child.stdout?.on('data', (chunk: Buffer) => { totalBytes += chunk.length; if (totalBytes <= maxBytes) { stdout += chunk.toString(); } else if (!truncated) { truncated = true; stdout += '\n[OUTPUT TRUNCATED — exceeded limit]'; child.kill('SIGTERM'); } }); child.stderr?.on('data', (chunk: Buffer) => { totalBytes += chunk.length; if (totalBytes <= maxBytes) { stderr += chunk.toString(); } }); child.on('close', (code) => { clearTimeout(timer); this.children.delete(child); resolvePromise({ exitCode: code ?? (timedOut ? 124 : 1), stdout, stderr, durationMs: Date.now() - startTime, timedOut, truncated, }); }); child.on('error', (err) => { clearTimeout(timer); this.children.delete(child); reject(new RuntimeExecutionError(`Failed to spawn: ${err.message}`)); }); const startTime = Date.now(); }); } } const SECRET_ENV = /(?:^ASI_)|(?:SECRET|TOKEN|PASSW(?:OR)?D|API_?KEY|PRIVATE_?KEY|CREDENTIAL)|(?:_AUTH$)/i; /** Copy of `env` without secret-like variables. */ function scrubSecretEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { const out: NodeJS.ProcessEnv = {}; for (const [k, v] of Object.entries(env)) { if (!SECRET_ENV.test(k)) out[k] = v; } return out; } // ============================================================================ // FILE ACCESSOR // ============================================================================ /** * Policy-scoped file system accessor. All paths are validated against * the sandbox policy before any I/O. * * **Error contract:** All public methods (`read`, `write`, `list`) return a * `{success: boolean, ...}` result object — they never throw. All access-denied * paths (path traversal, out-of-scope under `sourceProtection`, policy-blocked * reads/writes, and `SourceProtectionError`) are caught at the method boundary * and converted to `{success: false, error: }`. The `error` field * contains a short description without leaking internal path details. * * @example * ```typescript * const files = new FileAccessor(policy); * const result = await files.read('src/index.ts', 'reader-agent'); * ``` */ export class FileAccessor { private readonly policy: SandboxPolicy; constructor(policy: SandboxPolicy) { this.policy = policy; } /** * Checks whether the resolved absolute path is blocked by source protection. * Throws SourceProtectionError if access is denied. */ private checkSourceProtection(resolvedPath: string, agentId: string): void { const cfg = this.policy.getConfig(); if (!cfg.sourceProtection) return; const base = cfg.basePath; const env = cfg.env ?? ''; // The only permitted subtree under source protection is data// (when env // is set) or data/ (legacy). All source code paths are blocked. const dataEnvDir = env ? resolve(base, 'data', env) : resolve(base, 'data'); if (resolvedPath.startsWith(dataEnvDir + sep) || resolvedPath === dataEnvDir) { return; // allowed } throw new SourceProtectionError(resolvedPath, agentId); } /** Read a file within the sandbox scope */ async read(filePath: string, agentId: string): Promise { const start = Date.now(); const resolved = this.policy.resolvePath(filePath); if (!resolved) { return { success: false, path: filePath, error: 'Path traversal blocked', durationMs: Date.now() - start }; } if (!this.policy.isPathAllowed(filePath)) { return { success: false, path: filePath, error: 'Path not in allowed scope', durationMs: Date.now() - start }; } try { this.checkSourceProtection(resolved, agentId); } catch (err) { if (err instanceof SourceProtectionError) { return { success: false, path: resolved, error: err.message, durationMs: Date.now() - start }; } throw err; } try { const content = await readFile(resolved, 'utf-8'); return { success: true, path: resolved, content, durationMs: Date.now() - start }; } catch (err) { const msg = err instanceof Error ? err.message : String(err); return { success: false, path: resolved, error: msg, durationMs: Date.now() - start }; } } /** Write a file within the sandbox scope */ async write(filePath: string, content: string, agentId: string): Promise { const start = Date.now(); const resolved = this.policy.resolvePath(filePath); if (!resolved) { return { success: false, path: filePath, error: 'Path traversal blocked', durationMs: Date.now() - start }; } if (!this.policy.isPathAllowed(filePath)) { return { success: false, path: filePath, error: 'Path not in allowed scope', durationMs: Date.now() - start }; } try { this.checkSourceProtection(resolved, agentId); } catch (err) { if (err instanceof SourceProtectionError) { return { success: false, path: resolved, error: err.message, durationMs: Date.now() - start }; } throw err; } try { await mkdir(dirname(resolved), { recursive: true }); await writeFile(resolved, content, 'utf-8'); return { success: true, path: resolved, durationMs: Date.now() - start }; } catch (err) { const msg = err instanceof Error ? err.message : String(err); return { success: false, path: resolved, error: msg, durationMs: Date.now() - start }; } } /** List directory contents within the sandbox scope */ async list(dirPath: string, agentId: string): Promise { const start = Date.now(); const resolved = this.policy.resolvePath(dirPath); if (!resolved) { return { success: false, path: dirPath, error: 'Path traversal blocked', durationMs: Date.now() - start }; } if (!this.policy.isPathAllowed(dirPath)) { return { success: false, path: dirPath, error: 'Path not in allowed scope', durationMs: Date.now() - start }; } try { this.checkSourceProtection(resolved, agentId); } catch (err) { if (err instanceof SourceProtectionError) { return { success: false, path: resolved, error: err.message, durationMs: Date.now() - start }; } throw err; } try { const items = await readdir(resolved); const entries: string[] = []; for (const item of items) { const itemPath = join(resolved, item); const info = await stat(itemPath); entries.push(info.isDirectory() ? `${item}/` : item); } return { success: true, path: resolved, entries, durationMs: Date.now() - start }; } catch (err) { const msg = err instanceof Error ? err.message : String(err); return { success: false, path: resolved, error: msg, durationMs: Date.now() - start }; } } } // ============================================================================ // APPROVAL GATE // ============================================================================ /** * Human-in-the-loop approval gate. Queues requests and waits for * a decision from the configured callback. * * @example * ```typescript * const gate = new ApprovalGate(async (req) => { * return { approved: true, approvedBy: 'operator' }; * }); * const decision = await gate.request({ type: 'shell', target: 'npm publish', ... }); * ``` */ export class ApprovalGate extends EventEmitter { private readonly callback: ApprovalCallback | null; private readonly autoApproveAll: boolean; private readonly history: Array<{ request: ApprovalRequest; decision: ApprovalDecision }> = []; constructor(callback?: ApprovalCallback, autoApproveAll = false) { super(); this.callback = callback ?? null; this.autoApproveAll = autoApproveAll; } /** Request approval for an operation */ async request(req: ApprovalRequest): Promise { this.emit('requested', req); if (this.autoApproveAll) { const decision: ApprovalDecision = { approved: true, approvedBy: 'auto-approve-all' }; this.history.push({ request: req, decision }); this.emit('decided', req, decision); return decision; } if (!this.callback) { const decision: ApprovalDecision = { approved: false, reason: 'No approval callback configured' }; this.history.push({ request: req, decision }); this.emit('decided', req, decision); return decision; } const decision = await this.callback(req); this.history.push({ request: req, decision }); this.emit('decided', req, decision); return decision; } /** Get approval history */ getHistory(): ReadonlyArray<{ request: ApprovalRequest; decision: ApprovalDecision }> { return this.history; } /** Get count of approvals/denials */ getStats(): { total: number; approved: number; denied: number } { const approved = this.history.filter(h => h.decision.approved).length; return { total: this.history.length, approved, denied: this.history.length - approved }; } } // ============================================================================ // AGENT RUNTIME (Facade) // ============================================================================ /** * Unified agent execution runtime. Combines policy, shell, file access, * and approval into a single interface for agent consumption. * * @example * ```typescript * const runtime = new AgentRuntime({ * policy: { * basePath: '/project', * allowedCommands: ['npm *', 'node *', 'git status', 'git diff'], * }, * onApproval: async (req) => { * console.log(`Approve? ${req.type}: ${req.target}`); * return { approved: true, approvedBy: 'operator' }; * }, * }); * * const result = await runtime.exec('npm test', 'tester-agent'); * ``` */ export class AgentRuntime extends EventEmitter { readonly policy: SandboxPolicy; readonly shell: ShellExecutor; readonly files: FileAccessor; readonly gate: ApprovalGate; private auditLog: RuntimeAuditEntry[] = []; private readonly receiptManager = new SecureTokenManager(); private readonly asi: AgentRuntimeOptions['asi'] & { config: AsiStrictConfig } | undefined; private readonly lease: LeaseCheck | undefined; private readonly guarded: GuardedCheck | undefined; private readonly sandbox: AgentRuntimeOptions['sandbox']; constructor(opts: AgentRuntimeOptions) { super(); this.lease = opts.lease; this.guarded = opts.guarded; this.sandbox = opts.sandbox; const asiConfig = opts.asi ? (opts.asi.config ?? getAsiConfig()) : undefined; const enforcing = asiConfig !== undefined && isAsiEnforcing(asiConfig); this.asi = opts.asi && asiConfig ? { ...opts.asi, config: asiConfig } : undefined; this.policy = new SandboxPolicy(enforcing ? { ...opts.policy, sourceProtection: true } : opts.policy); this.shell = new ShellExecutor(this.policy, { scrubEnv: enforcing }); this.files = new FileAccessor(this.policy); this.gate = new ApprovalGate(opts.onApproval, opts.autoApproveAll); // Wire approval events this.gate.on('requested', (req: ApprovalRequest) => { this.emit('approval:requested', req); this.audit({ action: 'approval_requested', agentId: req.agentId, target: req.target, result: 'success' }); }); this.gate.on('decided', (req: ApprovalRequest, dec: ApprovalDecision) => { this.emit('approval:decided', req, dec); this.audit({ action: dec.approved ? 'approval_granted' : 'approval_denied', agentId: req.agentId, target: req.target, result: dec.approved ? 'success' : 'denied', details: { approvedBy: dec.approvedBy, reason: dec.reason }, }); }); } /** * Execute a shell command with policy + approval checks. * Returns ShellResult on success, throws on policy violation. */ async exec(command: string, agentId: string, opts: ShellOptions = {}): Promise { this.asi?.halt?.assertNotHalted(); this.lease?.assertActive({ tool: 'shell_exec' }); // Policy check if (!this.policy.isCommandAllowed(command)) { this.emit('policy:violation', agentId, command, 'Command not allowed by policy'); this.audit({ action: 'shell_execute', agentId, target: command, result: 'blocked' }); throw new RuntimePolicyError(`Command blocked by policy: ${command}`); } await this.checkProof('shell_exec', this.shellProofArgs(command), agentId, command, opts.proof); // Approval check const needsApproval = opts.requiresApproval ?? this.policy.requiresApproval(command); if (needsApproval) { const decision = await this.gate.request({ type: 'shell', target: command, agentId, risk: this.policy.assessRisk(command), timestamp: Date.now(), }); if (!decision.approved) { this.audit({ action: 'shell_execute', agentId, target: command, result: 'denied', details: { reason: decision.reason } }); throw new RuntimeApprovalError(`Command denied: ${decision.reason ?? 'no reason given'}`); } } // Execute this.emit('command:start', agentId, command); const result = this.sandbox ? await this.execSandboxed(command, opts) : await this.shell.execute(command, { ...opts, agentId }); this.emit('command:complete', agentId, command, result); // Issue outcome-bound receipt — runtime authority, not agent's word const outputHash = createHash('sha256') .update(result.stdout + result.stderr + String(result.exitCode)) .digest('hex'); result.receipt = this.receiptManager.generateReceipt(agentId, 'shell_execute', command, result.exitCode, outputHash); this.audit({ action: 'shell_execute', agentId, target: command, result: result.exitCode === 0 ? 'success' : (result.timedOut ? 'timeout' : 'error'), durationMs: result.durationMs, details: { exitCode: result.exitCode, timedOut: result.timedOut }, }); return result; } /** Read a file with policy + optional approval */ async readFile(filePath: string, agentId: string): Promise { if (!this.policy.isPathAllowed(filePath)) { this.emit('policy:violation', agentId, filePath, 'Path not allowed'); this.audit({ action: 'file_read', agentId, target: filePath, result: 'blocked' }); return { success: false, path: filePath, error: 'Path not allowed by policy', durationMs: 0 }; } // Reads can auto-approve if (!this.policy.autoApproveReads) { const decision = await this.gate.request({ type: 'file_read', target: filePath, agentId, risk: 'low', timestamp: Date.now(), }); if (!decision.approved) { this.audit({ action: 'file_read', agentId, target: filePath, result: 'denied' }); return { success: false, path: filePath, error: 'Read denied', durationMs: 0 }; } } this.emit('file:access', agentId, filePath, 'read'); const result = await this.files.read(filePath, agentId); this.audit({ action: 'file_read', agentId, target: filePath, result: result.success ? 'success' : 'error', durationMs: result.durationMs, }); return result; } /** * Write a file with policy + approval. * @param opts.proof ASI strict mode: proof for a gated `file_write` (see {@link writeProofArgs}). */ async writeFile(filePath: string, content: string, agentId: string, opts: { proof?: FormalProof } = {}): Promise { this.asi?.halt?.assertNotHalted(); if (this.lease) { try { this.lease.assertActive({ tool: 'file_write', path: filePath }); } catch (err) { this.audit({ action: 'file_write', agentId, target: filePath, result: 'blocked', details: { lease: err instanceof Error ? err.message : 'no lease' } }); return { success: false, path: filePath, error: err instanceof Error ? err.message : 'No valid lease', durationMs: 0 }; } } const guardedReason = this.guarded?.check({ kind: 'path', name: resolve(this.policy.basePath, filePath) }, content) ?? null; if (guardedReason) { this.audit({ action: 'file_write', agentId, target: filePath, result: 'blocked', details: { guarded: guardedReason } }); return { success: false, path: filePath, error: guardedReason, durationMs: 0 }; } if (!this.policy.isPathAllowed(filePath)) { this.emit('policy:violation', agentId, filePath, 'Path not allowed'); this.audit({ action: 'file_write', agentId, target: filePath, result: 'blocked' }); return { success: false, path: filePath, error: 'Path not allowed by policy', durationMs: 0 }; } try { await this.checkProof('file_write', this.writeProofArgs(filePath, content), agentId, filePath, opts.proof); } catch (err) { if (err instanceof AsiPolicyError) return { success: false, path: filePath, error: err.message, durationMs: 0 }; throw err; } const decision = await this.gate.request({ type: 'file_write', target: filePath, agentId, risk: 'medium', timestamp: Date.now(), }); if (!decision.approved) { this.audit({ action: 'file_write', agentId, target: filePath, result: 'denied' }); return { success: false, path: filePath, error: `Write denied: ${decision.reason ?? 'no reason'}`, durationMs: 0 }; } this.emit('file:access', agentId, filePath, 'write'); const result = await this.files.write(filePath, content, agentId); // Issue outcome-bound receipt on successful write if (result.success) { const contentHash = createHash('sha256').update(content).digest('hex'); result.receipt = this.receiptManager.generateReceipt(agentId, 'file_write', result.path, 0, contentHash); } this.audit({ action: 'file_write', agentId, target: filePath, result: result.success ? 'success' : 'error', durationMs: result.durationMs, }); return result; } /** List a directory with policy check */ async listDir(dirPath: string, agentId: string): Promise { if (!this.policy.isPathAllowed(dirPath)) { this.emit('policy:violation', agentId, dirPath, 'Path not allowed'); this.audit({ action: 'file_list', agentId, target: dirPath, result: 'blocked' }); return { success: false, path: dirPath, error: 'Path not allowed by policy', durationMs: 0 }; } this.emit('file:access', agentId, dirPath, 'list'); const result = await this.files.list(dirPath, agentId); this.audit({ action: 'file_list', agentId, target: dirPath, result: result.success ? 'success' : 'error', durationMs: result.durationMs, }); return result; } /** Get the internal audit log */ getAuditLog(): ReadonlyArray { return this.auditLog; } /** Arguments a `shell_exec` proof must bind to: the canonical command. */ shellProofArgs(command: string): { command: string } { return { command: this.policy.canonicalCommand(command) ?? command }; } /** Arguments a `file_write` proof must bind to: resolved path and content hash. */ writeProofArgs(filePath: string, content: string): { path: string; sha256: string } { return { path: this.policy.resolvePath(filePath) ?? filePath, sha256: createHash('sha256').update(content).digest('hex'), }; } /** Kill-switch hook (ASI `HaltCoordinator`): terminate running child processes. */ halt(reason: string): number { const killed = this.shell.killAll(); this.audit({ action: 'shell_execute', agentId: 'system', target: 'halt', result: 'blocked', details: { reason, killed } }); return killed; } private async execSandboxed(command: string, opts: ShellOptions): Promise { const sandbox = this.sandbox!; const argv = this.policy.tokenizeCommand(command); if (!argv || argv.length === 0) throw new RuntimePolicyError(`Command rejected — shell metacharacters are not permitted: ${command}`); const workspace = opts.cwd ? this.policy.resolvePath(opts.cwd) : this.policy.basePath; if (!workspace) throw new RuntimePolicyError(`Working directory not allowed: ${opts.cwd}`); const r = await sandbox.runner.run({ argv, workspace, env: opts.env, network: sandbox.network ?? 'none', limits: { ...sandbox.limits, ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}) }, maxOutputBytes: opts.maxOutputBytes ?? this.policy.defaultMaxOutputBytes, }); return { exitCode: r.exitCode, stdout: r.stdout, stderr: r.stderr, durationMs: r.durationMs, timedOut: r.timedOut, truncated: r.truncated }; } private async checkProof(tool: string, args: unknown, agentId: string, target: string, proof: FormalProof | undefined): Promise { const gate = this.asi?.proofGate; if (!gate || !isAsiActive(this.asi!.config) || !gate.requiresProof(tool)) return; const decision = await gate.check({ tool, args, agentId, proof }); if (!decision.allowed) { this.emit('policy:violation', agentId, target, decision.violation ?? 'proof required'); this.audit({ action: tool === 'shell_exec' ? 'shell_execute' : 'file_write', agentId, target, result: 'blocked', details: { asi: decision.violation } }); throw new AsiPolicyError(`ASI strict mode: ${decision.violation ?? 'proof required'}`, 'ASI_PROOF_REQUIRED'); } } /** Clear the internal audit log */ clearAuditLog(): void { this.auditLog = []; } private audit(entry: Omit): void { const full: RuntimeAuditEntry = { ...entry, timestamp: new Date().toISOString() }; this.auditLog.push(full); this.emit('audit', full); } } // ============================================================================ // ERROR TYPES // ============================================================================ /** Thrown when an operation violates the sandbox policy */ export class RuntimePolicyError extends Error { readonly code = 'POLICY_VIOLATION'; constructor(message: string) { super(message); this.name = 'RuntimePolicyError'; } } /** Thrown when an operation is denied by the approval gate */ export class RuntimeApprovalError extends Error { readonly code = 'APPROVAL_DENIED'; constructor(message: string) { super(message); this.name = 'RuntimeApprovalError'; } } /** Thrown when a command fails to spawn */ export class RuntimeExecutionError extends Error { readonly code = 'EXECUTION_ERROR'; constructor(message: string) { super(message); this.name = 'RuntimeExecutionError'; } }