All files / src/sdk base.toolset.ts

81.37% Statements 83/102
65.59% Branches 61/93
70% Functions 14/20
81.37% Lines 83/102

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391  7x 7x                 7x 7x 7x                         7x 7x 7x 7x                     7x       7x 7x                       7x                   7x                                                               7x     7x 7x             7x 7x 7x 7x 7x 7x 7x 7x 7x   7x   7x           7x       7x 7x               1x                         26x 26x   26x                                   26x                 26x 26x 3x 3x     3x             26x         26x           26x   26x 5739x   5739x 5742x         5739x   26x           3x       6x   6x                               6x               6x                   6x   6x             6x 7x               6x 2x 2x   1x         1x       2x           2x           4x             4x                         4x               4x 4x 7x         4x       1x 1x         1x       1x 1x         1x       1x 1x         1x       1x                      
import { z } from "zod";
import { Composio } from "../sdk";
import {
  RawActionData,
  TPostProcessor,
  TPreProcessor,
  TSchemaProcessor,
  ZExecuteActionParams,
  ZToolSchemaFilter,
} from "../types/base_toolset";
import type { Optional, Sequence } from "../types/util";
import logger from "../utils/logger";
import { getEnvVariable } from "../utils/shared";
import {
  ActionRegistry,
  CreateActionOptions,
  Parameters,
} from "./actionRegistry";
import { ActionExecutionResDto } from "./client/types.gen";
import { ActionExecuteResponse, Actions } from "./models/actions";
import { ActiveTriggers } from "./models/activeTriggers";
import { Apps } from "./models/apps";
import { AxiosBackendClient } from "./models/backendClient";
import { ConnectedAccounts } from "./models/connectedAccounts";
import { Integrations } from "./models/integrations";
import { Triggers } from "./models/triggers";
import { getUserDataJson } from "./utils/config";
import { CEG } from "./utils/error";
import { COMPOSIO_SDK_ERROR_CODES } from "./utils/errors/src/constants";
import {
  FILE_DOWNLOADABLE_PROCESSOR,
  FILE_INPUT_PROCESSOR,
  FILE_SCHEMA_PROCESSOR,
} from "./utils/processor/file";
 
export type ExecuteActionParams = z.infer<typeof ZExecuteActionParams> & {
  /** @deprecated use actionName field instead */
  action?: string;
  actionName?: string;
};
export class ComposioToolSet {
  client: Composio;
  apiKey: string;
  runtime: string | null;
  entityId: string = "default";
  connectedAccountIds: Record<string, string> = {};
 
  backendClient: AxiosBackendClient;
  connectedAccounts: ConnectedAccounts;
  apps: Apps;
  actions: Actions;
  triggers: Triggers;
  integrations: Integrations;
  activeTriggers: ActiveTriggers;
 
  userActionRegistry: ActionRegistry;
 
  private internalProcessors: {
    pre: TPreProcessor[];
    post: TPostProcessor[];
    schema: TSchemaProcessor[];
  } = {
    pre: [FILE_INPUT_PROCESSOR],
    post: [FILE_DOWNLOADABLE_PROCESSOR],
    schema: [FILE_SCHEMA_PROCESSOR],
  };
 
  private userDefinedProcessors: {
    pre?: TPreProcessor;
    post?: TPostProcessor;
    schema?: TSchemaProcessor;
  } = {};
 
  /**
   * Creates a new instance of ComposioToolSet
   * @param {Object} config - Configuration object
   * @param {string|null} config.apiKey - API key for authentication
   * @param {string|null} config.baseUrl - Base URL for API requests
   * @param {string|null} config.runtime - Runtime environment
   * @param {string} config.entityId - Entity ID for operations
   * @param {Record<string, string>} config.connectedAccountIds - Map of app names to their connected account IDs
   * @param {boolean} config.allowTracing - Whether to allow tracing for the SDK
   */
  constructor({
    apiKey,
    baseUrl,
    runtime,
    entityId,
    connectedAccountIds,
    allowTracing,
  }: {
    apiKey?: string | null;
    baseUrl?: string | null;
    runtime?: string | null;
    entityId?: string;
    connectedAccountIds?: Record<string, string>;
    allowTracing?: boolean;
  } = {}) {
    const clientApiKey: string | undefined =
      apiKey ||
      getEnvVariable("COMPOSIO_API_KEY") ||
      (getUserDataJson().api_key as string);
    this.apiKey = clientApiKey;
    this.client = new Composio({
      apiKey: this.apiKey,
      baseUrl: baseUrl || undefined,
      runtime: runtime as string,
      allowTracing: allowTracing || false,
    });
 
    this.runtime = runtime || null;
    this.backendClient = this.client.backendClient;
    this.connectedAccounts = this.client.connectedAccounts;
    this.apps = this.client.apps;
    this.actions = this.client.actions;
    this.triggers = this.client.triggers;
    this.integrations = this.client.integrations;
    this.activeTriggers = this.client.activeTriggers;
    this.connectedAccountIds = connectedAccountIds || {};
 
    this.userActionRegistry = new ActionRegistry(this.client);
 
    Iif (entityId && connectedAccountIds) {
      logger.warn(
        "When both entity and connectedAccountIds are provided, preference will be given to connectedAccountIds"
      );
    }
 
    Iif (connectedAccountIds) {
      this.connectedAccountIds = connectedAccountIds;
    }
 
    if (entityId) {
      this.entityId = entityId;
    }
  }
 
  async getActionsSchema(
    filters: { actions?: Optional<Sequence<string>> } = {},
    _entityId?: Optional<string>
  ) {
    return this.getToolsSchema(
      {
        actions: filters.actions || [],
      },
      _entityId
    );
  }
 
  async getToolsSchema(
    filters: z.infer<typeof ZToolSchemaFilter>,
    _entityId?: Optional<string>,
    _integrationId?: Optional<string>
  ): Promise<RawActionData[]> {
    const parsedFilters = ZToolSchemaFilter.parse(filters);
    let actions = parsedFilters.actions;
 
    Iif (_integrationId) {
      const integration = await this.integrations.get({
        integrationId: _integrationId,
      });
      Iif (integration?.limitedActions) {
        if (!actions) {
          actions = [...integration.limitedActions];
        } else {
          const limitedActionsUppercase = integration.limitedActions.map(
            (action) => action.toUpperCase()
          );
          actions = actions.filter((action) =>
            limitedActionsUppercase.includes(action.toUpperCase())
          );
        }
      }
    }
 
    const appActions = await this.client.actions.list({
      apps: parsedFilters.apps?.join(","),
      tags: parsedFilters.tags?.join(","),
      useCase: parsedFilters.useCase,
      actions: actions?.join(","),
      usecaseLimit: parsedFilters.useCaseLimit,
      filterByAvailableApps: parsedFilters.filterByAvailableApps,
    });
 
    const customActions = await this.userActionRegistry.getAllActions();
    const toolsWithCustomActions = customActions.filter((action) => {
      const { name: actionName } = action || {};
      return (
        (!filters.actions ||
          filters.actions.some(
            (name) => name.toLowerCase() === actionName?.toLowerCase()
          )) &&
        (!filters.tags ||
          filters.tags.some((tag) => tag.toLowerCase() === "custom"))
      );
    });
 
    const toolsActions = [
      ...(appActions?.items || []),
      ...toolsWithCustomActions,
    ];
 
    const allSchemaProcessor = [
      ...this.internalProcessors.schema,
      ...(this.userDefinedProcessors.schema
        ? [this.userDefinedProcessors.schema]
        : []),
    ];
    const processedTools = [];
    // Iterate over the tools and process them
    for (const tool of toolsActions) {
      let schema = tool as RawActionData;
      // Process the schema with all the processors
      for (const processor of allSchemaProcessor) {
        schema = await processor({
          actionName: schema?.name,
          toolSchema: schema,
        });
      }
      processedTools.push(schema);
    }
    return processedTools;
  }
 
  async createAction<P extends Parameters = z.ZodObject<{}>>(
    options: CreateActionOptions<P>
  ) {
    return this.userActionRegistry.createAction<P>(options);
  }
 
  private isCustomAction(action: string) {
    return this.userActionRegistry
      .getActions({ actions: [action] })
      .then((actions) => actions.length > 0);
  }
 
  async getEntity(entityId: string) {
    return this.client.getEntity(entityId);
  }
 
  async executeAction(
    functionParams: ExecuteActionParams
  ): Promise<ActionExecuteResponse> {
    const {
      action,
      params: inputParams = {},
      entityId = this.entityId,
      nlaText = "",
      connectedAccountId,
    } = ZExecuteActionParams.parse({
      action: functionParams.actionName || functionParams.action,
      params: functionParams.params,
      entityId: functionParams.entityId,
      nlaText: functionParams.nlaText,
      connectedAccountId: functionParams.connectedAccountId,
    });
 
    Iif (!entityId && !connectedAccountId) {
      throw CEG.getCustomError(
        COMPOSIO_SDK_ERROR_CODES.SDK.NO_CONNECTED_ACCOUNT_FOUND,
        {
          message: `No entityId or connectedAccountId provided`,
          description: `Please provide either entityId or connectedAccountId`,
        }
      );
    }
 
    let params = (inputParams as Record<string, unknown>) || {};
 
    const allInputProcessor = [
      ...this.internalProcessors.pre,
      ...(this.userDefinedProcessors.pre
        ? [this.userDefinedProcessors.pre]
        : []),
    ];
 
    for (const processor of allInputProcessor) {
      params = await processor({
        params: params,
        actionName: action,
        client: this.client.backendClient.instance,
      });
    }
 
    // Custom actions are always executed in the host/local environment for JS SDK
    if (await this.isCustomAction(action)) {
      let accountId = connectedAccountId;
      if (!accountId) {
        // fetch connected account id
        const connectedAccounts = await this.client.connectedAccounts.list({
          user_uuid: entityId,
          status: "ACTIVE",
          showActiveOnly: true,
        });
        accountId = connectedAccounts?.items[0]?.id;
      }
 
      // allows the user to use custom actions and tools without a connected account
      Iif (!accountId) {
        logger.warn(
          "No connected account found for the user. If your custom action requires a connected account, please double check if you have active accounts connected to it."
        );
      }
 
      return this.userActionRegistry.executeAction(action, params, {
        entityId: entityId,
        connectionId: accountId,
      });
    }
 
    const data = await this.client.getEntity(entityId).execute({
      actionName: action,
      params: params,
      text: nlaText,
      connectedAccountId: connectedAccountId,
    });
 
    return this.processResponse(data, {
      action: action,
      entityId: entityId,
    });
  }
 
  private async processResponse(
    data: ActionExecutionResDto,
    meta: {
      action: string;
      entityId: string;
    }
  ): Promise<ActionExecutionResDto> {
    const allOutputProcessor = [
      ...this.internalProcessors.post,
      ...(this.userDefinedProcessors.post
        ? [this.userDefinedProcessors.post]
        : []),
    ];
 
    // Dirty way to avoid copy
    let dataToReturn = JSON.parse(JSON.stringify(data));
    for (const processor of allOutputProcessor) {
      dataToReturn = await processor({
        actionName: meta.action,
        toolResponse: dataToReturn,
      });
    }
    return dataToReturn;
  }
 
  async addSchemaProcessor(processor: TSchemaProcessor) {
    if (typeof processor === "function") {
      this.userDefinedProcessors.schema = processor as TSchemaProcessor;
    } else E{
      throw new Error("Invalid processor type");
    }
 
    return this;
  }
 
  async addPreProcessor(processor: TPreProcessor) {
    if (typeof processor === "function") {
      this.userDefinedProcessors.pre = processor as unknown as TPreProcessor;
    } else E{
      throw new Error("Invalid processor type");
    }
 
    return this;
  }
 
  async addPostProcessor(processor: TPostProcessor) {
    if (typeof processor === "function") {
      this.userDefinedProcessors.post = processor as unknown as TPostProcessor;
    } else E{
      throw new Error("Invalid processor type");
    }
 
    return this;
  }
 
  async removePreProcessor() {
    delete this.userDefinedProcessors.pre;
  }
 
  async removePostProcessor() {
    delete this.userDefinedProcessors.post;
  }
 
  async removeSchemaProcessor() {
    delete this.userDefinedProcessors.schema;
  }
}