Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

12.1 KB
Raw Blame
/**
 * Imperative RPC wrapper for the Composio domain — typed counterpart
 * to `crates/openhuman-core/src/integrations/composio/*` on the Rust side.
 *
 * Every function here calls the core sidecar via JSON-RPC. The core
 * in turn proxies to the openhuman backend's
 * `/agent-integrations/composio/*` routes, so the frontend never talks
 * to Composio directly and never handles the API key.
 *
 * Keep this file stylistically consistent with the other RPC wrappers
 * in `app/src/utils/tauriCommands` so the domain stays easy to grok.
 */
import { callCoreRpc } from '../../services/coreRpcClient';
import type {
  ComposioActiveTriggersResponse,
  ComposioAgentReadyToolkitsResponse,
  ComposioAuthorizeResponse,
  ComposioAvailableTriggersResponse,
  ComposioConnectionsResponse,
  ComposioDeleteResponse,
  ComposioDisableTriggerResponse,
  ComposioEnableTriggerResponse,
  ComposioExecuteResponse,
  ComposioGithubReposResponse,
  ComposioToolkitsResponse,
  ComposioToolsResponse,
  ComposioUserScopePref,
} from './types';

/**
 * Every `composio_*` op on the Rust side returns an `Outcome` with a
 * user-visible log line attached. `Outcome::into_cli_compatible_json`
 * (see `crates/openhuman-rpc/src/mod.rs`) therefore wraps the payload as
 * `{ "result": <flat shape>, "logs": [...] }` before handing it to the
 * JSON-RPC layer. This helper peels that envelope back off so every
 * caller in this file can work with the flat shapes declared in
 * `./types`. Responses without logs pass through unchanged.
 */
function unwrapCliEnvelope<T>(value: unknown): T {
  if (
    value !== null &&
    typeof value === 'object' &&
    'result' in (value as Record<string, unknown>) &&
    'logs' in (value as Record<string, unknown>) &&
    Array.isArray((value as { logs: unknown }).logs)
  ) {
    return (value as { result: T }).result;
  }
  return value as T;
}

/**
 * Shorter-than-default per-call timeout the Connections page's loading
 * state opts into for the two RPCs it waits on (`listToolkits` +
 * `listConnections`).
 *
 * Both fetches are *non-critical on that surface*: the toolkit catalog has
 * a 24h stale cache AND a hardcoded `KNOWN_COMPOSIO_TOOLKITS` fallback, so a
 * slow or dead backend should degrade to the fallback fast rather than
 * pinning the Connections grid on a loading skeleton. The skeleton window is
 * bounded by the *slower* of these two calls (the hook clears `loading` only
 * after `Promise.allSettled([getToolkitCatalog(), listConnections()])`
 * settles — see `useComposioIntegrations` in ./hooks.ts), so BOTH must opt
 * into the shorter budget. Without this the window stretches to the global
 * `CORE_RPC_TIMEOUT_MS` (30s) on a cold cache against a down backend.
 *
 * It is deliberately **opt-in** via the `timeoutMs` option rather than the
 * wrapper default: `listConnections` is also called by the GitHub repo
 * picker, SmartIssuePicker, the add-memory-source dialog and the connect
 * modal's poll loop, where a slow-but-successful 8–30s call must still be
 * allowed to complete rather than being failed early (#4079 review).
 */
export const COMPOSIO_FETCH_TIMEOUT_MS = 8_000;

/** Per-call options shared by the bounded read wrappers. */
interface ComposioReadOptions {
  /**
   * Override the RPC timeout (ms). Omit to inherit the global
   * `CORE_RPC_TIMEOUT_MS`. Pass `COMPOSIO_FETCH_TIMEOUT_MS` only from the
   * Connections-page loading path (see the constant's doc comment).
   */
  timeoutMs?: number;
}

// ── Read operations ───────────────────────────────────────────────

export async function listToolkits(
  options?: ComposioReadOptions
): Promise<ComposioToolkitsResponse> {
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_list_toolkits',
    // Timeout is opt-in: the Connections loading skeleton passes the shorter
    // budget so the hardcoded fallback surfaces fast (#3933); other callers
    // inherit the global default.
    ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
  });
  return unwrapCliEnvelope<ComposioToolkitsResponse>(raw);
}

/**
 * Fetch the slugs of toolkits that have an agent-ready curated
 * catalog on the core side. The response is sorted alphabetically
 * and is safe to cache once per session — the set only changes
 * with core releases.
 *
 * Used by the Skills grid (issue #2283) to label connected
 * toolkits without a catalog as "preview / coming soon" so users
 * don't trigger the max-iterations failure that uncurated
 * connections cause.
 */
export async function listAgentReadyToolkits(): Promise<ComposioAgentReadyToolkitsResponse> {
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_list_agent_ready_toolkits',
  });
  return unwrapCliEnvelope<ComposioAgentReadyToolkitsResponse>(raw);
}

export async function listConnections(
  options?: ComposioReadOptions
): Promise<ComposioConnectionsResponse> {
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_list_connections',
    // Timeout is opt-in (see `listToolkits`): only the Connections loading
    // path passes the shorter budget. Shared callers (repo/issue pickers,
    // add-memory-source, connect-modal poll) inherit the global default so a
    // slow-but-successful call still completes (#4079 review).
    ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
  });
  return unwrapCliEnvelope<ComposioConnectionsResponse>(raw);
}

export async function listTools(toolkits?: string[]): Promise<ComposioToolsResponse> {
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_list_tools',
    params: toolkits && toolkits.length > 0 ? { toolkits } : {},
  });
  return unwrapCliEnvelope<ComposioToolsResponse>(raw);
}

// ── Write operations ──────────────────────────────────────────────

/**
 * Begin an OAuth handoff for `toolkit`. The returned `connectUrl`
 * must be opened in a browser for the user to complete the flow.
 * The core publishes a `ComposioConnectionCreated` event on success.
 *
 * `extraParams` is merged into the backend request body. Required for
 * toolkits that need additional fields (e.g. `whatsapp` needs `waba_id`).
 */
export async function authorize(
  toolkit: string,
  extraParams?: Record<string, string>
): Promise<ComposioAuthorizeResponse> {
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_authorize',
    params: extraParams ? { toolkit, extra_params: extraParams } : { toolkit },
  });
  return unwrapCliEnvelope<ComposioAuthorizeResponse>(raw);
}

/**
 * Delete an existing Composio connection. Backend verifies ownership
 * before forwarding to Composio
 */
export async function deleteConnection(connectionId: string): Promise<ComposioDeleteResponse> {
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_delete_connection',
    params: { connection_id: connectionId },
  });
  return unwrapCliEnvelope<ComposioDeleteResponse>(raw);
}

/**
 * Read the per-toolkit user scope preference (read/write/admin) used
 * to gate `composio_execute`. Returns the default
 * `{ read: true, write: true, admin: false }` when nothing is stored.
 */
export async function getUserScopes(toolkit: string): Promise<ComposioUserScopePref> {
  console.debug('[composio][scopes] → openhuman.composio_get_user_scopes toolkit=%s', toolkit);
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_get_user_scopes',
    params: { toolkit },
  });
  const pref = unwrapCliEnvelope<ComposioUserScopePref>(raw);
  console.debug(
    '[composio][scopes] ← openhuman.composio_get_user_scopes toolkit=%s pref=%o',
    toolkit,
    pref
  );
  return pref;
}

/**
 * Persist a per-toolkit user scope preference. The agent will only be
 * able to invoke composio actions whose classified scope is enabled
 * here.
 */
export async function setUserScopes(
  toolkit: string,
  pref: ComposioUserScopePref
): Promise<ComposioUserScopePref> {
  console.debug(
    '[composio][scopes] → openhuman.composio_set_user_scopes toolkit=%s pref=%o',
    toolkit,
    pref
  );
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_set_user_scopes',
    params: { toolkit, ...pref },
  });
  const persisted = unwrapCliEnvelope<ComposioUserScopePref>(raw);
  console.debug(
    '[composio][scopes] ← openhuman.composio_set_user_scopes toolkit=%s persisted=%o',
    toolkit,
    persisted
  );
  return persisted;
}

/**
 * Execute a Composio action slug (e.g. `GMAIL_SEND_EMAIL`). The core
 * charges the caller, tracks usage, and publishes a
 * `ComposioActionExecuted` event.
 */
export async function execute(
  tool: string,
  args?: Record<string, unknown>
): Promise<ComposioExecuteResponse> {
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_execute',
    params: { tool, arguments: args ?? {} },
  });
  return unwrapCliEnvelope<ComposioExecuteResponse>(raw);
}

/**
 * List GitHub repositories available through the user's authorized
 * Composio connection. Wraps `openhuman.composio_list_github_repos`
 * which hits the dedicated backend endpoint (not `composio_execute`).
 */
export async function listGithubRepos(connectionId?: string): Promise<ComposioGithubReposResponse> {
  const params: Record<string, unknown> = {};
  if (connectionId) params.connection_id = connectionId;
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_list_github_repos',
    params,
  });
  return unwrapCliEnvelope<ComposioGithubReposResponse>(raw);
}

// ── Trigger management ────────────────────────────────────────────

/**
 * List the catalog of triggers the user could enable for a toolkit.
 * For GitHub, the backend fans out into per-repo entries — pass the
 * GitHub `connectionId` (or the user's first GitHub connection is
 * picked by the backend).
 */
export async function listAvailableTriggers(
  toolkit: string,
  connectionId?: string
): Promise<ComposioAvailableTriggersResponse> {
  const params: Record<string, unknown> = { toolkit };
  if (connectionId) params.connection_id = connectionId;
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_list_available_triggers',
    params,
    // A 401 here is a single trigger-catalog read failure, not whole-session
    // death (the connection itself is still active). Suppress the global
    // sign-out so the trigger panel can show an in-place "Sign in again" CTA
    // instead of being torn down (#4281, #2286).
    suppressAuthExpiredEvent: true,
  });
  return unwrapCliEnvelope<ComposioAvailableTriggersResponse>(raw);
}

/**
 * List the user's currently enabled Composio triggers.
 */
export async function listTriggers(toolkit?: string): Promise<ComposioActiveTriggersResponse> {
  const params: Record<string, unknown> = {};
  if (toolkit) params.toolkit = toolkit;
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_list_triggers',
    params,
    // Loaded alongside the available-triggers catalog in the same panel —
    // keep its 401 handling local too (see `listAvailableTriggers`).
    suppressAuthExpiredEvent: true,
  });
  return unwrapCliEnvelope<ComposioActiveTriggersResponse>(raw);
}

/**
 * Enable a single trigger on a connection the caller owns.
 */
export async function enableTrigger(
  connectionId: string,
  slug: string,
  triggerConfig?: Record<string, unknown>
): Promise<ComposioEnableTriggerResponse> {
  const params: Record<string, unknown> = { connection_id: connectionId, slug };
  if (triggerConfig !== undefined) params.trigger_config = triggerConfig;
  const raw = await callCoreRpc<unknown>({ method: 'openhuman.composio_enable_trigger', params });
  return unwrapCliEnvelope<ComposioEnableTriggerResponse>(raw);
}

/**
 * Disable (delete) a trigger owned by the caller.
 */
export async function disableTrigger(triggerId: string): Promise<ComposioDisableTriggerResponse> {
  const raw = await callCoreRpc<unknown>({
    method: 'openhuman.composio_disable_trigger',
    params: { trigger_id: triggerId },
  });
  return unwrapCliEnvelope<ComposioDisableTriggerResponse>(raw);
}