function isObject(v) { return !!v && typeof v === 'object' && !Array.isArray(v); }
function parseJson(str) { try {
    return JSON.parse(str);
}
catch {
    return null;
} }
function getBlacklist() {
    const env = String(process?.env?.ROUTECODEX_TOOLARGS_BLACKLIST || '').trim();
    if (!env)
        return [];
    return env.split(',').map(s => s.trim()).filter(Boolean);
}
/**
 * ResponseToolArgumentsBlacklistFilter
 * - Remove keys listed in ROUTECODEX_TOOLARGS_BLACKLIST from tool_calls[].function.arguments (after decode).
 * - Default: empty blacklist (no-op). Enables incremental hardening without risking valid params.
 * Stage: response_pre
 */
export class ResponseToolArgumentsBlacklistFilter {
    name = 'response_tool_arguments_blacklist';
    stage = 'response_pre';
    apply(input) {
        const blacklist = getBlacklist();
        if (blacklist.length === 0)
            return { ok: true, data: input };
        try {
            const out = JSON.parse(JSON.stringify(input || {}));
            const choices = Array.isArray(out.choices) ? out.choices : [];
            for (const ch of choices) {
                const msg = ch && ch.message ? ch.message : undefined;
                const tcs = msg && Array.isArray(msg.tool_calls) ? msg.tool_calls : [];
                for (const tc of tcs) {
                    const fn = tc && tc.function ? tc.function : undefined;
                    const argStr = fn && typeof fn.arguments === 'string' ? fn.arguments : undefined;
                    if (!argStr)
                        continue;
                    const parsed = parseJson(argStr);
                    if (!isObject(parsed))
                        continue;
                    let changed = false;
                    for (const k of blacklist) {
                        if (k in parsed) {
                            delete parsed[k];
                            changed = true;
                        }
                    }
                    if (changed) {
                        try {
                            fn.arguments = JSON.stringify(parsed);
                        }
                        catch { /* keep original */ }
                    }
                }
            }
            out.choices = choices;
            return { ok: true, data: out };
        }
        catch {
            return { ok: true, data: input };
        }
    }
}
