// engine/sandbox/runner-sandbox-exec.ts — macOS sandbox-exec runner (SPEC-742)
import { spawn } from 'node:child_process';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { sanitizeEnv } from './env-sanitizer.js';
const PROFILES_DIR = join(fileURLToPath(import.meta.url), '..', 'profiles');
const MACOS_PROFILE = join(PROFILES_DIR, 'macos.sb');
/**
 * Run a command inside an Apple sandbox-exec sandbox on macOS.
 * Restrictions:
 *   - Filesystem writes restricted to projectRoot + /tmp via profile param
 *   - Network egress blocked by default (profile denies network)
 *   - LD_PRELOAD / DYLD_* env vars stripped
 */
export async function runWithSandboxExec(command, args, options) {
    const { projectRoot } = options;
    const startMs = Date.now();
    const sanitized = sanitizeEnv(process.env);
    const sandboxArgs = ['-f', MACOS_PROFILE, '-D', `PROJECT_ROOT=${projectRoot}`, command, ...args];
    return new Promise((resolve) => {
        let stdout = '';
        let stderr = '';
        const child = spawn('sandbox-exec', sandboxArgs, {
            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: 'sandbox-exec',
            });
        });
        child.on('error', (err) => {
            resolve({
                exitCode: 1,
                stdout,
                stderr: stderr + '\n' + err.message,
                durationMs: Date.now() - startMs,
                runner: 'sandbox-exec',
            });
        });
    });
}
//# sourceMappingURL=runner-sandbox-exec.js.map