var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { tool } from "langchain";
const emptyToolSchema = {
    type: "object",
    properties: {},
    additionalProperties: true,
};
function normalizeToolInputSchema(inputSchema) {
    if (!inputSchema || typeof inputSchema !== "object" || Array.isArray(inputSchema)) {
        return emptyToolSchema;
    }
    const schema = JSON.parse(JSON.stringify(inputSchema));
    if (schema.type !== "object") {
        return emptyToolSchema;
    }
    const notes = [];
    if ("if" in schema || "then" in schema || "else" in schema || "allOf" in schema) {
        delete schema.if;
        delete schema.then;
        delete schema.else;
        delete schema.allOf;
        notes.push("Runtime applies additional conditional validation rules.");
    }
    if ("oneOf" in schema || "anyOf" in schema || "not" in schema || "enum" in schema) {
        delete schema.oneOf;
        delete schema.anyOf;
        delete schema.not;
        delete schema.enum;
        notes.push("Top-level composite validation rules are omitted for tool compatibility.");
    }
    if (notes.length > 0) {
        schema.description = typeof schema.description === "string"
            ? `${schema.description}\n\n${notes.join(" ")}`
            : notes.join(" ");
    }
    return schema;
}
export function createApiTool(toolName, apiBasedTool) {
    var _a;
    return tool((input, runtime) => __awaiter(this, void 0, void 0, function* () {
        const normalizedInput = (input !== null && input !== void 0 ? input : {});
        return apiBasedTool.call({
            adminUser: runtime.context.adminUser,
            abortSignal: runtime.context.abortSignal,
            inputs: normalizedInput,
            userTimeZone: runtime.context.userTimeZone,
        });
    }), {
        name: toolName,
        description: (_a = apiBasedTool.description) !== null && _a !== void 0 ? _a : `${toolName} tool`,
        schema: normalizeToolInputSchema(apiBasedTool.input_schema),
    });
}
