import { Composio } from "composio-core";
let _client = null;
function getClient() {
    if (_client)
        return _client;
    const apiKey = process.env.COMPOSIO_API_KEY;
    if (!apiKey) {
        return null;
    }
    _client = new Composio({ apiKey });
    return _client;
}
/**
 * Create a Composio entity for a given user. In Composio's model, an "entity"
 * represents an end-user who can connect apps and execute actions.
 */
export function getComposioSession(userId) {
    const client = getClient();
    if (!client)
        return null;
    return client.getEntity(userId);
}
/**
 * Get tool/action definitions for a set of apps, scoped to a user entity.
 * `apps` is a comma-separated string of app keys (e.g. "github,slack").
 */
export async function getToolsForApps(userId, apps) {
    const client = getClient();
    if (!client)
        return [];
    try {
        const actions = await client.actions.list({
            apps: apps.join(","),
        });
        return actions?.items ?? (Array.isArray(actions) ? actions : []);
    }
    catch (err) {
        console.error("[composio] getToolsForApps failed:", err);
        return [];
    }
}
/**
 * Initiate an OAuth connection for a user with a specific app.
 * Returns a ConnectionRequest with a redirectUrl the user should visit.
 */
export async function initiateConnection(userId, appName, redirectUrl) {
    const client = getClient();
    if (!client)
        return null;
    try {
        const connectionRequest = await client.connectedAccounts.initiate({
            appName,
            entityId: userId,
            redirectUri: redirectUrl,
        });
        return {
            redirectUrl: connectionRequest.redirectUrl,
            connectedAccountId: connectionRequest.connectedAccountId,
        };
    }
    catch (err) {
        console.error("[composio] initiateConnection failed:", err);
        return null;
    }
}
/**
 * List all connected accounts for a given user entity.
 */
export async function getConnectedApps(userId) {
    const client = getClient();
    if (!client)
        return [];
    try {
        const entity = client.getEntity(userId);
        const connections = await entity.getConnections();
        return connections ?? [];
    }
    catch (err) {
        console.error("[composio] getConnectedApps failed:", err);
        return [];
    }
}
/**
 * Execute a tool call (action) on behalf of a user.
 */
export async function executeToolCall(userId, toolName, toolInput) {
    const client = getClient();
    if (!client)
        return { error: "Composio not configured" };
    try {
        const entity = client.getEntity(userId);
        const result = await entity.execute({
            actionName: toolName,
            params: toolInput,
        });
        return result;
    }
    catch (err) {
        console.error("[composio] executeToolCall failed:", err);
        return { error: String(err) };
    }
}
/** Well-known logo URLs for popular tools (fallback when Composio doesn't provide one) */
const TOOL_LOGOS = {
    gmail: "https://cdn.simpleicons.org/gmail",
    slack: "https://cdn.simpleicons.org/slack",
    github: "https://cdn.simpleicons.org/github/white",
    notion: "https://cdn.simpleicons.org/notion/white",
    google_calendar: "https://cdn.simpleicons.org/googlecalendar",
    google_drive: "https://cdn.simpleicons.org/googledrive",
    google_sheets: "https://cdn.simpleicons.org/googlesheets",
    google_docs: "https://cdn.simpleicons.org/googledocs",
    hubspot: "https://cdn.simpleicons.org/hubspot",
    salesforce: "https://cdn.simpleicons.org/salesforce",
    jira: "https://cdn.simpleicons.org/jira",
    linear: "https://cdn.simpleicons.org/linear/white",
    trello: "https://cdn.simpleicons.org/trello",
    asana: "https://cdn.simpleicons.org/asana",
    discord: "https://cdn.simpleicons.org/discord",
    microsoft_teams: "https://cdn.simpleicons.org/microsoftteams",
    outlook: "https://cdn.simpleicons.org/microsoftoutlook",
    dropbox: "https://cdn.simpleicons.org/dropbox",
    airtable: "https://cdn.simpleicons.org/airtable",
    figma: "https://cdn.simpleicons.org/figma",
    zoom: "https://cdn.simpleicons.org/zoom",
    stripe: "https://cdn.simpleicons.org/stripe",
    shopify: "https://cdn.simpleicons.org/shopify",
    twilio: "https://cdn.simpleicons.org/twilio",
    sendgrid: "https://cdn.simpleicons.org/sendgrid",
    mailchimp: "https://cdn.simpleicons.org/mailchimp",
    intercom: "https://cdn.simpleicons.org/intercom",
    zendesk: "https://cdn.simpleicons.org/zendesk",
    supabase: "https://cdn.simpleicons.org/supabase",
    vercel: "https://cdn.simpleicons.org/vercel/white",
    gitlab: "https://cdn.simpleicons.org/gitlab",
    bitbucket: "https://cdn.simpleicons.org/bitbucket",
    confluence: "https://cdn.simpleicons.org/confluence",
    monday: "https://cdn.simpleicons.org/mondaydotcom",
    clickup: "https://cdn.simpleicons.org/clickup",
    todoist: "https://cdn.simpleicons.org/todoist",
    calendly: "https://cdn.simpleicons.org/calendly",
    typeform: "https://cdn.simpleicons.org/typeform",
    linkedin: "https://cdn.simpleicons.org/linkedin",
    twitter: "https://cdn.simpleicons.org/x/white",
    facebook: "https://cdn.simpleicons.org/facebook",
    instagram: "https://cdn.simpleicons.org/instagram",
    youtube: "https://cdn.simpleicons.org/youtube",
    whatsapp: "https://cdn.simpleicons.org/whatsapp",
    telegram: "https://cdn.simpleicons.org/telegram",
    composio: "https://cdn.simpleicons.org/composio",
};
/** Human-friendly display names for tools with non-obvious keys */
const TOOL_DISPLAY_NAMES = {
    gmail: "Gmail",
    github: "GitHub",
    slack: "Slack",
    notion: "Notion",
    google_calendar: "Google Calendar",
    googlecalendar: "Google Calendar",
    google_drive: "Google Drive",
    googledrive: "Google Drive",
    google_sheets: "Google Sheets",
    googlesheets: "Google Sheets",
    google_docs: "Google Docs",
    googledocs: "Google Docs",
    hubspot: "HubSpot",
    salesforce: "Salesforce",
    jira: "Jira",
    linear: "Linear",
    trello: "Trello",
    asana: "Asana",
    discord: "Discord",
    microsoft_teams: "Microsoft Teams",
    outlook: "Outlook",
    dropbox: "Dropbox",
    airtable: "Airtable",
    figma: "Figma",
    zoom: "Zoom",
    stripe: "Stripe",
    shopify: "Shopify",
    twilio: "Twilio",
    sendgrid: "SendGrid",
    mailchimp: "Mailchimp",
    intercom: "Intercom",
    zendesk: "Zendesk",
    supabase: "Supabase",
    vercel: "Vercel",
    gitlab: "GitLab",
    bitbucket: "Bitbucket",
    confluence: "Confluence",
    monday: "Monday.com",
    clickup: "ClickUp",
    todoist: "Todoist",
    calendly: "Calendly",
    typeform: "Typeform",
    linkedin: "LinkedIn",
    twitter: "Twitter / X",
    facebook: "Facebook",
    instagram: "Instagram",
    youtube: "YouTube",
    whatsapp: "WhatsApp",
    telegram: "Telegram",
    composio: "Composio",
};
/** Capitalize a tool name: "google_calendar" → "Google Calendar" */
function capitalizeToolName(key) {
    if (TOOL_DISPLAY_NAMES[key])
        return TOOL_DISPLAY_NAMES[key];
    return key
        .split(/[_-]/)
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
        .join(" ");
}
/**
 * List all available apps from the Composio platform (250+ integrations).
 * Normalizes the response to a consistent shape with logo URLs.
 */
export async function listAvailableApps() {
    const client = getClient();
    if (!client)
        return [];
    try {
        const raw = await client.apps.list();
        const apps = raw?.items ?? (Array.isArray(raw) ? raw : []);
        return apps.map((app) => {
            const key = (app.key ?? app.name ?? app.appId ?? "").toLowerCase();
            return {
                appName: key,
                displayName: capitalizeToolName(key),
                description: app.description ?? "",
                logoUrl: app.logo ?? app.logoUrl ?? app.meta?.logo ?? TOOL_LOGOS[key] ?? null,
                categories: app.categories ?? app.tags ?? [],
            };
        });
    }
    catch (err) {
        console.error("[composio] listAvailableApps failed:", err);
        return [];
    }
}
//# sourceMappingURL=composio.js.map