Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

perf(cli): fetch the toolkit catalog once per process

jkomyno4a764c100a72
diff --git a/ts/packages/cli/CHANGELOG.md b/ts/packages/cli/CHANGELOG.md
index c149f6888..b576e3617 100644
--- a/ts/packages/cli/CHANGELOG.md
+++ b/ts/packages/cli/CHANGELOG.md
@@ -37,6 +37,13 @@
to the `composio_search` toolkit, whose slug their names happen to start
with. A failed meta call used to suggest linking an app that had nothing to
do with the call.
+- Commands that consult the toolkit catalog more than once now fetch it once.
+ `composio tools execute` was downloading the full ~800 KB list up to four
+ times per run.
+- A cached API request that fails is no longer sent a second time. The caching
+ layer treated the request's own failure as a cache failure and retried it,
+ so every failed toolkit, tool, or trigger listing cost two round trips and
+ twice the wait before reporting the same error.
## 0.3.1
diff --git a/ts/packages/cli/src/services/composio-clients-cached.ts b/ts/packages/cli/src/services/composio-clients-cached.ts
index 4ebd33093..25bbc6b2f 100644
--- a/ts/packages/cli/src/services/composio-clients-cached.ts
+++ b/ts/packages/cli/src/services/composio-clients-cached.ts
@@ -55,69 +55,90 @@ function createCachedEffect<T, E, R>(
computation: Effect.Effect<T, E, R>,
cacheFilter?: (data: T) => Effect.Effect<T, E, never>
): Effect.Effect<T, E, R> {
- // First define the cache-handling function that will run with all required services
- const cacheEffect = Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const cacheDir = yield* setupCacheDir;
+ /**
+ * The cached value, or none when there is nothing usable to serve: caching
+ * is off, the file is absent, it does not parse, or it does not cover the
+ * request. Every one of those is a cache miss, never a failure — the caller
+ * falls through to the computation.
+ */
+ const readFromCache = (fs: FileSystem.FileSystem, cacheFilePath: string) =>
+ Effect.gen(function* () {
+ const consumeFromCache = yield* FORCE_CONFIG['USE_CACHE'];
+ if (!consumeFromCache) {
+ return Option.none<T>();
+ }
- const cacheFilePath = path.join(cacheDir, cacheFileName);
- const cacheFileExists = yield* fs
- .exists(cacheFilePath)
- .pipe(Effect.orElse(() => Effect.succeed(false)));
- const consumeFromCache = yield* FORCE_CONFIG['USE_CACHE'];
+ const cacheFileExists = yield* fs
+ .exists(cacheFilePath)
+ .pipe(Effect.orElse(() => Effect.succeed(false)));
+ if (!cacheFileExists) {
+ return Option.none<T>();
+ }
- if (consumeFromCache && cacheFileExists) {
yield* Effect.logDebug(`Cache HIT for ${cacheFileName}`);
- // Try to read from cache
- const cachedResult = yield* fs.readFileString(cacheFilePath).pipe(
- Effect.flatMap(decoder),
- Effect.asSome,
- Effect.catchAll(error => {
- // Log cache read/parse errors but don't fail - fall through to computation
- return Effect.logWarning(`Failed to read/parse cache ${cacheFilePath}: ${error}`).pipe(
- Effect.as(Option.none<T>())
- );
- })
- );
+ const cached = yield* fs.readFileString(cacheFilePath).pipe(Effect.flatMap(decoder));
+
+ // A filter that rejects the cached data means the cache does not answer
+ // this request — e.g. it predates a toolkit the caller asked for.
+ return Option.some(cacheFilter ? yield* cacheFilter(cached) : cached);
+ }).pipe(
+ Effect.catchAll(error =>
+ Effect.logWarning(`Ignoring cache ${cacheFilePath}: ${error}`).pipe(
+ Effect.as(Option.none<T>())
+ )
+ )
+ );
+
+ const writeToCache = (fs: FileSystem.FileSystem, cacheFilePath: string, result: T) =>
+ encoder(result).pipe(
+ Effect.flatMap(content => fs.writeFileString(cacheFilePath, content)),
+ Effect.catchAll(error =>
+ Effect.logWarning(`Failed to write to cache ${cacheFilePath}: ${error}`)
+ )
+ );
+
+ const cacheEffect = Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
- if (Option.isSome(cachedResult)) {
- return yield* cacheFilter
- ? cacheFilter(cachedResult.value)
- : Effect.succeed(cachedResult.value);
+ // A cache directory we cannot resolve or create means no caching, not a
+ // failed command.
+ const cacheFilePath = yield* setupCacheDir.pipe(
+ Effect.map(cacheDir => Option.some(path.join(cacheDir, cacheFileName))),
+ Effect.catchAll(error =>
+ Effect.logWarning(`Cache unavailable for ${cacheFileName}: ${error}`).pipe(
+ Effect.as(Option.none<string>())
+ )
+ )
+ );
+
+ if (Option.isSome(cacheFilePath)) {
+ const cached = yield* readFromCache(fs, cacheFilePath.value);
+ if (Option.isSome(cached)) {
+ return cached.value;
}
}
yield* Effect.logDebug(`Cache MISS for ${cacheFileName}`);
- // Fetch from the underlying service
+ // Fetch from the underlying service. Its failure is the caller's failure:
+ // retrying here would double every failed request, and the retry would
+ // fail the same way.
const result = yield* computation;
// Write to cache only if we're fetching the full dataset (no cacheFilter).
// Filtered API calls fetch partial data that would corrupt the shared cache file.
- if (!cacheFilter) {
- yield* encoder(result).pipe(
- Effect.flatMap(content => fs.writeFileString(cacheFilePath, content)),
- Effect.catchAll(error =>
- Effect.logWarning(`Failed to write to cache ${cacheFilePath}: ${error}`)
- )
- );
+ if (!cacheFilter && Option.isSome(cacheFilePath)) {
+ yield* writeToCache(fs, cacheFilePath.value, result);
}
return result;
});
- // Handle any cache errors by falling back to the original computation
- const handledCacheEffect = cacheEffect.pipe(
- Effect.catchAll(error =>
- Effect.logWarning(`Cache operation failed: ${error}`).pipe(Effect.flatMap(() => computation))
- )
- );
-
// This ensures the returned effect has the same error type as the original computation
// by providing all the required cache services
- return handledCacheEffect.pipe(
+ return cacheEffect.pipe(
Effect.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer, NodeOs.Default))
) as Effect.Effect<T, E, R>;
}
@@ -133,16 +154,30 @@ export const ComposioToolkitsRepositoryCached = Layer.effect(
Effect.gen(function* () {
const underlyingRepository = yield* ComposioToolkitsRepository;
+ // The full toolkit list is ~800 KB over two pages, and a single command can
+ // ask for it several times (toolkit resolution, validation, telemetry). The
+ // file cache only helps when `FORCE_USE_CACHE` is on, so memoize the whole
+ // lookup for the lifetime of the layer: the first caller pays, the rest
+ // await the same result.
+ //
+ // `Effect.cached` memoizes the outcome, not just the success — a failed
+ // first fetch stays failed for the rest of the process. That is the right
+ // trade for a one-shot CLI, where retrying a broken network per call would
+ // only multiply the wait before the same error surfaces.
+ const cachedGetToolkits = yield* Effect.cached(
+ createCachedEffect(
+ CACHE_FILES.toolkits,
+ toolkitsFromJSON,
+ toolkitsToJSON,
+ underlyingRepository.getToolkits()
+ )
+ );
+
// Create the cached implementation that wraps the original implementation
return ComposioToolkitsRepository.make({
- getToolkits: () => {
- return createCachedEffect(
- CACHE_FILES.toolkits,
- toolkitsFromJSON,
- toolkitsToJSON,
- underlyingRepository.getToolkits()
- );
- },
+ // Memoized per layer instance; `getToolkitsBySlugs` stays unmemoized
+ // because its result depends on the requested slugs.
+ getToolkits: () => cachedGetToolkits,
getToolkitsBySlugs: slugs => {
const cacheFilter = (data: Toolkits) => {
diff --git a/ts/packages/cli/test/__utils__/services/toolkits-repository-stub.ts b/ts/packages/cli/test/__utils__/services/toolkits-repository-stub.ts
new file mode 100644
index 000000000..7f89ddf20
--- /dev/null
+++ b/ts/packages/cli/test/__utils__/services/toolkits-repository-stub.ts
@@ -0,0 +1,71 @@
+import { Effect, Layer } from 'effect';
+import { ComposioToolkitsRepository } from 'src/services/composio-clients';
+import type { Toolkits } from 'src/models/toolkits';
+
+export type GetToolkitsError = Effect.Effect.Error<
+ ReturnType<ComposioToolkitsRepository['getToolkits']>
+>;
+
+const notUsed = (method: string) => () => Effect.die(`${method} is not used in this test`);
+
+/**
+ * Every repository method the toolkit-catalog suites do not exercise. A call
+ * to any of them is a defect in the test, not a scenario to handle.
+ */
+const unusedRepositoryMethods = {
+ getToolkitsBySlugs: notUsed('getToolkitsBySlugs'),
+ getMetrics: notUsed('getMetrics'),
+ getToolsAsEnums: notUsed('getToolsAsEnums'),
+ getTools: notUsed('getTools'),
+ getToolsByVersionSpecs: notUsed('getToolsByVersionSpecs'),
+ getTriggerTypesAsEnums: notUsed('getTriggerTypesAsEnums'),
+ getTriggerTypes: notUsed('getTriggerTypes'),
+ getTriggerTypeDetailed: notUsed('getTriggerTypeDetailed'),
+ validateToolkits: notUsed('validateToolkits'),
+ validateToolkitVersions: notUsed('validateToolkitVersions'),
+ // The repository's one synchronous method cannot return a dying Effect.
+ filterToolkitsBySlugs: (): never => {
+ throw new Error('filterToolkitsBySlugs is not used in this test');
+ },
+ searchToolkits: notUsed('searchToolkits'),
+ getToolkitDetailed: notUsed('getToolkitDetailed'),
+ searchTools: notUsed('searchTools'),
+ getToolDetailed: notUsed('getToolDetailed'),
+ listAuthConfigs: notUsed('listAuthConfigs'),
+ getAuthConfig: notUsed('getAuthConfig'),
+ createAuthConfig: notUsed('createAuthConfig'),
+ deleteAuthConfig: notUsed('deleteAuthConfig'),
+ listConnectedAccounts: notUsed('listConnectedAccounts'),
+ getConnectedAccount: notUsed('getConnectedAccount'),
+ deleteConnectedAccount: notUsed('deleteConnectedAccount'),
+ createConnectedAccountLink: notUsed('createConnectedAccountLink'),
+ listActiveTriggers: notUsed('listActiveTriggers'),
+ createTrigger: notUsed('createTrigger'),
+ enableTrigger: notUsed('enableTrigger'),
+ disableTrigger: notUsed('disableTrigger'),
+ deleteTrigger: notUsed('deleteTrigger'),
+} as const;
+
+/**
+ * A `ComposioToolkitsRepository` layer that counts catalog fetches, so a test
+ * can assert not just what was resolved but what it cost.
+ */
+export const countingToolkitsRepository = (
+ getToolkits: () => Effect.Effect<Toolkits, GetToolkitsError>
+) => {
+ let calls = 0;
+
+ const layer = Layer.succeed(
+ ComposioToolkitsRepository,
+ new ComposioToolkitsRepository({
+ ...unusedRepositoryMethods,
+ getToolkits: () =>
+ Effect.suspend(() => {
+ calls += 1;
+ return getToolkits();
+ }),
+ })
+ );
+
+ return { layer, calls: () => calls };
+};
diff --git a/ts/packages/cli/test/src/services/composio-clients-cached.test.ts b/ts/packages/cli/test/src/services/composio-clients-cached.test.ts
new file mode 100644
index 000000000..6bf99d00e
--- /dev/null
+++ b/ts/packages/cli/test/src/services/composio-clients-cached.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, it } from '@effect/vitest';
+import { ConfigProvider, DateTime, Effect, Layer } from 'effect';
+import * as tempy from 'tempy';
+import { ComposioToolkitsRepository, HttpServerError } from 'src/services/composio-clients';
+import { FileSystem } from '@effect/platform';
+import { BunFileSystem } from '@effect/platform-bun';
+import {
+ CACHE_FILES,
+ ComposioToolkitsRepositoryCached,
+} from 'src/services/composio-clients-cached';
+import { toolkitsToJSON, type Toolkits } from 'src/models/toolkits';
+import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
+import {
+ countingToolkitsRepository,
+ type GetToolkitsError,
+} from 'test/__utils__/services/toolkits-repository-stub';
+
+const testToolkits: Toolkits = [makeToolkitFixture('github'), makeToolkitFixture('gmail')];
+
+/**
+ * Cached repository over a counting stub, with the cache directory pointed at a
+ * fresh temp dir so nothing leaks between tests or into the developer's
+ * `~/.composio`. `FORCE_USE_CACHE` stays unset unless a test passes it in, i.e.
+ * the file cache is write-only — the default path this suite is about.
+ */
+const withCountingRepository = <A>(
+ getToolkits: () => Effect.Effect<Toolkits, GetToolkitsError>,
+ program: (context: {
+ readonly calls: () => number;
+ readonly cacheDir: string;
+ }) => Effect.Effect<A, GetToolkitsError, ComposioToolkitsRepository | FileSystem.FileSystem>,
+ config: ReadonlyArray<readonly [string, string]> = []
+) =>
+ Effect.suspend(() => {
+ const cacheDir = tempy.temporaryDirectory();
+ const repository = countingToolkitsRepository(getToolkits);
+
+ return program({ calls: repository.calls, cacheDir }).pipe(
+ Effect.provide(
+ Layer.merge(
+ Layer.provide(ComposioToolkitsRepositoryCached, repository.layer),
+ BunFileSystem.layer
+ )
+ ),
+ Effect.withConfigProvider(
+ ConfigProvider.fromMap(new Map([['CACHE_DIR', cacheDir], ...config]))
+ )
+ );
+ });
+
+describe('ComposioToolkitsRepositoryCached', () => {
+ it.effect('fetches the toolkit list once per layer, however many callers ask for it', () =>
+ withCountingRepository(
+ () => Effect.succeed(testToolkits),
+ ({ calls }) =>
+ Effect.gen(function* () {
+ const repository = yield* ComposioToolkitsRepository;
+
+ const results = yield* Effect.all([
+ repository.getToolkits(),
+ repository.getToolkits(),
+ repository.getToolkits(),
+ ]);
+
+ expect(results.map(toolkits => toolkits.map(t => t.slug))).toEqual([
+ ['github', 'gmail'],
+ ['github', 'gmail'],
+ ['github', 'gmail'],
+ ]);
+ expect(calls()).toBe(1);
+ })
+ )
+ );
+
+ // `it.live`: the stubbed fetch takes real time, so the callers genuinely overlap.
+ it.live('fetches once even when concurrent callers ask at the same time', () =>
+ withCountingRepository(
+ () => Effect.succeed(testToolkits).pipe(Effect.delay('10 millis')),
+ ({ calls }) =>
+ Effect.gen(function* () {
+ const repository = yield* ComposioToolkitsRepository;
+
+ yield* Effect.all(
+ [repository.getToolkits(), repository.getToolkits(), repository.getToolkits()],
+ { concurrency: 'unbounded' }
+ );
+
+ expect(calls()).toBe(1);
+ })
+ )
+ );
+
+ it.effect('surfaces a failed fetch once, and does not retry it', () =>
+ withCountingRepository(
+ () => Effect.fail(new HttpServerError({ cause: 'network down', status: 503 })),
+ ({ calls }) =>
+ Effect.gen(function* () {
+ const repository = yield* ComposioToolkitsRepository;
+
+ const first = yield* Effect.either(repository.getToolkits());
+ const second = yield* Effect.either(repository.getToolkits());
+
+ expect(second).toEqual(first);
+ // One attempt for both callers: the caching layer must not mistake
+ // the fetch's own failure for a cache failure worth retrying.
+ expect(calls()).toBe(1);
+ })
+ )
+ );
+
+ it.effect('serves the cached file when FORCE_USE_CACHE is on, without fetching', () =>
+ withCountingRepository(
+ () => Effect.die('the cached file should have answered this'),
+ ({ calls, cacheDir }) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ yield* fs
+ .writeFileString(
+ `${cacheDir}/${CACHE_FILES.toolkits}`,
+ yield* toolkitsToJSON(testToolkits).pipe(Effect.orDie)
+ )
+ .pipe(Effect.orDie);
+
+ const repository = yield* ComposioToolkitsRepository;
+ const toolkits = yield* repository.getToolkits();
+
+ expect(toolkits.map(t => t.slug)).toEqual(['github', 'gmail']);
+ expect(calls()).toBe(0);
+ }),
+ [['FORCE_USE_CACHE', 'true']]
+ )
+ );
+});