All files / sdk base.toolset.ts

68.65% Statements 92/134
62.77% Branches 113/180
54.83% Functions 17/31
69.17% Lines 92/133

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 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 4596x 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 6x                                                     16x   16x                     1x 1x           1x       1x 1x 1x       1x 1x 1x   1x                       1x           1x 1x                                                                     15x   15x               15x       15x 7x 7x     7x             15x   15x                                                                         15x           15x 3826x         3827x 3827x 3827x   3827x 11481x 1x             1x       3827x       1x       5x   5x                   5x 5x     5x 5x 1x           5x 1x 1x               1x       1x         4x           4x 4x           4x                         4x   4x 4x               4x 4x 3x           4x       1x 1x             1x 1x             1x              
import { Composio } from "../sdk";
import { ExecEnv, WorkspaceFactory } from "../env/factory";
import { COMPOSIO_BASE_URL } from "./client/core/OpenAPI";
import { RemoteWorkspace } from "../env/base";
import type { IPythonActionDetails, Optional, Sequence } from "./types";
import { getEnvVariable } from "../utils/shared";
import { WorkspaceConfig } from "../env/config";
import { Workspace } from "../env";
import { ActionExecutionResDto } from "./client/types.gen";
import { saveFile } from "./utils/fileUtils";
import { convertReqParams, converReqParamForActionExecution } from "./utils";
import { ActionRegistry, CreateActionOptions } from "./actionRegistry";
import { getUserDataJson } from "./utils/config";
import { z } from "zod";
type GetListActionsResponse = {
  items: any[];
};
 
const ZExecuteActionParams = z.object({
  action: z.string(),
  params: z.record(z.any()).optional(),
  entityId: z.string(),
  nlaText: z.string().optional(),
  connectedAccountId: z.string().optional(),
  config: z
    .object({
      labels: z.array(z.string()).optional(),
    })
    .optional(),
});
 
type TPreProcessor = ({
  action,
  toolRequest,
}: {
  action: string;
  toolRequest: Record<string, unknown>;
}) => Record<string, unknown>;
type TPostProcessor = ({
  action,
  toolResponse,
}: {
  action: string;
  toolResponse: ActionExecutionResDto;
}) => ActionExecutionResDto;
 
const fileProcessor = ({
  action,
  toolResponse,
}: {
  action: string;
  toolResponse: ActionExecutionResDto;
}): ActionExecutionResDto => {
  // @ts-expect-error
  const isFile = !!toolResponse.data.response_data.file as boolean;
 
  Iif (!isFile) {
    return toolResponse;
  }
 
  // @ts-expect-error
  const fileData = toolResponse.data.response_data.file;
  const { name, content } = fileData as { name: string; content: string };
  const file_name_prefix = `${action}_${Date.now()}`;
  const filePath = saveFile(file_name_prefix, content);
 
  // @ts-ignore
  delete toolResponse.data.response_data.file;
 
  return {
    error: toolResponse.error,
    successfull: toolResponse.successfull,
    data: {
      ...toolResponse.data,
      file_uri_path: filePath,
    },
  };
};
 
export class ComposioToolSet {
  client: Composio;
  apiKey: string;
  runtime: string | null;
  entityId: string;
  workspace: WorkspaceFactory;
  workspaceEnv: ExecEnv;
 
  localActions: IPythonActionDetails["data"] | undefined;
  customActionRegistry: ActionRegistry;
 
  private processors: {
    pre?: TPreProcessor;
    post?: TPostProcessor;
  } = {};
 
  constructor(
    apiKey: string | null,
    baseUrl: string | null = COMPOSIO_BASE_URL,
    runtime: string | null = null,
    entityId: string = "default",
    workspaceConfig: WorkspaceConfig = Workspace.Host()
  ) {
    const clientApiKey: string | undefined =
      apiKey ||
      getEnvVariable("COMPOSIO_API_KEY") ||
      (getUserDataJson().api_key as string);
    this.apiKey = clientApiKey;
    this.client = new Composio(
      this.apiKey,
      baseUrl || undefined,
      runtime as string
    );
    this.customActionRegistry = new ActionRegistry(this.client);
    this.runtime = runtime;
    this.entityId = entityId;
 
    if (!workspaceConfig.config.composioBaseURL) {
      workspaceConfig.config.composioBaseURL = baseUrl;
    }
    if (!workspaceConfig.config.composioAPIKey) {
      workspaceConfig.config.composioAPIKey = apiKey;
    }
    this.workspace = new WorkspaceFactory(workspaceConfig.env, workspaceConfig);
    this.workspaceEnv = workspaceConfig.env;
 
    if (typeof process !== "undefined") {
      process.on("exit", async () => {
        await this.workspace.workspace?.teardown();
      });
    }
  }
 
  /**
   * @deprecated This method is deprecated. Please use this.client.getExpectedParamsForUser instead.
   */
  async getExpectedParamsForUser(
    params: {
      app?: string;
      integrationId?: string;
      entityId?: string;
      authScheme?:
        | "OAUTH2"
        | "OAUTH1"
        | "API_KEY"
        | "BASIC"
        | "BEARER_TOKEN"
        | "BASIC_WITH_JWT";
    } = {}
  ) {
    return this.client.getExpectedParamsForUser(params);
  }
 
  async setup() {
    await this.workspace.new();
 
    Iif (!this.localActions && this.workspaceEnv !== ExecEnv.HOST) {
      this.localActions = await (
        this.workspace.workspace as RemoteWorkspace
      ).getLocalActionsSchema();
    }
  }
 
  async getActionsSchema(
    filters: { actions?: Optional<Sequence<string>> } = {},
    entityId?: Optional<string>
  ): Promise<Sequence<NonNullable<GetListActionsResponse["items"]>[0]>> {
    await this.setup();
    const actions = (
      await this.client.actions.list({
        actions: filters.actions?.join(","),
        showAll: true,
      })
    ).items;
    const localActionsMap = new Map<
      string,
      NonNullable<GetListActionsResponse["items"]>[0]
    >();
    filters.actions?.forEach((action: string) => {
      const actionData = this.localActions?.find((a: any) => a.name === action);
      Iif (actionData) {
        localActionsMap.set(actionData.name!, actionData);
      }
    });
    const uniqueLocalActions = Array.from(localActionsMap.values());
    const _newActions = filters.actions?.map((action: string) =>
      action.toLowerCase()
    );
    const toolsWithCustomActions = (
      await this.customActionRegistry.getActions({ actions: _newActions! })
    ).filter((action) => {
      Iif (
        _newActions &&
        !_newActions.includes(action.parameters.title.toLowerCase()!)
      ) {
        return false;
      }
      return true;
    });
 
    const toolsActions = [
      ...actions!,
      ...uniqueLocalActions,
      ...toolsWithCustomActions,
    ];
 
    return toolsActions.map((action) => {
      return this.modifyActionForLocalExecution(action);
    });
  }
 
  /**
   * @deprecated This method is deprecated. Please use this.client.connectedAccounts.getAuthParams instead.
   */
  async getAuthParams(data: { connectedAccountId: string }) {
    return this.client.connectedAccounts.getAuthParams({
      connectedAccountId: data.connectedAccountId,
    });
  }
 
  async getTools(
    filters: {
      apps: Sequence<string>;
      tags?: Optional<Array<string>>;
      useCase?: Optional<string>;
    },
    entityId?: Optional<string>
  ): Promise<unknown> {
    throw new Error("Not implemented. Please define in extended toolset");
  }
 
  async getToolsSchema(
    filters: {
      actions?: Optional<Array<string>>;
      apps?: Array<string>;
      tags?: Optional<Array<string>>;
      useCase?: Optional<string>;
      useCaseLimit?: Optional<number>;
      filterByAvailableApps?: Optional<boolean>;
    },
    entityId?: Optional<string>
  ): Promise<Sequence<NonNullable<GetListActionsResponse["items"]>[0]>> {
    await this.setup();
 
    const apps = await this.client.actions.list({
      ...(filters?.apps && { apps: filters?.apps?.join(",") }),
      ...(filters?.tags && { tags: filters?.tags?.join(",") }),
      ...(filters?.useCase && { useCase: filters?.useCase }),
      ...(filters?.actions && { actions: filters?.actions?.join(",") }),
      ...(filters?.useCaseLimit && { usecaseLimit: filters?.useCaseLimit }),
      filterByAvailableApps: filters?.filterByAvailableApps ?? undefined,
    });
    const localActions = new Map<
      string,
      NonNullable<GetListActionsResponse["items"]>[0]
    >();
    if (filters.apps && Array.isArray(filters.apps)) {
      for (const appName of filters.apps!) {
        const actionData = this.localActions?.filter(
          (a: { appName: string }) => a.appName === appName
        );
        Iif (actionData) {
          for (const action of actionData) {
            localActions.set(action.name, action);
          }
        }
      }
    }
    const uniqueLocalActions = Array.from(localActions.values());
 
    const toolsWithCustomActions = (
      await this.customActionRegistry.getAllActions()
    )
      .filter((action) => {
        Iif (
          filters.actions &&
          !filters.actions.some(
            (actionName) =>
              actionName.toLowerCase() ===
              action.metadata.actionName!.toLowerCase()
          )
        ) {
          return false;
        }
        Iif (
          filters.apps &&
          !filters.apps.some(
            (appName) =>
              appName.toLowerCase() === action.metadata.toolName!.toLowerCase()
          )
        ) {
          return false;
        }
        Iif (
          filters.tags &&
          !filters.tags.some(
            (tag) => tag.toLocaleLowerCase() === "custom".toLocaleLowerCase()
          )
        ) {
          return false;
        }
        return true;
      })
      .map((action) => {
        return action.schema;
      });
 
    const toolsActions = [
      ...apps?.items!,
      ...uniqueLocalActions,
      ...toolsWithCustomActions,
    ];
 
    return toolsActions.map((action) => {
      return this.modifyActionForLocalExecution(action);
    });
  }
 
  modifyActionForLocalExecution(toolSchema: any) {
    const properties = convertReqParams(toolSchema.parameters.properties);
    toolSchema.parameters.properties = properties;
    const response = toolSchema.response.properties;
 
    for (const responseKey of Object.keys(response)) {
      if (responseKey === "file") {
        response["file_uri_path"] = {
          type: "string",
          title: "Name",
          description:
            "Local absolute path to the file or http url to the file",
        };
 
        delete response[responseKey];
      }
    }
 
    return toolSchema;
  }
 
  async createAction(options: CreateActionOptions) {
    return this.customActionRegistry.createAction(options);
  }
 
  private isCustomAction(action: string) {
    return this.customActionRegistry
      .getActions({ actions: [action] })
      .then((actions) => actions.length > 0);
  }
 
  async executeAction(functionParams: z.infer<typeof ZExecuteActionParams>) {
    const {
      action,
      params: inputParams = {},
      entityId = "default",
      nlaText = "",
      connectedAccountId,
    } = ZExecuteActionParams.parse(functionParams);
    let params = inputParams;
 
    const isPreProcessorAndIsFunction =
      typeof this?.processors?.pre === "function";
    if (isPreProcessorAndIsFunction && this.processors.pre) {
      params = this.processors.pre({
        action: action,
        toolRequest: params,
      });
    }
    // Custom actions are always executed in the host/local environment for JS SDK
    if (await this.isCustomAction(action)) {
      let accountId = connectedAccountId;
      Iif (!accountId) {
        // fetch connected account id
        const connectedAccounts = await this.client.connectedAccounts.list({
          user_uuid: entityId,
        });
        accountId = connectedAccounts?.items[0]?.id;
      }
 
      Iif (!accountId) {
        throw new Error("No connected account found for the user");
      }
 
      return this.customActionRegistry.executeAction(action, params, {
        entityId: entityId,
        connectionId: accountId,
      });
    }
    Iif (this.workspaceEnv && this.workspaceEnv !== ExecEnv.HOST) {
      const workspace = await this.workspace.get();
      return workspace.executeAction(action, params, {
        entityId: this.entityId,
      });
    }
    const convertedParams = await converReqParamForActionExecution(params);
    const data = (await this.client.getEntity(entityId).execute({
      actionName: action,
      params: convertedParams,
      text: nlaText,
    })) as ActionExecutionResDto;
 
    return this.processResponse(data, {
      action: action,
      entityId: entityId,
    });
  }
 
  private async processResponse(
    data: ActionExecutionResDto,
    meta: {
      action: string;
      entityId: string;
    }
  ): Promise<ActionExecutionResDto> {
    let dataToReturn = { ...data };
    // @ts-ignore
    const isFile = !!data?.response_data?.file;
    Iif (isFile) {
      dataToReturn = fileProcessor({
        action: meta.action,
        toolResponse: dataToReturn,
      }) as ActionExecutionResDto;
    }
 
    const isPostProcessorAndIsFunction =
      !!this.processors.post && typeof this.processors.post === "function";
    if (isPostProcessorAndIsFunction && this.processors.post) {
      dataToReturn = this.processors.post({
        action: meta.action,
        toolResponse: dataToReturn,
      });
    }
 
    return dataToReturn;
  }
 
  async addPreProcessor(processor: TPreProcessor) {
    if (typeof processor === "function") {
      this.processors.pre = processor as TPreProcessor;
    } else E{
      throw new Error("Invalid processor type");
    }
  }
 
  async addPostProcessor(processor: TPostProcessor) {
    if (typeof processor === "function") {
      this.processors.post = processor as TPostProcessor;
    } else E{
      throw new Error("Invalid processor type");
    }
  }
 
  async removePreProcessor() {
    delete this.processors.pre;
  }
 
  async removePostProcessor() {
    delete this.processors.post;
  }
}