All files / src/sdk base.toolset.ts

89.15% Statements 74/83
71.42% Branches 55/77
80% Functions 16/20
89.15% Lines 74/83

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  6x 6x                 6x 6x                         6x 6x 6x 6x                     6x       6x                       6x                   6x                                                   6x     6x 6x           6x 6x 6x 6x 6x 6x 6x 6x   6x   6x 6x               1x                       21x   21x                 21x 21x 2x 2x     2x             21x   21x             21x 4783x 4783x 4786x         4783x             2x       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 { 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 { BackendClient } 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 {
  fileInputProcessor,
  fileResponseProcessor,
  fileSchemaProcessor,
} from "./utils/processor/file";
 
export type ExecuteActionParams = z.infer<typeof ZExecuteActionParams> & {
  // @deprecated
  action?: string;
  actionName?: string;
};
export class ComposioToolSet {
  client: Composio;
  apiKey: string;
  runtime: string | null;
  entityId: string = "default";
 
  backendClient: BackendClient;
  connectedAccounts: ConnectedAccounts;
  apps: Apps;
  actions: Actions;
  triggers: Triggers;
  integrations: Integrations;
  activeTriggers: ActiveTriggers;
 
  userActionRegistry: ActionRegistry;
 
  private internalProcessors: {
    pre: TPreProcessor[];
    post: TPostProcessor[];
    schema: TSchemaProcessor[];
  } = {
    pre: [fileInputProcessor],
    post: [fileResponseProcessor],
    schema: [fileSchemaProcessor],
  };
 
  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
   */
  constructor({
    apiKey,
    baseUrl,
    runtime,
    entityId,
  }: {
    apiKey?: string | null;
    baseUrl?: string | null;
    runtime?: string | null;
    entityId?: string;
  } = {}) {
    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,
    });
 
    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.userActionRegistry = new ActionRegistry(this.client);
 
    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>
  ): Promise<RawActionData[]> {
    const parsedFilters = ZToolSchemaFilter.parse(filters);
 
    const apps = await this.client.actions.list({
      apps: parsedFilters.apps?.join(","),
      tags: parsedFilters.tags?.join(","),
      useCase: parsedFilters.useCase,
      actions: parsedFilters.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 = [...(apps?.items || []), ...toolsWithCustomActions];
 
    const allSchemaProcessor = [
      ...this.internalProcessors.schema,
      ...(this.userDefinedProcessors.schema
        ? [this.userDefinedProcessors.schema]
        : []),
    ];
 
    return toolsActions.map((tool) => {
      let schema = tool as RawActionData;
      allSchemaProcessor.forEach((processor) => {
        schema = processor({
          actionName: schema?.name,
          toolSchema: schema,
        });
      });
      return schema;
    });
  }
 
  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 = processor({
        params: params,
        actionName: action,
      });
    }
 
    // 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;
      }
 
      Iif (!accountId) {
        throw new Error("No connected account found for the user");
      }
 
      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]
        : []),
    ];
 
    let dataToReturn = { ...data };
    for (const processor of allOutputProcessor) {
      dataToReturn = 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;
  }
}