import { requireApprovalForToolAction } from "../services/approval/approvalPolicy.js";
import { executeToolPlan } from "../services/tools/toolOrchestration.js";
import { baseTools } from "./registry.js";
export async function executeEnvelope(root, envelope, options = {}) {
    const results = await executeToolPlan(baseTools, envelope.actions, {
        root,
        allowShell: options.shellPolicy?.allowShell ?? false,
        allowBrowser: options.browserPolicy?.allowBrowser ?? false,
        dataDir: options.dataDir,
        fileStateCache: options.fileStateCache,
        state: options.state,
        runId: options.runId,
        memoryService: options.memoryService,
        skillRunner: options.skillRunner,
        abortSignal: options.abortSignal,
    }, {
        onEvent: options.onToolEvent,
        onBeforeTool: async (tool, action, context) => {
            const policyResult = await options.onBeforeTool?.(tool, action, context);
            if (policyResult)
                return policyResult;
            return requireApprovalForToolAction(options.approvalPolicy, tool, action, context);
        },
    });
    return {
        final_message: envelope.final_message,
        status: results.every((result) => result.status === "succeeded")
            ? "succeeded"
            : "failed",
        results,
    };
}
