/**
 * Factory for the sandboxed bash tool.
 *
 * Extracts all sandbox-specific tool wiring out of main.ts:
 * - Write-access approval prompts
 * - Network domain approval forwarding
 * - Proxy domain prompt wiring
 *
 * main.ts just calls createSandboxBashTool() and pushes the result.
 */
import { createBashTool } from '../../app/tools/bash.js';
import { createSandboxOperations } from './sandbox-executor.js';
import { SandboxManager } from './sandbox-manager.js';
/**
 * Create a fully-wired sandboxed bash tool.
 *
 * Handles:
 * - Routing commands through WSL2 + bwrap
 * - Write-access prompts (allow once / save / deny)
 * - Network domain approval prompts
 */
export function createSandboxBashTool(cwd, settingsManager, promptDomainApproval) {
    const sandboxMgr = new SandboxManager(cwd, settingsManager);
    let activeCtx = null;
    // Serialize domain check prompts — TUI can only show one at a time.
    // Without this, concurrent bash commands cause overlapping prompts
    // where only one succeeds and the rest get denied.
    let promptQueue = Promise.resolve();
    sandboxMgr.setDomainCheckHandler({
        onDomainCheck: async (domain) => {
            const uiCtx = activeCtx;
            if (!uiCtx || !promptDomainApproval) {
                return 'once';
            }
            return new Promise((resolve) => {
                promptQueue = promptQueue.then(async () => {
                    try {
                        const choice = await promptDomainApproval(domain, uiCtx);
                        resolve(choice ?? 'deny');
                    }
                    catch {
                        resolve('deny');
                    }
                });
            });
        }
    });
    return buildTool(cwd, sandboxMgr, (ctx) => {
        activeCtx = ctx;
    });
}
// ---------------------------------------------------------------------------
function buildTool(cwd, sandboxMgr, setActiveCtx) {
    const baseTool = createBashTool(cwd, {
        operations: createSandboxOperations(sandboxMgr),
        sandboxActive: true
    });
    return {
        name: baseTool.name,
        label: baseTool.label,
        description: baseTool.description,
        parameters: baseTool.parameters,
        async execute(toolCallId, params, signal, onUpdate, ctx) {
            const p = params;
            if (p.connections?.length) {
                throw new Error('Connections are not supported in sandbox mode. Disable the sandbox via /sandbox to use connection-backed execution.');
            }
            // Let the proxy's domain-check callback access this invocation's ctx
            setActiveCtx?.(ctx);
            // Sandboxed execution — auto-approved (sandbox is the security boundary)
            return baseTool.execute(toolCallId, p, signal, onUpdate, ctx);
        }
    };
}
//# sourceMappingURL=sandbox-bash-tool.js.map