// engine/sandbox/runner-bwrap.ts — Linux bwrap sandbox runner (SPEC-742)
import { spawn } from 'node:child_process';
import { sanitizeEnv } from './env-sanitizer.js';
/**
 * Run a command inside a bwrap (bubblewrap) sandbox on Linux.
 * Restrictions:
 *   - Filesystem writes restricted to projectRoot + /tmp
 *   - Network egress blocked (--unshare-net)
 *   - Dies with parent process (--die-with-parent)
 *   - LD_PRELOAD and related env vars stripped
 */
export async function runWithBwrap(command, args, options) {
    const { projectRoot, network } = options;
    const startMs = Date.now();
    const sanitized = sanitizeEnv(process.env);
    const bwrapArgs = [
        '--ro-bind',
        '/',
        '/',
        '--bind',
        projectRoot,
        projectRoot,
        '--bind',
        '/tmp',
        '/tmp',
        '--dev',
        '/dev',
        '--proc',
        '/proc',
        '--die-with-parent',
    ];
    // Block network unless explicitly requested
    if (network === 'none' || network === 'npm-registry-only') {
        bwrapArgs.push('--unshare-net');
    }
    bwrapArgs.push('--', command, ...args);
    return new Promise((resolve) => {
        let stdout = '';
        let stderr = '';
        const child = spawn('bwrap', bwrapArgs, {
            env: sanitized,
            stdio: ['pipe', 'pipe', 'pipe'],
        });
        child.stdout.on('data', (chunk) => {
            stdout += chunk.toString();
        });
        child.stderr.on('data', (chunk) => {
            stderr += chunk.toString();
        });
        child.on('close', (code) => {
            resolve({
                exitCode: code ?? 1,
                stdout,
                stderr,
                durationMs: Date.now() - startMs,
                runner: 'bwrap',
            });
        });
        child.on('error', (err) => {
            resolve({
                exitCode: 1,
                stdout,
                stderr: stderr + '\n' + err.message,
                durationMs: Date.now() - startMs,
                runner: 'bwrap',
            });
        });
    });
}
//# sourceMappingURL=runner-bwrap.js.map