function isObject(v) {
    return !!v && typeof v === 'object' && !Array.isArray(v);
}
function parseJson(str) {
    try {
        return JSON.parse(str);
    }
    catch {
        return null;
    }
}
/**
 * ResponseToolArgumentsSchemaConvergeFilter
 * - If tool schemas are available on context (context.toolSchemas[name] = JSONSchema),
 *   keep only keys defined in schema.properties for each tool call arguments.
 * - Does not validate or coerce types; only converges keys to schema surface.
 * - Stage: response_pre
 */
export class ResponseToolArgumentsSchemaConvergeFilter {
    name = 'response_tool_arguments_schema_converge';
    stage = 'response_pre';
    apply(input, context) {
        try {
            const schemaMap = context?.toolSchemas;
            if (!schemaMap || typeof schemaMap !== 'object')
                return { ok: true, data: input };
            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 name = fn && typeof fn.name === 'string' ? String(fn.name) : '';
                    if (!name)
                        continue;
                    const schema = schemaMap[name];
                    const props = schema && schema.properties && isObject(schema.properties) ? schema.properties : undefined;
                    if (!props || !isObject(fn))
                        continue;
                    const argStr = typeof fn.arguments === 'string' ? fn.arguments : undefined;
                    const parsed = argStr ? parseJson(argStr) : (isObject(fn.arguments) ? fn.arguments : null);
                    if (!isObject(parsed))
                        continue;
                    const whitelisted = {};
                    for (const k of Object.keys(props)) {
                        if (k in parsed)
                            whitelisted[k] = parsed[k];
                    }
                    try {
                        fn.arguments = JSON.stringify(whitelisted);
                    }
                    catch { /* keep original */ }
                }
            }
            out.choices = choices;
            return { ok: true, data: out };
        }
        catch {
            return { ok: true, data: input };
        }
    }
}
