@devries-cameron20 / composio-1 / commits / dfb8f1dfb
Fork 0

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

refactor(cli): route API calls through the owned @composio/client (#4598)

This PR: - rebuilds `services/composio-clients.ts` on `@composio/client@2.0.0-rc.8`: one `request`/`requestAll` core replaces the streaming body reader, the hand-rolled paginator, and the error-envelope parser - moves the ten plain-`fetch` account/session/consumer helpers onto typed client resources; project-key creation is never retried - deletes the mirrored response schemas and the `ComposioClientLive` facade; response types now come from `@composio/client`, and `utils/api-error-extraction.ts` collapses onto an `APIError` adapter - shrinks `composio-clients-cached.ts` to spread the underlying repository and override only its cached methods - preserves explicitly configured custom HTTP base URLs without an additional opt-in; ambient client-specific `COMPOSIO_*` env vars no longer reach the client outside `APP_CONFIG` - routes command tests through the mock client via a new `accountData` input; `globalThis.fetch` interceptors for migrated endpoints are gone - `HttpServerError`/`HttpDecodingError` tags, stdout credential allowlists, and the four singleton header assertions are unchanged ## Validation Reconciled with `next`, preserving project-scoped toolkit lists and caching. Removed the unrelated root `PLAN.md`. Paginated toolkit, tool, and trigger requests now receive Effect's cancellation signal. Client tests use an isolated credential store instead of deleting a real macOS keychain entry. - `pnpm typecheck`: passed (16 tasks). - `pnpm lint`: passed with existing warnings. - `pnpm --filter @composio/cli test`: 133 files passed; 1,476 tests passed, one skipped; CLI skill and boundary checks passed. - Final focused client suites: 34 tests passed. All three pagination interruption regressions fail without the signal propagation fix. - `pnpm validate:agent-skills` and `pnpm validate:skill-routing`: passed. Internal client migration; no new command workflow or recording required.

Alberto Schiabel committed Sep 28, 2026 at 15:45 UTC dfb8f1dfbd991d821cf9250def70e911cb6c1cf8
51 files changed +2988 -2872
.agents/skills/cli-command/references/client-cache-sync.md
+6 -9
@@ -1,17 +1,14 @@
1 # Client Cache Sync
2
3 -When modifying `ts/packages/cli/src/services/composio-clients.ts`, inspect `ts/packages/cli/src/services/composio-clients-cached.ts` in the same change.
4 -
5 -The cached repository wraps `ComposioToolkitsRepository` and must expose the same interface.
3 +`ts/packages/cli/src/services/composio-clients-cached.ts` spreads the underlying `ComposioToolkitsRepository` from `ts/packages/cli/src/services/composio-clients.ts` and overrides only the methods it caches: `getToolkits`, `getToolkitsBySlugs`, `getToolsAsEnums`, `getTriggerTypesAsEnums`, `getTriggerTypes`, and `getTools`.
4
5 Checklist:
6
9 -- New method: add a cached or passthrough implementation.
10 -- Signature change: update both services.
11 -- Removed method: remove both entries.
12 -- New exported error type: export or map it consistently.
13 -- Validation methods are usually passthrough.
14 -- Fetch/list methods are usually cached.
7 +- New passthrough method: add it to the repository only; the spread exposes it.
8 +- New full-catalog fetch that should be cached: add a cached override.
9 +- Signature or result change on a cached method: update both services.
10 +- Removed cached method: remove its override.
11 +- Validation, search, single-item, and CRUD methods stay passthrough.
12
13 Verification:
14
.agents/skills/effect-v4/references/core-patterns.md
+1 -1
@@ -172,7 +172,7 @@ the expression is** — an Effect value or a function — and **what the tracer
172 return {
173 get: Effect.fn(function* () {
174 // ...
175 - }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementError, never>,
175 + }),
176 getFor: Effect.fn(function* (params: {
177 userApiKey?: string;
178 orgId?: string;
ts/e2e-tests/cli/toolkits/info/e2e.test.ts
-1
@@ -35,7 +35,6 @@ e2e(import.meta.url, {
35
36 const envPrefix = [
37 `COMPOSIO_BASE_URL=${server.dockerBaseUrl}`,
38 - 'COMPOSIO_ALLOW_INSECURE_HTTP=1',
38 'COMPOSIO_CACHE_DIR=/tmp/composio-toolkits-info',
39 'COMPOSIO_USER_API_KEY=uak_mock_toolkits_info',
40 ].join(' ');
ts/e2e-tests/cli/toolkits/list/e2e.test.ts
-1
@@ -28,7 +28,6 @@ e2e(import.meta.url, {
28
29 const envPrefix = [
30 `COMPOSIO_BASE_URL=${server.dockerBaseUrl}`,
31 - 'COMPOSIO_ALLOW_INSECURE_HTTP=1',
31 'COMPOSIO_CACHE_DIR=/tmp/composio-toolkits-list',
32 'COMPOSIO_USER_API_KEY=uak_mock_toolkits_list',
33 ].join(' ');
ts/e2e-tests/cli/toolkits/search/e2e.test.ts
-1
@@ -35,7 +35,6 @@ e2e(import.meta.url, {
35
36 const envPrefix = [
37 `COMPOSIO_BASE_URL=${server.dockerBaseUrl}`,
38 - 'COMPOSIO_ALLOW_INSECURE_HTTP=1',
38 'COMPOSIO_CACHE_DIR=/tmp/composio-toolkits-search',
39 'COMPOSIO_USER_API_KEY=uak_mock_toolkits_search',
40 ].join(' ');
ts/packages/cli/AGENTS.md
+15 -12
@@ -64,15 +64,18 @@ Named options use `Flag.String()`, `Flag.Boolean()`, `Flag.Int()`, `Flag.Literal
64
65 ### Services — `src/services/`
66
67 -| Service | Purpose |
68 -| ---------------------------------- | ---------------------------------------------------------------------------- |
69 -| `ComposioUserContext` | Auth state — reads/writes `~/.composio/user-config.json`, merges env vars |
70 -| `ComposioSessionRepository` | Creates OAuth2 sessions, polls until `linked` state |
71 -| `ComposioToolkitsRepository` | API client — fetches toolkits, tools, trigger types; validates versions |
72 -| `ComposioToolkitsRepositoryCached` | Decorator over base repository with file-based caching and graceful fallback |
73 -| `NodeOs` | OS abstraction (`homedir`, `platform`, `arch`) |
74 -| `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
75 -| `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
67 +| Service | Purpose |
68 +| ---------------------------------- | ---------------------------------------------------------------------------------------------- |
69 +| `ComposioUserContext` | Auth state — reads/writes `~/.composio/user-config.json`, merges env vars |
70 +| `ComposioClientSingleton` | Builds and caches `@composio/client` instances per key, org, and project; owns request metrics |
71 +| `ComposioSessionRepository` | Creates OAuth2 sessions, polls until `linked` state |
72 +| `ComposioToolkitsRepository` | API client — fetches toolkits, tools, trigger types; validates versions |
73 +| `ComposioToolkitsRepositoryCached` | Decorator over base repository with file-based caching and graceful fallback |
74 +| `NodeOs` | OS abstraction (`homedir`, `platform`, `arch`) |
75 +| `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
76 +| `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
77 +
78 +Every Composio API request goes through a `@composio/client` instance from `ComposioClientSingleton` (`src/services/composio-clients.ts`). Clients are built with `Composio.fromEnv({}, …)` so the ambient environment is never read, with `logLevel: 'off'`, the CLI's own `defaultHeaders` (`x-user-api-key`, plus `x-org-id`/`x-project-id` when both are known), and a counting `fetch` (`composio-client-metrics.ts`). Explicitly configured HTTP base URLs remain supported without an additional environment flag. Repository methods and the account helpers (`listOrganizations`, `getSessionInfo*`, `resolveConsumerProject`, …) run client calls through one module-private `request` helper that maps `APIError` to `services/HttpServerError` with `status`, `details`, and `requestId`. Endpoints the client does not type yet use `client.get`/`client.post`; inside `composio-clients.ts` those go through the same `request` helper, while `src/services/tool-permissions.ts` reaches them through its own `requestJson`, which raises `services/ToolPermissionsRequestError` because its callers fail closed on that tag. Do not add a raw `fetch` to the Composio backend from `src/commands`, `src/effects`, or `src/services` — the one sanctioned exception is the bundled companion runtime (`run-helpers-runtime.ts`), which runs in the user's spawned process outside the Effect runtime. Tool-execution and proxy errors are classified from `APIError.details` by `src/utils/api-error-extraction.ts`.
79
80 Services are `Context.Service` classes that export a `<Name>Shape` type and an explicit `static readonly Default` layer (`Layer.effect` / `Layer.sync`, dependencies provided with `Layer.provide`). Build a test double with `Service.of({ ... })`; there are no generated accessors or constructors.
81
@@ -108,7 +111,7 @@ Steps 3–4 (and the TypeScript compiler they need) ship as the `generation-runt
111
112 ### Key Dependencies
113
111 -`effect` (pinned `4.0.0-rc.115`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/unstable/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (Composio API), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/cli-local-tools` (local toolkit defs), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
114 +`effect` (pinned `4.0.0-rc.115`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/unstable/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (owned Composio API client, `2.0.0-rc.8` via the workspace catalog), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/cli-local-tools` (local toolkit defs), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
115
116 ## Output Conventions: Composable CLI Output
117
@@ -167,7 +170,7 @@ Each `Arr.bind` adds one independent axis to the generated cases.
170
171 - Never branch on an Effect value's internal tag field directly. Use the owning module's public refinement or matcher (`Option`, `Result`, `Exit`, `Cause`, `CliError`), `Match.valueTags` for exhaustive unions, or `Predicate.isTagged` for a single narrowing guard.
172 - Do not wrap a plain `Error` in `Effect.fail` for expected failures. Give the failure a meaningful `Data.TaggedError` type with structured fields and a preserved cause, then recover with `catchTag` / `catchTags`. Reserve `Effect.die` and `Effect.dieMessage` for impossible invariants.
170 -- Treat `unknown`, JSON, persisted state, and API payloads as trust boundaries. Decode them with `effect/Schema` or narrow them with `Predicate`; an `as` assertion is not validation, and hand-rolled structural guards (`'x' in obj` / `typeof` chains) are not a substitute for a schema. `effect/Schema` is the CLI's schema tool — do not introduce zod here (zod is the convention in the SDK packages and docs).
173 +- Treat `unknown`, JSON, and persisted state as trust boundaries. Decode them with `effect/Schema` or narrow them with `Predicate`; an `as` assertion is not validation, and hand-rolled structural guards (`'x' in obj` / `typeof` chains) are not a substitute for a schema. A Composio API response that `@composio/client` types is already a contract the CLI owns end to end, so trust it the way `@composio/core` does rather than re-decoding it. Keep `effect/Schema` for the payloads the client does not type for you: the persisted catalog cache files (`src/models/toolkits.ts`, `tools.ts`, `trigger-types.ts`), anything printed to stdout that must exclude credential-bearing fields (the auth-config and connected-account allowlists, including the `auth-configs create` response), the `ToolkitSlug` path-safety check, the `Session` `DateTime` transform, `TriggerInstanceItems`, and every escape-hatch response fetched with `client.get`/`client.post` (`LatestToolVersionResponse`, and the consumer config and permission payloads in `tool-permissions.ts`). `effect/Schema` is the CLI's schema tool — do not introduce zod here (zod is the convention in the SDK packages and docs).
174 - Do not inspect private `effect/unstable/cli` internals (parser state, `HelpDoc` string shapes, `CliError` suggestion machinery). `Command.runWith` renders help and parse/validation errors itself — see the entry-point section above — so command-tree introspection must stay on the public `Command.Any` surface (`name`, `alias`, `subcommands`). `CliError.InvalidValue` takes structured `{ option, value, expected, kind }` fields, not a free-form message — commands that need a custom validation message raise a local `Data.TaggedError` instead (see `src/commands/login.cmd.ts`'s `LoginOptionError`) and let it flow through the existing `effect-errors` pretty-printer, not a hand-built `CliError`.
175 - Prefer `Effect.mapError`, `Effect.matchEffect`, and typed recovery over `Effect.catch` blocks (the v4 name for what was `Effect.catchAll`) that flatten distinct failures into one message-only error.
176
@@ -221,7 +224,7 @@ Use these when adding new commands or making UX decisions.
224
225 ## Client Cache Sync
226
224 -When modifying `src/services/composio-clients.ts`, inspect `src/services/composio-clients-cached.ts` in the same change. The cached repository is a layer wrapper over `ComposioToolkitsRepository`; method additions, removals, signature changes, and new exported error types must stay in sync. Decide for each new method whether it should be cached or passed through. Validation-style methods are usually passthrough; fetch methods are usually cached.
227 +`src/services/composio-clients-cached.ts` spreads the underlying `ComposioToolkitsRepository` and overrides only the methods it caches (`getToolkits`, `getToolkitsBySlugs`, `getToolsAsEnums`, `getTriggerTypesAsEnums`, `getTriggerTypes`, `getTools`). Adding a passthrough method to the repository needs no edit there. Edit the cached file in the same change only when a cached method's signature or result changes, or when a new full-catalog fetch should be cached. Validation, search, single-item, and CRUD methods stay passthrough.
228
229 ## Recording CLI Demos
230
ts/packages/cli/CHANGELOG.md
+9
@@ -4,6 +4,15 @@
4
5 ### Patch Changes
6
7 +- Every Composio API call now goes through the `@composio/client` 2.0 runtime,
8 + the same client `@composio/core` uses. Org, project, session-info, and
9 + consumer lookups gain the client's retries and redirect handling, and API
10 + error messages now keep a server message even when it carries no suggested
11 + fix. Creating a project API key during `composio dev init` is never retried,
12 + so a timed-out request cannot mint a second key.
13 +- Ambient `COMPOSIO_CUSTOM_HEADERS` and `COMPOSIO_LOG_LEVEL` values no longer
14 + leak into CLI requests or output. Custom HTTP base URLs remain supported
15 + without an additional environment flag.
16 - `composio run` now validates binary download URLs returned by the proxy API
17 before fetching them. Private, loopback, link-local, and redirect-based SSRF
18 targets are blocked, DNS resolutions are pinned to prevent rebinding, and the
ts/packages/cli/src/commands/auth-configs/format.ts
+1 -1
@@ -1,5 +1,5 @@
1 import type { AuthConfigItem } from 'src/models/auth-configs';
2 -import type { AuthConfigCreateResponse } from 'src/services/composio-clients';
2 +import type { AuthConfigCreateResponse } from '@composio/client/resources/auth-configs';
3 import { bold, gray } from 'src/ui/colors';
4 import { redact } from 'src/ui/redact';
5 import { truncate } from 'src/ui/truncate';
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+2 -3
@@ -6,7 +6,7 @@ import { ComposioUserContext } from 'src/services/user-context';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { requireAuth } from 'src/effects/require-auth';
8 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
9 -import { extractMessage, extractSlug } from 'src/utils/api-error-extraction';
9 +import { extractApiErrorDetails, extractMessage } from 'src/utils/api-error-extraction';
10 import { ProjectContext } from 'src/services/project-context';
11 import { ComposioClientSingleton, getSessionInfoByUserApiKey } from 'src/services/composio-clients';
12 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
@@ -254,7 +254,6 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boo
254 let orgName = '~';
255 if (apiKey) {
256 const sessionInfo = yield* getSessionInfoByUserApiKey({
257 - baseURL: userContext.data.baseURL,
257 userApiKey: apiKey,
258 orgId: Option.getOrUndefined(userContext.data.orgId),
259 }).pipe(Effect.catch(() => Effect.succeed(null)));
@@ -921,7 +920,7 @@ const runConnectedAccountsLink = (params: {
920 Effect.asSome,
921 Effect.catch(error =>
922 Effect.gen(function* () {
924 - const slug = extractSlug(error);
923 + const slug = extractApiErrorDetails(error)?.slug;
924
925 if (slug === 'ToolRouterV2_NoManagedAuth') {
926 yield* handleNoManagedAuth(ui, toolkitSlug, params.noBrowser);
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts
+1 -6
@@ -1,6 +1,5 @@
1 import { Command, Flag } from 'effect/unstable/cli';
2 import { Data, Effect, Option } from 'effect';
3 -import type { ConnectedAccountListParams } from '@composio/client/resources/connected-accounts';
3 import { ComposioClientSingleton } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
@@ -83,11 +82,7 @@ export const connectedAccountsCmd$List = Command.make(
82 client.connectedAccounts.list({
83 toolkit_slugs: toolkitSlugs,
84 user_ids: Option.isSome(userId) ? [userId.value] : undefined,
86 - // Bypass the stale Stainless union (still missing 'REVOKED')
87 - // until @composio/client is regenerated.
88 - statuses: Option.isSome(status)
89 - ? ([status.value] as ConnectedAccountListParams['statuses'])
90 - : undefined,
85 + statuses: Option.isSome(status) ? [status.value] : undefined,
86 limit: clampLimit(limit),
87 }),
88 catch: cause =>
ts/packages/cli/src/commands/init.cmd.ts
+16 -12
@@ -10,6 +10,8 @@ import {
10 createProjectApiKey,
11 getSessionInfo,
12 listOrgProjects,
13 + sessionProjectApiKeyOf,
14 + sessionUserIdOf,
15 type OrgProject,
16 } from 'src/services/composio-clients';
17 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
@@ -105,7 +107,6 @@ const ensureProjectApiKeyInEnv = (params: { cwd: string; selected: ProjectKeys }
107 const ui = yield* TerminalUI;
108 const fs = yield* FileSystem.FileSystem;
109 const path = yield* Path.Path;
108 - const ctx = yield* ComposioUserContext;
110
111 const envPath = path.join(cwd, '.env.local');
112 const envExists = yield* fs.exists(envPath);
@@ -120,18 +121,16 @@ const ensureProjectApiKeyInEnv = (params: { cwd: string; selected: ProjectKeys }
121 }
122
123 const sessionInfo = yield* getSessionInfo({
123 - baseURL: ctx.data.baseURL,
124 apiKey: uakApiKey,
125 orgId: selected.orgId,
126 projectId: selected.projectId,
127 });
128 yield* linkApolloIdentityForAnalytics(sessionInfo.org_member.id, uakApiKey);
129
130 - let projectApiKey = sessionInfo.api_key?.api_key ?? sessionInfo.api_key?.key ?? null;
130 + let projectApiKey = sessionProjectApiKeyOf(sessionInfo);
131 if (!projectApiKey && !hasProjectApiKey) {
132 const dateSuffix = new Date().toISOString().slice(0, 10);
133 projectApiKey = yield* createProjectApiKey({
134 - baseURL: ctx.data.baseURL,
134 apiKey: uakApiKey,
135 orgId: selected.orgId,
136 projectId: selected.projectId,
@@ -139,7 +138,7 @@ const ensureProjectApiKeyInEnv = (params: { cwd: string; selected: ProjectKeys }
138 });
139 }
140
142 - const sessionUserId = sessionInfo.org_member.user_id ?? sessionInfo.org_member.id;
141 + const sessionUserId = sessionUserIdOf(sessionInfo);
142 const composioTestUserId = `pg-test-${sessionUserId}`;
143 const composioDir = path.join(cwd, constants.PROJECT_COMPOSIO_DIR);
144
@@ -169,7 +168,7 @@ const ensureProjectApiKeyInEnv = (params: { cwd: string; selected: ProjectKeys }
168
169 const logEnvCreationHttpError =
170 (ui: TerminalUI) =>
172 - (e: { status?: number; details?: { message: string; suggestedFix: string }; cause?: unknown }) =>
171 + (e: { status?: number; details?: { message: string; suggestedFix?: string }; cause?: unknown }) =>
172 Effect.gen(function* () {
173 yield* ui.log.warn('Could not create .env.local from session info.');
174 if (e.status) {
@@ -177,7 +176,9 @@ const logEnvCreationHttpError =
176 }
177 if (e.details) {
178 yield* ui.log.error(e.details.message);
180 - yield* ui.log.step(e.details.suggestedFix);
179 + if (e.details.suggestedFix !== undefined) {
180 + yield* ui.log.step(e.details.suggestedFix);
181 + }
182 } else if (e.cause) {
183 yield* ui.log.error(String(e.cause));
184 }
@@ -271,7 +272,6 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
272 }
273
274 const orgProjects = yield* listOrgProjects({
274 - baseURL: ctx.data.baseURL,
275 apiKey: globalApiKey,
276 orgId: orgIdValue,
277 }).pipe(
@@ -286,9 +286,11 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
286 return yield* Effect.fail(e);
287 })
288 ),
289 - Effect.catchTag('services/HttpDecodingError', e =>
289 + // Every other failure to reach the API gets the same guidance; only the
290 + // wording differs by how far the request got.
291 + Effect.catch(e =>
292 Effect.gen(function* () {
291 - yield* Effect.logDebug('Failed to decode org projects response:', e);
293 + yield* Effect.logDebug('Failed to fetch org projects:', e);
294 yield* ui.log.warn('Unexpected response from the server.');
295 yield* ui.log.info(
296 'Create a project at https://platform.composio.dev, then run `composio dev init` again.'
@@ -342,9 +344,11 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
344 yield* logEnvCreationHttpError(ui)(e);
345 })
346 ),
345 - Effect.catchTag('services/HttpDecodingError', e =>
347 + // The project is already written; a key the CLI could not resolve is a
348 + // warning with manual instructions, never a failed init.
349 + Effect.catch(e =>
350 Effect.gen(function* () {
347 - yield* Effect.logDebug('Failed to decode API key response:', e);
351 + yield* Effect.logDebug('Failed to resolve the project API key:', e);
352 yield* logEnvCreationDecodingError(ui)(e);
353 })
354 )
ts/packages/cli/src/commands/login.cmd.ts
+12 -34
@@ -8,6 +8,7 @@ import {
8 getSessionInfo,
9 getSessionInfoByUserApiKey,
10 listOrganizations,
11 + sessionUserIdOf,
12 type OrganizationSummary,
13 type SessionInfoResponse,
14 } from 'src/services/composio-clients';
@@ -328,14 +329,13 @@ const completeAgentLogin = (identity: AgentIdentity) =>
329
330 const resolveDirectLoginOrganization = (params: {
331 apiKey: string;
331 - baseURL: string;
332 requestedOrg?: string;
333 fallbackOrgId: string;
334 fallbackOrgName?: string;
335 }) =>
336 Effect.gen(function* () {
337 const ui = yield* TerminalUI;
338 - const { apiKey, baseURL, requestedOrg, fallbackOrgId, fallbackOrgName } = params;
338 + const { apiKey, requestedOrg, fallbackOrgId, fallbackOrgName } = params;
339
340 if (!requestedOrg) {
341 return {
@@ -344,10 +344,7 @@ const resolveDirectLoginOrganization = (params: {
344 };
345 }
346
347 - const organizations = yield* listOrganizations({
348 - baseURL,
349 - apiKey,
350 - });
347 + const organizations = yield* listOrganizations({ apiKey });
348 const match = organizations.data.find(
349 org => org.id === requestedOrg || org.name === requestedOrg
350 );
@@ -367,19 +364,17 @@ const directLogin = (params: { userApiKey: string; org?: string }) =>
364 Effect.gen(function* () {
365 const ctx = yield* ComposioUserContext;
366 const sessionInfo = yield* getSessionInfoByUserApiKey({
370 - baseURL: ctx.data.baseURL,
367 userApiKey: params.userApiKey,
368 });
369
370 const selectedOrg = yield* resolveDirectLoginOrganization({
371 apiKey: params.userApiKey,
376 - baseURL: ctx.data.baseURL,
372 requestedOrg: params.org,
373 fallbackOrgId: sessionInfo.project.org.id,
374 fallbackOrgName: sessionInfo.project.org.name,
375 });
376
382 - const sessionUserId = sessionInfo.org_member.user_id ?? sessionInfo.org_member.id;
377 + const sessionUserId = sessionUserIdOf(sessionInfo);
378 const testUserId = sessionUserId
379 ? `pg-test-${sessionUserId}`
380 : Option.getOrUndefined(ctx.data.testUserId);
@@ -387,7 +382,6 @@ const directLogin = (params: { userApiKey: string; org?: string }) =>
382 yield* ctx.login(params.userApiKey, selectedOrg.id, testUserId);
383 yield* linkAnalyticsIdentityForOrg({
384 apiKey: params.userApiKey,
390 - baseURL: ctx.data.baseURL,
385 orgId: selectedOrg.id,
386 knownIdentity: {
387 orgId: sessionInfo.project.org.id,
@@ -412,7 +406,6 @@ const directLogin = (params: { userApiKey: string; org?: string }) =>
406 * data and avoids hand-rolled structural types.
407 */
408 const storeCredentials = (params: {
415 - baseURL: string;
409 uakApiKey: string;
410 initialOrgId: string;
411 initialProjectId: string;
@@ -428,7 +421,6 @@ const storeCredentials = (params: {
421 const ctx = yield* ComposioUserContext;
422
423 const {
431 - baseURL,
424 uakApiKey,
425 initialOrgId,
426 initialProjectId,
@@ -441,20 +433,16 @@ const storeCredentials = (params: {
433 // Call session/info to enrich the login with org/project metadata.
434 // All errors are non-fatal (browser login) since the linked session is already authenticated.
435 const sessionInfo: SessionInfoResponse | undefined = yield* getSessionInfo({
444 - baseURL,
436 apiKey: uakApiKey,
437 orgId: initialOrgId,
438 projectId: initialProjectId,
439 }).pipe(
449 - Effect.catchTag('services/HttpServerError', e =>
450 - Effect.gen(function* () {
451 - yield* Effect.logDebug(`Session info fetch failed (HTTP ${e.status ?? '?'}):`, e);
452 - return undefined;
453 - })
454 - ),
455 - Effect.catchTag('services/HttpDecodingError', e =>
440 + // Catch-all rather than per-tag: the linked session is already
441 + // authenticated, so no way this enrichment can fail may stop the
442 + // credential from being stored.
443 + Effect.catch(e =>
444 Effect.gen(function* () {
457 - yield* Effect.logDebug('Session info decoding error:', e);
445 + yield* Effect.logDebug('Session info fetch failed:', e);
446 return undefined;
447 })
448 )
@@ -464,7 +452,7 @@ const storeCredentials = (params: {
452 // The initial IDs come from the linked session response (which may use session-level
453 // identifiers rather than the actual org/project IDs).
454 const orgId = sessionInfo?.project.org.id ?? initialOrgId;
467 - const sessionUserId = sessionInfo?.org_member.user_id ?? sessionInfo?.org_member.id;
455 + const sessionUserId = sessionInfo ? sessionUserIdOf(sessionInfo) : undefined;
456 const testUserId = sessionUserId
457 ? `pg-test-${sessionUserId}`
458 : Option.getOrUndefined(ctx.data.testUserId);
@@ -480,7 +468,6 @@ const storeCredentials = (params: {
468 if (!deferAnalyticsIdentity) {
469 yield* linkAnalyticsIdentityForOrg({
470 apiKey: uakApiKey,
483 - baseURL,
471 orgId,
472 knownIdentity: sessionInfo
473 ? {
@@ -583,13 +570,11 @@ const loginWithKey = (params: {
570 const uakApiKey = linkedSession.api_key;
571
572 const uakSessionInfo = yield* getSessionInfoByUserApiKey({
586 - baseURL: ctx.data.baseURL,
573 userApiKey: uakApiKey,
574 });
575
576 const organizations = params.defaultToFirstOrg
577 ? yield* listOrganizations({
592 - baseURL: ctx.data.baseURL,
578 apiKey: uakApiKey,
579 }).pipe(
580 Effect.map(response => response.data),
@@ -608,7 +593,6 @@ const loginWithKey = (params: {
593
594 const willRunPicker = !params.skipOrgProjectPicker;
595 yield* storeCredentials({
611 - baseURL: ctx.data.baseURL,
596 uakApiKey,
597 initialOrgId: xOrgId,
598 initialProjectId: xProjectId,
@@ -621,7 +605,6 @@ const loginWithKey = (params: {
605 if (willRunPicker) {
606 const result = yield* runOrgSelection({
607 apiKey: uakApiKey,
624 - baseURL: ctx.data.baseURL,
608 }).pipe(
609 Effect.catch(error =>
610 Effect.gen(function* () {
@@ -632,7 +615,7 @@ const loginWithKey = (params: {
615 )
616 );
617 if (result) {
635 - const sessionUserId = uakSessionInfo.org_member.user_id ?? uakSessionInfo.org_member.id;
618 + const sessionUserId = sessionUserIdOf(uakSessionInfo);
619 const testUserId = sessionUserId ? `pg-test-${sessionUserId}` : undefined;
620 yield* ctx.login(
621 uakApiKey,
@@ -647,7 +630,6 @@ const loginWithKey = (params: {
630 const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';
631 yield* linkAnalyticsIdentityForOrg({
632 apiKey: uakApiKey,
650 - baseURL: ctx.data.baseURL,
633 orgId: finalOrgId,
634 knownIdentity: {
635 orgId: uakSessionInfo.project.org.id,
@@ -802,7 +784,6 @@ export const browserLogin = (params: {
784 const uakApiKey = linkedSession.api_key;
785
786 const uakSessionInfo = yield* getSessionInfoByUserApiKey({
805 - baseURL: ctx.data.baseURL,
787 userApiKey: uakApiKey,
788 });
789
@@ -815,7 +796,6 @@ export const browserLogin = (params: {
796
797 const willRunPicker = params.scope === 'user' && !params.skipOrgProjectPicker;
798 yield* storeCredentials({
818 - baseURL: ctx.data.baseURL,
799 uakApiKey,
800 initialOrgId: xOrgId,
801 initialProjectId: xProjectId,
@@ -828,7 +808,6 @@ export const browserLogin = (params: {
808 if (willRunPicker) {
809 const result = yield* runOrgSelection({
810 apiKey: uakApiKey,
831 - baseURL: ctx.data.baseURL,
811 }).pipe(
812 Effect.catch(error =>
813 Effect.gen(function* () {
@@ -839,7 +818,7 @@ export const browserLogin = (params: {
818 )
819 );
820 if (result) {
842 - const sessionUserId = uakSessionInfo.org_member.user_id ?? uakSessionInfo.org_member.id;
821 + const sessionUserId = sessionUserIdOf(uakSessionInfo);
822 const testUserId = sessionUserId ? `pg-test-${sessionUserId}` : undefined;
823 yield* ctx.login(
824 uakApiKey,
@@ -854,7 +833,6 @@ export const browserLogin = (params: {
833 const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';
834 yield* linkAnalyticsIdentityForOrg({
835 apiKey: uakApiKey,
857 - baseURL: ctx.data.baseURL,
836 orgId: finalOrgId,
837 knownIdentity: {
838 orgId: uakSessionInfo.project.org.id,
ts/packages/cli/src/commands/orgs/commands/orgs.list.cmd.ts
-1
@@ -31,7 +31,6 @@ export const orgsCmd$List = Command.make('list', { limit }, ({ limit }) =>
31 const organizations = yield* ui.withSpinner(
32 'Loading organizations...',
33 listOrganizations({
34 - baseURL: ctx.data.baseURL,
34 apiKey,
35 limit: clampedLimit,
36 }),
ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts
-2
@@ -38,7 +38,6 @@ export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId,
38
39 const result = yield* runOrgSelection({
40 apiKey,
41 - baseURL: ctx.data.baseURL,
41 explicitOrgId: Option.getOrUndefined(orgId),
42 currentOrgId: Option.getOrUndefined(ctx.data.orgId),
43 limit,
@@ -52,7 +51,6 @@ export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId,
51 yield* ctx.login(apiKey, result.id, Option.getOrUndefined(ctx.data.testUserId));
52 yield* linkAnalyticsIdentityForOrg({
53 apiKey,
55 - baseURL: ctx.data.baseURL,
54 orgId: result.id,
55 });
56
ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts
-1
@@ -40,7 +40,6 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,
40 const projects = yield* ui.withSpinner(
41 'Loading projects...',
42 listOrganizationProjects({
43 - baseURL: ctx.data.baseURL,
43 apiKey,
44 orgId: resolvedOrgId,
45 limit: clampedLimit,
ts/packages/cli/src/commands/tools/format.ts
+3 -3
@@ -1,5 +1,5 @@
1 import type { Tool } from 'src/models/tools';
2 -import type { ToolDetailedResponse } from 'src/services/composio-clients';
2 +import type { ToolRetrieveResponse } from '@composio/client/resources/tools';
3 import { bold, gray } from 'src/ui/colors';
4 import { truncate } from 'src/ui/truncate';
5 import { extractSchemaProperties } from 'src/ui/extract-schema-properties';
@@ -94,7 +94,7 @@ function formatSchemaPropertiesDetailed(schema: Record<string, unknown>): string
94 /**
95 * Format a detailed tool for interactive display.
96 */
97 -export function formatToolInfo(tool: ToolDetailedResponse): string {
97 +export function formatToolInfo(tool: ToolRetrieveResponse): string {
98 const lines: string[] = [];
99
100 lines.push(`${bold('Name:')} ${tool.name}`);
@@ -130,7 +130,7 @@ export function formatToolInfo(tool: ToolDetailedResponse): string {
130 /**
131 * Format only tool input parameters for execute-help flows.
132 */
133 -export function formatToolInputParameters(tool: ToolDetailedResponse): string {
133 +export function formatToolInputParameters(tool: ToolRetrieveResponse): string {
134 const lines: string[] = [];
135 lines.push(`${bold('Name:')} ${tool.name}`);
136 lines.push(`${bold('Slug:')} ${tool.slug}`);
ts/packages/cli/src/commands/whoami.cmd.ts
-1
@@ -30,7 +30,6 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
30 onSome: apiKey =>
31 Effect.gen(function* () {
32 const sessionInfo = yield* getSessionInfoByUserApiKey({
33 - baseURL: ctx.data.baseURL,
33 userApiKey: apiKey,
34 // Reflect the org selected via `composio orgs switch`, not the key's home org.
35 orgId: Option.getOrUndefined(ctx.data.orgId),
ts/packages/cli/src/effects/handle-http-error.ts
+3 -1
@@ -63,7 +63,9 @@ export const handleHttpServerError =
63
64 if (e.details) {
65 yield* ui.log.error(e.details.message);
66 - yield* ui.log.step(e.details.suggestedFix);
66 + if (e.details.suggestedFix !== undefined) {
67 + yield* ui.log.step(e.details.suggestedFix);
68 + }
69 } else {
70 yield* ui.log.error(opts.fallbackMessage);
71 }
ts/packages/cli/src/effects/link-analytics-identity.ts
-2
@@ -12,7 +12,6 @@ type KnownOrgIdentity = {
12
13 export const linkAnalyticsIdentityForOrg = (params: {
14 readonly apiKey: string;
15 - readonly baseURL: string;
15 readonly orgId: string;
16 readonly knownIdentity?: KnownOrgIdentity;
17 }) =>
@@ -25,7 +24,6 @@ export const linkAnalyticsIdentityForOrg = (params: {
24 const orgMemberId = knownIdentity
25 ? knownIdentity.orgMemberId
26 : yield* getSessionInfoByUserApiKey({
28 - baseURL: params.baseURL,
27 userApiKey: params.apiKey,
28 orgId: params.orgId,
29 }).pipe(
ts/packages/cli/src/effects/select-org-project.ts
+1 -3
@@ -38,14 +38,13 @@ const selectOrganization = (params: {
38
39 export const runOrgSelection = (params: {
40 apiKey: string;
41 - baseURL: string;
41 explicitOrgId?: string;
42 currentOrgId?: string;
43 limit?: number;
44 }) =>
45 Effect.gen(function* () {
46 const ui = yield* TerminalUI;
48 - const { apiKey, baseURL, explicitOrgId, currentOrgId, limit = DEFAULT_LIMIT } = params;
47 + const { apiKey, explicitOrgId, currentOrgId, limit = DEFAULT_LIMIT } = params;
48 const clampedLimit = clampLimit(limit);
49
50 const selectedOrganization =
@@ -53,7 +52,6 @@ export const runOrgSelection = (params: {
52 ? ({ id: explicitOrgId, name: explicitOrgId } satisfies OrganizationSummary)
53 : yield* Effect.gen(function* () {
54 const organizations = yield* listOrganizations({
56 - baseURL,
55 apiKey,
56 limit: clampedLimit,
57 });
ts/packages/cli/src/effects/validate-toolkit-versions.ts
+9
@@ -214,6 +214,15 @@ export const validateToolkitVersionOverrides = ({
214 reason: 'client-unavailable',
215 })
216 )
217 + ),
218 + Effect.catchTag('services/ComposioClientConfigurationError', error =>
219 + Effect.fail(
220 + new ToolkitVersionValidationError({
221 + cause: error,
222 + message: error.message,
223 + reason: 'client-unavailable',
224 + })
225 + )
226 )
227 );
228
ts/packages/cli/src/services/agents.ts
+1 -1
@@ -460,7 +460,7 @@ export const loginWithAgentIdentity = (identity: AgentIdentity) =>
460
461 yield* ctx.login(userApiKey, orgId);
462 // Best-effort analytics stitch after the credential persists; must never break login.
463 - yield* getSessionInfoByUserApiKey({ baseURL: ctx.data.baseURL, userApiKey, orgId }).pipe(
463 + yield* getSessionInfoByUserApiKey({ userApiKey, orgId }).pipe(
464 Effect.flatMap(info => linkApolloIdentityForAnalytics(info.org_member.id, userApiKey)),
465 Effect.catchCause(() => Effect.void)
466 );
ts/packages/cli/src/services/command-project.ts
-3
@@ -50,7 +50,6 @@ export const resolveCommandProject = (params: { mode: ProjectMode; projectName?:
50 if (params.mode === 'consumer') {
51 if (params.projectName) {
52 const developerProject = yield* findDeveloperProjectByName({
53 - baseURL: ctx.data.baseURL,
53 apiKey,
54 orgId: currentOrgId,
55 name: params.projectName,
@@ -66,7 +65,6 @@ export const resolveCommandProject = (params: { mode: ProjectMode; projectName?:
65 }
66
67 const consumerProject = yield* resolveConsumerProject({
69 - baseURL: ctx.data.baseURL,
68 apiKey,
69 orgId: currentOrgId,
70 });
@@ -83,7 +81,6 @@ export const resolveCommandProject = (params: { mode: ProjectMode; projectName?:
81
82 if (params.projectName) {
83 const developerProject = yield* findDeveloperProjectByName({
86 - baseURL: ctx.data.baseURL,
84 apiKey,
85 orgId: currentOrgId,
86 name: params.projectName,
ts/packages/cli/src/services/composio-client-metrics.ts new
+80
@@ -0,0 +1,80 @@
1 +import { Effect } from 'effect';
2 +
3 +/**
4 + * Request and byte totals for every Composio API call a client made.
5 + */
6 +export interface ClientMetrics {
7 + readonly byteSize: number;
8 + readonly requests: number;
9 +}
10 +
11 +export interface ClientMetricsCollector {
12 + /**
13 + * A `fetch` to hand to the Composio client. It resolves `globalThis.fetch`
14 + * on every call, so a spy installed after the client was built still
15 + * intercepts the request.
16 + */
17 + readonly fetch: typeof globalThis.fetch;
18 + readonly getMetrics: () => Effect.Effect<ClientMetrics>;
19 +}
20 +
21 +// Statuses whose response carries no body by definition. `new Response(body,
22 +// init)` rejects a body for them, and there is nothing to count anyway.
23 +const BODYLESS_STATUSES: ReadonlySet<number> = new Set([101, 204, 205, 304]);
24 +
25 +const isRedirect = (response: Response): boolean => response.status >= 300 && response.status < 400;
26 +
27 +/**
28 + * Builds a counting `fetch` wrapper plus a reader for its totals.
29 + *
30 + * The byte count comes from `Content-Length` when the server sends it, and
31 + * otherwise from a pass-through `TransformStream` over the body, so the body
32 + * is never buffered a second time.
33 + */
34 +export const makeClientMetricsCollector = (): ClientMetricsCollector => {
35 + let requests = 0;
36 + let byteSize = 0;
37 +
38 + const countResponse = (response: Response): Response => {
39 + const contentLength = response.headers.get('content-length');
40 + if (contentLength !== null) {
41 + const parsed = Number.parseInt(contentLength, 10);
42 + if (parsed >= 0) {
43 + byteSize += parsed;
44 + return response;
45 + }
46 + }
47 +
48 + // A redirect is handed back untouched: the client inspects `type` and
49 + // `url` on it to decide whether following the hop is safe, and a rewrapped
50 + // response reports neither. Its body is discarded before the next hop, so
51 + // nothing is lost by not counting it.
52 + if (response.body === null || BODYLESS_STATUSES.has(response.status) || isRedirect(response)) {
53 + return response;
54 + }
55 +
56 + const counting = new TransformStream<Uint8Array, Uint8Array>({
57 + transform(chunk, controller) {
58 + byteSize += chunk.byteLength;
59 + controller.enqueue(chunk);
60 + },
61 + });
62 +
63 + return new Response(response.body.pipeThrough(counting), response);
64 + };
65 +
66 + const fetch: typeof globalThis.fetch = Object.assign(
67 + (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
68 + requests += 1;
69 + return globalThis.fetch(input, init).then(countResponse);
70 + },
71 + // Bun's `fetch` carries a `preconnect` helper; forward it so the wrapper
72 + // satisfies the same type.
73 + { preconnect: (url: string | URL) => globalThis.fetch.preconnect(url) }
74 + );
75 +
76 + return {
77 + fetch,
78 + getMetrics: () => Effect.sync(() => ({ byteSize, requests })),
79 + };
80 +};
ts/packages/cli/src/services/composio-clients-cached.ts
+12 -54
@@ -10,7 +10,6 @@ import {
10 InvalidToolkitsError,
11 type ToolkitProjectScope,
12 } from './composio-clients';
13 -import type { ToolkitVersionSpec } from 'src/effects/toolkit-version-overrides';
13 import { NodeOs } from './node-os';
14 import { toolkitsFromJSON, toolkitsToJSON, type Toolkits } from 'src/models/toolkits';
15 import {
@@ -155,10 +154,18 @@ function createCachedEffect<T, E, R>(
154 }
155
156 /**
158 - * Cached implementation of ComposioToolkitsRepository using the wrapper layer pattern
157 + * Cached implementation of ComposioToolkitsRepository using the wrapper layer pattern.
158 *
160 - * This layer adds file-based caching to the repository methods while preserving the
161 - * exact same interface and error types.
159 + * Only full-catalog fetches are cached: `getToolkits`, `getToolkitsBySlugs`,
160 + * `getToolsAsEnums`, `getTriggerTypesAsEnums`, `getTriggerTypes`, and
161 + * `getTools`. Every other method passes through to the underlying repository,
162 + * so adding a method there needs no edit here. In particular these stay
163 + * uncached on purpose:
164 + * - version-specific tool fetches, which would need per-version cache keys and
165 + * must not pollute the `latest` cache;
166 + * - version validation, because `available_versions` changes as versions ship;
167 + * - searches and single-item details, which depend on the query or must be fresh;
168 + * - auth config, connected account, and trigger instance CRUD.
169 */
170 export const ComposioToolkitsRepositoryCached = Layer.effect(
171 ComposioToolkitsRepository,
@@ -211,6 +218,7 @@ export const ComposioToolkitsRepositoryCached = Layer.effect(
218
219 // Create the cached implementation that wraps the original implementation
220 return ComposioToolkitsRepository.of({
221 + ...underlyingRepository,
222 // Memoized per layer instance; `getToolkitsBySlugs` stays unmemoized
223 // because its result depends on the requested slugs.
224 getToolkits: () => cachedGetToolkits,
@@ -264,9 +272,6 @@ export const ComposioToolkitsRepositoryCached = Layer.effect(
272 );
273 },
274
267 - // Trigger type detail should NOT be cached (single-item fetch, should be fresh)
268 - getTriggerTypeDetailed: slug => underlyingRepository.getTriggerTypeDetailed(slug),
269 -
275 getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) => {
276 const cacheFilter =
277 toolkitSlugs && toolkitSlugs.length > 0
@@ -294,53 +299,6 @@ export const ComposioToolkitsRepositoryCached = Layer.effect(
299 cacheFilter
300 );
301 },
297 -
298 - // Version-specific tools bypass cache because:
299 - // 1. Different versions = different cache keys needed
300 - // 2. Version-specific data shouldn't pollute the main cache
301 - // The cache is mainly useful for 'latest' during repeated dev iterations.
302 - getToolsByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) => {
303 - return underlyingRepository.getToolsByVersionSpecs(specs);
304 - },
305 -
306 - // These methods don't need caching as they operate on already fetched data
307 - // or perform validation that should always be fresh
308 - getMetrics: () => underlyingRepository.getMetrics(),
309 - validateToolkits: toolkitSlugs => underlyingRepository.validateToolkits(toolkitSlugs),
310 - filterToolkitsBySlugs: (toolkits, toolkitSlugs) =>
311 - underlyingRepository.filterToolkitsBySlugs(toolkits, toolkitSlugs),
312 - // Version validation should NOT be cached because:
313 - // 1. available_versions can change frequently as new versions are released
314 - // 2. Validation should always reflect the current API state
315 - // 3. Caching validation results could cause false positives/negatives
316 - validateToolkitVersions: (overrides, relevantToolkits) =>
317 - underlyingRepository.validateToolkitVersions(overrides, relevantToolkits),
318 - // These methods should NOT be cached:
319 - // - searchToolkits: results depend on query params, caching would be misleading
320 - // - getToolkitDetailed: detailed info should be fresh (auth config fields change)
321 - searchToolkits: params => underlyingRepository.searchToolkits(params),
322 - getToolkitDetailed: slug => underlyingRepository.getToolkitDetailed(slug),
323 - // Tool search/detail should NOT be cached (query-dependent, should be fresh)
324 - searchTools: params => underlyingRepository.searchTools(params),
325 - getToolDetailed: slug => underlyingRepository.getToolDetailed(slug),
326 - // Auth config operations should NOT be cached (CRUD operations, must be fresh)
327 - listAuthConfigs: params => underlyingRepository.listAuthConfigs(params),
328 - getAuthConfig: nanoid => underlyingRepository.getAuthConfig(nanoid),
329 - createAuthConfig: params => underlyingRepository.createAuthConfig(params),
330 - deleteAuthConfig: nanoid => underlyingRepository.deleteAuthConfig(nanoid),
331 - // Connected account operations should NOT be cached (CRUD operations, must be fresh)
332 - listConnectedAccounts: params => underlyingRepository.listConnectedAccounts(params),
333 - getConnectedAccount: nanoid => underlyingRepository.getConnectedAccount(nanoid),
334 - deleteConnectedAccount: nanoid => underlyingRepository.deleteConnectedAccount(nanoid),
335 - createConnectedAccountLink: params => underlyingRepository.createConnectedAccountLink(params),
336 - // Trigger instance listing should NOT be cached (status can change frequently)
337 - listActiveTriggers: params => underlyingRepository.listActiveTriggers(params),
338 - // Trigger instance mutations should NOT be cached
339 - createTrigger: (triggerSlug, params) =>
340 - underlyingRepository.createTrigger(triggerSlug, params),
341 - enableTrigger: triggerId => underlyingRepository.enableTrigger(triggerId),
342 - disableTrigger: triggerId => underlyingRepository.disableTrigger(triggerId),
343 - deleteTrigger: triggerId => underlyingRepository.deleteTrigger(triggerId),
302 });
303 })
304 ).pipe(
ts/packages/cli/src/services/composio-clients.ts
+832 -1798
@@ -1,47 +1,45 @@
1 import {
2 - pipe,
2 Context,
3 Data,
4 Effect,
5 Layer,
6 Option,
7 + Predicate,
8 Schema,
9 Array,
10 Order,
11 String,
12 - Stream,
13 - SynchronizedRef,
12 } from 'effect';
13 import * as FileSystem from 'effect/FileSystem';
14 import * as Path from 'effect/Path';
15 import type { Cause } from 'effect';
18 -import { Composio as _RawComposioClient, APIPromise } from '@composio/client';
16 +import { Composio as _RawComposioClient, APIError, type RequestOptions } from '@composio/client';
17 +import { paginate, type CursorPage } from '@composio/client/pagination';
18 import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
19 import type { ConnectedAccountListParams } from '@composio/client/resources/connected-accounts';
21 -import {
22 - Toolkit,
23 - Toolkits,
24 - ToolkitDetailed,
25 - ToolkitSlug,
26 - type ToolkitSearchResult,
27 -} from 'src/models/toolkits';
20 +import type { OrgListResponse, ProjectListResponse } from '@composio/client/resources/org';
21 +import type {
22 + ConsumerListConnectedToolkitsResponse,
23 + ProjectResolveResponse,
24 +} from '@composio/client/resources/org/consumer';
25 +import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
26 +import { Toolkit, Toolkits, ToolkitDetailed, type ToolkitSearchResult } from 'src/models/toolkits';
27 import { AuthConfigItem, AuthConfigItems } from 'src/models/auth-configs';
28 import { ConnectedAccountItem, ConnectedAccountItems } from 'src/models/connected-accounts';
29 import { TriggerInstanceItems } from 'src/models/triggers';
31 -import { ToolsAsEnums, Tools, Tool } from 'src/models/tools';
30 +import { ToolsAsEnums, Tools } from 'src/models/tools';
31 import {
32 groupByVersion,
33 type ToolkitVersionSpec,
34 type ToolkitVersionOverrides,
35 } from 'src/effects/toolkit-version-overrides';
37 -import { JsonRecordSchema } from 'src/effects/json';
36 import { Session, RetrievedSession } from 'src/models/session';
37 import { TriggerType, TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigger-types';
38 import * as constants from 'src/constants';
39 import { getCurrentCwdSessionId } from 'src/analytics/dispatch';
40 import { ComposioUserContext, ComposioUserContextLive } from './user-context';
41 import { ProjectContext } from './project-context';
44 -import { renderPrettyError } from './utils/pretty-error';
42 +import { makeClientMetricsCollector } from './composio-client-metrics';
43 import { NodeOs } from './node-os';
44
45 type NoSuchElementError = Cause.NoSuchElementError;
@@ -51,21 +49,36 @@ type NoSuchElementError = Cause.NoSuchElementError;
49 */
50
51 /**
54 - * Structured error details from the Composio API.
52 + * Structured error details from the Composio API error envelope.
53 */
54 export interface HttpErrorDetails {
55 readonly message: string;
58 - readonly suggestedFix: string;
56 + readonly suggestedFix?: string;
57 readonly code: number;
58 }
59
60 /**
61 * Error thrown when a HTTP request fails.
62 + *
63 + * `status`, `details`, and `requestId` are populated from the client's
64 + * `APIError` when the failure is an API response; a connection failure or an
65 + * unexpected rejection carries only `cause`.
66 */
67 export class HttpServerError extends Data.TaggedError('services/HttpServerError')<{
68 readonly cause?: unknown;
69 readonly status?: number;
70 readonly details?: HttpErrorDetails;
71 + readonly requestId?: string;
72 +}> {}
73 +
74 +/**
75 + * Error thrown when a client cannot be constructed from the current configuration.
76 + */
77 +export class ComposioClientConfigurationError extends Data.TaggedError(
78 + 'services/ComposioClientConfigurationError'
79 +)<{
80 + readonly message: string;
81 + readonly cause: unknown;
82 }> {}
83
84 /**
@@ -103,6 +116,85 @@ export class HttpDecodingError extends Data.TaggedError('services/HttpDecodingEr
116
117 export type HttpError = HttpServerError | HttpDecodingError;
118
119 +/**
120 + * Every failure a client call can produce: the request itself, decoding a
121 + * CLI-owned contract, or obtaining a client from the singleton.
122 + */
123 +export type ClientError = HttpError | ComposioClientConfigurationError | NoSuchElementError;
124 +
125 +/**
126 + * Request helpers
127 + */
128 +
129 +// Maximum items per page allowed by the server
130 +const MAX_PAGE_SIZE = 1000;
131 +
132 +// Maximum concurrent requests per each endpoint
133 +const MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 4;
134 +
135 +const toHttpServerError = (cause: unknown): HttpServerError => {
136 + if (cause instanceof APIError) {
137 + const details = cause.details;
138 + return new HttpServerError({
139 + cause,
140 + status: cause.status,
141 + requestId: cause.requestId,
142 + details: details
143 + ? { message: details.message, code: details.code, suggestedFix: details.suggested_fix }
144 + : undefined,
145 + });
146 + }
147 + return new HttpServerError({ cause });
148 +};
149 +
150 +/**
151 + * Runs one client call. The client parses JSON and rejects on non-2xx, so the
152 + * only work left is mapping its rejection onto `HttpServerError`.
153 + */
154 +const request = <A, E>(
155 + client: Effect.Effect<_RawComposioClient, E>,
156 + call: (client: _RawComposioClient, signal: AbortSignal) => PromiseLike<A>
157 +): Effect.Effect<A, E | HttpServerError> =>
158 + client.pipe(
159 + Effect.flatMap(resolved =>
160 + Effect.tryPromise({ try: signal => call(resolved, signal), catch: toHttpServerError })
161 + )
162 + );
163 +
164 +/**
165 + * Runs a paginated client call to exhaustion and returns every item, asking
166 + * for `MAX_PAGE_SIZE` items per page.
167 + */
168 +const requestAll = <Page extends CursorPage<unknown>, E>(
169 + client: Effect.Effect<_RawComposioClient, E>,
170 + fetchPage: (
171 + client: _RawComposioClient,
172 + page: { readonly cursor: string | undefined; readonly limit: number },
173 + signal: AbortSignal
174 + ) => PromiseLike<Page>
175 +) =>
176 + request(client, (resolved, signal) =>
177 + paginate<Page>(({ cursor }) =>
178 + fetchPage(resolved, { cursor, limit: MAX_PAGE_SIZE }, signal)
179 + ).toArray()
180 + );
181 +
182 +/**
183 + * Decodes a payload against a CLI-owned contract.
184 + */
185 +const decode =
186 + <S extends Schema.Top>(schema: S) =>
187 + (input: unknown): Effect.Effect<S['Type'], HttpDecodingError, S['DecodingServices']> =>
188 + Schema.decodeUnknownEffect(schema)(input).pipe(
189 + Effect.catchTag(
190 + 'SchemaError',
191 + e =>
192 + new HttpDecodingError({
193 + cause: `SchemaError\n ${e.message}`,
194 + })
195 + )
196 + );
197 +
198 // Sort items by slug.
199 // TODO: make sure this happens on the server-side.
200 const sortBySlug = <T extends { readonly slug: string }>(
@@ -113,12 +205,27 @@ const sortBySlug = <T extends { readonly slug: string }>(
205 Order.mapInput(Order.String, (item: T) => item.slug)
206 );
207
208 +/**
209 + * Converts a 404 from a toolkit lookup into `InvalidToolkitsError` naming
210 + * that slug; every other failure propagates unchanged.
211 + */
212 +const invalidToolkitOn404 = <A>(slug: string, toolkit: Effect.Effect<A, ClientError>) =>
213 + Effect.catchTag(
214 + toolkit,
215 + 'services/HttpServerError',
216 + (e): Effect.Effect<never, InvalidToolkitsError | HttpServerError> =>
217 + e.status === 404
218 + ? Effect.fail(
219 + new InvalidToolkitsError({
220 + invalidToolkits: [slug],
221 + availableToolkits: [],
222 + })
223 + )
224 + : Effect.fail(e)
225 + );
226 +
227 const validateToolkitVersionsImpl = (
117 - client: {
118 - toolkits: {
119 - retrieve: (slug: string) => Effect.Effect<Toolkit, HttpError | NoSuchElementError, never>;
120 - };
121 - },
228 + retrieveToolkit: (slug: string) => Effect.Effect<Toolkit, ClientError, never>,
229 overrides: ToolkitVersionOverrides,
230 relevantToolkits?: ReadonlyArray<string>
231 ): Effect.Effect<
@@ -126,7 +233,7 @@ const validateToolkitVersionsImpl = (
233 validatedOverrides: ToolkitVersionOverrides;
234 warnings: ReadonlyArray<string>;
235 },
129 - InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementError
236 + InvalidToolkitVersionsError | InvalidToolkitsError | ClientError
237 > =>
238 Effect.gen(function* () {
239 const determineOverridesToValidate = (
@@ -167,28 +274,19 @@ const validateToolkitVersionsImpl = (
274 availableVersions: ReadonlyArray<string>;
275 isValid: boolean;
276 }>,
170 - InvalidToolkitsError | HttpError | NoSuchElementError
277 + InvalidToolkitsError | ClientError
278 > =>
279 Effect.all(
280 overridesToValidate.map(([toolkit, requestedVersion]) =>
174 - client.toolkits.retrieve(toolkit).pipe(
175 - Effect.map(toolkitData => ({
176 - toolkit,
177 - requestedVersion,
178 - availableVersions: toolkitData.meta.available_versions,
179 - isValid: toolkitData.meta.available_versions.includes(requestedVersion),
180 - })),
181 - Effect.catchTag(
182 - 'services/HttpServerError',
183 - (e): Effect.Effect<never, InvalidToolkitsError | HttpServerError> =>
184 - e.status === 404
185 - ? Effect.fail(
186 - new InvalidToolkitsError({
187 - invalidToolkits: [toolkit],
188 - availableToolkits: [],
189 - })
190 - )
191 - : Effect.fail(e)
281 + invalidToolkitOn404(
282 + toolkit,
283 + retrieveToolkit(toolkit).pipe(
284 + Effect.map(toolkitData => ({
285 + toolkit,
286 + requestedVersion,
287 + availableVersions: toolkitData.meta.available_versions,
288 + isValid: toolkitData.meta.available_versions.includes(requestedVersion),
289 + }))
290 )
291 )
292 ),
@@ -239,273 +337,13 @@ const validateToolkitVersionsImpl = (
337 });
338
339 /**
242 - * Response schemas
243 - */
244 -
245 -export const CliCreateSessionResponse = Session;
246 -export type CliCreateSessionResponse = Schema.Schema.Type<typeof CliCreateSessionResponse>;
247 -
248 -export const CliGetSessionResponse = RetrievedSession;
249 -export type CliRetrieveSessionResponse = Schema.Schema.Type<typeof CliGetSessionResponse>;
250 -
251 -export const CliRealtimeCredentialsResponse = Schema.Struct({
252 - project_id: Schema.String,
253 - pusher_key: Schema.String,
254 - pusher_cluster: Schema.String,
255 -}).annotate({ identifier: 'CliRealtimeCredentialsResponse' });
256 -export type CliRealtimeCredentialsResponse = Schema.Schema.Type<
257 - typeof CliRealtimeCredentialsResponse
258 ->;
259 -
260 -export const CliRealtimeAuthResponse = Schema.Struct({
261 - auth: Schema.String,
262 - channel_data: Schema.optional(Schema.String),
263 -}).annotate({ identifier: 'CliRealtimeAuthResponse' });
264 -export type CliRealtimeAuthResponse = Schema.Schema.Type<typeof CliRealtimeAuthResponse>;
265 -
266 -export const ToolkitsResponse = Schema.Struct({
267 - items: Toolkits,
268 - total_pages: Schema.Int,
269 - next_cursor: Schema.NullOr(Schema.String),
270 -}).annotate({ identifier: 'ToolkitsResponse' });
271 -export type ToolkitsResponse = Schema.Schema.Type<typeof ToolkitsResponse>;
272 -
273 -// Similar to Toolkits, without auth_schemes, with auth_config_details instead
274 -export const ToolkitRetrieveResponse = Schema.Struct({
275 - name: Schema.String,
276 - slug: ToolkitSlug,
277 - is_local_toolkit: Schema.Boolean,
278 - composio_managed_auth_schemes: Schema.Array(Schema.String).pipe(
279 - Schema.withDecodingDefaultType(Effect.succeed([]))
280 - ),
281 - no_auth: Schema.Boolean.pipe(Schema.withDecodingDefaultType(Effect.succeed(false))),
282 - meta: Schema.Struct({
283 - description: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
284 - categories: Schema.Array(Schema.Unknown).pipe(
285 - Schema.withDecodingDefaultType(Effect.succeed([]))
286 - ),
287 - created_at: Schema.DateTimeUtcFromString,
288 - updated_at: Schema.DateTimeUtcFromString,
289 - available_versions: Schema.Array(Schema.String).pipe(
290 - Schema.withDecodingDefaultType(Effect.succeed([]))
291 - ),
292 - tools_count: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
293 - triggers_count: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
294 - }),
295 -}).annotate({ identifier: 'ToolkitRetrieveResponse' });
296 -export type ToolkitRetrieveResponse = Schema.Schema.Type<typeof ToolkitRetrieveResponse>;
297 -
298 -export const ToolsAsEnumsResponse = ToolsAsEnums;
299 -export type ToolsAsEnumsResponse = Schema.Schema.Type<typeof ToolsAsEnumsResponse>;
300 -
301 -export const ToolsResponse = Schema.Struct({
302 - items: Tools,
303 - total_pages: Schema.Int,
304 - next_cursor: Schema.NullOr(Schema.String),
305 -}).annotate({ identifier: 'ToolsResponse' });
306 -export type ToolsResponse = Schema.Schema.Type<typeof ToolsResponse>;
307 -
308 -export const ToolDetailedResponse = Schema.Struct({
309 - name: Schema.String,
310 - slug: Schema.String,
311 - description: Schema.String,
312 - tags: Schema.Array(Schema.String),
313 - available_versions: Schema.Array(Schema.String),
314 - input_parameters: JsonRecordSchema,
315 - output_parameters: JsonRecordSchema,
316 - no_auth: Schema.Boolean.pipe(Schema.withDecodingDefaultType(Effect.succeed(false))),
317 - toolkit: Schema.Struct({
318 - name: Schema.String,
319 - slug: Schema.String,
320 - }).pipe(Schema.withDecodingDefaultType(Effect.succeed({ name: '', slug: '' }))),
321 -}).annotate({ identifier: 'ToolDetailedResponse' });
322 -export type ToolDetailedResponse = Schema.Schema.Type<typeof ToolDetailedResponse>;
323 -
324 -export const TriggerTypesAsEnumsResponse = TriggerTypesAsEnums;
325 -export type TriggerTypesAsEnumsResponse = Schema.Schema.Type<typeof TriggerTypesAsEnumsResponse>;
326 -
327 -export const TriggerTypesResponse = Schema.Struct({
328 - items: TriggerTypes,
329 - total_pages: Schema.Int,
330 - next_cursor: Schema.NullOr(Schema.String),
331 -}).annotate({ identifier: 'TriggerTypesResponse' });
332 -export type TriggerTypesResponse = Schema.Schema.Type<typeof TriggerTypesResponse>;
333 -
334 -export const TriggerInstancesListActiveResponse = Schema.Struct({
335 - items: TriggerInstanceItems,
336 - total_items: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
337 - total_pages: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(1))),
338 - current_page: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(1))),
339 - next_cursor: Schema.NullOr(Schema.String).pipe(
340 - Schema.withDecodingDefaultType(Effect.succeed(null))
341 - ),
342 -}).annotate({ identifier: 'TriggerInstancesListActiveResponse' });
343 -export type TriggerInstancesListActiveResponse = Schema.Schema.Type<
344 - typeof TriggerInstancesListActiveResponse
345 ->;
346 -
347 -export const TriggerInstanceUpsertResponse = Schema.Struct({
348 - trigger_id: Schema.String,
349 -}).annotate({ identifier: 'TriggerInstanceUpsertResponse' });
350 -export type TriggerInstanceUpsertResponse = Schema.Schema.Type<
351 - typeof TriggerInstanceUpsertResponse
352 ->;
353 -
354 -export const TriggerInstanceManageUpdateResponse = Schema.Struct({
355 - status: Schema.Literal('success'),
356 -}).annotate({ identifier: 'TriggerInstanceManageUpdateResponse' });
357 -export type TriggerInstanceManageUpdateResponse = Schema.Schema.Type<
358 - typeof TriggerInstanceManageUpdateResponse
359 ->;
360 -
361 -export const TriggerInstanceManageDeleteResponse = Schema.Struct({
362 - trigger_id: Schema.String,
363 -}).annotate({ identifier: 'TriggerInstanceManageDeleteResponse' });
364 -export type TriggerInstanceManageDeleteResponse = Schema.Schema.Type<
365 - typeof TriggerInstanceManageDeleteResponse
366 ->;
367 -
368 -/**
369 - * Response from GET /api/v3/auth/session/info.
370 - * Contains project, org member, and API key details for the authenticated session.
371 - * Fields like webhook_url, webhook_secret, auto_id, deleted are intentionally omitted.
340 + * CLI-owned response contracts
341 + *
342 + * Response types otherwise come from `@composio/client`. A schema stays here
343 + * only where the CLI owns the contract: output allowlists that keep
344 + * credential-bearing fields off stdout, and the single escape-hatch endpoint
345 + * the client does not type.
346 */
373 -export const SessionInfoResponse = Schema.Struct({
374 - project: Schema.Struct({
375 - name: Schema.String,
376 - id: Schema.String,
377 - org_id: Schema.String,
378 - nano_id: Schema.String,
379 - email: Schema.String,
380 - created_at: Schema.String,
381 - updated_at: Schema.String,
382 - org: Schema.Struct({
383 - name: Schema.String,
384 - id: Schema.String,
385 - plan: Schema.String,
386 - }),
387 - }),
388 - org_member: Schema.Struct({
389 - id: Schema.String,
390 - user_id: Schema.optional(Schema.String),
391 - email: Schema.String,
392 - name: Schema.String,
393 - role: Schema.String,
394 - }),
395 - api_key: Schema.NullOr(
396 - Schema.Struct({
397 - name: Schema.String,
398 - project_id: Schema.String,
399 - id: Schema.String,
400 - org_member_id: Schema.String,
401 - api_key: Schema.optional(Schema.String),
402 - key: Schema.optional(Schema.String),
403 - })
404 - ),
405 -}).annotate({ identifier: 'SessionInfoResponse' });
406 -export type SessionInfoResponse = Schema.Schema.Type<typeof SessionInfoResponse>;
407 -
408 -const authHeaderForApiKey = (apiKey: string): Record<string, string> => ({
409 - 'x-user-api-key': apiKey,
410 -});
411 -
412 -export interface TriggerInstancesListActiveParams {
413 - user_ids?: string[];
414 - connected_account_ids?: string[];
415 - auth_config_ids?: string[];
416 - trigger_ids?: string[];
417 - trigger_names?: string[];
418 - show_disabled?: boolean;
419 - limit?: number;
420 -}
421 -
422 -export interface TriggerInstanceUpsertParams {
423 - connected_account_id?: string;
424 - trigger_config?: Record<string, unknown>;
425 -}
426 -
427 -function buildTriggerInstancesNamespace(
428 - clientSingleton: ComposioClientSingletonShape,
429 - withMetrics: <A, E, R>(
430 - effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
431 - ) => Effect.Effect<A, E, R>
432 -) {
433 - return {
434 - /**
435 - * Lists active trigger instances with optional filters.
436 - * Returns a single page of results.
437 - */
438 - listActive: (params: TriggerInstancesListActiveParams) =>
439 - withMetrics(
440 - callClient(
441 - clientSingleton,
442 - client =>
443 - client.triggerInstances.listActive({
444 - user_ids: params.user_ids,
445 - connected_account_ids: params.connected_account_ids,
446 - auth_config_ids: params.auth_config_ids,
447 - trigger_ids: params.trigger_ids,
448 - trigger_names: params.trigger_names,
449 - show_disabled: params.show_disabled,
450 - limit: params.limit,
451 - }),
452 - TriggerInstancesListActiveResponse
453 - )
454 - ),
455 - upsert: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
456 - withMetrics(
457 - callClient(
458 - clientSingleton,
459 - client => client.triggerInstances.upsert(triggerSlug, params),
460 - TriggerInstanceUpsertResponse
461 - )
462 - ),
463 - manageUpdate: (triggerId: string, params: { status: 'enable' | 'disable' }) =>
464 - withMetrics(
465 - callClient(
466 - clientSingleton,
467 - client => client.triggerInstances.manage.update(triggerId, params),
468 - TriggerInstanceManageUpdateResponse
469 - )
470 - ),
471 - manageDelete: (triggerId: string) =>
472 - withMetrics(
473 - callClient(
474 - clientSingleton,
475 - client => client.triggerInstances.manage.delete(triggerId),
476 - TriggerInstanceManageDeleteResponse
477 - )
478 - ),
479 - };
480 -}
481 -
482 -function buildTriggerInstanceRepositoryOperations(client: ComposioClientLiveShape) {
483 - return {
484 - listActiveTriggers: (params: TriggerInstancesListActiveParams) =>
485 - client.triggerInstances.listActive(params),
486 - createTrigger: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
487 - client.triggerInstances.upsert(triggerSlug, params),
488 - enableTrigger: (triggerId: string) =>
489 - client.triggerInstances.manageUpdate(triggerId, { status: 'enable' }),
490 - disableTrigger: (triggerId: string) =>
491 - client.triggerInstances.manageUpdate(triggerId, { status: 'disable' }),
492 - deleteTrigger: (triggerId: string) => client.triggerInstances.manageDelete(triggerId),
493 - };
494 -}
495 -
496 -// Single-page search response (includes total_items for "Listing X of Y" display)
497 -export const ToolkitSearchResponse = Schema.Struct({
498 - items: Toolkits,
499 - total_items: Schema.Int,
500 - total_pages: Schema.Int,
501 - current_page: Schema.Int,
502 - next_cursor: Schema.NullOr(Schema.String),
503 -}).annotate({ identifier: 'ToolkitSearchResponse' });
504 -
505 -// Detailed retrieve response (includes auth_config_details)
506 -export const ToolkitDetailedResponse = ToolkitDetailed.annotate({
507 - identifier: 'ToolkitDetailedResponse',
508 -});
347
348 // Auth config list response (single page with total_items for "Listing X of Y" display)
349 export const AuthConfigListResponse = Schema.Struct({
@@ -519,25 +357,6 @@ export const AuthConfigListResponse = Schema.Struct({
357 }).annotate({ identifier: 'AuthConfigListResponse' });
358 export type AuthConfigListResponse = Schema.Schema.Type<typeof AuthConfigListResponse>;
359
522 -// Auth config retrieve response (same shape as a single list item)
523 -export const AuthConfigRetrieveResponse = AuthConfigItem.annotate({
524 - identifier: 'AuthConfigRetrieveResponse',
525 -});
526 -export type AuthConfigRetrieveResponse = Schema.Schema.Type<typeof AuthConfigRetrieveResponse>;
527 -
528 -// Auth config create response
529 -export const AuthConfigCreateResponse = Schema.Struct({
530 - auth_config: Schema.Struct({
531 - id: Schema.String,
532 - auth_scheme: Schema.String,
533 - is_composio_managed: Schema.Boolean,
534 - }),
535 - toolkit: Schema.Struct({
536 - slug: Schema.String,
537 - }),
538 -}).annotate({ identifier: 'AuthConfigCreateResponse' });
539 -export type AuthConfigCreateResponse = Schema.Schema.Type<typeof AuthConfigCreateResponse>;
540 -
360 // Connected account list response (single page with total_items for "Listing X of Y" display)
361 export const ConnectedAccountListResponse = Schema.Struct({
362 items: ConnectedAccountItems,
@@ -550,196 +369,83 @@ export const ConnectedAccountListResponse = Schema.Struct({
369 }).annotate({ identifier: 'ConnectedAccountListResponse' });
370 export type ConnectedAccountListResponse = Schema.Schema.Type<typeof ConnectedAccountListResponse>;
371
553 -// Connected account retrieve response (same shape as a single list item)
554 -export const ConnectedAccountRetrieveResponse = ConnectedAccountItem.annotate({
555 - identifier: 'ConnectedAccountRetrieveResponse',
556 -});
557 -
558 -// Link create response
559 -export const LinkCreateResponse = Schema.Struct({
560 - connected_account_id: Schema.String,
561 - expires_at: Schema.String,
562 - link_token: Schema.String,
563 - redirect_url: Schema.String,
564 -}).annotate({ identifier: 'LinkCreateResponse' });
565 -export type LinkCreateResponse = Schema.Schema.Type<typeof LinkCreateResponse>;
566 -export type ConnectedAccountRetrieveResponse = Schema.Schema.Type<
567 - typeof ConnectedAccountRetrieveResponse
568 ->;
569 -
570 -/**
571 - * Error response schemas
572 - */
573 -export const HttpErrorResponse = Schema.Struct({
574 - status: Schema.Int,
575 - error: Schema.Struct({
576 - error: Schema.Struct({
577 - message: Schema.NonEmptyString,
578 - suggested_fix: Schema.String,
579 - code: Schema.Int,
580 - }),
372 +// `auth-configs create` prints this response to stdout, so it stays an
373 +// allowlist rather than the client's full type: a field the API adds later
374 +// must not reach a pipe without a decision here.
375 +export const AuthConfigCreateResponse = Schema.Struct({
376 + auth_config: Schema.Struct({
377 + id: Schema.String,
378 + auth_scheme: Schema.String,
379 + is_composio_managed: Schema.Boolean,
380 + }),
381 + toolkit: Schema.Struct({
382 + slug: Schema.String,
383 }),
582 -}).annotate({ identifier: 'HttpErrorResponse' });
583 -export type HttpErrorResponse = Schema.Schema.Type<typeof HttpErrorResponse>;
384 +}).annotate({ identifier: 'AuthConfigCreateResponse' });
385 +export type AuthConfigCreateResponse = Schema.Schema.Type<typeof AuthConfigCreateResponse>;
386 +
387 +export const LatestToolVersionResponse = Schema.Struct({
388 + tool_slug: Schema.String,
389 + version: Schema.String,
390 +}).annotate({ identifier: 'LatestToolVersionResponse' });
391 +export type LatestToolVersionResponse = Schema.Schema.Type<typeof LatestToolVersionResponse>;
392
393 /**
586 - * Result of streaming a response with byte counting.
394 + * Session info as the CLI consumes it: the client's response with `project`
395 + * present. The endpoint answers `project: null` for org-level credentials,
396 + * which every caller here treats as an unusable session.
397 */
588 -interface StreamedResponse {
589 - /** The parsed JSON data from the response body */
590 - readonly json: unknown;
591 - /** The exact byte size of the response body */
592 - readonly byteSize: number;
593 -}
594 -
595 -type Metrics = {
596 - readonly byteSize: number;
597 - readonly requests: number;
398 +export type SessionInfoResponse = SessionRetrieveInfoResponse & {
399 + readonly project: NonNullable<SessionRetrieveInfoResponse['project']>;
400 };
401
402 +const requireSessionProject = (
403 + info: SessionRetrieveInfoResponse
404 +): Effect.Effect<SessionInfoResponse, HttpDecodingError> =>
405 + info.project === null
406 + ? Effect.fail(
407 + new HttpDecodingError({
408 + cause: 'Session info response has no project (org-level credentials)',
409 + })
410 + )
411 + : Effect.succeed({ ...info, project: info.project });
412 +
413 /**
601 - * Handles HTTP error responses by reading the body and formatting a proper error message.
602 - * Attempts to decode the response as HttpErrorResponse for structured errors,
603 - * otherwise falls back to a generic error with status code.
604 - *
605 - * @param response - The Fetch API Response object with a non-OK status
606 - * @returns An Effect that always fails with HttpServerError containing formatted error details
414 + * The org member's user id, falling back to the member id. The backend still
415 + * sends `org_member.user_id` although the v3.1 spec omits it, and the persisted
416 + * test user id derives from it, so it is read defensively.
417 */
608 -const handleHttpErrorResponse = (response: Response): Effect.Effect<never, HttpServerError> =>
609 - Effect.gen(function* () {
610 - const status = response.status;
611 - const statusText = response.statusText;
612 -
613 - // Try to read the error body as JSON
614 - const errorBodyOpt = yield* Effect.tryPromise({
615 - try: () => response.json() as Promise<unknown>,
616 - catch: () => new HttpServerError({ cause: 'Failed to parse error response body' }),
617 - }).pipe(Effect.option);
618 -
619 - // Try to decode as structured error response
620 - if (Option.isSome(errorBodyOpt)) {
621 - const decodedOpt = Schema.decodeUnknownOption(HttpErrorResponse)(errorBodyOpt.value);
622 -
623 - if (Option.isSome(decodedOpt)) {
624 - const {
625 - error: { error },
626 - } = decodedOpt.value;
627 - const pretty = renderPrettyError([
628 - ['code', error.code],
629 - ['message', error.message],
630 - ['suggested fix', error.suggested_fix],
631 - ]);
632 -
633 - return yield* Effect.fail(
634 - new HttpServerError({
635 - cause: `HTTP ${status}\n${pretty}`,
636 - status,
637 - details: {
638 - message: error.message,
639 - suggestedFix: error.suggested_fix,
640 - code: error.code,
641 - },
642 - })
643 - );
644 - }
645 - }
646 -
647 - // Fallback to generic error message
648 - return yield* Effect.fail(
649 - new HttpServerError({
650 - cause: `HTTP ${status} ${statusText}`,
651 - status,
652 - })
653 - );
654 - });
418 +export const sessionUserIdOf = (info: SessionInfoResponse): string => {
419 + const member: object = info.org_member;
420 + return Predicate.hasProperty(member, 'user_id') && Predicate.isString(member.user_id)
421 + ? member.user_id
422 + : info.org_member.id;
423 +};
424
425 /**
657 - * Streams a Fetch Response body, counting bytes precisely and parsing JSON in a single pass.
658 - * Uses streaming to avoid loading the entire response into memory at once.
659 - *
660 - * @param response - The Fetch API Response object
661 - * @returns An Effect that yields the parsed JSON data and byte count
426 + * The project API key carried by a session, or null. The v3.1 spec names the
427 + * field `key`, and older responses spell it `api_key`; reading both keeps
428 + * `composio dev init` from minting a second key when the backend sends the
429 + * older spelling.
430 */
663 -const streamResponseWithByteCount = (
664 - response: Response
665 -): Effect.Effect<StreamedResponse, HttpServerError> =>
666 - Effect.gen(function* () {
667 - const body = response.body;
668 - if (!body) {
669 - return yield* Effect.fail(
670 - new HttpServerError({
671 - cause: 'Response body is null',
672 - })
673 - );
674 - }
675 -
676 - // Convert the ReadableStream to an Effect Stream
677 - const byteStream = Stream.fromReadableStream({
678 - evaluate: () => body,
679 - onError: (error: unknown) =>
680 - new HttpServerError({
681 - cause: error,
682 - }),
683 - });
684 -
685 - // Collect all chunks while counting bytes (mutate array in-place for O(N) instead of O(N^2))
686 - const [chunks, byteSize] = yield* pipe(
687 - byteStream,
688 - Stream.runFold(
689 - (): [Uint8Array[], number] => [[], 0],
690 - ([chunks, size], chunk) => {
691 - chunks.push(chunk);
692 - return [chunks, size + chunk.byteLength] as [Uint8Array[], number];
693 - }
694 - )
695 - );
696 -
697 - // Merge chunks into a single Uint8Array
698 - const merged = new Uint8Array(byteSize);
699 - let offset = 0;
700 - for (const chunk of chunks) {
701 - merged.set(chunk, offset);
702 - offset += chunk.byteLength;
703 - }
704 -
705 - // Decode and parse JSON
706 - const text = new TextDecoder().decode(merged);
707 - const json = yield* Effect.try({
708 - try: () => JSON.parse(text) as unknown,
709 - catch: error =>
710 - new HttpServerError({
711 - cause: `Failed to parse JSON response: ${error}`,
712 - }),
713 - });
714 -
715 - return { json, byteSize };
716 - });
431 +export const sessionProjectApiKeyOf = (info: SessionInfoResponse): string | null => {
432 + const apiKey: object | null = info.api_key;
433 + if (apiKey === null) return null;
434 + if (Predicate.hasProperty(apiKey, 'api_key') && Predicate.isString(apiKey.api_key)) {
435 + return apiKey.api_key;
436 + }
437 + return info.api_key?.key ?? null;
438 +};
439
440 /**
719 - * A single project entry returned by GET /api/v3/org/project/list.
441 + * A single project entry returned by GET /api/v3.1/org/project/list.
442 */
721 -export const OrgProject = Schema.Struct({
722 - id: Schema.String,
723 - name: Schema.String,
724 - email: Schema.String,
725 - deleted: Schema.Boolean,
726 - org_id: Schema.String,
727 - created_at: Schema.String,
728 - updated_at: Schema.String,
729 -}).annotate({ identifier: 'OrgProject' });
730 -export type OrgProject = Schema.Schema.Type<typeof OrgProject>;
443 +export type OrgProject = ProjectListResponse.Data;
444
445 /**
733 - * Response from GET /api/v3/org/project/list.
446 + * Response from GET /api/v3.1/org/project/list.
447 */
735 -export const OrgProjectListResponse = Schema.Struct({
736 - data: Schema.Array(OrgProject),
737 - next_cursor: Schema.NullOr(Schema.String),
738 - total_pages: Schema.Int,
739 - current_page: Schema.Int,
740 - total_items: Schema.Int,
741 -}).annotate({ identifier: 'OrgProjectListResponse' });
742 -export type OrgProjectListResponse = Schema.Schema.Type<typeof OrgProjectListResponse>;
448 +export type OrgProjectListResponse = ProjectListResponse;
449
450 export interface OrganizationSummary {
451 readonly id: string;
@@ -761,597 +467,35 @@ export interface OrganizationProjectListResponse {
467 readonly total_items: number;
468 }
469
764 -export const ConsumerProjectResolveResponse = Schema.Struct({
765 - project_id: Schema.String,
766 - project_nano_id: Schema.String,
767 - project_name: Schema.String,
768 - org_id: Schema.String,
769 - project_type: Schema.Literal('CONSUMER'),
770 - consumer_user_id: Schema.String,
771 -}).annotate({ identifier: 'ConsumerProjectResolveResponse' });
772 -export type ConsumerProjectResolveResponse = Schema.Schema.Type<
773 - typeof ConsumerProjectResolveResponse
774 ->;
775 -
776 -export const LatestToolVersionResponse = Schema.Struct({
777 - tool_slug: Schema.String,
778 - version: Schema.String,
779 -}).annotate({ identifier: 'LatestToolVersionResponse' });
780 -export type LatestToolVersionResponse = Schema.Schema.Type<typeof LatestToolVersionResponse>;
781 -
782 -export const ConsumerConnectedToolkitsResponse = Schema.Struct({
783 - toolkits: Schema.Array(Schema.String),
784 -}).annotate({ identifier: 'ConsumerConnectedToolkitsResponse' });
785 -export type ConsumerConnectedToolkitsResponse = Schema.Schema.Type<
786 - typeof ConsumerConnectedToolkitsResponse
787 ->;
788 -
789 -const extractArrayPayload = (json: unknown): ReadonlyArray<unknown> => {
790 - if (Array.isArray(json)) return json;
791 - if (json && typeof json === 'object') {
792 - const record = json as Record<string, unknown>;
793 - if (Array.isArray(record.organizations)) return record.organizations;
794 - if (Array.isArray(record.projects)) return record.projects;
795 - if (Array.isArray(record.data)) return record.data;
796 - if (Array.isArray(record.items)) return record.items;
797 - if (record.data && typeof record.data === 'object') {
798 - const nested = record.data as Record<string, unknown>;
799 - if (Array.isArray(nested.organizations)) return nested.organizations;
800 - if (Array.isArray(nested.projects)) return nested.projects;
801 - if (Array.isArray(nested.items)) return nested.items;
802 - if (Array.isArray(nested.data)) return nested.data;
803 - }
804 - }
805 - return [];
806 -};
807 -
808 -const readIdFromItem = (item: unknown): string | undefined => {
809 - if (!item || typeof item !== 'object') return undefined;
810 - const record = item as Record<string, unknown>;
811 - if (typeof record.id === 'string') return record.id;
812 - if (typeof record.nano_id === 'string') return record.nano_id;
813 - if (typeof record.org_id === 'string') return record.org_id;
814 - if (typeof record.project_id === 'string') return record.project_id;
815 - return undefined;
816 -};
817 -
818 -const readNameFromItem = (item: unknown): string | undefined => {
819 - if (!item || typeof item !== 'object') return undefined;
820 - const record = item as Record<string, unknown>;
821 - if (typeof record.name === 'string' && record.name.trim().length > 0) return record.name;
822 - if (typeof record.slug === 'string' && record.slug.trim().length > 0) return record.slug;
823 - return undefined;
824 -};
470 +export type ConsumerProjectResolveResponse = ProjectResolveResponse;
471 +export type ConsumerConnectedToolkitsResponse = ConsumerListConnectedToolkitsResponse;
472
826 -/**
827 - * Lists organizations available to the current user API key.
828 - * Uses plain fetch since this endpoint is not available in @composio/client.
829 - */
830 -export const listOrganizations = (params: {
831 - baseURL: string;
832 - apiKey: string;
473 +export interface TriggerInstancesListActiveParams {
474 + user_ids?: string[];
475 + connected_account_ids?: string[];
476 + auth_config_ids?: string[];
477 + trigger_ids?: string[];
478 + trigger_names?: string[];
479 + show_disabled?: boolean;
480 limit?: number;
834 -}): Effect.Effect<OrganizationListResponse, HttpServerError | HttpDecodingError> =>
835 - Effect.gen(function* () {
836 - const limit = params.limit ?? 50;
837 - const response = yield* Effect.tryPromise({
838 - try: () =>
839 - fetch(`${params.baseURL}/api/v3/org/list?limit=${limit}`, {
840 - method: 'GET',
841 - redirect: 'error',
842 - headers: {
843 - 'x-user-api-key': params.apiKey,
844 - 'User-Agent': '@composio/cli',
845 - Accept: 'application/json',
846 - 'Content-Type': 'application/json',
847 - },
848 - }),
849 - catch: error => new HttpServerError({ cause: error }),
850 - });
851 -
852 - if (!response.ok) {
853 - return yield* handleHttpErrorResponse(response);
854 - }
855 -
856 - const { json } = yield* streamResponseWithByteCount(response);
857 - const items = extractArrayPayload(json);
858 - const organizations = items
859 - .map(item => {
860 - const id = readIdFromItem(item);
861 - const name = readNameFromItem(item);
862 - if (!id || !name) return undefined;
863 - return { id, name } satisfies OrganizationSummary;
864 - })
865 - .filter((value): value is OrganizationSummary => value !== undefined);
481 +}
482
867 - return {
868 - data: organizations,
869 - total_items: organizations.length,
870 - };
871 - });
483 +export interface TriggerInstanceUpsertParams {
484 + connected_account_id?: string;
485 + trigger_config?: Record<string, unknown>;
486 +}
487
488 /**
874 - * Lists projects for a specific organization.
875 - * Uses plain fetch since this endpoint is not available in @composio/client.
489 + * Client singleton
490 */
877 -export const listOrganizationProjects = (params: {
878 - baseURL: string;
879 - apiKey: string;
880 - orgId: string;
881 - limit?: number;
882 -}): Effect.Effect<OrganizationProjectListResponse, HttpServerError | HttpDecodingError> =>
883 - Effect.gen(function* () {
884 - const limit = params.limit ?? 50;
885 - const response = yield* Effect.tryPromise({
886 - try: () =>
887 - fetch(`${params.baseURL}/api/v3/org/project/list?limit=${limit}`, {
888 - method: 'GET',
889 - redirect: 'error',
890 - headers: {
891 - 'x-user-api-key': params.apiKey,
892 - 'x-org-id': params.orgId,
893 - 'User-Agent': '@composio/cli',
894 - Accept: 'application/json',
895 - 'Content-Type': 'application/json',
896 - },
897 - }),
898 - catch: error => new HttpServerError({ cause: error }),
899 - });
491
901 - if (!response.ok) {
902 - return yield* handleHttpErrorResponse(response);
903 - }
492 +const normalizeApiKey = (rawApiKey?: string): string | undefined =>
493 + typeof rawApiKey === 'string' && rawApiKey.trim().length > 0 ? rawApiKey : undefined;
494
905 - const { json } = yield* streamResponseWithByteCount(response);
906 - const items = extractArrayPayload(json);
907 - const projects = items
908 - .map(item => {
909 - const id = readIdFromItem(item);
910 - const name = readNameFromItem(item);
911 - if (!id || !name) return undefined;
912 - return { id, name } satisfies OrganizationProjectSummary;
913 - })
914 - .filter((value): value is OrganizationProjectSummary => value !== undefined);
915 -
916 - return {
917 - data: projects,
918 - total_items: projects.length,
919 - };
920 - });
921 -
922 -/**
923 - * Lists all projects for the logged-in user's organization.
924 - * Uses plain fetch since this endpoint is not available in @composio/client.
925 - *
926 - * @param params.baseURL - API base URL
927 - * @param params.apiKey - UAK (sent as `x-user-api-key`)
928 - * @param params.orgId - Organization ID (sent as `x-org-id`)
929 - * @param params.limit - Max projects to return (default 50)
930 - */
931 -export const listOrgProjects = (params: {
932 - baseURL: string;
933 - apiKey: string;
934 - orgId: string;
935 - limit?: number;
936 -}): Effect.Effect<OrgProjectListResponse, HttpServerError | HttpDecodingError> =>
937 - Effect.gen(function* () {
938 - const limit = params.limit ?? 50;
939 - const response = yield* Effect.tryPromise({
940 - try: () =>
941 - fetch(
942 - `${params.baseURL}/api/v3/org/project/list?list_all_org_projects=true&limit=${limit}`,
943 - {
944 - method: 'GET',
945 - redirect: 'error',
946 - headers: {
947 - 'x-user-api-key': params.apiKey,
948 - 'x-org-id': params.orgId,
949 - 'User-Agent': '@composio/cli',
950 - Accept: 'application/json',
951 - 'Content-Type': 'application/json',
952 - },
953 - }
954 - ),
955 - catch: error => new HttpServerError({ cause: error }),
956 - });
957 -
958 - if (!response.ok) {
959 - return yield* handleHttpErrorResponse(response);
960 - }
961 -
962 - const { json } = yield* streamResponseWithByteCount(response);
963 -
964 - return yield* pipe(
965 - Schema.decodeUnknownEffect(OrgProjectListResponse)(json),
966 - Effect.catchTag(
967 - 'SchemaError',
968 - e =>
969 - new HttpDecodingError({
970 - cause: `SchemaError\n ${e.message}`,
971 - })
972 - )
973 - );
974 - });
975 -
976 -/**
977 - * Calls GET /api/v3/auth/session/info with the full layered auth headers.
978 - * Uses plain fetch since this endpoint is not available in @composio/client.
979 - * This is a standalone function, NOT on ComposioSessionRepository, to keep
980 - * the repository as a pure facade over @composio/client.
981 - */
982 -export const getSessionInfo = (params: {
983 - baseURL: string;
984 - apiKey: string;
985 - orgId: string;
986 - projectId: string;
987 -}): Effect.Effect<SessionInfoResponse, HttpServerError | HttpDecodingError> =>
988 - Effect.gen(function* () {
989 - const response = yield* Effect.tryPromise({
990 - try: () =>
991 - fetch(`${params.baseURL}/api/v3/auth/session/info`, {
992 - method: 'GET',
993 - redirect: 'error',
994 - headers: {
995 - ...authHeaderForApiKey(params.apiKey),
996 - 'x-org-id': params.orgId,
997 - 'x-project-id': params.projectId,
998 - 'User-Agent': '@composio/cli',
999 - Accept: '*/*',
1000 - 'Content-Type': 'application/json',
1001 - },
1002 - }),
1003 - catch: error => new HttpServerError({ cause: error }),
1004 - });
1005 -
1006 - if (!response.ok) {
1007 - return yield* handleHttpErrorResponse(response);
1008 - }
1009 -
1010 - const { json } = yield* streamResponseWithByteCount(response);
1011 -
1012 - return yield* pipe(
1013 - Schema.decodeUnknownEffect(SessionInfoResponse)(json),
1014 - Effect.catchTag(
1015 - 'SchemaError',
1016 - e =>
1017 - new HttpDecodingError({
1018 - cause: `SchemaError\n ${e.message}`,
1019 - })
1020 - )
1021 - );
1022 - });
1023 -
1024 -/**
1025 - * Calls GET /api/v3/auth/session/info using the x-user-api-key header.
1026 - * Unlike getSessionInfo which requires both org AND project IDs, this variant
1027 - * resolves session metadata from the UAK alone — useful during login before
1028 - * org/project context is known.
1029 - *
1030 - * When `orgId` is provided, it is forwarded as `x-org-id` so the backend
1031 - * resolves the session against the caller's currently-selected global org
1032 - * (set via `composio orgs switch`). Without it, the backend falls back to the
1033 - * API key's home org, which makes the response ignore any org switch.
1034 - * Uses plain fetch since this endpoint is not available in @composio/client.
1035 - */
1036 -export const getSessionInfoByUserApiKey = (params: {
1037 - baseURL: string;
1038 - userApiKey: string;
1039 - orgId?: string;
1040 -}): Effect.Effect<SessionInfoResponse, HttpServerError | HttpDecodingError> =>
1041 - Effect.gen(function* () {
1042 - const response = yield* Effect.tryPromise({
1043 - try: () =>
1044 - fetch(`${params.baseURL}/api/v3/auth/session/info`, {
1045 - method: 'GET',
1046 - redirect: 'error',
1047 - headers: {
1048 - 'x-user-api-key': params.userApiKey,
1049 - ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
1050 - 'User-Agent': '@composio/cli',
1051 - Accept: '*/*',
1052 - 'Content-Type': 'application/json',
1053 - },
1054 - }),
1055 - catch: error => new HttpServerError({ cause: error }),
1056 - });
1057 -
1058 - if (!response.ok) {
1059 - return yield* handleHttpErrorResponse(response);
1060 - }
1061 -
1062 - const { json } = yield* streamResponseWithByteCount(response);
1063 -
1064 - return yield* pipe(
1065 - Schema.decodeUnknownEffect(SessionInfoResponse)(json),
1066 - Effect.catchTag(
1067 - 'SchemaError',
1068 - e =>
1069 - new HttpDecodingError({
1070 - cause: `SchemaError\n ${e.message}`,
1071 - })
1072 - )
1073 - );
1074 - });
1075 -
1076 -const getApiKeyFromPayload = (payload: unknown): string | undefined => {
1077 - const candidates = new Set<string>(['api_key', 'apiKey', 'key', 'token']);
1078 - const keyPrefixes = ['uak_', 'ak_'];
1079 - const queue: unknown[] = [payload];
1080 -
1081 - while (queue.length > 0) {
1082 - const current = queue.shift();
1083 - if (!current || typeof current !== 'object') continue;
1084 -
1085 - if (Array.isArray(current)) {
1086 - queue.push(...current);
1087 - continue;
1088 - }
1089 -
1090 - const entries = Object.entries(current as Record<string, unknown>);
1091 - for (const [key, value] of entries) {
1092 - if (
1093 - typeof value === 'string' &&
1094 - candidates.has(key) &&
1095 - keyPrefixes.some(prefix => value.startsWith(prefix))
1096 - ) {
1097 - return value;
1098 - }
1099 - if (value && typeof value === 'object') {
1100 - queue.push(value);
1101 - }
1102 - }
1103 - }
1104 -
1105 - return undefined;
1106 -};
1107 -
1108 -export const createProjectApiKey = (params: {
1109 - baseURL: string;
1110 - apiKey: string;
1111 - orgId: string;
1112 - projectId: string;
1113 - name: string;
1114 -}): Effect.Effect<string, HttpServerError | HttpDecodingError> =>
1115 - Effect.gen(function* () {
1116 - const response = yield* Effect.tryPromise({
1117 - try: () =>
1118 - fetch(`${params.baseURL}/api/v3/org/project/${params.projectId}/api_keys/create`, {
1119 - method: 'POST',
1120 - redirect: 'error',
1121 - headers: {
1122 - ...authHeaderForApiKey(params.apiKey),
1123 - 'x-org-id': params.orgId,
1124 - 'x-project-id': params.projectId,
1125 - 'User-Agent': '@composio/cli',
1126 - Accept: '*/*',
1127 - 'Content-Type': 'application/json',
1128 - },
1129 - body: JSON.stringify({ name: params.name }),
1130 - }),
1131 - catch: error => new HttpServerError({ cause: error }),
1132 - });
1133 -
1134 - if (!response.ok) {
1135 - return yield* handleHttpErrorResponse(response);
1136 - }
1137 -
1138 - const { json } = yield* streamResponseWithByteCount(response);
1139 - const createdApiKey = getApiKeyFromPayload(json);
1140 -
1141 - if (!createdApiKey) {
1142 - return yield* Effect.fail(
1143 - new HttpDecodingError({
1144 - cause: 'Create API key response did not contain an API key',
1145 - })
1146 - );
1147 - }
1148 -
1149 - return createdApiKey;
1150 - });
1151 -
1152 -export const resolveConsumerProject = (params: {
1153 - baseURL: string;
1154 - apiKey: string;
1155 - orgId: string;
1156 -}): Effect.Effect<ConsumerProjectResolveResponse, HttpServerError | HttpDecodingError> =>
1157 - Effect.gen(function* () {
1158 - const response = yield* Effect.tryPromise({
1159 - try: () =>
1160 - fetch(`${params.baseURL}/api/v3/org/consumer/project/resolve`, {
1161 - method: 'POST',
1162 - redirect: 'error',
1163 - headers: {
1164 - 'x-user-api-key': params.apiKey,
1165 - 'x-org-id': params.orgId,
1166 - 'User-Agent': '@composio/cli',
1167 - Accept: 'application/json',
1168 - 'Content-Type': 'application/json',
1169 - },
1170 - }),
1171 - catch: error => new HttpServerError({ cause: error }),
1172 - });
1173 -
1174 - if (!response.ok) {
1175 - return yield* handleHttpErrorResponse(response);
1176 - }
1177 -
1178 - const { json } = yield* streamResponseWithByteCount(response);
1179 -
1180 - return yield* pipe(
1181 - Schema.decodeUnknownEffect(ConsumerProjectResolveResponse)(json),
1182 - Effect.catchTag(
1183 - 'SchemaError',
1184 - e =>
1185 - new HttpDecodingError({
1186 - cause: `SchemaError\n ${e.message}`,
1187 - })
1188 - )
1189 - );
1190 - });
1191 -
1192 -export const getLatestToolVersion = (params: {
1193 - baseURL: string;
1194 - apiKey: string;
1195 - toolSlug: string;
1196 - orgId?: string;
1197 - projectId?: string;
1198 - projectApiKey?: string;
1199 -}): Effect.Effect<LatestToolVersionResponse, HttpServerError | HttpDecodingError> =>
1200 - Effect.gen(function* () {
1201 - const response = yield* Effect.tryPromise({
1202 - try: () =>
1203 - fetch(
1204 - `${params.baseURL}/api/v3/tools/${encodeURIComponent(params.toolSlug)}/get_latest_version`,
1205 - {
1206 - method: 'GET',
1207 - redirect: 'error',
1208 - headers: {
1209 - ...(params.projectApiKey
1210 - ? ({ 'x-api-key': params.projectApiKey } satisfies Record<string, string>)
1211 - : ({ 'x-user-api-key': params.apiKey } satisfies Record<string, string>)),
1212 - ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
1213 - ...(params.projectId ? { 'x-project-id': params.projectId } : {}),
1214 - 'User-Agent': '@composio/cli',
1215 - Accept: 'application/json',
1216 - 'Content-Type': 'application/json',
1217 - },
1218 - }
1219 - ),
1220 - catch: error => new HttpServerError({ cause: error }),
1221 - });
1222 -
1223 - if (!response.ok) {
1224 - return yield* handleHttpErrorResponse(response);
1225 - }
1226 -
1227 - const { json } = yield* streamResponseWithByteCount(response);
1228 -
1229 - return yield* pipe(
1230 - Schema.decodeUnknownEffect(LatestToolVersionResponse)(json),
1231 - Effect.catchTag(
1232 - 'SchemaError',
1233 - e =>
1234 - new HttpDecodingError({
1235 - cause: `SchemaError\n ${e.message}`,
1236 - })
1237 - )
1238 - );
1239 - });
1240 -
1241 -export const getConsumerConnectedToolkits = (params: {
1242 - baseURL: string;
1243 - apiKey: string;
1244 - orgId: string;
1245 - consumerUserId: string;
1246 -}): Effect.Effect<ConsumerConnectedToolkitsResponse, HttpServerError | HttpDecodingError> =>
1247 - Effect.gen(function* () {
1248 - const response = yield* Effect.tryPromise({
1249 - try: () =>
1250 - fetch(
1251 - `${params.baseURL}/api/v3/org/consumer/connected_toolkits?user_id=${encodeURIComponent(params.consumerUserId)}`,
1252 - {
1253 - method: 'GET',
1254 - redirect: 'error',
1255 - headers: {
1256 - 'x-user-api-key': params.apiKey,
1257 - 'x-org-id': params.orgId,
1258 - 'User-Agent': '@composio/cli',
1259 - Accept: 'application/json',
1260 - 'Content-Type': 'application/json',
1261 - },
1262 - }
1263 - ),
1264 - catch: error => new HttpServerError({ cause: error }),
1265 - });
1266 -
1267 - if (!response.ok) {
1268 - return yield* handleHttpErrorResponse(response);
1269 - }
1270 -
1271 - const { json } = yield* streamResponseWithByteCount(response);
1272 -
1273 - return yield* pipe(
1274 - Schema.decodeUnknownEffect(ConsumerConnectedToolkitsResponse)(json),
1275 - Effect.catchTag(
1276 - 'SchemaError',
1277 - e =>
1278 - new HttpDecodingError({
1279 - cause: `SchemaError\n ${e.message}`,
1280 - })
1281 - )
1282 - );
1283 - });
1284 -
1285 -export class DeveloperProjectNotFoundError extends Data.TaggedError(
1286 - 'services/DeveloperProjectNotFoundError'
1287 -)<{
1288 - readonly orgId: string;
1289 - readonly projectName: string;
1290 -}> {}
1291 -
1292 -export class AmbiguousDeveloperProjectNameError extends Data.TaggedError(
1293 - 'services/AmbiguousDeveloperProjectNameError'
1294 -)<{
1295 - readonly orgId: string;
1296 - readonly projectName: string;
1297 - readonly matches: ReadonlyArray<OrganizationProjectSummary>;
1298 -}> {}
1299 -
1300 -export const findDeveloperProjectByName = (params: {
1301 - baseURL: string;
1302 - apiKey: string;
1303 - orgId: string;
1304 - name: string;
1305 - limit?: number;
1306 -}): Effect.Effect<
1307 - OrganizationProjectSummary,
1308 - | DeveloperProjectNotFoundError
1309 - | AmbiguousDeveloperProjectNameError
1310 - | HttpServerError
1311 - | HttpDecodingError
1312 -> =>
1313 - Effect.gen(function* () {
1314 - const projects = yield* listOrgProjects({
1315 - baseURL: params.baseURL,
1316 - apiKey: params.apiKey,
1317 - orgId: params.orgId,
1318 - limit: params.limit,
1319 - });
1320 -
1321 - const normalizedName = String.toLowerCase(params.name.trim());
1322 - const matches = projects.data.filter(
1323 - project => String.toLowerCase(project.name) === normalizedName
1324 - );
1325 -
1326 - if (matches.length === 0) {
1327 - return yield* Effect.fail(
1328 - new DeveloperProjectNotFoundError({
1329 - orgId: params.orgId,
1330 - projectName: params.name,
1331 - })
1332 - );
1333 - }
1334 -
1335 - if (matches.length > 1) {
1336 - return yield* Effect.fail(
1337 - new AmbiguousDeveloperProjectNameError({
1338 - orgId: params.orgId,
1339 - projectName: params.name,
1340 - matches,
1341 - })
1342 - );
1343 - }
1344 -
1345 - return matches[0];
1346 - });
1347 -
1348 -const normalizeApiKey = (rawApiKey?: string): string | undefined =>
1349 - typeof rawApiKey === 'string' && rawApiKey.trim().length > 0 ? rawApiKey : undefined;
1350 -
1351 -const detectCliRuntime = (): string => {
1352 - if (typeof Bun !== 'undefined') {
1353 - return 'BUN';
1354 - }
495 +const detectCliRuntime = (): string => {
496 + if (typeof Bun !== 'undefined') {
497 + return 'BUN';
498 + }
499
500 if (typeof process !== 'undefined' && process.versions?.node) {
501 return 'NODEJS';
@@ -1385,171 +529,42 @@ const buildDefaultHeaders = (params: {
529 : {}),
530 };
531
1388 - return Object.keys(defaultHeaders).length > 0 ? defaultHeaders : undefined;
1389 -};
1390 -
1391 -// Utility function for calling the Composio API and decoding its response.
1392 -const callClient = <T, S extends Schema.Top>(
1393 - clientSingleton: ComposioClientSingletonShape,
1394 - apiCall: (client: _RawComposioClient) => APIPromise<T>,
1395 - responseSchema: S
1396 -): Effect.Effect<
1397 - { data: S['Type']; metrics: Metrics },
1398 - HttpError | NoSuchElementError,
1399 - S['DecodingServices']
1400 -> =>
1401 - Effect.gen(function* () {
1402 - const client = yield* clientSingleton.get();
1403 - const response = yield* Effect.tryPromise({
1404 - try: () => apiCall(client).asResponse(),
1405 - catch: e =>
1406 - new HttpServerError({
1407 - cause: e,
1408 - }),
1409 - });
1410 -
1411 - // Check HTTP status before streaming - .asResponse() doesn't throw on HTTP errors
1412 - if (!response.ok) {
1413 - return yield* handleHttpErrorResponse(response);
1414 - }
1415 -
1416 - // Stream the response body with byte counting
1417 - const { json, byteSize } = yield* streamResponseWithByteCount(response);
1418 - const metrics = { byteSize, requests: 1 };
1419 -
1420 - const typedJson: S['Type'] = yield* pipe(
1421 - Schema.decodeUnknownEffect(responseSchema)(json),
1422 - Effect.catchTag(
1423 - 'SchemaError',
1424 - e =>
1425 - new HttpDecodingError({
1426 - cause: `SchemaError\n ${e.message}`,
1427 - })
1428 - )
1429 - );
1430 -
1431 - return { metrics, data: typedJson };
1432 - });
1433 -
1434 -// Schema constraint for paginated responses: the decoded page must expose the
1435 -// pagination envelope, expressed through the schema's `Type` phantom property so
1436 -// concrete item types stay free of `any`.
1437 -type PaginatedSchema = Schema.Top & {
1438 - readonly Type: {
1439 - readonly items: ReadonlyArray<unknown>;
1440 - readonly next_cursor: string | null;
1441 - readonly total_pages: number;
1442 - };
532 + return defaultHeaders;
533 };
534
1445 -// Maximum items per page allowed by the server
1446 -const MAX_PAGE_SIZE = 1000;
1447 -
1448 -// Maximum concurrent requests per each endpoint
1449 -const MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 4;
1450 -
1451 -// Utility function for calling paginated Composio API endpoints.
1452 -// Automatically fetches all pages, using MAX_PAGE_SIZE per request.
1453 -const callClientWithPagination = <T, S extends PaginatedSchema>(
1454 - clientSingleton: ComposioClientSingletonShape,
1455 - apiCall: (client: _RawComposioClient, cursor?: string, limit?: number) => APIPromise<T>,
1456 - responseSchema: S
1457 -): Effect.Effect<
1458 - { data: S['Type']; metrics: Metrics },
1459 - HttpError | NoSuchElementError,
1460 - S['DecodingServices']
1461 -> =>
1462 - Effect.gen(function* () {
1463 - const client = yield* clientSingleton.get();
1464 - let totalByteSize = 0;
1465 - let totalRequests = 0;
1466 -
1467 - const fetchPage = (cursor?: string): Effect.Effect<StreamedResponse, HttpServerError> =>
1468 - Effect.gen(function* () {
1469 - const response = yield* Effect.tryPromise({
1470 - try: () => apiCall(client, cursor, MAX_PAGE_SIZE).asResponse(),
1471 - catch: e =>
1472 - new HttpServerError({
1473 - cause: e,
1474 - }),
1475 - });
1476 -
1477 - // Check HTTP status before streaming - .asResponse() doesn't throw on HTTP errors
1478 - if (!response.ok) {
1479 - return yield* handleHttpErrorResponse(response);
1480 - }
1481 -
1482 - // Stream the response body with byte counting
1483 - return yield* streamResponseWithByteCount(response);
1484 - });
1485 -
1486 - type DecodedPage = S['Type'];
1487 -
1488 - const decodeResponse = (json: unknown): Effect.Effect<DecodedPage, HttpDecodingError> =>
1489 - pipe(
1490 - Schema.decodeUnknownEffect(responseSchema)(json),
1491 - Effect.catchTag(
1492 - 'SchemaError',
1493 - e =>
1494 - new HttpDecodingError({
1495 - cause: `SchemaError\n ${e.message}`,
1496 - })
1497 - )
1498 - ) as Effect.Effect<DecodedPage, HttpDecodingError>;
1499 -
1500 - let allItems: ReadonlyArray<unknown> = [];
1501 - let currentCursor: string | null = null;
1502 - let totalPages = 0;
1503 -
1504 - // Fetch all pages using MAX_PAGE_SIZE per request
1505 - while (true) {
1506 - const { json, byteSize } = yield* fetchPage(currentCursor ?? undefined);
1507 - totalByteSize += byteSize;
1508 - totalRequests += 1;
1509 -
1510 - const decoded: DecodedPage = yield* decodeResponse(json);
1511 -
1512 - allItems = allItems.concat(decoded.items);
1513 - totalPages = decoded.total_pages;
1514 - currentCursor = decoded.next_cursor;
1515 -
1516 - // Stop if no more pages
1517 - if (currentCursor === null) {
1518 - break;
1519 - }
1520 - }
1521 -
1522 - const metrics = { byteSize: totalByteSize, requests: totalRequests };
1523 -
1524 - return {
1525 - data: {
1526 - items: allItems,
1527 - total_pages: totalPages,
1528 - next_cursor: currentCursor,
1529 - } as DecodedPage,
1530 - metrics,
1531 - };
1532 - });
1533 -
1534 -/**
1535 - * Services
1536 - */
1537 -
535 /**
536 * Shape exposed by {@link ComposioClientSingleton}.
537 */
538 export interface ComposioClientSingletonShape {
1542 - readonly get: () => Effect.Effect<_RawComposioClient, NoSuchElementError>;
539 + readonly get: () => Effect.Effect<
540 + _RawComposioClient,
541 + ComposioClientConfigurationError | NoSuchElementError
542 + >;
543 readonly getFor: (params: {
544 userApiKey?: string;
545 orgId?: string;
546 projectId?: string;
1547 - }) => Effect.Effect<_RawComposioClient, NoSuchElementError>;
547 + }) => Effect.Effect<_RawComposioClient, ComposioClientConfigurationError | NoSuchElementError>;
548 + /**
549 + * Returns a snapshot of the accumulated metrics (total bytes received and
550 + * request count) across every client this singleton built.
551 + */
552 + readonly getMetrics: () => Effect.Effect<{
553 + readonly byteSize: number;
554 + readonly requests: number;
555 + }>;
556 }
557
558 /**
559 * Singleton service that lazily accesses `Config` only when needed, which is used to build and provide
560 * a raw (uneffectful, Promise-based) Composio client instance.
561 + *
562 + * Clients are built with `Composio.fromEnv({}, ...)` so the ambient process
563 + * environment is never consulted: every credential and the base URL come from
564 + * the CLI's own configuration. Custom HTTP base URLs remain supported. The user key is
565 + * placed in `defaultHeaders` as `x-user-api-key`, which keeps today's wire
566 + * bytes on every operation; it is also passed as `userApiKey`, while the
567 + * caller-placed header still wins at dispatch.
568 */
569 const makeComposioClientSingleton = Effect.gen(function* () {
570 const ctx = yield* ComposioUserContext;
@@ -1557,6 +572,7 @@ const makeComposioClientSingleton = Effect.gen(function* () {
572 const fs = yield* FileSystem.FileSystem;
573 const path = yield* Path.Path;
574 const os = yield* NodeOs;
575 + const metrics = makeClientMetricsCollector();
576 const cache = new Map<string, _RawComposioClient>();
577
578 const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
@@ -1578,15 +594,33 @@ const makeComposioClientSingleton = Effect.gen(function* () {
594 Effect.provideService(NodeOs, os)
595 );
596
1581 - const client = new _RawComposioClient({
1582 - apiKey: null,
1583 - baseURL: ctx.data.baseURL,
1584 - defaultHeaders: buildDefaultHeaders({
1585 - userApiKey: apiKey,
1586 - orgId: params?.orgId,
1587 - projectId: params?.projectId,
1588 - cliSessionId,
1589 - }),
597 + const client = yield* Effect.try({
598 + try: () =>
599 + // An empty environment prevents implicit env reads, including COMPOSIO_CUSTOM_HEADERS.
600 + _RawComposioClient.fromEnv(
601 + {},
602 + {
603 + apiKey: null,
604 + userApiKey: apiKey ?? null,
605 + orgApiKey: null,
606 + baseURL: ctx.data.baseURL,
607 + // Preserve support for explicitly configured HTTP backends.
608 + allowInsecureHTTP: true,
609 + logLevel: 'off',
610 + defaultHeaders: buildDefaultHeaders({
611 + userApiKey: apiKey,
612 + orgId: params?.orgId,
613 + projectId: params?.projectId,
614 + cliSessionId,
615 + }),
616 + fetch: metrics.fetch,
617 + }
618 + ),
619 + catch: cause =>
620 + new ComposioClientConfigurationError({
621 + message: cause instanceof Error ? cause.message : global.String(cause),
622 + cause,
623 + }),
624 });
625
626 cache.set(cacheKey, client);
@@ -1608,19 +642,16 @@ const makeComposioClientSingleton = Effect.gen(function* () {
642 projectId: keys.projectId,
643 }),
644 });
1611 - }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementError, never>,
645 + }),
646 getFor: Effect.fn(function* (params: {
647 userApiKey?: string;
648 orgId?: string;
649 projectId?: string;
650 }) {
651 return yield* getFor(params);
1618 - }) satisfies (params: {
1619 - userApiKey?: string;
1620 - orgId?: string;
1621 - projectId?: string;
1622 - }) => Effect.Effect<_RawComposioClient, NoSuchElementError, never>,
1623 - };
652 + }),
653 + getMetrics: metrics.getMetrics,
654 + } satisfies ComposioClientSingletonShape;
655 });
656
657 /**
@@ -1631,19 +662,6 @@ export interface ToolkitProjectScope {
662 readonly projectId: string;
663 }
664
1634 -/**
1635 - * A view of `clientSingleton` whose `get()` builds the client for `scope`,
1636 - * so the shared call helpers can make a request for a project other than the
1637 - * one the project context resolves.
1638 - */
1639 -const scopedClientSingleton = (
1640 - clientSingleton: ComposioClientSingletonShape,
1641 - scope: ToolkitProjectScope
1642 -): ComposioClientSingletonShape => ({
1643 - ...clientSingleton,
1644 - get: () => clientSingleton.getFor({ orgId: scope.orgId, projectId: scope.projectId }),
1645 -});
1646 -
665 export class ComposioClientSingleton extends Context.Service<
666 ComposioClientSingleton,
667 ComposioClientSingletonShape
@@ -1654,477 +672,472 @@ export class ComposioClientSingleton extends Context.Service<
672 }
673
674 /**
1657 - * Build the `tools` namespace for ComposioClientLive.
1658 - * Extracted to keep the main generator under the max-lines-per-function limit.
675 + * Account, session-info, and consumer helpers
676 + *
677 + * Standalone functions rather than repository methods: they take explicit
678 + * credentials and scope, and callers already run inside layers that provide
679 + * `ComposioClientSingleton`.
680 */
1660 -function buildToolsNamespace(
1661 - clientSingleton: ComposioClientSingletonShape,
1662 - withMetrics: <A, E, R>(
1663 - effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1664 - ) => Effect.Effect<A, E, R>
1665 -) {
1666 - return {
1667 - /**
1668 - * Retrieve a list of all available tool enumeration values (tool slugs) for the project.
1669 - */
1670 - retrieveEnum: () =>
1671 - withMetrics(
1672 - callClient(clientSingleton, client => client.tools.retrieveEnum(), ToolsAsEnumsResponse)
1673 - ),
1674 - /**
1675 - * Retrieve a list of tools, automatically handling pagination.
1676 - * It always fetches the latest version of tools for each toolkit.
1677 - * For more granular toolkit version control, use `listByVersionSpecs`.
1678 - * @param toolkitSlugs - Array of toolkit slugs to filter by
1679 - */
1680 - list: (toolkitSlugs: ReadonlyArray<string>) =>
1681 - withMetrics(
1682 - callClientWithPagination(
1683 - clientSingleton,
1684 - (client, cursor, limit) =>
1685 - client.tools.list({
1686 - cursor,
1687 - toolkit_slug: toolkitSlugs.length > 0 ? toolkitSlugs.join(',') : undefined,
1688 - toolkit_versions: 'latest',
1689 - limit,
1690 - }),
1691 - ToolsResponse
1692 - )
1693 - ),
1694 - /**
1695 - * Retrieve tools for multiple toolkits, grouped by version.
1696 - * Makes parallel API calls for each version group, then merges results.
1697 - * @param specs - Array of toolkit version specifications
1698 - */
1699 - listByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>
1700 - Effect.gen(function* () {
1701 - const grouped = groupByVersion(specs);
1702 - const versionGroups = [...grouped.entries()];
1703 -
1704 - // Fetch all version groups in parallel with bounded concurrency
1705 - const responses = yield* Effect.all(
1706 - versionGroups.map(([version, slugs]) =>
1707 - withMetrics(
1708 - callClientWithPagination(
1709 - clientSingleton,
1710 - (client, cursor, limit) =>
1711 - client.tools.list({
1712 - cursor,
1713 - toolkit_slug: slugs.join(','),
1714 - toolkit_versions: version,
1715 - limit,
1716 - }),
1717 - ToolsResponse
1718 - )
1719 - )
1720 - ),
1721 - { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
1722 - );
681
1724 - // Merge all tools from all version groups
1725 - const allTools = responses.flatMap(response => response.items);
1726 - return { items: allTools };
682 +const orgScopedOptions = (orgId: string | undefined): RequestOptions | undefined =>
683 + orgId ? { headers: { 'x-org-id': orgId } } : undefined;
684 +
685 +/**
686 + * Lists organizations available to the current user API key.
687 + */
688 +export const listOrganizations = (params: {
689 + apiKey: string;
690 + limit?: number;
691 +}): Effect.Effect<OrganizationListResponse, ClientError, ComposioClientSingleton> =>
692 + Effect.gen(function* () {
693 + const clientSingleton = yield* ComposioClientSingleton;
694 + const response = yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
695 + client.org.list({ limit: params.limit ?? 50 })
696 + );
697 + const organizations = response.organizations.map(
698 + (organization: OrgListResponse.Organization) =>
699 + ({ id: organization.id, name: organization.name }) satisfies OrganizationSummary
700 + );
701 +
702 + return {
703 + data: organizations,
704 + total_items: organizations.length,
705 + };
706 + });
707 +
708 +/**
709 + * Lists projects for a specific organization.
710 + */
711 +export const listOrganizationProjects = (params: {
712 + apiKey: string;
713 + orgId: string;
714 + limit?: number;
715 +}): Effect.Effect<OrganizationProjectListResponse, ClientError, ComposioClientSingleton> =>
716 + Effect.gen(function* () {
717 + const clientSingleton = yield* ComposioClientSingleton;
718 + const response = yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
719 + client.org.project.list({ limit: params.limit ?? 50 }, orgScopedOptions(params.orgId))
720 + );
721 + const projects = response.data.map(
722 + (project: OrgProject) =>
723 + ({ id: project.id, name: project.name }) satisfies OrganizationProjectSummary
724 + );
725 +
726 + return {
727 + data: projects,
728 + total_items: projects.length,
729 + };
730 + });
731 +
732 +/**
733 + * Lists all projects for the logged-in user's organization.
734 + *
735 + * @param params.apiKey - UAK (sent as `x-user-api-key`)
736 + * @param params.orgId - Organization ID (sent as `x-org-id`)
737 + * @param params.limit - Max projects to return (default 50)
738 + */
739 +export const listOrgProjects = (params: {
740 + apiKey: string;
741 + orgId: string;
742 + limit?: number;
743 +}): Effect.Effect<OrgProjectListResponse, ClientError, ComposioClientSingleton> =>
744 + Effect.gen(function* () {
745 + const clientSingleton = yield* ComposioClientSingleton;
746 + return yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
747 + client.org.project.list(
748 + { list_all_org_projects: true, limit: params.limit ?? 50 },
749 + orgScopedOptions(params.orgId)
750 + )
751 + );
752 + });
753 +
754 +/**
755 + * Calls GET /api/v3.1/auth/session/info with the full layered auth headers.
756 + */
757 +export const getSessionInfo = (params: {
758 + apiKey: string;
759 + orgId: string;
760 + projectId: string;
761 +}): Effect.Effect<SessionInfoResponse, ClientError, ComposioClientSingleton> =>
762 + Effect.gen(function* () {
763 + const clientSingleton = yield* ComposioClientSingleton;
764 + const info = yield* request(
765 + clientSingleton.getFor({
766 + userApiKey: params.apiKey,
767 + orgId: params.orgId,
768 + projectId: params.projectId,
769 }),
1728 - /**
1729 - * Search tools with optional filters. Returns a single page of results (no auto-pagination).
1730 - * @param params - Search/filter parameters
1731 - */
1732 - search: (params: {
1733 - search?: string;
1734 - toolkit_slug?: string;
1735 - tags?: string;
1736 - limit?: number;
1737 - cursor?: string;
1738 - }) =>
1739 - withMetrics(
1740 - callClient(
1741 - clientSingleton,
1742 - client =>
1743 - client.tools.list({
1744 - search: params.search,
1745 - toolkit_slug: params.toolkit_slug,
1746 - tags: params.tags ? params.tags.split(',').map(t => t.trim()) : undefined,
1747 - limit: params.limit,
1748 - cursor: params.cursor,
1749 - toolkit_versions: 'latest',
1750 - }),
1751 - ToolsResponse
1752 - )
1753 - ),
1754 - /**
1755 - * Retrieves detailed info about a single tool by slug.
1756 - * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")
1757 - */
1758 - retrieve: (slug: string) =>
1759 - withMetrics(
1760 - callClient(
1761 - clientSingleton,
1762 - client => client.tools.retrieve(slug, { toolkit_versions: 'latest' }),
1763 - ToolDetailedResponse
1764 - )
1765 - ),
1766 - };
1767 -}
770 + client => client.auth.session.retrieveInfo()
771 + );
772 + return yield* requireSessionProject(info);
773 + });
774 +
775 +/**
776 + * Calls GET /api/v3.1/auth/session/info using the x-user-api-key header.
777 + * Unlike getSessionInfo which requires both org AND project IDs, this variant
778 + * resolves session metadata from the UAK alone — useful during login before
779 + * org/project context is known.
780 + *
781 + * When `orgId` is provided, it is forwarded as `x-org-id` so the backend
782 + * resolves the session against the caller's currently-selected global org
783 + * (set via `composio orgs switch`). Without it, the backend falls back to the
784 + * API key's home org, which makes the response ignore any org switch.
785 + */
786 +export const getSessionInfoByUserApiKey = (params: {
787 + userApiKey: string;
788 + orgId?: string;
789 +}): Effect.Effect<SessionInfoResponse, ClientError, ComposioClientSingleton> =>
790 + Effect.gen(function* () {
791 + const clientSingleton = yield* ComposioClientSingleton;
792 + const info = yield* request(clientSingleton.getFor({ userApiKey: params.userApiKey }), client =>
793 + client.auth.session.retrieveInfo(orgScopedOptions(params.orgId))
794 + );
795 + return yield* requireSessionProject(info);
796 + });
797 +
798 +// The create-api-key response shape is not documented in the client. Walk the
799 +// body for the first `uak_`/`ak_`-prefixed string under a key-like name.
800 +const getApiKeyFromPayload = (payload: unknown): string | undefined => {
801 + const candidates = new Set<string>(['api_key', 'apiKey', 'key', 'token']);
802 + const keyPrefixes = ['uak_', 'ak_'];
803 + const queue: unknown[] = [payload];
804 +
805 + while (queue.length > 0) {
806 + const current = queue.shift();
807 + if (!current || typeof current !== 'object') continue;
808 +
809 + if (Array.isArray(current)) {
810 + queue.push(...current);
811 + continue;
812 + }
813 +
814 + const entries = Object.entries(current as Record<string, unknown>);
815 + for (const [key, value] of entries) {
816 + if (
817 + typeof value === 'string' &&
818 + candidates.has(key) &&
819 + keyPrefixes.some(prefix => value.startsWith(prefix))
820 + ) {
821 + return value;
822 + }
823 + if (value && typeof value === 'object') {
824 + queue.push(value);
825 + }
826 + }
827 + }
828 +
829 + return undefined;
830 +};
831 +
832 +/**
833 + * Mints a project API key. Never retried: a retry after a timed-out create
834 + * would mint a second key the caller never sees.
835 + */
836 +export const createProjectApiKey = (params: {
837 + apiKey: string;
838 + orgId: string;
839 + projectId: string;
840 + name: string;
841 +}): Effect.Effect<string, ClientError, ComposioClientSingleton> =>
842 + Effect.gen(function* () {
843 + const clientSingleton = yield* ComposioClientSingleton;
844 + const payload = yield* request(
845 + clientSingleton.getFor({
846 + userApiKey: params.apiKey,
847 + orgId: params.orgId,
848 + projectId: params.projectId,
849 + }),
850 + client =>
851 + client.post<unknown>(`/api/v3/org/project/${params.projectId}/api_keys/create`, {
852 + body: { name: params.name },
853 + maxRetries: 0,
854 + })
855 + );
856 + const createdApiKey = getApiKeyFromPayload(payload);
857
1769 -/**
1770 - * Build the `authConfigs` namespace for ComposioClientLive.
1771 - * Extracted to keep the main generator under the max-lines-per-function limit.
1772 - */
1773 -function buildAuthConfigsNamespace(
1774 - clientSingleton: ComposioClientSingletonShape,
1775 - withMetrics: <A, E, R>(
1776 - effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1777 - ) => Effect.Effect<A, E, R>
1778 -) {
1779 - return {
1780 - /**
1781 - * List auth configs with optional filters. Returns a single page of results.
1782 - * @param params - Search/filter parameters
1783 - */
1784 - list: (params: {
1785 - search?: string;
1786 - toolkit_slug?: string;
1787 - limit?: number;
1788 - show_disabled?: boolean;
1789 - }) =>
1790 - withMetrics(
1791 - callClient(
1792 - clientSingleton,
1793 - client =>
1794 - client.authConfigs.list({
1795 - search: params.search,
1796 - toolkit_slug: params.toolkit_slug,
1797 - limit: params.limit,
1798 - show_disabled: params.show_disabled ?? true,
1799 - }),
1800 - AuthConfigListResponse
1801 - )
1802 - ),
1803 - /**
1804 - * Retrieves detailed info about a single auth config by its nanoid.
1805 - * @param nanoid - Auth config ID
1806 - */
1807 - retrieve: (nanoid: string) =>
1808 - withMetrics(
1809 - callClient(
1810 - clientSingleton,
1811 - client => client.authConfigs.retrieve(nanoid),
1812 - AuthConfigRetrieveResponse
1813 - )
1814 - ),
1815 - /**
1816 - * Creates a new auth config for a toolkit.
1817 - * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
1818 - */
1819 - create: (params: AuthConfigCreateParams) =>
1820 - withMetrics(
1821 - callClient(
1822 - clientSingleton,
1823 - client => client.authConfigs.create(params),
1824 - AuthConfigCreateResponse
1825 - )
1826 - ),
1827 - /**
1828 - * Soft-deletes an auth config by its nanoid.
1829 - * @param nanoid - Auth config ID
1830 - */
1831 - delete: (nanoid: string) =>
1832 - withMetrics(
1833 - callClient(clientSingleton, client => client.authConfigs.delete(nanoid), Schema.Unknown)
1834 - ),
1835 - };
1836 -}
858 + if (!createdApiKey) {
859 + return yield* Effect.fail(
860 + new HttpDecodingError({
861 + cause: 'Create API key response did not contain an API key',
862 + })
863 + );
864 + }
865 +
866 + return createdApiKey;
867 + });
868 +
869 +export const resolveConsumerProject = (params: {
870 + apiKey: string;
871 + orgId: string;
872 +}): Effect.Effect<ConsumerProjectResolveResponse, ClientError, ComposioClientSingleton> =>
873 + Effect.gen(function* () {
874 + const clientSingleton = yield* ComposioClientSingleton;
875 + return yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
876 + client.org.consumer.project.resolve({
877 + 'x-user-api-key': params.apiKey,
878 + 'x-org-id': params.orgId,
879 + })
880 + );
881 + });
882
883 /**
1839 - * Build the `connectedAccounts` namespace for ComposioClientLive.
1840 - * Extracted to keep the main generator under the max-lines-per-function limit.
884 + * Resolves the latest version of a tool. When `projectApiKey` is given the
885 + * request carries `x-api-key` instead of the user key, so exactly one
886 + * credential is sent.
887 */
1842 -function buildConnectedAccountsNamespace(
1843 - clientSingleton: ComposioClientSingletonShape,
1844 - withMetrics: <A, E, R>(
1845 - effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1846 - ) => Effect.Effect<A, E, R>
1847 -) {
1848 - return {
1849 - /**
1850 - * List connected accounts with optional filters. Returns a single page of results.
1851 - * @param params - Search/filter parameters
1852 - */
1853 - list: (params: {
1854 - toolkit_slugs?: string[];
1855 - user_ids?: string[];
1856 - statuses?: string[];
1857 - limit?: number;
1858 - }) =>
1859 - withMetrics(
1860 - callClient(
1861 - clientSingleton,
1862 - client =>
1863 - client.connectedAccounts.list({
1864 - toolkit_slugs: params.toolkit_slugs,
1865 - user_ids: params.user_ids,
1866 - // Bypass the stale Stainless union (still missing 'REVOKED')
1867 - // until @composio/client is regenerated.
1868 - statuses: params.statuses as ConnectedAccountListParams['statuses'],
1869 - limit: params.limit,
1870 - }),
1871 - ConnectedAccountListResponse
1872 - )
1873 - ),
1874 - /**
1875 - * Retrieves detailed info about a single connected account by its nanoid.
1876 - * @param nanoid - Connected account ID (e.g. "con_1a2b3c4d5e6f")
1877 - */
1878 - retrieve: (nanoid: string) =>
1879 - withMetrics(
1880 - callClient(
1881 - clientSingleton,
1882 - client => client.connectedAccounts.retrieve(nanoid),
1883 - ConnectedAccountRetrieveResponse
1884 - )
1885 - ),
1886 - /**
1887 - * Soft-deletes a connected account by its nanoid.
1888 - * @param nanoid - Connected account ID
1889 - */
1890 - delete: (nanoid: string) =>
1891 - withMetrics(
1892 - callClient(
1893 - clientSingleton,
1894 - client => client.connectedAccounts.delete(nanoid),
1895 - Schema.Unknown
888 +export const getLatestToolVersion = (params: {
889 + apiKey: string;
890 + toolSlug: string;
891 + orgId?: string;
892 + projectId?: string;
893 + projectApiKey?: string;
894 +}): Effect.Effect<LatestToolVersionResponse, ClientError, ComposioClientSingleton> =>
895 + Effect.gen(function* () {
896 + const clientSingleton = yield* ComposioClientSingleton;
897 + const headers = {
898 + ...(params.projectApiKey
899 + ? { 'x-api-key': params.projectApiKey, 'x-user-api-key': null }
900 + : {}),
901 + ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
902 + ...(params.projectId ? { 'x-project-id': params.projectId } : {}),
903 + };
904 + const payload = yield* request(
905 + clientSingleton.getFor({
906 + userApiKey: params.apiKey,
907 + orgId: params.orgId,
908 + projectId: params.projectId,
909 + }),
910 + client =>
911 + client.get<unknown>(
912 + `/api/v3/tools/${encodeURIComponent(params.toolSlug)}/get_latest_version`,
913 + { headers }
914 )
1897 - ),
1898 - /**
1899 - * Creates a new authentication link session for connecting an external account.
1900 - * @param params - auth_config_id and user_id
1901 - */
1902 - createLink: (params: { auth_config_id: string; user_id: string }) =>
1903 - withMetrics(
1904 - callClient(clientSingleton, client => client.link.create(params), LinkCreateResponse)
1905 - ),
1906 - };
1907 -}
915 + );
916 + return yield* decode(LatestToolVersionResponse)(payload);
917 + });
918
1909 -// Service that wraps the raw Composio client, which is shared by all client services.
1910 -const makeComposioClientLive = Effect.gen(function* () {
1911 - const clientSingleton = yield* ComposioClientSingleton;
919 +export const getConsumerConnectedToolkits = (params: {
920 + apiKey: string;
921 + orgId: string;
922 + consumerUserId: string;
923 +}): Effect.Effect<ConsumerConnectedToolkitsResponse, ClientError, ComposioClientSingleton> =>
924 + Effect.gen(function* () {
925 + const clientSingleton = yield* ComposioClientSingleton;
926 + return yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
927 + client.org.consumer.listConnectedToolkits({
928 + user_id: params.consumerUserId,
929 + 'x-user-api-key': params.apiKey,
930 + 'x-org-id': params.orgId,
931 + })
932 + );
933 + });
934
1913 - // Initialize metrics tracking via SynchronizedRef
1914 - const metricsRef = yield* SynchronizedRef.make<Metrics>({ byteSize: 0, requests: 0 });
935 +export class DeveloperProjectNotFoundError extends Data.TaggedError(
936 + 'services/DeveloperProjectNotFoundError'
937 +)<{
938 + readonly orgId: string;
939 + readonly projectName: string;
940 +}> {}
941
1916 - // Helper to update metrics and return just the data
1917 - const withMetrics = <A, E, R>(
1918 - effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1919 - ): Effect.Effect<A, E, R> =>
1920 - Effect.gen(function* () {
1921 - const { data, metrics } = yield* effect;
1922 - yield* SynchronizedRef.update(metricsRef, current => ({
1923 - byteSize: current.byteSize + metrics.byteSize,
1924 - requests: current.requests + metrics.requests,
1925 - }));
1926 - return data;
942 +export class AmbiguousDeveloperProjectNameError extends Data.TaggedError(
943 + 'services/AmbiguousDeveloperProjectNameError'
944 +)<{
945 + readonly orgId: string;
946 + readonly projectName: string;
947 + readonly matches: ReadonlyArray<OrganizationProjectSummary>;
948 +}> {}
949 +
950 +export const findDeveloperProjectByName = (params: {
951 + apiKey: string;
952 + orgId: string;
953 + name: string;
954 + limit?: number;
955 +}): Effect.Effect<
956 + OrganizationProjectSummary,
957 + DeveloperProjectNotFoundError | AmbiguousDeveloperProjectNameError | ClientError,
958 + ComposioClientSingleton
959 +> =>
960 + Effect.gen(function* () {
961 + const projects = yield* listOrgProjects({
962 + apiKey: params.apiKey,
963 + orgId: params.orgId,
964 + limit: params.limit,
965 });
966
1929 - return {
1930 - /**
1931 - * Returns a snapshot of the current accumulated metrics (total bytes received and request count).
1932 - */
1933 - getMetrics: () => SynchronizedRef.get(metricsRef),
1934 - toolkits: {
1935 - /**
1936 - * Retrieves a comprehensive list of toolkits that are available to the authenticated project.
1937 - * Automatically handles pagination to fetch all items.
1938 - * @param managedBy - Which toolkits to list; the API defaults to Composio-managed ones
1939 - * @param scope - The org/project to list for, instead of the one the project context resolves
1940 - */
1941 - list: (managedBy?: 'composio' | 'project' | 'all', scope?: ToolkitProjectScope) =>
1942 - withMetrics(
1943 - callClientWithPagination(
1944 - scope ? scopedClientSingleton(clientSingleton, scope) : clientSingleton,
1945 - (client, cursor, limit) =>
1946 - client.toolkits.list({ cursor, limit, managed_by: managedBy }),
1947 - ToolkitsResponse
1948 - )
1949 - ),
1950 - /**
1951 - * Retrieves a single toolkit by its slug.
1952 - * Transforms the response to match the Toolkit schema.
1953 - */
1954 - retrieve: (slug: string) =>
1955 - withMetrics(
1956 - callClient(
1957 - clientSingleton,
1958 - client => client.toolkits.retrieve(slug),
1959 - ToolkitRetrieveResponse
1960 - )
1961 - ).pipe(
1962 - // Transform to Toolkit format by adding missing fields
1963 - Effect.map(
1964 - retrieved =>
1965 - ({
1966 - name: retrieved.name,
1967 - slug: retrieved.slug,
1968 - auth_schemes: [], // retrieve endpoint doesn't return auth_schemes
1969 - composio_managed_auth_schemes: retrieved.composio_managed_auth_schemes,
1970 - is_local_toolkit: retrieved.is_local_toolkit,
1971 - no_auth: retrieved.no_auth,
1972 - meta: retrieved.meta,
1973 - }) satisfies Toolkit
1974 - )
1975 - ),
1976 - /**
1977 - * Searches toolkits with optional filters. Returns a single page of results (no auto-pagination).
1978 - * @param params - Search/filter parameters
1979 - */
1980 - search: (params: { search?: string; category?: string; limit?: number; cursor?: string }) =>
1981 - withMetrics(
1982 - callClient(
1983 - clientSingleton,
1984 - client =>
1985 - client.toolkits.list({
1986 - search: params.search,
1987 - category: params.category,
1988 - limit: params.limit,
1989 - cursor: params.cursor,
1990 - }),
1991 - ToolkitSearchResponse
1992 - )
1993 - ).pipe(
1994 - Effect.map(
1995 - response =>
1996 - ({
1997 - items: response.items,
1998 - total_items: response.total_items,
1999 - total_pages: response.total_pages,
2000 - next_cursor: response.next_cursor,
2001 - }) satisfies ToolkitSearchResult
2002 - )
2003 - ),
2004 - /**
2005 - * Retrieves detailed toolkit info including auth_config_details.
2006 - * @param slug - Toolkit slug
2007 - */
2008 - retrieveDetailed: (slug: string) =>
2009 - withMetrics(
2010 - callClient(
2011 - clientSingleton,
2012 - client => client.toolkits.retrieve(slug),
2013 - ToolkitDetailedResponse
2014 - )
2015 - ),
2016 - },
2017 - tools: buildToolsNamespace(clientSingleton, withMetrics),
2018 - triggersTypes: {
2019 - /**
2020 - * Retrieves a list of all available trigger type enum values that can be used across the API.
2021 - */
2022 - retrieveEnum: () =>
2023 - withMetrics(
2024 - callClient(
2025 - clientSingleton,
2026 - client => client.triggersTypes.retrieveEnum(),
2027 - TriggerTypesAsEnumsResponse
2028 - )
2029 - ),
2030 - /**
2031 - * Retrieves detailed info about a single trigger type by slug.
2032 - * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
2033 - */
2034 - retrieve: (slug: string) =>
2035 - withMetrics(
2036 - callClient(clientSingleton, client => client.triggersTypes.retrieve(slug), TriggerType)
2037 - ),
2038 - /**
2039 - * Retrieve a list of trigger types, automatically handling pagination.
2040 - * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2041 - */
2042 - list: (toolkitSlugs?: ReadonlyArray<string>) =>
2043 - withMetrics(
2044 - callClientWithPagination(
2045 - clientSingleton,
2046 - (client, cursor, limit) =>
2047 - client.triggersTypes.list({
2048 - cursor,
2049 - limit,
2050 - toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,
2051 - }),
2052 - TriggerTypesResponse
2053 - )
2054 - ),
2055 - },
2056 - triggerInstances: buildTriggerInstancesNamespace(clientSingleton, withMetrics),
2057 - cli: {
2058 - /**
2059 - * Generates a new CLI session with a random 6-character code.
2060 - * @param params.scope - 'user' for login, 'project' for init (future)
2061 - *
2062 - * TODO: don't use `@composio/client`, wrap `fetch` directly.
2063 - */
2064 - createSession: (params?: { scope?: 'user' | 'project' }) =>
2065 - withMetrics(
2066 - callClient(
2067 - clientSingleton,
2068 - client =>
2069 - client.cli.createSession(
2070 - { scope: params?.scope ?? 'user' },
2071 - { headers: { 'Content-Type': 'application/json' } }
2072 - ),
2073 - CliCreateSessionResponse
2074 - )
2075 - ),
967 + const normalizedName = String.toLowerCase(params.name.trim());
968 + const matches = projects.data.filter(
969 + project => String.toLowerCase(project.name) === normalizedName
970 + );
971
2077 - /**
2078 - * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.
2079 - */
2080 - getSession: (session: { id: string }) =>
2081 - withMetrics(
2082 - callClient(
2083 - clientSingleton,
2084 - client => client.cli.getSession(session),
2085 - CliGetSessionResponse
2086 - )
2087 - ),
2088 - getRealtimeCredentials: () =>
2089 - withMetrics(
2090 - callClient(
2091 - clientSingleton,
2092 - client => client.cli.realtime.credentials(),
2093 - CliRealtimeCredentialsResponse
2094 - )
2095 - ),
2096 - authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2097 - withMetrics(
2098 - callClient(
2099 - clientSingleton,
2100 - client => client.cli.realtime.auth(params),
2101 - CliRealtimeAuthResponse
2102 - )
2103 - ),
2104 - },
2105 - authConfigs: buildAuthConfigsNamespace(clientSingleton, withMetrics),
2106 - connectedAccounts: buildConnectedAccountsNamespace(clientSingleton, withMetrics),
2107 - };
2108 -});
972 + if (matches.length === 0) {
973 + return yield* Effect.fail(
974 + new DeveloperProjectNotFoundError({
975 + orgId: params.orgId,
976 + projectName: params.name,
977 + })
978 + );
979 + }
980 +
981 + if (matches.length > 1) {
982 + return yield* Effect.fail(
983 + new AmbiguousDeveloperProjectNameError({
984 + orgId: params.orgId,
985 + projectName: params.name,
986 + matches,
987 + })
988 + );
989 + }
990
2110 -export type ComposioClientLiveShape = Effect.Success<typeof makeComposioClientLive>;
991 + return matches[0];
992 + });
993
2112 -export class ComposioClientLive extends Context.Service<
2113 - ComposioClientLive,
2114 - ComposioClientLiveShape
2115 ->()('services/ComposioClientLive') {
2116 - static readonly Default = Layer.effect(ComposioClientLive, makeComposioClientLive).pipe(
2117 - Layer.provide(ComposioClientSingleton.Default)
2118 - );
2119 -}
994 +/**
995 + * Repositories
996 + */
997 +
998 +/**
999 + * Auth config, connected account, and trigger instance operations: single-page
1000 + * CRUD with no catalog caching.
1001 + */
1002 +const resourceOperations = (client: Effect.Effect<_RawComposioClient, ClientError>) => ({
1003 + /**
1004 + * Lists auth configs with optional filters. Returns a single page of results.
1005 + * @param params - Search/filter parameters
1006 + */
1007 + listAuthConfigs: (params: {
1008 + search?: string;
1009 + toolkit_slug?: string;
1010 + limit?: number;
1011 + show_disabled?: boolean;
1012 + }) =>
1013 + request(client, c =>
1014 + c.authConfigs.list({
1015 + search: params.search,
1016 + toolkit_slug: params.toolkit_slug,
1017 + limit: params.limit,
1018 + show_disabled: params.show_disabled ?? true,
1019 + })
1020 + ).pipe(Effect.flatMap(decode(AuthConfigListResponse))),
1021 + /**
1022 + * Retrieves detailed info about a single auth config by its nanoid.
1023 + * @param nanoid - Auth config ID
1024 + */
1025 + getAuthConfig: (nanoid: string) =>
1026 + request(client, c => c.authConfigs.retrieve(nanoid)).pipe(
1027 + Effect.flatMap(decode(AuthConfigItem))
1028 + ),
1029 + /**
1030 + * Creates a new auth config for a toolkit.
1031 + * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
1032 + */
1033 + createAuthConfig: (params: AuthConfigCreateParams) =>
1034 + request(client, c => c.authConfigs.create(params)).pipe(
1035 + Effect.flatMap(decode(AuthConfigCreateResponse))
1036 + ),
1037 + /**
1038 + * Soft-deletes an auth config by its nanoid.
1039 + * @param nanoid - Auth config ID
1040 + */
1041 + deleteAuthConfig: (nanoid: string) => request(client, c => c.authConfigs.delete(nanoid)),
1042 + /**
1043 + * List connected accounts with optional filters. Returns a single page of results.
1044 + * @param params - Search/filter parameters
1045 + */
1046 + listConnectedAccounts: (params: {
1047 + toolkit_slugs?: string[];
1048 + user_ids?: string[];
1049 + statuses?: ConnectedAccountListParams['statuses'];
1050 + limit?: number;
1051 + }) =>
1052 + request(client, c =>
1053 + c.connectedAccounts.list({
1054 + toolkit_slugs: params.toolkit_slugs,
1055 + user_ids: params.user_ids,
1056 + statuses: params.statuses,
1057 + limit: params.limit,
1058 + })
1059 + ).pipe(Effect.flatMap(decode(ConnectedAccountListResponse))),
1060 + /**
1061 + * Retrieves detailed info about a single connected account by its nanoid.
1062 + * @param nanoid - Connected account ID (e.g. "con_1a2b3c4d5e6f")
1063 + */
1064 + getConnectedAccount: (nanoid: string) =>
1065 + request(client, c => c.connectedAccounts.retrieve(nanoid)).pipe(
1066 + Effect.flatMap(decode(ConnectedAccountItem))
1067 + ),
1068 + /**
1069 + * Soft-deletes a connected account by its nanoid.
1070 + * @param nanoid - Connected account ID
1071 + */
1072 + deleteConnectedAccount: (nanoid: string) =>
1073 + request(client, c => c.connectedAccounts.delete(nanoid)),
1074 + /**
1075 + * Creates a new authentication link session for connecting an external account.
1076 + * @param params - auth_config_id and user_id
1077 + */
1078 + createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>
1079 + request(client, c => c.link.create(params)),
1080 + /**
1081 + * Lists active trigger instances with optional filters.
1082 + * Returns a single page of results.
1083 + */
1084 + listActiveTriggers: (params: TriggerInstancesListActiveParams) =>
1085 + request(client, c =>
1086 + c.triggerInstances.listActive({
1087 + user_ids: params.user_ids,
1088 + connected_account_ids: params.connected_account_ids,
1089 + auth_config_ids: params.auth_config_ids,
1090 + trigger_ids: params.trigger_ids,
1091 + trigger_names: params.trigger_names,
1092 + show_disabled: params.show_disabled,
1093 + limit: params.limit,
1094 + })
1095 + ).pipe(
1096 + Effect.flatMap(response =>
1097 + decode(TriggerInstanceItems)(response.items).pipe(
1098 + // `triggers status` prints `total_items` directly, so a response that
1099 + // omits a count renders as a number rather than `undefined`.
1100 + Effect.map(items => ({
1101 + ...response,
1102 + items,
1103 + total_items: response.total_items ?? items.length,
1104 + total_pages: response.total_pages ?? 1,
1105 + current_page: response.current_page ?? 1,
1106 + next_cursor: response.next_cursor ?? null,
1107 + }))
1108 + )
1109 + )
1110 + ),
1111 + createTrigger: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
1112 + request(client, c => c.triggerInstances.upsert(triggerSlug, params)),
1113 + enableTrigger: (triggerId: string) =>
1114 + request(client, c => c.triggerInstances.manage.update(triggerId, { status: 'enable' })),
1115 + disableTrigger: (triggerId: string) =>
1116 + request(client, c => c.triggerInstances.manage.update(triggerId, { status: 'disable' })),
1117 + deleteTrigger: (triggerId: string) =>
1118 + request(client, c => c.triggerInstances.manage.delete(triggerId)),
1119 +});
1120
1121 const makeComposioToolkitsRepository = Effect.gen(function* () {
2122 - const client = yield* ComposioClientLive;
1122 + const clientSingleton = yield* ComposioClientSingleton;
1123 + const client = clientSingleton.get();
1124
1125 const listToolkits = (managedBy?: 'project', scope?: ToolkitProjectScope) =>
2125 - client.toolkits.list(managedBy, scope).pipe(
2126 - Effect.map(response => response.items),
2127 - Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>)
1126 + requestAll(scope ? clientSingleton.getFor(scope) : client, (c, { cursor, limit }, signal) =>
1127 + c.toolkits.list({ cursor, limit, managed_by: managedBy }, { signal })
1128 + ).pipe(Effect.flatMap(decode(Toolkits)), Effect.map(sortBySlug));
1129 +
1130 + const getToolkitDetailed = (slug: string) =>
1131 + request(client, c => c.toolkits.retrieve(slug)).pipe(Effect.flatMap(decode(ToolkitDetailed)));
1132 +
1133 + // The retrieve endpoint omits `auth_schemes`; fill it so the result
1134 + // satisfies the catalog `Toolkit` contract.
1135 + const getToolkit = (slug: string): Effect.Effect<Toolkit, ClientError> =>
1136 + getToolkitDetailed(slug).pipe(
1137 + Effect.map(({ auth_config_details: _authConfigDetails, ...toolkit }) => ({
1138 + ...toolkit,
1139 + auth_schemes: [],
1140 + }))
1141 );
1142
1143 const getToolkits = () => listToolkits();
@@ -2145,69 +1158,78 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
1158 */
1159 const getToolkitsBySlugs = (slugs: ReadonlyArray<string>) =>
1160 Effect.all(
2148 - slugs.map(slug =>
2149 - client.toolkits.retrieve(slug).pipe(
2150 - // Only convert 404 errors to InvalidToolkitsError.
2151 - // Other HTTP errors (500, 401, network failures, etc.) should propagate as-is.
2152 - Effect.catchTag(
2153 - 'services/HttpServerError',
2154 - (e): Effect.Effect<never, InvalidToolkitsError | HttpServerError> =>
2155 - e.status === 404
2156 - ? Effect.fail(
2157 - new InvalidToolkitsError({
2158 - invalidToolkits: [slug],
2159 - availableToolkits: [],
2160 - })
2161 - )
2162 - : Effect.fail(e)
2163 - )
2164 - )
2165 - ),
1161 + slugs.map(slug => invalidToolkitOn404(slug, getToolkit(slug))),
1162 { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
2167 - ).pipe(Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>));
1163 + ).pipe(Effect.map(sortBySlug));
1164 +
1165 + const listTools = (query: { toolkit_slug?: string; toolkit_versions: string }) =>
1166 + requestAll(client, (c, { cursor, limit }, signal) =>
1167 + c.tools.list({ ...query, cursor, limit }, { signal })
1168 + ).pipe(Effect.flatMap(decode(Tools)));
1169
1170 return {
1171 getToolkits,
1172 getProjectToolkits,
1173 getToolkitsBySlugs,
2173 - getMetrics: () => client.getMetrics(),
2174 - getToolsAsEnums: () => client.tools.retrieveEnum(),
1174 + getMetrics: () => clientSingleton.getMetrics(),
1175 + /**
1176 + * Retrieve a list of all available tool enumeration values (tool slugs) for the project.
1177 + */
1178 + getToolsAsEnums: () =>
1179 + request(client, c => c.tools.retrieveEnum()).pipe(Effect.flatMap(decode(ToolsAsEnums))),
1180 /**
2176 - * Fetches tools with optional toolkit filtering.
2177 - * When toolkitSlugs is provided, fetches all matching tools.
1181 + * Fetches tools with optional toolkit filtering, always at the latest
1182 + * toolkit version. For per-toolkit versions use `getToolsByVersionSpecs`.
1183 * @param toolkitSlugs - Optional array of toolkit slugs to filter by
1184 */
1185 getTools: (toolkitSlugs?: ReadonlyArray<string>) =>
2181 - client.tools.list(toolkitSlugs ?? []).pipe(
2182 - Effect.map(response => response.items),
2183 - Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2184 - ),
1186 + listTools({
1187 + toolkit_slug: toolkitSlugs && toolkitSlugs.length > 0 ? toolkitSlugs.join(',') : undefined,
1188 + toolkit_versions: 'latest',
1189 + }).pipe(Effect.map(sortBySlug)),
1190 /**
1191 * Fetches tools with per-toolkit version support.
1192 * Groups toolkits by version and makes separate API calls for each group.
1193 * @param specs - Array of { toolkitSlug, toolkitVersion } specifications
1194 */
1195 getToolsByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>
2191 - client.tools.listByVersionSpecs(specs).pipe(
2192 - Effect.map(response => response.items),
2193 - Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
1196 + Effect.all(
1197 + [...groupByVersion(specs).entries()].map(([version, slugs]) =>
1198 + listTools({ toolkit_slug: slugs.join(','), toolkit_versions: version })
1199 + ),
1200 + { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
1201 + ).pipe(Effect.map(groups => sortBySlug(groups.flat()))),
1202 + /**
1203 + * Retrieves a list of all available trigger type enum values that can be used across the API.
1204 + */
1205 + getTriggerTypesAsEnums: () =>
1206 + request(client, c => c.triggersTypes.retrieveEnum()).pipe(
1207 + Effect.flatMap(decode(TriggerTypesAsEnums))
1208 ),
2195 - getTriggerTypesAsEnums: () => client.triggersTypes.retrieveEnum(),
1209 /**
1210 * Retrieves detailed info about a single trigger type by slug.
1211 * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
1212 */
2200 - getTriggerTypeDetailed: (slug: string) => client.triggersTypes.retrieve(slug),
1213 + getTriggerTypeDetailed: (slug: string) =>
1214 + request(client, c => c.triggersTypes.retrieve(slug)).pipe(
1215 + Effect.flatMap(decode(TriggerType))
1216 + ),
1217 /**
1218 * Fetches trigger types with optional toolkit filtering.
1219 * When toolkitSlugs is provided, fetches all matching trigger types.
1220 * @param toolkitSlugs - Optional array of toolkit slugs to filter by
1221 */
1222 getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>
2207 - client.triggersTypes.list(toolkitSlugs).pipe(
2208 - Effect.map(response => response.items),
2209 - Effect.map(items => sortBySlug(items) as ReadonlyArray<TriggerType>)
2210 - ),
1223 + requestAll(client, (c, { cursor, limit }, signal) =>
1224 + c.triggersTypes.list(
1225 + {
1226 + cursor,
1227 + limit,
1228 + toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,
1229 + },
1230 + { signal }
1231 + )
1232 + ).pipe(Effect.flatMap(decode(TriggerTypes)), Effect.map(sortBySlug)),
1233 /**
1234 * Validates that the given toolkit slugs are valid by comparing them against the list
1235 * of available toolkits. Returns the list of valid toolkit slugs (normalized to lowercase).
@@ -2215,10 +1237,7 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
1237 */
1238 validateToolkits: (
1239 toolkitSlugs: ReadonlyArray<string>
2218 - ): Effect.Effect<
2219 - ReadonlyArray<string>,
2220 - InvalidToolkitsError | HttpError | NoSuchElementError
2221 - > =>
1240 + ): Effect.Effect<ReadonlyArray<string>, InvalidToolkitsError | ClientError> =>
1241 Effect.gen(function* () {
1242 // Normalize input slugs to lowercase for comparison
1243 const normalizedInputSlugs = toolkitSlugs.map(slug => String.toLowerCase(slug));
@@ -2269,8 +1288,8 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
1288 validatedOverrides: ToolkitVersionOverrides;
1289 warnings: ReadonlyArray<string>;
1290 },
2272 - InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementError
2273 - > => validateToolkitVersionsImpl(client, overrides, relevantToolkits),
1291 + InvalidToolkitVersionsError | InvalidToolkitsError | ClientError
1292 + > => validateToolkitVersionsImpl(getToolkit, overrides, relevantToolkits),
1293 /**
1294 * Searches toolkits with optional filters. Returns a single page of results.
1295 * @param params - Search/filter parameters
@@ -2280,12 +1299,34 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
1299 category?: string;
1300 limit?: number;
1301 cursor?: string;
2283 - }) => client.toolkits.search(params),
1302 + }): Effect.Effect<ToolkitSearchResult, ClientError> =>
1303 + request(client, c =>
1304 + c.toolkits.list({
1305 + search: params.search,
1306 + category: params.category,
1307 + limit: params.limit,
1308 + cursor: params.cursor,
1309 + })
1310 + ).pipe(
1311 + Effect.flatMap(response =>
1312 + decode(Toolkits)(response.items).pipe(
1313 + Effect.map(
1314 + items =>
1315 + ({
1316 + items,
1317 + total_items: response.total_items,
1318 + total_pages: response.total_pages,
1319 + next_cursor: response.next_cursor ?? null,
1320 + }) satisfies ToolkitSearchResult
1321 + )
1322 + )
1323 + )
1324 + ),
1325 /**
1326 * Retrieves detailed toolkit info including auth_config_details.
1327 * @param slug - Toolkit slug
1328 */
2288 - getToolkitDetailed: (slug: string) => client.toolkits.retrieveDetailed(slug),
1329 + getToolkitDetailed,
1330 /**
1331 * Searches tools with optional filters. Returns a single page of results.
1332 * @param params - Search/filter parameters
@@ -2296,45 +1337,24 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
1337 tags?: string;
1338 limit?: number;
1339 cursor?: string;
2299 - }) => client.tools.search(params),
1340 + }) =>
1341 + request(client, c =>
1342 + c.tools.list({
1343 + search: params.search,
1344 + toolkit_slug: params.toolkit_slug,
1345 + tags: params.tags ? params.tags.split(',').map(t => t.trim()) : undefined,
1346 + limit: params.limit,
1347 + cursor: params.cursor,
1348 + toolkit_versions: 'latest',
1349 + })
1350 + ),
1351 /**
1352 * Retrieves detailed info about a single tool by slug.
1353 * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")
1354 */
2304 - getToolDetailed: (slug: string) => client.tools.retrieve(slug),
2305 - /**
2306 - * Lists auth configs with optional filters. Returns a single page of results.
2307 - * @param params - Search/filter parameters
2308 - */
2309 - listAuthConfigs: (params: {
2310 - search?: string;
2311 - toolkit_slug?: string;
2312 - limit?: number;
2313 - show_disabled?: boolean;
2314 - }) => client.authConfigs.list(params),
2315 - /**
2316 - * Retrieves detailed info about a single auth config by its nanoid.
2317 - * @param nanoid - Auth config ID
2318 - */
2319 - getAuthConfig: (nanoid: string) => client.authConfigs.retrieve(nanoid),
2320 - /**
2321 - * Creates a new auth config for a toolkit.
2322 - * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
2323 - */
2324 - createAuthConfig: (params: AuthConfigCreateParams) => client.authConfigs.create(params),
2325 - deleteAuthConfig: (nanoid: string) => client.authConfigs.delete(nanoid),
2326 - // Connected account operations (thin wrappers — see buildConnectedAccountsNamespace)
2327 - listConnectedAccounts: (params: {
2328 - toolkit_slugs?: string[];
2329 - user_ids?: string[];
2330 - statuses?: string[];
2331 - limit?: number;
2332 - }) => client.connectedAccounts.list(params),
2333 - getConnectedAccount: (nanoid: string) => client.connectedAccounts.retrieve(nanoid),
2334 - deleteConnectedAccount: (nanoid: string) => client.connectedAccounts.delete(nanoid),
2335 - createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>
2336 - client.connectedAccounts.createLink(params),
2337 - ...buildTriggerInstanceRepositoryOperations(client),
1355 + getToolDetailed: (slug: string) =>
1356 + request(client, c => c.tools.retrieve(slug, { toolkit_versions: 'latest' })),
1357 + ...resourceOperations(client),
1358 };
1359 });
1360
@@ -2347,18 +1367,32 @@ export class ComposioToolkitsRepository extends Context.Service<
1367 static readonly Default = Layer.effect(
1368 ComposioToolkitsRepository,
1369 makeComposioToolkitsRepository
2350 - ).pipe(Layer.provide(ComposioClientLive.Default));
1370 + ).pipe(Layer.provide(ComposioClientSingleton.Default));
1371 }
1372
1373 const makeComposioSessionRepository = Effect.gen(function* () {
2354 - const client = yield* ComposioClientLive;
1374 + const clientSingleton = yield* ComposioClientSingleton;
1375 + const client = clientSingleton.get();
1376
1377 return {
2357 - createSession: (params?: { scope?: 'user' | 'project' }) => client.cli.createSession(params),
2358 - getSession: (session: { id: string }) => client.cli.getSession({ id: session.id }),
2359 - getRealtimeCredentials: () => client.cli.getRealtimeCredentials(),
1378 + /**
1379 + * Generates a new CLI session with a random 6-character code.
1380 + * @param params.scope - 'user' for login, 'project' for init (future)
1381 + */
1382 + createSession: (params?: { scope?: 'user' | 'project' }) =>
1383 + request(client, c => c.cli.createSession({ scope: params?.scope ?? 'user' })).pipe(
1384 + Effect.flatMap(decode(Session))
1385 + ),
1386 + /**
1387 + * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.
1388 + */
1389 + getSession: (session: { id: string }) =>
1390 + request(client, c => c.cli.getSession({ id: session.id })).pipe(
1391 + Effect.flatMap(decode(RetrievedSession))
1392 + ),
1393 + getRealtimeCredentials: () => request(client, c => c.cli.realtime.credentials()),
1394 authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2361 - client.cli.authRealtimeChannel(params),
1395 + request(client, c => c.cli.realtime.auth(params)),
1396 };
1397 });
1398
@@ -2371,5 +1405,5 @@ export class ComposioSessionRepository extends Context.Service<
1405 static readonly Default = Layer.effect(
1406 ComposioSessionRepository,
1407 makeComposioSessionRepository
2374 - ).pipe(Layer.provide(ComposioClientLive.Default));
1408 + ).pipe(Layer.provide(ComposioClientSingleton.Default));
1409 }
ts/packages/cli/src/services/composio-error-overrides.ts
+3 -47
@@ -2,7 +2,6 @@ import { Predicate } from 'effect';
2 import {
3 extractApiErrorDetails,
4 extractMessage,
5 - extractSlug,
5 type ApiErrorDetails,
6 } from 'src/utils/api-error-extraction';
7 import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
@@ -12,34 +11,6 @@ const NO_CONNECTION_SLUGS: ReadonlySet<string> = new Set([
11 'ToolRouterV2_NoActiveConnection',
12 ]);
13
15 -const extractNestedDetails = (value: unknown): unknown => {
16 - let current: unknown = value;
17 - const seen = new Set<unknown>();
18 -
19 - while (Predicate.isObject(current) && !seen.has(current)) {
20 - seen.add(current);
21 -
22 - if (Predicate.hasProperty(current, 'details')) {
23 - const details = current.details;
24 - if (details !== undefined) {
25 - return details;
26 - }
27 - }
28 -
29 - if (Predicate.hasProperty(current, 'error')) {
30 - current = current.error;
31 - continue;
32 - }
33 - if (Predicate.hasProperty(current, 'cause')) {
34 - current = current.cause;
35 - continue;
36 - }
37 - break;
38 - }
39 -
40 - return undefined;
41 -};
42 -
14 export const normalizeCliError = (error: unknown): unknown => {
15 let current: unknown = error;
16 const seen = new Set<unknown>();
@@ -124,25 +95,14 @@ export const mapComposioError = (params: {
95 readonly toolSlug?: string;
96 }) => {
97 const normalized = normalizeCliError(params.error);
127 - const nestedDetails = extractNestedDetails(params.error) ?? extractNestedDetails(normalized);
98 const apiDetails =
99 extractApiErrorDetails(params.error) ??
130 - extractApiErrorDetails(nestedDetails) ??
131 - extractApiErrorDetails(normalized) ??
100 (normalized instanceof ComposioNoActiveConnectionError ? normalized.apiDetails : undefined);
133 - const slugValue =
134 - apiDetails?.slug ??
135 - extractSlug(nestedDetails) ??
136 - extractSlug(params.error) ??
137 - extractSlug(normalized) ??
138 - (normalized instanceof ComposioNoActiveConnectionError
139 - ? normalized.apiDetails?.slug
140 - : undefined);
101 + const slugValue = apiDetails?.slug;
102
103 if (
104 normalized instanceof ComposioNoActiveConnectionError ||
144 - isNoActiveConnectionApiError(apiDetails) ||
145 - isNoConnectionSlug(slugValue)
105 + isNoActiveConnectionApiError(apiDetails)
106 ) {
107 const mapped =
108 normalized instanceof ComposioNoActiveConnectionError
@@ -170,11 +130,7 @@ export const mapComposioError = (params: {
130 normalized,
131 apiDetails,
132 slugValue,
173 - message:
174 - extractMessage(apiDetails) ??
175 - extractMessage(nestedDetails) ??
176 - extractMessage(normalized) ??
177 - 'Unknown error',
133 + message: extractMessage(apiDetails) ?? extractMessage(normalized) ?? 'Unknown error',
134 override: null,
135 };
136 };
ts/packages/cli/src/services/consumer-short-term-cache.ts
-3
@@ -399,7 +399,6 @@ const resolveConsumerScope = (params?: {
399 return null;
400 }
401 const consumerProject = yield* resolveConsumerProject({
402 - baseURL: userContext.data.baseURL,
402 apiKey,
403 orgId,
404 }).pipe(Effect.option);
@@ -433,7 +432,6 @@ export const refreshConsumerConnectedToolkitsCache = (params?: {
432 const clientSingleton = yield* ComposioClientSingleton;
433 const directToolkits = yield* Effect.gen(function* () {
434 const consumerProject = yield* resolveConsumerProject({
436 - baseURL: userContext.data.baseURL,
435 apiKey,
436 orgId: scope.orgId,
437 });
@@ -456,7 +454,6 @@ export const refreshConsumerConnectedToolkitsCache = (params?: {
454 Option.isSome(directToolkits) && directToolkits.value.connectedToolkits.length > 0
455 ? directToolkits.value.connectedToolkits
456 : (yield* getConsumerConnectedToolkits({
459 - baseURL: userContext.data.baseURL,
457 apiKey,
458 orgId: scope.orgId,
459 consumerUserId: scope.consumerUserId,
ts/packages/cli/src/services/tool-input-validation.ts
-2
@@ -197,9 +197,7 @@ const fetchLatestToolVersionOnce = memoizeInProcess({
197 }) => `${input.slug}\u0000${input.params?.orgId ?? ''}\u0000${input.params?.projectId ?? ''}`,
198 make: ({ slug, apiKey, params }) =>
199 Effect.gen(function* () {
200 - const userContext = yield* ComposioUserContext;
200 const latest = yield* getLatestToolVersion({
202 - baseURL: userContext.data.baseURL,
201 apiKey,
202 toolSlug: slug,
203 orgId: params?.orgId,
ts/packages/cli/src/services/tool-permissions.ts
+76 -64
@@ -1,6 +1,7 @@
1 import http from 'node:http';
2 import * as FileSystem from 'effect/FileSystem';
3 import * as Path from 'effect/Path';
4 +import type { Composio as RawComposioClient } from '@composio/client';
5 import open from 'open';
6 import { detectCliPlatform } from '@composio/cli-local-tools';
7 import {
@@ -22,6 +23,7 @@ import {
23 requestNativeUiPermissionDecision,
24 type NativeUiCallerAgent,
25 } from 'src/services/native-ui-sidecar';
26 +import { ComposioClientSingleton, type ClientError } from 'src/services/composio-clients';
27 import { ComposioUserContext } from 'src/services/user-context';
28
29 const ENHANCED_CONTROLS_UNSUPPORTED_PLATFORMS: ReadonlySet<string> = new Set(['darwin-x64']);
@@ -33,6 +35,11 @@ export const ENHANCED_LINK_URL_OVERWRITE = 'https://connect.composio.dev/enhance
35
36 const CACHE_FILE_NAME = 'tool-permissions-cache.json';
37 const PERMISSION_SNAPSHOT_CACHE_TTL_MS = 5 * 60 * 1000;
38 +
39 +// Each path is passed once for the request and once for the error payload, so
40 +// they live in constants to keep those uses in sync.
41 +const ORG_CONSUMER_CONFIG_PATH = '/api/v3.1/org/consumer/config';
42 +const CONSUMER_PERMISSIONS_RESOLVE_PATH = '/api/v3.1/consumer/permissions/resolve';
43 const ALLOW_FOR_DURATION_LABEL = '1 hr';
44 const ALLOW_FOR_DURATION_MS = 60 * 60 * 1000;
45 const NO_CONNECTED_ACCOUNT = '__none__';
@@ -185,7 +192,6 @@ const cachePath = (path: Path.Path, cacheDirectory: string) =>
192 path.join(cacheDirectory, CACHE_FILE_NAME);
193 const cacheKey = (params: { orgId: string; projectId: string; consumerUserId: string }) =>
194 [params.orgId, params.projectId, params.consumerUserId].join(':');
188 -const normalizeBaseUrl = (baseURL: string) => baseURL.replace(/\/$/, '');
195
196 const uniq = (values: ReadonlyArray<string | undefined>) => [
197 ...new Set(values.filter((value): value is string => Boolean(value))),
@@ -301,46 +307,73 @@ const isFreshForAccounts = (
307 const readEnhancedControlsFlag = (payload: ConsumerConfigResponse): boolean =>
308 payload.enhanced_controls === true || payload.enhancedControls === true;
309
304 -const fetchJson = async <S extends Schema.ConstraintDecoder<unknown>>(
310 +// These two consumer endpoints are absent from the v3.1 spec, so they go
311 +// through the client's generic escape hatch rather than a typed resource. The
312 +// client still supplies credentials, retries, and redirect handling.
313 +const requestJson = async <S extends Schema.ConstraintDecoder<unknown>>(
314 responseSchema: S,
315 {
307 - baseURL,
308 - apiKey,
309 - orgId,
310 - projectId,
316 + client,
317 path,
318 method = 'GET',
319 body,
320 }: {
315 - readonly baseURL: string;
316 - readonly apiKey: string;
317 - readonly orgId: string;
318 - readonly projectId: string;
321 + readonly client: RawComposioClient;
322 readonly path: string;
323 readonly method?: 'GET' | 'POST';
324 readonly body?: unknown;
325 }
326 ): Promise<S['Type']> => {
324 - const response = await fetch(`${normalizeBaseUrl(baseURL)}${path}`, {
325 - method,
326 - redirect: 'error',
327 - headers: {
328 - 'x-user-api-key': apiKey,
329 - 'x-org-id': orgId,
330 - 'x-project-id': projectId,
331 - 'User-Agent': '@composio/cli',
332 - Accept: 'application/json',
333 - 'Content-Type': 'application/json',
334 - },
335 - ...(body === undefined ? {} : { body: JSON.stringify(body) }),
336 - });
337 - if (!response.ok) {
338 - throw new Error(`HTTP ${response.status} ${response.statusText}`);
339 - }
340 - const responseBody: unknown = await response.json();
327 + const responseBody: unknown =
328 + method === 'GET' ? await client.get(path) : await client.post(path, { body });
329 return Schema.decodeUnknownPromise(responseSchema)(responseBody);
330 };
331
332 +/**
333 + * The client for the caller's org and project, with a failure the permission
334 + * paths already recover from.
335 + */
336 +const permissionsClient = (params: {
337 + readonly apiKey: string;
338 + readonly orgId: string;
339 + readonly projectId: string;
340 + readonly path: string;
341 +}): Effect.Effect<RawComposioClient, ToolPermissionsRequestError, ComposioClientSingleton> =>
342 + Effect.gen(function* () {
343 + const clientSingleton = yield* ComposioClientSingleton;
344 + return yield* clientSingleton
345 + .getFor({
346 + userApiKey: params.apiKey,
347 + orgId: params.orgId,
348 + projectId: params.projectId,
349 + })
350 + .pipe(
351 + Effect.mapError(
352 + (cause: ClientError) =>
353 + new ToolPermissionsRequestError({
354 + path: params.path,
355 + message: 'Failed to build a Composio client for the consumer permission request.',
356 + cause,
357 + })
358 + )
359 + );
360 + });
361 +
362 +const fetchConsumerConfig = (client: RawComposioClient) =>
363 + Effect.tryPromise({
364 + try: () =>
365 + requestJson(ConsumerConfigResponseSchema, {
366 + client,
367 + path: ORG_CONSUMER_CONFIG_PATH,
368 + }),
369 + catch: cause =>
370 + new ToolPermissionsRequestError({
371 + path: ORG_CONSUMER_CONFIG_PATH,
372 + message: 'Failed to fetch the org consumer config.',
373 + cause,
374 + }),
375 + });
376 +
377 export const refreshConsumerPermissionSnapshot = (params: {
378 readonly orgId: string;
379 readonly projectId: string;
@@ -356,22 +389,13 @@ export const refreshConsumerPermissionSnapshot = (params: {
389 if (!apiKey) return undefined;
390
391 const connectedAccountIds = uniq(params.connectedAccountIds ?? []);
359 - const config = yield* Effect.tryPromise({
360 - try: () =>
361 - fetchJson(ConsumerConfigResponseSchema, {
362 - baseURL: userContext.data.baseURL,
363 - apiKey,
364 - orgId: params.orgId,
365 - projectId: params.projectId,
366 - path: '/api/v3.1/org/consumer/config',
367 - }),
368 - catch: cause =>
369 - new ToolPermissionsRequestError({
370 - path: '/api/v3.1/org/consumer/config',
371 - message: 'Failed to fetch the org consumer config.',
372 - cause,
373 - }),
392 + const client = yield* permissionsClient({
393 + apiKey,
394 + orgId: params.orgId,
395 + projectId: params.projectId,
396 + path: ORG_CONSUMER_CONFIG_PATH,
397 });
398 + const config = yield* fetchConsumerConfig(client);
399 const platformSupportsEnhancedControls = isEnhancedControlsPlatformSupported();
400 const remoteEnhancedControlsEnabled = readEnhancedControlsFlag(config);
401 if (remoteEnhancedControlsEnabled && !platformSupportsEnhancedControls) {
@@ -385,12 +409,9 @@ export const refreshConsumerPermissionSnapshot = (params: {
409 enhancedControlsEnabled && connectedAccountIds.length > 0
410 ? yield* Effect.tryPromise({
411 try: () =>
388 - fetchJson(PermissionResolveResponseSchema, {
389 - baseURL: userContext.data.baseURL,
390 - apiKey,
391 - orgId: params.orgId,
392 - projectId: params.projectId,
393 - path: '/api/v3.1/consumer/permissions/resolve',
412 + requestJson(PermissionResolveResponseSchema, {
413 + client,
414 + path: CONSUMER_PERMISSIONS_RESOLVE_PATH,
415 method: 'POST',
416 body: {
417 connected_account_ids: connectedAccountIds,
@@ -399,7 +420,7 @@ export const refreshConsumerPermissionSnapshot = (params: {
420 }),
421 catch: cause =>
422 new ToolPermissionsRequestError({
402 - path: '/api/v3.1/consumer/permissions/resolve',
423 + path: CONSUMER_PERMISSIONS_RESOLVE_PATH,
424 message: 'Failed to resolve consumer permissions.',
425 cause,
426 }),
@@ -501,22 +522,13 @@ export const getOrgEnhancedControlsStatus = (params: {
522 const apiKey = Option.getOrUndefined(userContext.data.apiKey);
523 if (!apiKey) return undefined;
524
504 - const config = yield* Effect.tryPromise({
505 - try: () =>
506 - fetchJson(ConsumerConfigResponseSchema, {
507 - baseURL: userContext.data.baseURL,
508 - apiKey,
509 - orgId: params.orgId,
510 - projectId: params.projectId,
511 - path: '/api/v3.1/org/consumer/config',
512 - }),
513 - catch: cause =>
514 - new ToolPermissionsRequestError({
515 - path: '/api/v3.1/org/consumer/config',
516 - message: 'Failed to fetch the org consumer config.',
517 - cause,
518 - }),
525 + const client = yield* permissionsClient({
526 + apiKey,
527 + orgId: params.orgId,
528 + projectId: params.projectId,
529 + path: ORG_CONSUMER_CONFIG_PATH,
530 });
531 + const config = yield* fetchConsumerConfig(client);
532 const remoteEnabled = readEnhancedControlsFlag(config);
533 const platformSupported = isEnhancedControlsPlatformSupported();
534 return {
ts/packages/cli/src/services/tools-executor.ts
+1
@@ -86,6 +86,7 @@ export interface ToolsExecutor {
86 | NodeOs
87 | NodeProcess
88 | ComposioUserContext
89 + | ComposioClientSingleton
90 | ComposioToolkitsRepository
91 | ComposioCliUserConfig
92 | TerminalUI
ts/packages/cli/src/services/triggers-realtime.ts
+5 -6
@@ -10,12 +10,11 @@ import {
10 Layer,
11 } from 'effect';
12 import { JsonRecordSchema } from 'src/effects/json';
13 -import {
14 - ComposioClientSingleton,
15 - ComposioSessionRepository,
16 - type CliRealtimeAuthResponse,
17 - type CliRealtimeCredentialsResponse,
18 -} from 'src/services/composio-clients';
13 +import type {
14 + RealtimeAuthResponse as CliRealtimeAuthResponse,
15 + RealtimeCredentialsResponse as CliRealtimeCredentialsResponse,
16 +} from '@composio/client/resources/cli';
17 +import { ComposioClientSingleton, ComposioSessionRepository } from 'src/services/composio-clients';
18
19 const RawRealtimeEvent = JsonRecordSchema;
20 type RawRealtimeEvent = typeof RawRealtimeEvent.Type;
ts/packages/cli/src/utils/api-error-extraction.ts
+37 -104
@@ -1,14 +1,16 @@
1 /**
2 - * Utilities for extracting structured information from deeply-nested API errors.
2 + * Adapters from failures to the Composio API error envelope.
3 *
4 - * The Composio SDK wraps errors in multiple layers (ComposioToolExecutionError → API response → JSON body).
5 - * These functions traverse the `.error` / `.cause` chain to find the actual error details,
6 - * the error slug, and a human-readable message.
4 + * `@composio/client` rejects with an `APIError` whose `details` is the parsed
5 + * `{ error: { message, code, slug, ... } }` envelope. Effect wrappers keep the
6 + * original rejection in `.cause`, so the adapter walks that chain to the first
7 + * `APIError`.
8 *
9 * Used by both the `ToolsExecutor` service (for error classification) and the
10 * `tools execute` command (for error display).
11 */
12
13 +import { APIError } from '@composio/client';
14 import { Predicate } from 'effect';
15
16 export interface ApiErrorDetails {
@@ -20,31 +22,40 @@ export interface ApiErrorDetails {
22 readonly suggested_fix?: string;
23 }
24
23 -const pickString = (value: object, key: string): string | undefined =>
24 - Predicate.hasProperty(value, key) && Predicate.isString(value[key]) ? value[key] : undefined;
25 +/**
26 + * Returns the first `APIError` along the `.cause` chain, starting at `value`.
27 + */
28 +export const findApiError = (value: unknown): APIError | undefined => {
29 + const seen = new Set<unknown>();
30 + let current: unknown = value;
31
26 -const pickNumber = (value: object, key: string): number | undefined =>
27 - Predicate.hasProperty(value, key) && Predicate.isNumber(value[key]) ? value[key] : undefined;
32 + while (Predicate.isObject(current) && !seen.has(current)) {
33 + if (current instanceof APIError) return current;
34 + seen.add(current);
35 + current = Predicate.hasProperty(current, 'cause') ? current.cause : undefined;
36 + }
37
29 -// Field-by-field extraction: a present-but-mistyped field (e.g. a numeric
30 -// `message`) drops only that field, not the node's other perfectly good
31 -// details like `slug` and `request_id`.
32 -const extractCandidate = (value: object): ApiErrorDetails | undefined => {
33 - const candidate: ApiErrorDetails = {
34 - message: pickString(value, 'message'),
35 - code: pickNumber(value, 'code'),
36 - slug: pickString(value, 'slug'),
37 - status: pickNumber(value, 'status'),
38 - request_id: pickString(value, 'request_id'),
39 - suggested_fix: pickString(value, 'suggested_fix'),
38 + return undefined;
39 +};
40 +
41 +/**
42 + * The API error envelope carried by the first `APIError` in the cause chain,
43 + * with the HTTP status and request id. A body that is not the envelope keeps
44 + * the status and falls back to the error's own message.
45 + */
46 +export const extractApiErrorDetails = (value: unknown): ApiErrorDetails | undefined => {
47 + const apiError = findApiError(value);
48 + if (!apiError) return undefined;
49 +
50 + const details = apiError.details;
51 + return {
52 + message: details?.message ?? apiError.message,
53 + code: details?.code,
54 + slug: details?.slug,
55 + status: apiError.status,
56 + request_id: apiError.requestId ?? details?.request_id,
57 + suggested_fix: details?.suggested_fix,
58 };
41 - const hasAnyApiField =
42 - candidate.message !== undefined ||
43 - candidate.code !== undefined ||
44 - candidate.slug !== undefined ||
45 - candidate.status !== undefined ||
46 - candidate.request_id !== undefined;
47 - return hasAnyApiField ? candidate : undefined;
59 };
60
61 /**
@@ -87,81 +98,3 @@ export const extractMessage = (value: unknown, seen?: Set<unknown>): string | un
98
99 return undefined;
100 };
90 -
91 -/**
92 - * Walk the `.error` / `.cause` chain looking for a `slug` string field.
93 - */
94 -export const extractSlug = (value: unknown): string | undefined => {
95 - let current: unknown = value;
96 - const seen = new Set<unknown>();
97 -
98 - while (Predicate.isObject(current) && !seen.has(current)) {
99 - seen.add(current);
100 -
101 - if (Predicate.hasProperty(current, 'slug') && Predicate.isString(current.slug)) {
102 - return current.slug;
103 - }
104 -
105 - if (Predicate.hasProperty(current, 'error')) {
106 - current = current.error;
107 - continue;
108 - }
109 -
110 - if (Predicate.hasProperty(current, 'cause')) {
111 - current = current.cause;
112 - continue;
113 - }
114 -
115 - break;
116 - }
117 -
118 - return undefined;
119 -};
120 -
121 -/**
122 - * BFS through the `.error` / `.cause` chain to find a plain object with
123 - * API-specific fields (slug, request_id, code, status, message).
124 - *
125 - * Prefers objects with "strong" API fields (slug or request_id) over
126 - * objects that merely have a `message` (which any Error has).
127 - * Skips Error instances and Effect's UnknownException wrappers.
128 - */
129 -export const extractApiErrorDetails = (value: unknown): ApiErrorDetails | undefined => {
130 - const hasStrongApiFields = (candidate: ApiErrorDetails): boolean =>
131 - typeof candidate.slug === 'string' || typeof candidate.request_id === 'string';
132 -
133 - const seen = new Set<unknown>();
134 - const queue: unknown[] = [value];
135 - let head = 0;
136 - let fallback: ApiErrorDetails | undefined;
137 -
138 - while (head < queue.length) {
139 - const current = queue[head++];
140 - if (!Predicate.isObject(current) || seen.has(current)) {
141 - continue;
142 - }
143 - seen.add(current);
144 -
145 - const candidate = extractCandidate(current);
146 - const isWrapper = current instanceof Error || Predicate.isTagged(current, 'UnknownException');
147 -
148 - if (candidate !== undefined && !isWrapper) {
149 - if (hasStrongApiFields(candidate)) {
150 - return candidate;
151 - }
152 - if (!fallback) {
153 - fallback = candidate;
154 - }
155 - }
156 -
157 - if (Predicate.hasProperty(current, 'error')) {
158 - queue.push(current.error);
159 - }
160 -
161 - if (Predicate.hasProperty(current, 'cause')) {
162 - queue.push(current.cause);
163 - }
164 - }
165 -
166 - return fallback;
167 -};
ts/packages/cli/test/__utils__/models/account.ts new
+92
@@ -0,0 +1,92 @@
1 +import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
2 +import type { OrgProject } from 'src/services/composio-clients';
3 +
4 +export const TIMESTAMP = '2026-01-01T00:00:00.000Z';
5 +
6 +/**
7 + * A complete `GET /api/v3.1/auth/session/info` response. Suites override only
8 + * the fields their scenario is about.
9 + */
10 +export const makeSessionInfo = (
11 + params: {
12 + readonly orgId?: string;
13 + readonly orgName?: string;
14 + readonly projectId?: string;
15 + readonly projectNanoId?: string;
16 + readonly projectName?: string;
17 + readonly orgMemberId?: string;
18 + readonly userId?: string;
19 + readonly email?: string;
20 + readonly name?: string;
21 + readonly apiKey?: string;
22 + } = {}
23 +): SessionRetrieveInfoResponse => {
24 + const orgId = params.orgId ?? 'org_default';
25 + const projectId = params.projectId ?? 'project_id_default';
26 + return {
27 + project: {
28 + auto_id: 1,
29 + id: projectId,
30 + org_id: orgId,
31 + name: params.projectName ?? 'Default Project',
32 + email: 'project@example.com',
33 + nano_id: params.projectNanoId ?? 'project_default',
34 + created_at: TIMESTAMP,
35 + updated_at: TIMESTAMP,
36 + webhook_url: null,
37 + event_webhook_url: null,
38 + webhook_secret: null,
39 + triggers_enabled: true,
40 + last_subscribed_at: null,
41 + deleted: false,
42 + is_new_webhook: false,
43 + webhook_version: 'V3',
44 + org: { id: orgId, name: params.orgName ?? 'Example Org', plan: 'enterprise' },
45 + },
46 + api_key:
47 + params.apiKey === undefined
48 + ? null
49 + : {
50 + auto_id: 1,
51 + id: 'api_key_id',
52 + name: 'CLI key',
53 + project_id: projectId,
54 + org_member_id: params.orgMemberId ?? 'member_default',
55 + created_at: TIMESTAMP,
56 + updated_at: TIMESTAMP,
57 + deleted_at: null,
58 + key: params.apiKey,
59 + deleted: false,
60 + },
61 + org_member: {
62 + id: params.orgMemberId ?? 'member_default',
63 + email: params.email ?? 'cli@example.com',
64 + name: params.name ?? 'CLI User',
65 + role: 'admin',
66 + metadata: {},
67 + // Sent by the backend although the v3.1 spec omits it.
68 + ...(params.userId === undefined ? {} : { user_id: params.userId }),
69 + },
70 + };
71 +};
72 +
73 +/**
74 + * One entry of `GET /api/v3.1/org/project/list`.
75 + */
76 +export const makeOrgProject = (params: {
77 + readonly id: string;
78 + readonly name: string;
79 + readonly orgId?: string;
80 +}): OrgProject => ({
81 + id: params.id,
82 + org_id: params.orgId ?? 'org_default',
83 + name: params.name,
84 + email: 'project@example.com',
85 + created_at: TIMESTAMP,
86 + updated_at: TIMESTAMP,
87 + webhook_url: null,
88 + event_webhook_url: null,
89 + webhook_secret: null,
90 + webhook_version: 'V3',
91 + deleted: false,
92 +});
ts/packages/cli/test/__utils__/services/test-layer.ts
+468 -270
@@ -1,7 +1,19 @@
1 import path from 'node:path';
2 import * as tempy from 'tempy';
3 -import { Composio as RawComposioClient, NotFoundError } from '@composio/client';
4 -import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
3 +import {
4 + APIConnectionError,
5 + Composio as RawComposioClient,
6 + NotFoundError,
7 + type RequestOptions,
8 +} from '@composio/client';
9 +import type {
10 + AuthConfigCreateParams,
11 + AuthConfigCreateResponse,
12 +} from '@composio/client/resources/auth-configs';
13 +import type { LinkCreateResponse } from '@composio/client/resources/link';
14 +import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
15 +import type { ToolRetrieveResponse } from '@composio/client/resources/tools';
16 +import { TIMESTAMP } from '../models/account';
17 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
18 import * as BunPath from '@effect/platform-bun/BunPath';
19 import {
@@ -35,16 +47,17 @@ import {
47 InvalidToolkitsError,
48 InvalidToolkitVersionsError,
49 type InvalidVersionDetail,
50 + type OrganizationSummary,
51 + type OrgProject,
52 type ToolkitProjectScope,
53 } from 'src/services/composio-clients';
54 import type { ToolkitVersionOverrides } from 'src/effects/toolkit-version-overrides';
55 import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
42 -import type { Tools } from 'src/models/tools';
56 +import type { Tool, Tools } from 'src/models/tools';
57 import type { TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigger-types';
58 import type { AuthConfigItem } from 'src/models/auth-configs';
59 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
60 import type { TriggerInstanceItem } from 'src/models/triggers';
47 -import type { AuthConfigCreateResponse, LinkCreateResponse } from 'src/services/composio-clients';
61 import type { ToolkitVersionSpec } from 'src/effects/toolkit-version-overrides';
62 import { ComposioUserContextLive } from 'src/services/user-context';
63 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
@@ -83,6 +96,36 @@ import {
96 import { FetchHttpClient } from 'effect/unstable/http';
97 import * as BunServices from '@effect/platform-bun/BunServices';
98
99 +/**
100 + * The credentials and scope one mock-client request carries: the parameters
101 + * the client was obtained with, overridden by per-request headers.
102 + */
103 +export interface MockRequestScope {
104 + readonly userApiKey?: string;
105 + readonly apiKey?: string;
106 + readonly orgId?: string;
107 + readonly projectId?: string;
108 +}
109 +
110 +/**
111 + * One call to an account, session-info, or consumer endpoint of the mock client.
112 + */
113 +export interface MockAccountRequest {
114 + readonly operation:
115 + | 'org.list'
116 + | 'org.project.list'
117 + | 'org.consumer.project.resolve'
118 + | 'org.consumer.listConnectedToolkits'
119 + | 'auth.session.retrieveInfo'
120 + | 'tools.getLatestVersion'
121 + | 'org.project.createApiKey'
122 + | 'org.consumer.config'
123 + | 'consumer.permissions.resolve';
124 + readonly scope: MockRequestScope;
125 + readonly params?: unknown;
126 + readonly options?: RequestOptions;
127 +}
128 +
129 export interface TestLiveInput {
130 /**
131 * Base config provider to use in test.
@@ -133,6 +176,27 @@ export interface TestLiveInput {
176 triggerTypes?: TriggerTypes;
177 };
178
179 + /**
180 + * Account, session-info, and consumer data served by the mock client's
181 + * `org.*` and `auth.session.retrieveInfo` resources and its `get`/`post`
182 + * escape hatch. An endpoint without data rejects with a connection error,
183 + * as an unreachable backend would; consumer project resolution always
184 + * answers, echoing the requested org.
185 + */
186 + accountData?: {
187 + sessionInfo?:
188 + | SessionRetrieveInfoResponse
189 + | ((
190 + scope: MockRequestScope
191 + ) => SessionRetrieveInfoResponse | Promise<SessionRetrieveInfoResponse>);
192 + organizations?: ReadonlyArray<OrganizationSummary>;
193 + projects?: ReadonlyArray<OrgProject>;
194 + connectedToolkits?: ReadonlyArray<string>;
195 + latestToolVersion?: { readonly tool_slug: string; readonly version: string };
196 + projectApiKey?: string;
197 + onRequest?: (request: MockAccountRequest) => void;
198 + };
199 +
200 /**
201 * Mock auth-config data to use in test.
202 */
@@ -265,53 +329,29 @@ export interface TestLiveInput {
329
330 type RequiredLayer = Layer.Layer<CliCommand.Environment, unknown, never>;
331
268 -const ConsumerProjectResolveFetchMock = Layer.effectDiscard(
269 - Effect.acquireRelease(
270 - Effect.sync(() => {
271 - const originalFetch = globalThis.fetch;
272 -
273 - globalThis.fetch = (async (requestInput: RequestInfo | URL, init?: RequestInit) => {
274 - const url =
275 - typeof requestInput === 'string'
276 - ? requestInput
277 - : requestInput instanceof URL
278 - ? requestInput.toString()
279 - : requestInput.url;
280 -
281 - if (url.includes('/api/v3/org/consumer/project/resolve')) {
282 - const headers = new Headers(
283 - requestInput instanceof Request ? requestInput.headers : undefined
284 - );
285 - new Headers(init?.headers).forEach((value, key) => headers.set(key, value));
286 -
287 - const orgId = headers.get('x-org-id') ?? 'org_test';
288 - return new Response(
289 - JSON.stringify({
290 - project_id: 'consumer_project_id_test',
291 - project_nano_id: 'consumer_project_test',
292 - project_name: 'Consumer Project',
293 - org_id: orgId,
294 - project_type: 'CONSUMER',
295 - consumer_user_id: `consumer-user-${orgId}`,
296 - }),
297 - {
298 - status: 200,
299 - headers: { 'Content-Type': 'application/json' },
300 - }
301 - );
302 - }
303 -
304 - return originalFetch(requestInput, init);
305 - }) as typeof globalThis.fetch;
306 -
307 - return originalFetch;
308 - }),
309 - originalFetch =>
310 - Effect.sync(() => {
311 - globalThis.fetch = originalFetch;
312 - })
313 - )
314 -);
332 +const toClientTool = (tool: Tool): ToolRetrieveResponse => {
333 + // Derive toolkit slug from tool slug prefix (e.g. GMAIL_SEND_EMAIL -> gmail)
334 + const parts = tool.slug.split('_');
335 + const toolkitSlug = parts.length > 1 ? parts[0]!.toLowerCase() : '';
336 + return {
337 + ...tool,
338 + available_versions: [...tool.available_versions],
339 + tags: [...tool.tags],
340 + no_auth: false,
341 + version: 'latest',
342 + scopes: [],
343 + scope_requirements: null,
344 + is_deprecated: false,
345 + deprecated: {
346 + displayName: tool.name,
347 + version: 'latest',
348 + available_versions: [...tool.available_versions],
349 + is_deprecated: false,
350 + toolkit: { logo: '' },
351 + },
352 + toolkit: { name: toolkitSlug, slug: toolkitSlug, logo: '' },
353 + };
354 +};
355
356 /**
357 * Effect layer that injects all the services needed for tests, using mocks to avoid
@@ -571,10 +611,12 @@ export const TestLayer = (input?: TestLiveInput) =>
611 }
612
613 const limit = params.limit ?? 30;
574 - const items = results.slice(0, limit);
614 + const items = results.slice(0, limit).map(toClientTool);
615 return Effect.succeed({
616 items,
617 + total_items: results.length,
618 total_pages: Math.ceil(results.length / limit),
619 + current_page: 1,
620 next_cursor: null,
621 });
622 },
@@ -585,14 +627,7 @@ export const TestLayer = (input?: TestLiveInput) =>
627 new HttpServerError({ cause: `Tool "${slug}" not found`, status: 404 })
628 );
629 }
588 - // Derive toolkit slug from tool slug prefix (e.g. GMAIL_SEND_EMAIL -> gmail)
589 - const parts = found.slug.split('_');
590 - const toolkitSlug = parts.length > 1 ? parts[0]!.toLowerCase() : '';
591 - return Effect.succeed({
592 - ...found,
593 - no_auth: false,
594 - toolkit: { name: toolkitSlug, slug: toolkitSlug },
595 - });
630 + return Effect.succeed(toClientTool(found));
631 },
632 getToolkitDetailed: (slug: string) => {
633 const found = toolkitsData.detailedToolkits.find(
@@ -676,12 +711,12 @@ export const TestLayer = (input?: TestLiveInput) =>
711 })
712 );
713 }
679 - return Effect.succeed({});
714 + return Effect.succeed({ success: true, message: 'Auth config deleted' });
715 },
716 listConnectedAccounts: (params: {
717 toolkit_slugs?: string[];
718 user_ids?: string[];
684 - statuses?: string[];
719 + statuses?: ReadonlyArray<string> | null;
720 limit?: number;
721 }) => {
722 let results = [...connectedAccountsData.items];
@@ -743,7 +778,7 @@ export const TestLayer = (input?: TestLiveInput) =>
778 })
779 );
780 }
746 - return Effect.succeed({});
781 + return Effect.succeed({ success: true });
782 },
783 createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) => {
784 if (connectedAccountsData.linkResponse) {
@@ -1040,247 +1075,411 @@ export const TestLayer = (input?: TestLiveInput) =>
1075 instructions: 'Reuse this session id for follow-up calls.',
1076 },
1077 time_info: {
1043 - current_time_utc: '2026-01-01T00:00:00.000Z',
1078 + current_time_utc: TIMESTAMP,
1079 current_time_utc_epoch_seconds: 1767225600,
1080 message: 'UTC time',
1081 },
1082 };
1083 };
1084
1050 - const mockComposioClient = Object.assign(new RawComposioClient({ apiKey: 'test' }), {
1051 - link: {
1052 - create: async (params: { auth_config_id: string; user_id: string }) => {
1053 - const response = connectedAccountsData.linkResponse ?? {
1054 - connected_account_id: 'con_test_link',
1055 - expires_at: '2026-12-31T23:59:59Z',
1056 - link_token: 'lt_test_token',
1057 - redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
1058 - };
1059 - return response;
1060 - },
1085 + const failOnNetworkCall: typeof globalThis.fetch = Object.assign(
1086 + (input: RequestInfo | URL): Promise<Response> => {
1087 + const url =
1088 + typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
1089 + throw new Error(`unexpected network call from the mock Composio client: ${url}`);
1090 },
1062 - patch: async (path: string, options?: { body?: Record<string, unknown> }) => {
1063 - connectedAccountsData.onPatch?.({ path, body: options?.body });
1064 -
1065 - const match = path.match(/^\/api\/v3\/connected_accounts\/([^/]+)$/);
1066 - if (!match) {
1067 - throw new Error(`Unhandled PATCH path "${path}"`);
1068 - }
1069 -
1070 - const connectedAccountId = match[1];
1071 - const account = connectedAccountsData.items.find(item => item.id === connectedAccountId);
1072 - if (!account) {
1073 - throw new Error(`Connected account "${connectedAccountId}" not found`);
1074 - }
1091 + { preconnect: () => undefined }
1092 + );
1093
1076 - if (typeof options?.body?.alias === 'string') {
1077 - Object.assign(account as { alias?: string | null }, {
1078 - alias: options.body.alias,
1079 - });
1094 + // `fromEnv({}, ...)` is what production uses, so the mock cannot read the
1095 + // developer's COMPOSIO_* variables either. The throwing `fetch` turns a
1096 + // resource this mock forgot to shadow into a named test failure instead of
1097 + // a live request against the real backend.
1098 + const mockComposioClient = Object.assign(
1099 + RawComposioClient.fromEnv(
1100 + {},
1101 + {
1102 + apiKey: 'test',
1103 + userApiKey: null,
1104 + orgApiKey: null,
1105 + baseURL: 'https://mock.invalid',
1106 + logLevel: 'off',
1107 + fetch: failOnNetworkCall,
1108 }
1109 + ),
1110 + {
1111 + link: {
1112 + create: async (params: { auth_config_id: string; user_id: string }) => {
1113 + const response = connectedAccountsData.linkResponse ?? {
1114 + connected_account_id: 'con_test_link',
1115 + expires_at: '2026-12-31T23:59:59Z',
1116 + link_token: 'lt_test_token',
1117 + redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
1118 + };
1119 + return response;
1120 + },
1121 + },
1122 + patch: async (path: string, options?: { body?: Record<string, unknown> }) => {
1123 + connectedAccountsData.onPatch?.({ path, body: options?.body });
1124
1082 - return account;
1083 - },
1084 - connectedAccounts: {
1085 - list: async (params?: {
1086 - toolkit_slugs?: string[];
1087 - user_ids?: string[];
1088 - statuses?: string[];
1089 - limit?: number;
1090 - }) => {
1091 - let results = [...connectedAccountsData.items];
1092 -
1093 - if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
1094 - const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
1095 - results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
1125 + const match = path.match(/^\/api\/v3\/connected_accounts\/([^/]+)$/);
1126 + if (!match) {
1127 + throw new Error(`Unhandled PATCH path "${path}"`);
1128 }
1129
1098 - if (params?.user_ids && params.user_ids.length > 0) {
1099 - const userIds = new Set(params.user_ids);
1100 - results = results.filter(item => userIds.has(item.user_id));
1130 + const connectedAccountId = match[1];
1131 + const account = connectedAccountsData.items.find(item => item.id === connectedAccountId);
1132 + if (!account) {
1133 + throw new Error(`Connected account "${connectedAccountId}" not found`);
1134 }
1135
1103 - if (params?.statuses && params.statuses.length > 0) {
1104 - const statuses = new Set(params.statuses);
1105 - results = results.filter(item => statuses.has(item.status));
1136 + if (typeof options?.body?.alias === 'string') {
1137 + Object.assign(account as { alias?: string | null }, {
1138 + alias: options.body.alias,
1139 + });
1140 }
1141
1108 - const limit = params?.limit ?? 30;
1109 - return {
1110 - items: results.slice(0, limit),
1111 - total_items: results.length,
1112 - total_pages: Math.ceil(results.length / limit),
1113 - current_page: 1,
1114 - next_cursor: null,
1115 - };
1116 - },
1117 - retrieve: async (nanoid: string) => {
1118 - const found = connectedAccountsData.items.find(item => item.id === nanoid);
1119 - if (!found) {
1120 - throw new Error(`Connected account "${nanoid}" not found`);
1121 - }
1122 - return found;
1142 + return account;
1143 },
1124 - delete: async (nanoid: string) => {
1125 - const found = connectedAccountsData.items.find(item => item.id === nanoid);
1126 - if (!found) {
1127 - throw new Error(`Connected account "${nanoid}" not found`);
1128 - }
1129 - connectedAccountsData.onDelete?.(nanoid);
1130 - return {};
1144 + connectedAccounts: {
1145 + list: async (params?: {
1146 + toolkit_slugs?: string[];
1147 + user_ids?: string[];
1148 + statuses?: string[];
1149 + limit?: number;
1150 + }) => {
1151 + let results = [...connectedAccountsData.items];
1152 +
1153 + if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
1154 + const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
1155 + results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
1156 + }
1157 +
1158 + if (params?.user_ids && params.user_ids.length > 0) {
1159 + const userIds = new Set(params.user_ids);
1160 + results = results.filter(item => userIds.has(item.user_id));
1161 + }
1162 +
1163 + if (params?.statuses && params.statuses.length > 0) {
1164 + const statuses = new Set(params.statuses);
1165 + results = results.filter(item => statuses.has(item.status));
1166 + }
1167 +
1168 + const limit = params?.limit ?? 30;
1169 + return {
1170 + items: results.slice(0, limit),
1171 + total_items: results.length,
1172 + total_pages: Math.ceil(results.length / limit),
1173 + current_page: 1,
1174 + next_cursor: null,
1175 + };
1176 + },
1177 + retrieve: async (nanoid: string) => {
1178 + const found = connectedAccountsData.items.find(item => item.id === nanoid);
1179 + if (!found) {
1180 + throw new Error(`Connected account "${nanoid}" not found`);
1181 + }
1182 + return found;
1183 + },
1184 + delete: async (nanoid: string) => {
1185 + const found = connectedAccountsData.items.find(item => item.id === nanoid);
1186 + if (!found) {
1187 + throw new Error(`Connected account "${nanoid}" not found`);
1188 + }
1189 + connectedAccountsData.onDelete?.(nanoid);
1190 + return {};
1191 + },
1192 },
1132 - },
1133 - triggersTypes: {
1134 - retrieve: async (slug: string) => {
1135 - const found = toolkitsData.triggerTypes.find(
1136 - trigger => trigger.slug.toUpperCase() === slug.toUpperCase()
1137 - );
1138 - if (!found) {
1139 - throw new NotFoundError(
1140 - 404,
1141 - { error: { message: `Trigger type "${slug}" not found` } },
1142 - `Trigger type "${slug}" not found`,
1143 - new Headers()
1193 + triggersTypes: {
1194 + retrieve: async (slug: string) => {
1195 + const found = toolkitsData.triggerTypes.find(
1196 + trigger => trigger.slug.toUpperCase() === slug.toUpperCase()
1197 );
1145 - }
1146 - return found;
1198 + if (!found) {
1199 + throw new NotFoundError(
1200 + 404,
1201 + { error: { message: `Trigger type "${slug}" not found` } },
1202 + `Trigger type "${slug}" not found`,
1203 + new Headers()
1204 + );
1205 + }
1206 + return found;
1207 + },
1208 },
1148 - },
1149 - triggerInstances: {
1150 - upsert: async (
1151 - triggerSlug: string,
1152 - params?: {
1153 - connected_account_id?: string;
1154 - trigger_config?: Record<string, unknown>;
1155 - }
1156 - ) => {
1157 - if (
1158 - input?.triggersData?.rejectUnknownTriggerSlugs &&
1159 - !toolkitsData.triggerTypes.some(
1160 - trigger => trigger.slug.toUpperCase() === triggerSlug.toUpperCase()
1161 - )
1162 - ) {
1163 - throw new Error(`Trigger type "${triggerSlug}" not found`);
1164 - }
1165 - return {
1166 - trigger_id: `trg_${triggerSlug.toLowerCase()}_${params?.connected_account_id ?? 'new'}`,
1167 - };
1209 + triggerInstances: {
1210 + upsert: async (
1211 + triggerSlug: string,
1212 + params?: {
1213 + connected_account_id?: string;
1214 + trigger_config?: Record<string, unknown>;
1215 + }
1216 + ) => {
1217 + if (
1218 + input?.triggersData?.rejectUnknownTriggerSlugs &&
1219 + !toolkitsData.triggerTypes.some(
1220 + trigger => trigger.slug.toUpperCase() === triggerSlug.toUpperCase()
1221 + )
1222 + ) {
1223 + throw new Error(`Trigger type "${triggerSlug}" not found`);
1224 + }
1225 + return {
1226 + trigger_id: `trg_${triggerSlug.toLowerCase()}_${params?.connected_account_id ?? 'new'}`,
1227 + };
1228 + },
1229 + manage: {
1230 + update: async (triggerId: string, params: { status: 'enable' | 'disable' }) => ({
1231 + trigger_id: triggerId,
1232 + status: params.status,
1233 + }),
1234 + delete: async (triggerId: string) => ({ trigger_id: triggerId }),
1235 + },
1236 },
1169 - manage: {
1170 - update: async (triggerId: string, params: { status: 'enable' | 'disable' }) => ({
1171 - trigger_id: triggerId,
1172 - status: params.status,
1237 + toolkits: {
1238 + retrieve: async (slug: string) => {
1239 + const detailed = toolkitsData.detailedToolkits.find(
1240 + t => t.slug.toLowerCase() === slug.toLowerCase()
1241 + );
1242 + if (detailed) {
1243 + return {
1244 + name: detailed.name,
1245 + slug: detailed.slug,
1246 + is_local_toolkit: detailed.is_local_toolkit,
1247 + composio_managed_auth_schemes: [...detailed.composio_managed_auth_schemes],
1248 + no_auth: detailed.no_auth,
1249 + meta: detailed.meta,
1250 + };
1251 + }
1252 +
1253 + const found = toolkitsData.toolkits.find(
1254 + t => t.slug.toLowerCase() === slug.toLowerCase()
1255 + );
1256 + if (!found) {
1257 + throw new Error(`Toolkit "${slug}" not found`);
1258 + }
1259 + return {
1260 + name: found.name,
1261 + slug: found.slug,
1262 + is_local_toolkit: found.is_local_toolkit,
1263 + composio_managed_auth_schemes: [...found.composio_managed_auth_schemes],
1264 + no_auth: found.no_auth,
1265 + meta: found.meta,
1266 + };
1267 + },
1268 + },
1269 + files: {
1270 + createPresignedURL: async (params: {
1271 + filename: string;
1272 + mimetype: string;
1273 + md5: string;
1274 + tool_slug: string;
1275 + toolkit_slug: string;
1276 + }) => ({
1277 + key: `uploads/${params.filename}`,
1278 + new_presigned_url: 'https://s3.test.composio.dev/upload',
1279 }),
1174 - delete: async (triggerId: string) => ({ trigger_id: triggerId }),
1280 },
1176 - },
1177 - toolkits: {
1178 - retrieve: async (slug: string) => {
1179 - const detailed = toolkitsData.detailedToolkits.find(
1180 - t => t.slug.toLowerCase() === slug.toLowerCase()
1181 - );
1182 - if (detailed) {
1281 + toolRouter: {
1282 + session: {
1283 + create:
1284 + toolRouterOverrides?.create ??
1285 + (async (params: SessionCreateParams) => ({
1286 + session_id: 'trs_test_session',
1287 + config: { user_id: params.user_id },
1288 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
1289 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
1290 + })),
1291 + execute:
1292 + toolRouterOverrides?.execute ??
1293 + (async (_sessionId: string, params: SessionExecuteParams) => ({
1294 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
1295 + error: null,
1296 + log_id: 'log_test',
1297 + })),
1298 + executeMeta:
1299 + toolRouterOverrides?.executeMeta ??
1300 + (async (_sessionId: string, params: SessionExecuteMetaParams) => ({
1301 + data: { slug: params.slug, arguments: params.arguments },
1302 + error: null,
1303 + log_id: 'log_test',
1304 + })),
1305 + link:
1306 + toolRouterOverrides?.link ??
1307 + (async () => ({
1308 + connected_account_id: 'con_test_link',
1309 + link_token: 'lt_test_token',
1310 + redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
1311 + account_type: 'PRIVATE' as const,
1312 + })),
1313 + proxyExecute:
1314 + toolRouterOverrides?.proxyExecute ??
1315 + (async (_sessionId: string, params: SessionProxyExecuteParams) => ({
1316 + status: 200,
1317 + data: {
1318 + toolkit_slug: params.toolkit_slug,
1319 + endpoint: params.endpoint,
1320 + method: params.method,
1321 + body: params.body ?? null,
1322 + parameters: params.parameters ?? [],
1323 + },
1324 + headers: {},
1325 + })),
1326 + search: toolRouterOverrides?.search ?? defaultSearchHandler,
1327 + toolkits: toolRouterOverrides?.toolkits ?? defaultToolkitsHandler,
1328 + tools: async () => ({
1329 + items: [],
1330 + }),
1331 + },
1332 + },
1333 + }
1334 + );
1335 +
1336 + // --- Account, session-info, and consumer endpoints ---
1337 + // Served per client scope, so a handler sees the credentials and org or
1338 + // project the real client would have placed in its default headers.
1339 + const accountData = input?.accountData ?? {};
1340 + const noTestData = (operation: MockAccountRequest['operation']) =>
1341 + new APIConnectionError({ message: `No test data for ${operation}` });
1342 +
1343 + const scopeOf = (base: MockRequestScope, options?: RequestOptions): MockRequestScope => {
1344 + // The CLI only ever passes plain header records.
1345 + const headers = (options?.headers ?? {}) as Record<string, string | null | undefined>;
1346 + const userApiKey = headers['x-user-api-key'];
1347 + return {
1348 + userApiKey: userApiKey === null ? undefined : (userApiKey ?? base.userApiKey),
1349 + apiKey: headers['x-api-key'] ?? undefined,
1350 + orgId: headers['x-org-id'] ?? base.orgId,
1351 + projectId: headers['x-project-id'] ?? base.projectId,
1352 + };
1353 + };
1354 +
1355 + const accountBranches = (base: MockRequestScope) => {
1356 + const record = (
1357 + operation: MockAccountRequest['operation'],
1358 + options: RequestOptions | undefined,
1359 + params?: unknown
1360 + ): MockRequestScope => {
1361 + const scope = scopeOf(base, options);
1362 + accountData.onRequest?.({ operation, scope, params, options });
1363 + return scope;
1364 + };
1365 + const timestamps = {
1366 + created_at: TIMESTAMP,
1367 + updated_at: TIMESTAMP,
1368 + };
1369 +
1370 + return {
1371 + org: Object.assign(Object.create(mockComposioClient.org) as typeof mockComposioClient.org, {
1372 + list: async (query?: { limit?: number } | null, options?: RequestOptions) => {
1373 + record('org.list', options, query);
1374 + if (!accountData.organizations) throw noTestData('org.list');
1375 + const organizations = accountData.organizations.map(org => ({ ...org, ...timestamps }));
1376 return {
1184 - name: detailed.name,
1185 - slug: detailed.slug,
1186 - is_local_toolkit: detailed.is_local_toolkit,
1187 - composio_managed_auth_schemes: [...detailed.composio_managed_auth_schemes],
1188 - no_auth: detailed.no_auth,
1189 - meta: detailed.meta,
1377 + organizations,
1378 + next_cursor: null,
1379 + total_pages: 1,
1380 + current_page: 1,
1381 + total_items: organizations.length,
1382 };
1383 + },
1384 + project: {
1385 + list: async (
1386 + query?: { limit?: number; list_all_org_projects?: boolean | null } | null,
1387 + options?: RequestOptions
1388 + ) => {
1389 + record('org.project.list', options, query);
1390 + if (!accountData.projects) throw noTestData('org.project.list');
1391 + return {
1392 + data: [...accountData.projects],
1393 + next_cursor: null,
1394 + total_pages: 1,
1395 + current_page: 1,
1396 + total_items: accountData.projects.length,
1397 + };
1398 + },
1399 + },
1400 + consumer: {
1401 + project: {
1402 + resolve: async (
1403 + params: { 'x-user-api-key': string; 'x-org-id': string },
1404 + options?: RequestOptions
1405 + ) => {
1406 + record('org.consumer.project.resolve', options, params);
1407 + const orgId = params['x-org-id'];
1408 + return {
1409 + project_id: 'consumer_project_id_test',
1410 + project_nano_id: 'consumer_project_test',
1411 + project_name: 'Consumer Project',
1412 + org_id: orgId,
1413 + project_type: 'CONSUMER' as const,
1414 + config: { consumer_experience_enabled: true, enhanced_controls: false },
1415 + consumer_user_id: `consumer-user-${orgId}`,
1416 + };
1417 + },
1418 + },
1419 + listConnectedToolkits: async (
1420 + params: { user_id: string; 'x-user-api-key': string; 'x-org-id': string },
1421 + options?: RequestOptions
1422 + ) => {
1423 + record('org.consumer.listConnectedToolkits', options, params);
1424 + if (!accountData.connectedToolkits) {
1425 + throw noTestData('org.consumer.listConnectedToolkits');
1426 + }
1427 + return { toolkits: [...accountData.connectedToolkits] };
1428 + },
1429 + },
1430 + }),
1431 + auth: {
1432 + session: {
1433 + retrieveInfo: async (options?: RequestOptions) => {
1434 + const scope = record('auth.session.retrieveInfo', options);
1435 + const sessionInfo = accountData.sessionInfo;
1436 + if (sessionInfo === undefined) throw noTestData('auth.session.retrieveInfo');
1437 + return typeof sessionInfo === 'function' ? sessionInfo(scope) : sessionInfo;
1438 + },
1439 + },
1440 + },
1441 + get: async (path: string, options?: RequestOptions) => {
1442 + if (/^\/api\/v3\/tools\/[^/]+\/get_latest_version$/.test(path)) {
1443 + record('tools.getLatestVersion', options, { path });
1444 + if (!accountData.latestToolVersion) throw noTestData('tools.getLatestVersion');
1445 + return accountData.latestToolVersion;
1446 }
1192 -
1193 - const found = toolkitsData.toolkits.find(
1194 - t => t.slug.toLowerCase() === slug.toLowerCase()
1195 - );
1196 - if (!found) {
1197 - throw new Error(`Toolkit "${slug}" not found`);
1198 - }
1199 - return {
1200 - name: found.name,
1201 - slug: found.slug,
1202 - is_local_toolkit: found.is_local_toolkit,
1203 - composio_managed_auth_schemes: [...found.composio_managed_auth_schemes],
1204 - no_auth: found.no_auth,
1205 - meta: found.meta,
1206 - };
1447 + throw new Error(`Unhandled GET path "${path}"`);
1448 },
1208 - },
1209 - files: {
1210 - createPresignedURL: async (params: {
1211 - filename: string;
1212 - mimetype: string;
1213 - md5: string;
1214 - tool_slug: string;
1215 - toolkit_slug: string;
1216 - }) => ({
1217 - key: `uploads/${params.filename}`,
1218 - new_presigned_url: 'https://s3.test.composio.dev/upload',
1219 - }),
1220 - },
1221 - toolRouter: {
1222 - session: {
1223 - create:
1224 - toolRouterOverrides?.create ??
1225 - (async (params: SessionCreateParams) => ({
1226 - session_id: 'trs_test_session',
1227 - config: { user_id: params.user_id },
1228 - mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
1229 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
1230 - })),
1231 - execute:
1232 - toolRouterOverrides?.execute ??
1233 - (async (_sessionId: string, params: SessionExecuteParams) => ({
1234 - data: { tool_slug: params.tool_slug, arguments: params.arguments },
1235 - error: null,
1236 - log_id: 'log_test',
1237 - })),
1238 - executeMeta:
1239 - toolRouterOverrides?.executeMeta ??
1240 - (async (_sessionId: string, params: SessionExecuteMetaParams) => ({
1241 - data: { slug: params.slug, arguments: params.arguments },
1242 - error: null,
1243 - log_id: 'log_test',
1244 - })),
1245 - link:
1246 - toolRouterOverrides?.link ??
1247 - (async () => ({
1248 - connected_account_id: 'con_test_link',
1249 - link_token: 'lt_test_token',
1250 - redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
1251 - account_type: 'PRIVATE' as const,
1252 - })),
1253 - proxyExecute:
1254 - toolRouterOverrides?.proxyExecute ??
1255 - (async (_sessionId: string, params: SessionProxyExecuteParams) => ({
1256 - status: 200,
1257 - data: {
1258 - toolkit_slug: params.toolkit_slug,
1259 - endpoint: params.endpoint,
1260 - method: params.method,
1261 - body: params.body ?? null,
1262 - parameters: params.parameters ?? [],
1263 - },
1264 - headers: {},
1265 - })),
1266 - search: toolRouterOverrides?.search ?? defaultSearchHandler,
1267 - toolkits: toolRouterOverrides?.toolkits ?? defaultToolkitsHandler,
1268 - tools: async () => ({
1269 - items: [],
1270 - }),
1449 + post: async (path: string, options?: RequestOptions & { body?: unknown }) => {
1450 + if (/^\/api\/v3\/org\/project\/[^/]+\/api_keys\/create$/.test(path)) {
1451 + record('org.project.createApiKey', options, { path, body: options?.body });
1452 + if (!accountData.projectApiKey) throw noTestData('org.project.createApiKey');
1453 + return { api_key: accountData.projectApiKey };
1454 + }
1455 + throw new Error(`Unhandled POST path "${path}"`);
1456 },
1272 - },
1273 - });
1457 + };
1458 + };
1459 +
1460 + const scopedClients = new Map<string, typeof mockComposioClient>();
1461 + const mockClientFor = (scope: MockRequestScope) => {
1462 + const key = JSON.stringify([scope.userApiKey, scope.orgId, scope.projectId]);
1463 + const cached = scopedClients.get(key);
1464 + if (cached) return cached;
1465 + const scoped = Object.assign(
1466 + Object.create(mockComposioClient) as typeof mockComposioClient,
1467 + accountBranches(scope)
1468 + );
1469 + scopedClients.set(key, scoped);
1470 + return scoped;
1471 + };
1472
1473 const ComposioClientSingletonTest = Layer.succeed(
1474 ComposioClientSingleton,
1475 ComposioClientSingleton.of({
1476 get: Effect.fn(function* () {
1279 - return mockComposioClient;
1477 + return mockClientFor({});
1478 }),
1281 - getFor: Effect.fn(function* () {
1282 - return mockComposioClient;
1479 + getFor: Effect.fn(function* (params: MockRequestScope) {
1480 + return mockClientFor(params);
1481 }),
1482 + getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
1483 })
1484 );
1485
@@ -1381,7 +1580,6 @@ export const TestLayer = (input?: TestLiveInput) =>
1580 MockTerminal.layer,
1581 BunPath.layer,
1582 FetchHttpClient.layer,
1384 - ConsumerProjectResolveFetchMock,
1583 StdinTest,
1584 TerminalUILayer,
1585 // `src/commands/index.ts` provides these for real invocations; direct-effect tests that
ts/packages/cli/test/__utils__/services/toolkits-repository-stub.ts
+13
@@ -54,6 +54,19 @@ export type GetProjectToolkitsError = Effect.Error<
54 ReturnType<ComposioToolkitsRepositoryShape['getProjectToolkits']>
55 >;
56
57 +/**
58 + * A repository whose every method dies unless the test overrides it.
59 + */
60 +export const makeToolkitsRepositoryStub = (
61 + overrides: Partial<ComposioToolkitsRepositoryShape>
62 +): ComposioToolkitsRepositoryShape =>
63 + ComposioToolkitsRepository.of({
64 + ...unusedRepositoryMethods,
65 + getToolkits: notUsed('getToolkits'),
66 + getProjectToolkits: notUsed('getProjectToolkits'),
67 + ...overrides,
68 + });
69 +
70 /**
71 * A `ComposioToolkitsRepository` layer that counts catalog fetches, so a test
72 * can assert not just what was resolved but what it cost. The native and
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+30 -54
@@ -1,7 +1,10 @@
1 +import { APIError } from '@composio/client';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { ConfigProvider, Console, Effect } from 'effect';
4 import { extendConfigProvider } from 'src/services/config';
5 import { cli, TestLive, MockConsole } from 'test/__utils__';
6 +import { makeSessionInfo } from 'test/__utils__/models/account';
7 +import type { MockRequestScope } from 'test/__utils__/services/test-layer';
8 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
9 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
10 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
@@ -351,6 +354,7 @@ describe('CLI: composio dev connected-accounts link', () => {
354 );
355 });
356
357 + const sessionInfoScopes: MockRequestScope[] = [];
358 layer(
359 TestLive({
360 baseConfigProvider: testConfigProvider,
@@ -358,8 +362,31 @@ describe('CLI: composio dev connected-accounts link', () => {
362 fixture: 'global-test-user-id',
363 toolRouter: {
364 link: async () => {
361 - throw Object.assign(new Error('No managed auth'), {
362 - slug: 'ToolRouterV2_NoManagedAuth',
365 + throw APIError.generate(
366 + 400,
367 + {
368 + error: {
369 + message: 'No managed auth',
370 + code: 400,
371 + slug: 'ToolRouterV2_NoManagedAuth',
372 + status: 400,
373 + },
374 + },
375 + undefined,
376 + new Headers()
377 + );
378 + },
379 + },
380 + accountData: {
381 + sessionInfo: scope => {
382 + sessionInfoScopes.push(scope);
383 + return makeSessionInfo({
384 + orgId: 'org_selected',
385 + orgName: 'Selected Org',
386 + orgMemberId: 'member_selected',
387 + projectId: 'project_id_selected',
388 + projectNanoId: 'project_selected',
389 + projectName: 'Selected Project',
390 });
391 },
392 },
@@ -370,60 +397,9 @@ describe('CLI: composio dev connected-accounts link', () => {
397 const userContext = yield* ComposioUserContext;
398 yield* userContext.login('test_api_key', 'org_selected', 'consumer-user-org_selected');
399
373 - const originalFetch = globalThis.fetch;
374 - const sessionInfoRequests: Headers[] = [];
375 - vi.spyOn(globalThis, 'fetch').mockImplementation(
376 - async (requestInput: RequestInfo | URL, init?: RequestInit) => {
377 - const url =
378 - typeof requestInput === 'string'
379 - ? requestInput
380 - : requestInput instanceof URL
381 - ? requestInput.toString()
382 - : requestInput.url;
383 -
384 - if (url.includes('/api/v3/auth/session/info')) {
385 - const headers = new Headers(init?.headers);
386 - sessionInfoRequests.push(headers);
387 - return new Response(
388 - JSON.stringify({
389 - project: {
390 - name: 'Selected Project',
391 - id: 'project_id_selected',
392 - org_id: 'org_selected',
393 - nano_id: 'project_selected',
394 - email: 'project@example.com',
395 - created_at: '2026-01-01T00:00:00.000Z',
396 - updated_at: '2026-01-01T00:00:00.000Z',
397 - org: {
398 - id: 'org_selected',
399 - name: 'Selected Org',
400 - plan: 'enterprise',
401 - },
402 - },
403 - org_member: {
404 - id: 'member_selected',
405 - user_id: 'user_123',
406 - email: 'cli@example.com',
407 - name: 'CLI User',
408 - role: 'admin',
409 - },
410 - api_key: null,
411 - }),
412 - {
413 - status: 200,
414 - headers: { 'Content-Type': 'application/json' },
415 - }
416 - );
417 - }
418 -
419 - return originalFetch(requestInput, init);
420 - }
421 - );
422 -
400 yield* cli(['link', 'gmail', '--no-browser']);
401
425 - expect(sessionInfoRequests).toHaveLength(1);
426 - expect(sessionInfoRequests[0].get('x-org-id')).toBe('org_selected');
402 + expect(sessionInfoScopes.map(scope => scope.orgId)).toEqual(['org_selected']);
403 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
404 expect(output).toContain('/Selected%20Org/~/connect/apps/gmail?open=true');
405 })
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts
+29
@@ -257,4 +257,33 @@ describe('CLI: composio dev connected-accounts list', () => {
257 })
258 );
259 });
260 +
261 + // Credential-bearing fields the API may send must never reach stdout.
262 + const credentialBearingAccounts = [
263 + {
264 + ...testConnectedAccounts[0],
265 + state: { authScheme: 'OAUTH2', val: { access_token: 'tok_secret_state' } },
266 + data: { access_token: 'tok_secret_data' },
267 + params: { refresh_token: 'tok_secret_params' },
268 + },
269 + ];
270 +
271 + layer(
272 + TestLive({
273 + baseConfigProvider: testDevConfigProvider,
274 + connectedAccountsData: { items: credentialBearingAccounts },
275 + })
276 + )('[Given] an account payload with tokens [Then] prints it without them', it => {
277 + it.effect('keeps state, data, and params out of the output', () =>
278 + Effect.gen(function* () {
279 + const userContext = yield* ComposioUserContext;
280 + yield* userContext.login('test_api_key', 'org_test');
281 + yield* cli(['dev', 'connected-accounts', 'list']);
282 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
283 +
284 + expect(output).toContain('con_gmail_active');
285 + expect(output).not.toContain('tok_secret');
286 + })
287 + );
288 + });
289 });
ts/packages/cli/test/src/commands/login.cmd.test.ts
+70 -97
@@ -10,7 +10,10 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
10 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
11 import { writeStoredAgentIdentity } from 'src/services/agents';
12 import { ComposioUserContext } from 'src/services/user-context';
13 +import { InternalServerError } from '@composio/client';
14 import { ComposioSessionRepository } from 'src/services/composio-clients';
15 +import { makeSessionInfo } from 'test/__utils__/models/account';
16 +import type { MockAccountRequest } from 'test/__utils__/services/test-layer';
17
18 vi.mock('open', () => ({
19 default: vi.fn(async () => undefined),
@@ -394,55 +397,33 @@ describe('CLI: composio login', () => {
397 );
398 });
399
397 - layer(TestLive())(it => {
400 + const directLoginRequests: MockAccountRequest[] = [];
401 + layer(
402 + TestLive({
403 + accountData: {
404 + organizations: [
405 + { id: 'org_default', name: 'Example Org' },
406 + { id: 'org_selected', name: 'Selected Org' },
407 + ],
408 + sessionInfo: scope =>
409 + scope.orgId === undefined
410 + ? makeSessionInfo({
411 + orgId: 'org_default',
412 + orgMemberId: 'member_default',
413 + userId: 'user_123',
414 + })
415 + : makeSessionInfo({
416 + orgId: scope.orgId,
417 + orgName: 'Selected Org',
418 + orgMemberId: 'member_selected',
419 + userId: 'user_123',
420 + }),
421 + onRequest: request => directLoginRequests.push(request),
422 + },
423 + })
424 + )(it => {
425 it.effect('[When] logging in with --user-api-key --org [Then] stores the chosen org', () =>
426 Effect.gen(function* () {
400 - vi.spyOn(globalThis, 'fetch').mockImplementation(
401 - async (requestInput: RequestInfo | URL, init?: RequestInit) => {
402 - const url = requestUrl(requestInput);
403 -
404 - if (url.includes('/api/v3/auth/session/info')) {
405 - const selectedOrgId = new Headers(init?.headers).get('x-org-id');
406 - return mockFetchResponse({
407 - project: {
408 - name: 'Default Project',
409 - id: 'project_id_default',
410 - org_id: selectedOrgId ?? 'org_default',
411 - nano_id: 'project_default',
412 - email: 'project@example.com',
413 - created_at: '2026-01-01T00:00:00.000Z',
414 - updated_at: '2026-01-01T00:00:00.000Z',
415 - org: {
416 - id: selectedOrgId ?? 'org_default',
417 - name: selectedOrgId ? 'Selected Org' : 'Example Org',
418 - plan: 'enterprise',
419 - },
420 - },
421 - org_member: {
422 - id: selectedOrgId ? 'member_selected' : 'member_default',
423 - user_id: 'user_123',
424 - email: 'cli@example.com',
425 - name: 'CLI User',
426 - role: 'admin',
427 - },
428 - api_key: null,
429 - });
430 - }
431 -
432 - if (url.includes('/api/v3/org/list?limit=50')) {
433 - expect(new Headers(init?.headers).get('x-user-api-key')).toBe('uak_direct_key');
434 - return mockFetchResponse({
435 - organizations: [
436 - { id: 'org_default', name: 'Example Org' },
437 - { id: 'org_selected', name: 'Selected Org' },
438 - ],
439 - });
440 - }
441 -
442 - return mockFetchResponse({});
443 - }
444 - );
445 -
427 yield* cli([
428 'login',
429 '--user-api-key',
@@ -465,6 +446,11 @@ describe('CLI: composio login', () => {
446 // `~/.composio/config.json`.
447 expect(userConfig.api_key).toBe('uak_direct_key');
448 expect(userConfig.org_id).toBe('org_selected');
449 + expect(
450 + directLoginRequests
451 + .filter(request => request.operation === 'org.list')
452 + .map(request => request.scope.userApiKey)
453 + ).toEqual(['uak_direct_key']);
454 expect((yield* fs.stat(userConfigPath)).mode & 0o777).toBe(0o600);
455
456 // ComposioUserContext also exposes the resolved key in-memory
@@ -485,7 +471,43 @@ describe('CLI: composio login', () => {
471 );
472 });
473
488 - layer(TestLive())(it => {
474 + layer(
475 + TestLive({
476 + accountData: {
477 + organizations: [
478 + { id: 'org_selected', name: 'Selected Org' },
479 + { id: 'org_home', name: 'Home Org' },
480 + ],
481 + sessionInfo: scope => {
482 + if (scope.projectId !== undefined) {
483 + throw new InternalServerError(
484 + 500,
485 + { message: 'Selected-org enrichment failed' },
486 + 'Selected-org enrichment failed',
487 + new Headers()
488 + );
489 + }
490 + return scope.orgId === undefined
491 + ? makeSessionInfo({
492 + orgId: 'org_home',
493 + orgName: 'Home Org',
494 + orgMemberId: 'member_home',
495 + userId: 'user_123',
496 + email: 'poll@example.com',
497 + name: 'Poll User',
498 + })
499 + : makeSessionInfo({
500 + orgId: scope.orgId,
501 + orgName: 'Selected Org',
502 + orgMemberId: 'member_selected',
503 + userId: 'user_123',
504 + email: 'poll@example.com',
505 + name: 'Poll User',
506 + });
507 + },
508 + },
509 + })
510 + )(it => {
511 it.effect(
512 '[Given] selected-org enrichment fails [When] completing --poll [Then] links the selected org membership',
513 () =>
@@ -543,55 +565,6 @@ describe('CLI: composio login', () => {
565 )}\n`
566 );
567
546 - vi.spyOn(globalThis, 'fetch').mockImplementation(
547 - async (requestInput: RequestInfo | URL, init?: RequestInit) => {
548 - const url = requestUrl(requestInput);
549 - const headers = new Headers(init?.headers);
550 -
551 - if (url.includes('/api/v3/auth/session/info')) {
552 - const selectedOrgId = headers.get('x-org-id');
553 - if (headers.has('x-project-id')) {
554 - return mockFetchResponse({ message: 'Selected-org enrichment failed' }, 500);
555 - }
556 - return mockFetchResponse({
557 - project: {
558 - name: 'Default Project',
559 - id: 'project_id_default',
560 - org_id: selectedOrgId ?? 'org_home',
561 - nano_id: 'project_default',
562 - email: 'project@example.com',
563 - created_at: '2026-01-01T00:00:00.000Z',
564 - updated_at: '2026-01-01T00:00:00.000Z',
565 - org: {
566 - id: selectedOrgId ?? 'org_home',
567 - name: selectedOrgId ? 'Selected Org' : 'Home Org',
568 - plan: 'enterprise',
569 - },
570 - },
571 - org_member: {
572 - id: selectedOrgId ? 'member_selected' : 'member_home',
573 - user_id: 'user_123',
574 - email: 'poll@example.com',
575 - name: 'Poll User',
576 - role: 'admin',
577 - },
578 - api_key: null,
579 - });
580 - }
581 -
582 - if (url.includes('/api/v3/org/list?limit=50')) {
583 - return mockFetchResponse({
584 - organizations: [
585 - { id: 'org_selected', name: 'Selected Org' },
586 - { id: 'org_home', name: 'Home Org' },
587 - ],
588 - });
589 - }
590 -
591 - return mockFetchResponse({});
592 - }
593 - );
594 -
568 yield* cli(['login', '--poll', '--no-skill-install']).pipe(
569 Effect.provideService(ComposioSessionRepository, sessionRepository)
570 );
ts/packages/cli/test/src/commands/orgs.switch.cmd.test.ts
+19 -30
@@ -3,6 +3,8 @@ import { ConfigProvider, Effect } from 'effect';
3 import { afterEach, vi } from 'vitest';
4 import { extendConfigProvider } from 'src/services/config';
5 import { cli, TestLive } from 'test/__utils__';
6 +import { makeSessionInfo } from 'test/__utils__/models/account';
7 +import type { MockRequestScope } from 'test/__utils__/services/test-layer';
8
9 const analyticsMocks = vi.hoisted(() => ({
10 linkCalls: [] as string[],
@@ -31,40 +33,27 @@ describe('CLI: composio orgs switch', () => {
33 COMPOSIO_USER_API_KEY: 'uak_switch_test',
34 }).pipe(extendConfigProvider);
35
34 - layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
36 + const sessionInfoScopes: MockRequestScope[] = [];
37 + layer(
38 + TestLive({
39 + baseConfigProvider: testConfigProvider,
40 + accountData: {
41 + sessionInfo: scope => {
42 + sessionInfoScopes.push(scope);
43 + return makeSessionInfo({
44 + orgId: 'org_selected',
45 + orgName: 'Selected Org',
46 + orgMemberId: 'member_selected',
47 + });
48 + },
49 + },
50 + })
51 + )(it => {
52 it.effect('[Then] links analytics to the selected org membership', () =>
53 Effect.gen(function* () {
37 - vi.spyOn(globalThis, 'fetch').mockImplementation(
38 - async (_requestInput: RequestInfo | URL, init?: RequestInit) => {
39 - expect(new Headers(init?.headers).get('x-org-id')).toBe('org_selected');
40 - return new Response(
41 - JSON.stringify({
42 - project: {
43 - name: 'Selected Project',
44 - id: 'project_selected',
45 - org_id: 'org_selected',
46 - nano_id: 'project_selected',
47 - email: 'project@example.com',
48 - created_at: '2026-01-01T00:00:00.000Z',
49 - updated_at: '2026-01-01T00:00:00.000Z',
50 - org: { id: 'org_selected', name: 'Selected Org', plan: 'enterprise' },
51 - },
52 - org_member: {
53 - id: 'member_selected',
54 - user_id: 'user_123',
55 - email: 'cli@example.com',
56 - name: 'CLI User',
57 - role: 'admin',
58 - },
59 - api_key: null,
60 - }),
61 - { status: 200, headers: { 'Content-Type': 'application/json' } }
62 - );
63 - }
64 - );
65 -
54 yield* cli(['orgs', 'switch', '--org-id', 'org_selected']);
55
56 + expect(sessionInfoScopes.map(scope => scope.orgId)).toEqual(['org_selected']);
57 expect(analyticsMocks.linkCalls).toEqual(['member_selected']);
58 })
59 );
ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts
+23 -27
@@ -1,40 +1,36 @@
1 import { Effect } from 'effect';
2 import { describe, expect, layer } from '@effect/vitest';
3 -import { afterEach, vi } from 'vitest';
3 import { cli, MockConsole, TestLive } from 'test/__utils__';
5 -
6 -const mockFetchResponse = (body: unknown, status = 200) =>
7 - new Response(JSON.stringify(body), {
8 - status,
9 - headers: { 'Content-Type': 'application/json' },
10 - });
4 +import { makeOrgProject } from 'test/__utils__/models/account';
5 +import type { MockAccountRequest } from 'test/__utils__/services/test-layer';
6
7 describe('CLI: composio dev projects list', () => {
13 - afterEach(() => {
14 - vi.restoreAllMocks();
15 - });
8 + const requests: MockAccountRequest[] = [];
9
17 - layer(TestLive({ fixture: 'user-config-with-global-context' }))(it => {
10 + layer(
11 + TestLive({
12 + fixture: 'user-config-with-global-context',
13 + accountData: {
14 + projects: [
15 + makeOrgProject({ id: 'project_1', name: 'Project One', orgId: 'org_1' }),
16 + makeOrgProject({ id: 'project_2', name: 'Project Two', orgId: 'org_1' }),
17 + ],
18 + onRequest: request => requests.push(request),
19 + },
20 + })
21 + )(it => {
22 it.effect('[Then] lists developer projects and shows init guidance', () =>
23 Effect.gen(function* () {
20 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
21 - mockFetchResponse({
22 - data: [
23 - { id: 'project_1', name: 'Project One' },
24 - { id: 'project_2', name: 'Project Two' },
25 - ],
26 - })
27 - );
28 -
24 yield* cli(['dev', 'projects', 'list', '--org-id', 'org_1']);
25
31 - expect(fetchSpy).toHaveBeenCalledTimes(1);
32 - const [projectUrl, projectRequest] = fetchSpy.mock.calls[0]!;
33 - expect(projectUrl).toContain('/api/v3/org/project/list?limit=50');
34 - expect((projectRequest as RequestInit).headers).toMatchObject({
35 - 'x-user-api-key': 'uak_test_key',
36 - 'x-org-id': 'org_1',
37 - });
26 + expect(requests).toEqual([
27 + expect.objectContaining({
28 + operation: 'org.project.list',
29 + params: { limit: 50 },
30 + scope: expect.objectContaining({ userApiKey: 'uak_test_key', orgId: 'org_1' }),
31 + }),
32 + ]);
33 + expect(requests[0]?.scope.projectId).toBeUndefined();
34
35 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
36 expect(output).toContain('Loaded 2 projects');
ts/packages/cli/test/src/commands/proxy.cmd.test.ts
+13 -7
@@ -1,3 +1,4 @@
1 +import { APIError } from '@composio/client';
2 import { describe, expect, it, layer } from '@effect/vitest';
3 import { ConfigProvider, Effect, Exit, Option } from 'effect';
4 import { afterEach, vi } from 'vitest';
@@ -253,14 +254,19 @@ describe('CLI: composio proxy', () => {
254 fixture: 'global-test-user-id',
255 toolRouter: {
256 proxyExecute: async () => {
256 - throw {
257 - message: 'raw backend error',
258 - details: {
259 - code: 4302,
260 - slug: 'ToolRouterV2_NoActiveConnection',
261 - message: 'No active connection',
257 + throw APIError.generate(
258 + 400,
259 + {
260 + error: {
261 + code: 4302,
262 + slug: 'ToolRouterV2_NoActiveConnection',
263 + message: 'No active connection',
264 + status: 400,
265 + },
266 },
263 - };
267 + undefined,
268 + new Headers()
269 + );
270 },
271 },
272 });
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+29 -11
@@ -5,6 +5,7 @@ import { describe, expect, it, layer } from '@effect/vitest';
5 import { vi, beforeEach, afterEach } from 'vitest';
6 import { Config, ConfigProvider, DateTime, Effect, Option, Predicate } from 'effect';
7 import { extendConfigProvider } from 'src/services/config';
8 +import { APIError } from '@composio/client';
9 import { ComposioNoActiveConnectionError } from 'src/services/composio-error-overrides';
10 import { setupCacheDir } from 'src/effects/setup-cache-dir';
11 import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
@@ -2447,15 +2448,20 @@ describe('CLI: composio execute', () => {
2448 stdin: { isTTY: true, data: '' },
2449 toolRouter: {
2450 execute: async () => {
2450 - throw Object.assign(new Error("No active connection found for toolkit(s) 'gmail'"), {
2451 - error: {
2452 - message: "No active connection found for toolkit(s) 'gmail' in this session",
2453 - code: 4302,
2454 - slug: 'ToolRouterV2_NoActiveConnection',
2455 - status: 400,
2456 - request_id: 'test-request-id',
2451 + throw APIError.generate(
2452 + 400,
2453 + {
2454 + error: {
2455 + message: "No active connection found for toolkit(s) 'gmail' in this session",
2456 + code: 4302,
2457 + slug: 'ToolRouterV2_NoActiveConnection',
2458 + status: 400,
2459 + request_id: 'test-request-id',
2460 + },
2461 },
2458 - });
2462 + undefined,
2463 + new Headers()
2464 + );
2465 },
2466 },
2467 })
@@ -2543,11 +2549,23 @@ describe('CLI: composio execute', () => {
2549 fixture: 'global-test-user-id',
2550 stdin: { isTTY: true, data: '' },
2551 toolsExecutor: {
2546 - failWith: { error: { message: 'API error: invalid input' } },
2552 + failWith: APIError.generate(
2553 + 400,
2554 + {
2555 + error: {
2556 + message: 'API error: invalid input',
2557 + code: 1001,
2558 + slug: 'Validation_Failed',
2559 + status: 400,
2560 + },
2561 + },
2562 + undefined,
2563 + new Headers()
2564 + ),
2565 },
2566 })
2549 - )('[Given] executor throws object error [Then] prints message and details', it => {
2550 - it.effect('prints object error message and details', () =>
2567 + )('[Given] executor throws an API error [Then] prints message and details', it => {
2568 + it.effect('prints API error message and details', () =>
2569 Effect.gen(function* () {
2570 yield* cli([
2571 'execute',
ts/packages/cli/test/src/commands/whoami.cmd.test.ts
+15 -39
@@ -2,13 +2,9 @@ import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 import { extendConfigProvider } from 'src/services/config';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 -import { afterEach, vi } from 'vitest';
5 +import { makeSessionInfo } from 'test/__utils__/models/account';
6
7 describe('CLI: composio whoami', () => {
8 - afterEach(() => {
9 - vi.restoreAllMocks();
10 - });
11 -
8 const testConfigProvider = ConfigProvider.fromEnv({
9 env: { COMPOSIO_USER_API_KEY: 'api_key_from_test_config_provider' },
10 }).pipe(extendConfigProvider);
@@ -47,42 +43,22 @@ describe('CLI: composio whoami', () => {
43 );
44 });
45
50 - layer(TestLive({ baseConfigProvider: testConfigProvider }))('with session info', it => {
46 + layer(
47 + TestLive({
48 + baseConfigProvider: testConfigProvider,
49 + accountData: {
50 + sessionInfo: makeSessionInfo({
51 + orgId: 'org_123',
52 + orgName: 'Acme Org',
53 + orgMemberId: 'om_123',
54 + email: 'person@example.com',
55 + name: 'Test Person',
56 + }),
57 + },
58 + })
59 + )('with session info', it => {
60 it.effect('[Given] session info is available [Then] prints email and org name', () =>
61 Effect.gen(function* () {
53 - vi.spyOn(globalThis, 'fetch').mockResolvedValue(
54 - new Response(
55 - JSON.stringify({
56 - project: {
57 - name: 'Test Project',
58 - id: 'proj_123',
59 - org_id: 'org_123',
60 - nano_id: 'proj_nano_123',
61 - email: 'project@example.com',
62 - created_at: '2026-03-27T00:00:00.000Z',
63 - updated_at: '2026-03-27T00:00:00.000Z',
64 - org: {
65 - name: 'Acme Org',
66 - id: 'org_123',
67 - plan: 'enterprise',
68 - },
69 - },
70 - org_member: {
71 - id: 'om_123',
72 - user_id: 'usr_123',
73 - email: 'person@example.com',
74 - name: 'Test Person',
75 - role: 'admin',
76 - },
77 - api_key: null,
78 - }),
79 - {
80 - status: 200,
81 - headers: { 'Content-Type': 'application/json' },
82 - }
83 - )
84 - );
85 -
62 yield* cli(['whoami']);
63
64 const lines = yield* MockConsole.getLines();
ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+185 -18
@@ -1,16 +1,35 @@
1 -import { afterEach, beforeAll, describe, expect, it, vi } from '@effect/vitest';
1 +import { afterEach, describe, expect, it } from '@effect/vitest';
2 +import { vi } from 'vitest';
3 import * as FileSystem from 'effect/FileSystem';
4 import * as Path from 'effect/Path';
5 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
6 import * as BunPath from '@effect/platform-bun/BunPath';
7 import { ConfigProvider, Effect, Layer } from 'effect';
7 -import { execSync } from 'node:child_process';
8 import * as tempy from 'tempy';
9 import { ComposioClientSingleton } from 'src/services/composio-clients';
10 import { APP_VERSION } from 'src/constants';
11 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
12 import { extendConfigProvider } from 'src/services/config';
13
14 +// Exercise real user-context/config resolution without opening the OS credential store.
15 +vi.mock('@composio/cli-keyring/effect', async importOriginal => {
16 + const actual = await importOriginal<typeof import('@composio/cli-keyring/effect')>();
17 + const { Effect, Layer } = await import('effect');
18 + const { KeyringError } = await import('@composio/cli-keyring');
19 + return {
20 + ...actual,
21 + KeyringLiveWithBackend: () =>
22 + Layer.succeed(actual.KeyringService, {
23 + getPassword: () => Effect.fail(new KeyringError({ kind: 'NoEntry' })),
24 + getSecret: () => Effect.fail(new KeyringError({ kind: 'NoEntry' })),
25 + setPassword: () => Effect.die(new Error('Unexpected credential write')),
26 + setSecret: () => Effect.die(new Error('Unexpected credential write')),
27 + deleteCredential: () => Effect.die(new Error('Unexpected credential deletion')),
28 + isAvailable: Effect.succeed(true),
29 + }),
30 + };
31 +});
32 +
33 const withConfigLayer = (map: Map<string, string>, homedir: string) =>
34 Layer.mergeAll(
35 BunFileSystem.layer,
@@ -61,22 +80,6 @@ const writeCliSessionCache = (
80 });
81
82 describe('ComposioClientSingleton headers', () => {
64 - // Delete any real keychain entry so the subprocess keyring read
65 - // inside ComposioUserContextLive (baked into
66 - // ComposioClientSingleton.Default's dependencies) finds nothing
67 - // and apiKey resolves to Option.none(). Without this, the test
68 - // picks up real credentials and assertions on x-user-api-key fail.
69 - beforeAll(() => {
70 - try {
71 - execSync(
72 - '/usr/bin/security delete-generic-password -s com.composio.cli -a default 2>/dev/null',
73 - { stdio: 'ignore' }
74 - );
75 - } catch {
76 - // Entry may not exist — fine.
77 - }
78 - });
79 -
83 afterEach(() => {
84 vi.restoreAllMocks();
85 vi.unstubAllEnvs();
@@ -224,4 +227,168 @@ describe('ComposioClientSingleton headers', () => {
227 )
228 );
229 });
230 +
231 + it.effect('ignores ambient COMPOSIO_* variables and logs nothing', () => {
232 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
233 + const consoleSpies = (['log', 'info', 'warn', 'error', 'debug'] as const).map(method =>
234 + vi.spyOn(console, method)
235 + );
236 + vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_ambient');
237 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_ambient');
238 + vi.stubEnv('COMPOSIO_CUSTOM_HEADERS', '{"x-extra":"1"}');
239 + vi.stubEnv('COMPOSIO_LOG_LEVEL', 'debug');
240 + const homedir = tempy.temporaryDirectory();
241 + const configMap = new Map([['COMPOSIO_BASE_URL', 'https://backend.composio.dev']]);
242 +
243 + return Effect.gen(function* () {
244 + const clientSingleton = yield* ComposioClientSingleton;
245 + const client = yield* clientSingleton.get();
246 + yield* Effect.promise(() =>
247 + client.tools
248 + .list({ limit: 1, toolkit_versions: 'latest' })
249 + .then(() => undefined)
250 + .catch(() => undefined)
251 + );
252 +
253 + const [, init] = fetchSpy.mock.calls[0]!;
254 + const headers = new Headers((init as RequestInit).headers);
255 + expect(headers.has('x-extra')).toBe(false);
256 + expect(headers.has('x-user-api-key')).toBe(false);
257 + expect(headers.has('x-api-key')).toBe(false);
258 + for (const spy of consoleSpies) {
259 + expect(spy).not.toHaveBeenCalled();
260 + }
261 + }).pipe(
262 + Effect.provide(
263 + Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
264 + )
265 + );
266 + });
267 +
268 + it.effect('sends exactly one user credential when a user key is set', () => {
269 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
270 + const homedir = tempy.temporaryDirectory();
271 + const configMap = new Map([
272 + ['COMPOSIO_USER_API_KEY', 'uak_single'],
273 + ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
274 + ]);
275 +
276 + return Effect.gen(function* () {
277 + const clientSingleton = yield* ComposioClientSingleton;
278 + const client = yield* clientSingleton.get();
279 + // `auth.session.retrieveInfo` is an operation where the client would
280 + // attach its own `userApiKey` credential; the caller-placed header wins.
281 + yield* Effect.promise(() =>
282 + client.auth.session
283 + .retrieveInfo()
284 + .then(() => undefined)
285 + .catch(() => undefined)
286 + );
287 +
288 + const [input, init] = fetchSpy.mock.calls[0]!;
289 + expect(String(input)).toContain('/api/v3.1/auth/session/info');
290 + const headers = new Headers((init as RequestInit).headers);
291 + expect(headers.get('x-user-api-key')).toBe('uak_single');
292 + expect(headers.has('x-api-key')).toBe(false);
293 + }).pipe(
294 + Effect.provide(
295 + Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
296 + )
297 + );
298 + });
299 +
300 + it.effect('supports an explicitly configured plain-HTTP backend without an extra opt-in', () => {
301 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
302 + const homedir = tempy.temporaryDirectory();
303 + const configMap = new Map([
304 + ['COMPOSIO_USER_API_KEY', 'uak_insecure'],
305 + ['COMPOSIO_BASE_URL', 'http://host.docker.internal:9900'],
306 + ]);
307 +
308 + return Effect.gen(function* () {
309 + const clientSingleton = yield* ComposioClientSingleton;
310 + const client = yield* clientSingleton.get();
311 + yield* Effect.promise(() => client.tools.list({ limit: 1, toolkit_versions: 'latest' }));
312 +
313 + expect(fetchSpy).toHaveBeenCalledOnce();
314 + const [input, init] = fetchSpy.mock.calls[0]!;
315 + expect(String(input)).toContain('http://host.docker.internal:9900/');
316 + expect(new Headers((init as RequestInit).headers).get('x-user-api-key')).toBe('uak_insecure');
317 + }).pipe(
318 + Effect.provide(
319 + Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
320 + )
321 + );
322 + });
323 +
324 + it.effect('caches one client per key, org, and project', () => {
325 + const homedir = tempy.temporaryDirectory();
326 + const configMap = new Map([['COMPOSIO_BASE_URL', 'https://backend.composio.dev']]);
327 +
328 + return Effect.gen(function* () {
329 + const clientSingleton = yield* ComposioClientSingleton;
330 + const scope = { userApiKey: 'uak_a', orgId: 'org_a', projectId: 'proj_a' };
331 +
332 + const first = yield* clientSingleton.getFor(scope);
333 + const second = yield* clientSingleton.getFor(scope);
334 + const otherProject = yield* clientSingleton.getFor({ ...scope, projectId: 'proj_b' });
335 +
336 + expect(second).toBe(first);
337 + expect(otherProject).not.toBe(first);
338 + }).pipe(
339 + Effect.provide(
340 + Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
341 + )
342 + );
343 + });
344 +
345 + it.effect('counts requests and response bytes, with or without Content-Length', () => {
346 + const homedir = tempy.temporaryDirectory();
347 + const configMap = new Map([
348 + ['COMPOSIO_USER_API_KEY', 'uak_metrics'],
349 + ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
350 + ]);
351 + const sized = (length: number) =>
352 + new Response(JSON.stringify({ data: [] }).padEnd(length, ' '), {
353 + status: 200,
354 + headers: { 'Content-Type': 'application/json', 'Content-Length': String(length) },
355 + });
356 + const unsized = () =>
357 + new Response(
358 + new ReadableStream<Uint8Array>({
359 + start(controller) {
360 + controller.enqueue(new TextEncoder().encode('{"items":[]}'));
361 + controller.close();
362 + },
363 + }),
364 + { status: 200, headers: { 'Content-Type': 'application/json' } }
365 + );
366 +
367 + return Effect.gen(function* () {
368 + const clientSingleton = yield* ComposioClientSingleton;
369 + const client = yield* clientSingleton.get();
370 + // Installed after the client exists: the counting fetch still resolves
371 + // `globalThis.fetch` per call.
372 + vi.spyOn(globalThis, 'fetch')
373 + .mockResolvedValueOnce(sized(10))
374 + .mockResolvedValueOnce(sized(20))
375 + .mockResolvedValueOnce(unsized());
376 + const list = () =>
377 + Effect.promise(() => client.tools.list({ limit: 1, toolkit_versions: 'latest' }));
378 +
379 + yield* list();
380 + yield* list();
381 + expect(yield* clientSingleton.getMetrics()).toEqual({ requests: 2, byteSize: 30 });
382 +
383 + yield* list();
384 + expect(yield* clientSingleton.getMetrics()).toEqual({
385 + requests: 3,
386 + byteSize: 30 + '{"items":[]}'.length,
387 + });
388 + }).pipe(
389 + Effect.provide(
390 + Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
391 + )
392 + );
393 + });
394 });
ts/packages/cli/test/src/services/composio-clients-cached.test.ts
+49 -1
@@ -1,4 +1,4 @@
1 -import { describe, expect, it } from '@effect/vitest';
1 +import { describe, expect, it, vi } from '@effect/vitest';
2 import { ConfigProvider, DateTime, Effect, Layer } from 'effect';
3 import * as tempy from 'tempy';
4 import {
@@ -16,6 +16,7 @@ import { toolkitsToJSON, type Toolkits } from 'src/models/toolkits';
16 import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
17 import {
18 countingToolkitsRepository,
19 + makeToolkitsRepositoryStub,
20 type GetProjectToolkitsError,
21 type GetToolkitsError,
22 } from 'test/__utils__/services/toolkits-repository-stub';
@@ -226,4 +227,51 @@ describe('ComposioToolkitsRepositoryCached', () => {
227 scope => Effect.succeed([makeToolkitFixture(`custom_${scope?.projectId ?? 'unscoped'}`)])
228 )
229 );
230 +
231 + it.effect('passes an uncached method straight through to the underlying repository', () =>
232 + Effect.gen(function* () {
233 + const searchTools = vi.fn(() =>
234 + Effect.succeed({
235 + items: [],
236 + total_items: 0,
237 + total_pages: 0,
238 + current_page: 1,
239 + next_cursor: null,
240 + })
241 + );
242 + const underlying = makeToolkitsRepositoryStub({ searchTools });
243 + const params = { search: 'gmail', limit: 3 };
244 +
245 + const repository = yield* ComposioToolkitsRepository.pipe(
246 + Effect.provide(
247 + Layer.provide(
248 + ComposioToolkitsRepositoryCached,
249 + Layer.succeed(ComposioToolkitsRepository, underlying)
250 + )
251 + )
252 + );
253 + yield* repository.searchTools(params);
254 +
255 + expect(searchTools).toHaveBeenCalledOnce();
256 + expect(searchTools).toHaveBeenCalledWith(params);
257 + })
258 + );
259 +
260 + it.effect('exposes an underlying method it does not know about', () =>
261 + Effect.gen(function* () {
262 + const addedLater = () => Effect.succeed('added later');
263 + const underlying = Object.assign(makeToolkitsRepositoryStub({}), { addedLater });
264 +
265 + const repository = yield* ComposioToolkitsRepository.pipe(
266 + Effect.provide(
267 + Layer.provide(
268 + ComposioToolkitsRepositoryCached,
269 + Layer.succeed(ComposioToolkitsRepository, underlying)
270 + )
271 + )
272 + );
273 +
274 + expect((repository as typeof underlying).addedLater).toBe(addedLater);
275 + })
276 + );
277 });
ts/packages/cli/test/src/services/composio-clients.test.ts
+544 -41
@@ -1,67 +1,570 @@
1 -import { describe, expect, it } from '@effect/vitest';
2 -import { afterEach, vi } from 'vitest';
1 +import { afterEach, describe, expect, it } from '@effect/vitest';
2 +import { vi } from 'vitest';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import * as BunPath from '@effect/platform-bun/BunPath';
5 -import { ConfigProvider, Effect, Layer } from 'effect';
5 +import { ConfigProvider, Effect, Fiber, Layer } from 'effect';
6 import * as tempy from 'tempy';
7 import {
8 + AmbiguousDeveloperProjectNameError,
9 + ComposioClientSingleton,
10 ComposioToolkitsRepository,
11 + createProjectApiKey,
12 + findDeveloperProjectByName,
13 + getLatestToolVersion,
14 getSessionInfoByUserApiKey,
15 + HttpServerError,
16 + InvalidToolkitsError,
17 + listOrganizations,
18 + listOrgProjects,
19 } from 'src/services/composio-clients';
11 -import { defaultNodeOs, NodeOs } from 'src/services/node-os';
20 +import { handleHttpServerError } from 'src/effects/handle-http-error';
21 import { extendConfigProvider } from 'src/services/config';
22 +import { defaultNodeOs, NodeOs } from 'src/services/node-os';
23 +import { TerminalUI } from 'src/services/terminal-ui';
24 +import { makeOrgProject, makeSessionInfo } from 'test/__utils__/models/account';
25 +import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
26 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
27 +
28 +// Exercise real user-context/config resolution without opening the OS credential store.
29 +vi.mock('@composio/cli-keyring/effect', async importOriginal => {
30 + const actual = await importOriginal<typeof import('@composio/cli-keyring/effect')>();
31 + const { Effect, Layer } = await import('effect');
32 + const { KeyringError } = await import('@composio/cli-keyring');
33 + return {
34 + ...actual,
35 + KeyringLiveWithBackend: () =>
36 + Layer.succeed(actual.KeyringService, {
37 + getPassword: () => Effect.fail(new KeyringError({ kind: 'NoEntry' })),
38 + getSecret: () => Effect.fail(new KeyringError({ kind: 'NoEntry' })),
39 + setPassword: () => Effect.die(new Error('Unexpected credential write')),
40 + setSecret: () => Effect.die(new Error('Unexpected credential write')),
41 + deleteCredential: () => Effect.die(new Error('Unexpected credential deletion')),
42 + isAvailable: Effect.succeed(true),
43 + }),
44 + };
45 +});
46 +
47 +const BASE_URL = 'https://backend.composio.dev';
48 +
49 +const platformLayer = () =>
50 + Layer.mergeAll(
51 + BunFileSystem.layer,
52 + BunPath.layer,
53 + Layer.succeed(NodeOs, defaultNodeOs({ homedir: tempy.temporaryDirectory() })),
54 + Layer.succeed(
55 + ConfigProvider.ConfigProvider,
56 + extendConfigProvider(
57 + ConfigProvider.fromEnv({
58 + env: { COMPOSIO_USER_API_KEY: 'uak_config', COMPOSIO_BASE_URL: BASE_URL },
59 + })
60 + )
61 + )
62 + );
63
14 -const emptyOkResponse = () =>
15 - new Response(JSON.stringify({}), {
16 - status: 200,
17 - headers: { 'Content-Type': 'application/json' },
64 +const withSingleton = Layer.provide(ComposioClientSingleton.Default, platformLayer());
65 +const withRepository = Layer.provide(ComposioToolkitsRepository.Default, platformLayer());
66 +
67 +const jsonResponse = (body: unknown, status = 200, headers: Record<string, string> = {}) =>
68 + new Response(JSON.stringify(body), {
69 + status,
70 + headers: { 'Content-Type': 'application/json', ...headers },
71 });
72
20 -describe('getSessionInfoByUserApiKey org context', () => {
73 +// Error responses opt out of the client's retry policy so a scenario sees
74 +// exactly one request, unless the scenario is about retries.
75 +const errorResponse = (status: number, body: unknown) =>
76 + jsonResponse(body, status, { 'x-should-retry': 'false' });
77 +
78 +const errorEnvelope = (fields: { message: string; code: number; suggested_fix?: string }) => ({
79 + error: { slug: 'Test_Error', status: 0, ...fields },
80 +});
81 +
82 +const requestOf = (call: readonly unknown[] | undefined) => {
83 + const [input, init] = call ?? [];
84 + return {
85 + url: new URL(String(input)),
86 + headers: new Headers((init as RequestInit | undefined)?.headers),
87 + };
88 +};
89 +
90 +// `toolkits.list` items as the API sends them: dates as strings.
91 +const toolkitListItem = (slug: string) => ({
92 + ...makeToolkitFixture(slug),
93 + meta: {
94 + ...makeToolkitFixture(slug).meta,
95 + created_at: '2024-05-03T11:44:32.061Z',
96 + updated_at: '2024-05-03T11:44:32.061Z',
97 + },
98 +});
99 +
100 +describe('composio-clients', () => {
101 afterEach(() => {
102 vi.restoreAllMocks();
103 });
104
25 - // The response body does not satisfy SessionInfoResponse, so decoding fails —
26 - // but the fetch call (whose headers we assert) has already happened by then.
27 - const callIgnoringDecode = (params: { baseURL: string; userApiKey: string; orgId?: string }) =>
28 - getSessionInfoByUserApiKey(params).pipe(Effect.ignore);
29 -
30 - it.effect(
31 - '[Given] orgId [Then] forwards it as x-org-id so the backend honors the switched org',
32 - () =>
105 + describe('account helpers', () => {
106 + it.effect('[Given] orgId [Then] session info carries x-org-id without x-project-id', () =>
107 Effect.gen(function* () {
34 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(emptyOkResponse());
108 + const fetchSpy = vi
109 + .spyOn(globalThis, 'fetch')
110 + .mockResolvedValue(jsonResponse(makeSessionInfo()));
111
36 - yield* callIgnoringDecode({
37 - baseURL: 'https://backend.composio.dev',
38 - userApiKey: 'uak_test',
39 - orgId: 'ok_selected_org',
40 - });
112 + yield* getSessionInfoByUserApiKey({ userApiKey: 'uak_test', orgId: 'ok_selected_org' });
113
42 - const [url, init] = fetchSpy.mock.calls[0]!;
43 - expect(String(url)).toContain('/api/v3/auth/session/info');
44 - const headers = new Headers((init as RequestInit).headers);
114 + const { url, headers } = requestOf(fetchSpy.mock.calls[0]);
115 + expect(url.pathname).toBe('/api/v3.1/auth/session/info');
116 expect(headers.get('x-user-api-key')).toBe('uak_test');
117 expect(headers.get('x-org-id')).toBe('ok_selected_org');
47 - })
48 - );
118 + expect(headers.has('x-project-id')).toBe(false);
119 + expect(headers.has('x-api-key')).toBe(false);
120 + }).pipe(Effect.provide(withSingleton))
121 + );
122
50 - it.effect('[Given] no orgId [Then] omits x-org-id (login-time behavior is unchanged)', () =>
51 - Effect.gen(function* () {
52 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(emptyOkResponse());
123 + it.effect('[Given] no orgId [Then] session info omits x-org-id', () =>
124 + Effect.gen(function* () {
125 + const fetchSpy = vi
126 + .spyOn(globalThis, 'fetch')
127 + .mockResolvedValue(jsonResponse(makeSessionInfo()));
128
54 - yield* callIgnoringDecode({
55 - baseURL: 'https://backend.composio.dev',
56 - userApiKey: 'uak_test',
57 - });
129 + yield* getSessionInfoByUserApiKey({ userApiKey: 'uak_test' });
130
59 - const [, init] = fetchSpy.mock.calls[0]!;
60 - const headers = new Headers((init as RequestInit).headers);
61 - expect(headers.get('x-user-api-key')).toBe('uak_test');
62 - expect(headers.has('x-org-id')).toBe(false);
63 - })
64 - );
131 + const { headers } = requestOf(fetchSpy.mock.calls[0]);
132 + expect(headers.get('x-user-api-key')).toBe('uak_test');
133 + expect(headers.has('x-org-id')).toBe(false);
134 + }).pipe(Effect.provide(withSingleton))
135 + );
136 +
137 + it.effect('[Given] a session without a project [Then] fails with HttpDecodingError', () =>
138 + Effect.gen(function* () {
139 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
140 + jsonResponse({ ...makeSessionInfo(), project: null })
141 + );
142 +
143 + const error = yield* getSessionInfoByUserApiKey({ userApiKey: 'uak_test' }).pipe(
144 + Effect.flip
145 + );
146 +
147 + expect(error._tag).toBe('services/HttpDecodingError');
148 + }).pipe(Effect.provide(withSingleton))
149 + );
150 +
151 + it.effect('listOrganizations returns id and name for each organization', () =>
152 + Effect.gen(function* () {
153 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
154 + jsonResponse({
155 + organizations: [
156 + { id: 'org_a', name: 'A', created_at: 'x', updated_at: 'x' },
157 + { id: 'org_b', name: 'B', created_at: 'x', updated_at: 'x' },
158 + ],
159 + total_pages: 1,
160 + current_page: 1,
161 + total_items: 2,
162 + })
163 + );
164 +
165 + const result = yield* listOrganizations({ apiKey: 'uak_test' });
166 +
167 + expect(result).toEqual({
168 + data: [
169 + { id: 'org_a', name: 'A' },
170 + { id: 'org_b', name: 'B' },
171 + ],
172 + total_items: 2,
173 + });
174 + }).pipe(Effect.provide(withSingleton))
175 + );
176 +
177 + it.effect('listOrgProjects asks for every org project, scoped to the org only', () =>
178 + Effect.gen(function* () {
179 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
180 + jsonResponse({
181 + data: [makeOrgProject({ id: 'p1', name: 'One' })],
182 + total_pages: 1,
183 + current_page: 1,
184 + total_items: 1,
185 + })
186 + );
187 +
188 + yield* listOrgProjects({ apiKey: 'uak_test', orgId: 'org_1' });
189 +
190 + const { url, headers } = requestOf(fetchSpy.mock.calls[0]);
191 + expect(url.pathname).toBe('/api/v3.1/org/project/list');
192 + expect(url.searchParams.get('list_all_org_projects')).toBe('true');
193 + expect(url.searchParams.get('limit')).toBe('50');
194 + expect(headers.get('x-org-id')).toBe('org_1');
195 + expect(headers.has('x-project-id')).toBe(false);
196 + }).pipe(Effect.provide(withSingleton))
197 + );
198 +
199 + it.effect('findDeveloperProjectByName rejects a case-insensitive name collision', () =>
200 + Effect.gen(function* () {
201 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
202 + jsonResponse({
203 + data: [
204 + makeOrgProject({ id: 'p1', name: 'Shared' }),
205 + makeOrgProject({ id: 'p2', name: 'shared' }),
206 + ],
207 + total_pages: 1,
208 + current_page: 1,
209 + total_items: 2,
210 + })
211 + );
212 +
213 + const error = yield* findDeveloperProjectByName({
214 + apiKey: 'uak_test',
215 + orgId: 'org_1',
216 + name: 'SHARED',
217 + }).pipe(Effect.flip);
218 +
219 + expect(error).toBeInstanceOf(AmbiguousDeveloperProjectNameError);
220 + }).pipe(Effect.provide(withSingleton))
221 + );
222 +
223 + it.effect('createProjectApiKey returns the minted key from the response body', () =>
224 + Effect.gen(function* () {
225 + const fetchSpy = vi
226 + .spyOn(globalThis, 'fetch')
227 + .mockResolvedValue(jsonResponse({ data: { api_key: 'uak_minted' } }));
228 +
229 + const key = yield* createProjectApiKey({
230 + apiKey: 'uak_test',
231 + orgId: 'org_1',
232 + projectId: 'proj_1',
233 + name: 'cli',
234 + });
235 +
236 + expect(key).toBe('uak_minted');
237 + const { url, headers } = requestOf(fetchSpy.mock.calls[0]);
238 + expect(url.pathname).toBe('/api/v3/org/project/proj_1/api_keys/create');
239 + expect(headers.get('x-org-id')).toBe('org_1');
240 + expect(headers.get('x-project-id')).toBe('proj_1');
241 + }).pipe(Effect.provide(withSingleton))
242 + );
243 +
244 + it.effect('createProjectApiKey never retries a retryable failure', () =>
245 + Effect.gen(function* () {
246 + // A bare 500 is retryable by default; the create call must still send once.
247 + const fetchSpy = vi
248 + .spyOn(globalThis, 'fetch')
249 + .mockResolvedValue(jsonResponse({ message: 'boom' }, 500));
250 +
251 + const error = yield* createProjectApiKey({
252 + apiKey: 'uak_test',
253 + orgId: 'org_1',
254 + projectId: 'proj_1',
255 + name: 'cli',
256 + }).pipe(Effect.flip);
257 +
258 + expect(fetchSpy).toHaveBeenCalledOnce();
259 + expect(error).toBeInstanceOf(HttpServerError);
260 + expect((error as HttpServerError).status).toBe(500);
261 + }).pipe(Effect.provide(withSingleton))
262 + );
263 +
264 + it.effect('a connection failure maps to HttpServerError without a status', () =>
265 + Effect.gen(function* () {
266 + vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('fetch failed'));
267 +
268 + const error = yield* createProjectApiKey({
269 + apiKey: 'uak_test',
270 + orgId: 'org_1',
271 + projectId: 'proj_1',
272 + name: 'cli',
273 + }).pipe(Effect.flip);
274 +
275 + expect(error).toBeInstanceOf(HttpServerError);
276 + expect((error as HttpServerError).status).toBeUndefined();
277 + }).pipe(Effect.provide(withSingleton))
278 + );
279 +
280 + it.effect('retries a retryable failure and reports the eventual success', () =>
281 + Effect.gen(function* () {
282 + // No `x-should-retry: false` here: this scenario is about the retry
283 + // the owned client performs and the old hand-rolled fetch did not.
284 + const fetchSpy = vi
285 + .spyOn(globalThis, 'fetch')
286 + .mockResolvedValueOnce(jsonResponse({ message: 'flaky' }, 500))
287 + .mockResolvedValueOnce(jsonResponse(makeSessionInfo({ orgName: 'Retried Org' })));
288 +
289 + const info = yield* getSessionInfoByUserApiKey({ userApiKey: 'uak_test' });
290 +
291 + expect(fetchSpy).toHaveBeenCalledTimes(2);
292 + expect(info.project.org.name).toBe('Retried Org');
293 + }).pipe(Effect.provide(withSingleton))
294 + );
295 +
296 + it.effect('getLatestToolVersion with a project key sends exactly one credential', () =>
297 + Effect.gen(function* () {
298 + const fetchSpy = vi
299 + .spyOn(globalThis, 'fetch')
300 + .mockResolvedValue(jsonResponse({ tool_slug: 'GMAIL_SEND_EMAIL', version: '1' }));
301 +
302 + const result = yield* getLatestToolVersion({
303 + apiKey: 'uak_test',
304 + toolSlug: 'GMAIL_SEND_EMAIL',
305 + projectApiKey: 'ak_project',
306 + });
307 +
308 + expect(result.version).toBe('1');
309 + const { url, headers } = requestOf(fetchSpy.mock.calls[0]);
310 + expect(url.pathname).toBe('/api/v3/tools/GMAIL_SEND_EMAIL/get_latest_version');
311 + expect(headers.get('x-api-key')).toBe('ak_project');
312 + expect(headers.has('x-user-api-key')).toBe(false);
313 + }).pipe(Effect.provide(withSingleton))
314 + );
315 + });
316 +
317 + describe('repository request core', () => {
318 + for (const method of ['getToolkits', 'getTools', 'getTriggerTypes'] as const) {
319 + it.effect(`${method} aborts an in-flight pagination request when interrupted`, () =>
320 + Effect.gen(function* () {
321 + const started = Promise.withResolvers<AbortSignal>();
322 + const fetchSpy = vi
323 + .spyOn(globalThis, 'fetch')
324 + .mockResolvedValueOnce(
325 + jsonResponse({ items: [], next_cursor: 'page_2', total_pages: 2 })
326 + )
327 + .mockImplementationOnce((_input, init) => {
328 + const signal = init!.signal!;
329 + started.resolve(signal);
330 + return new Promise<Response>((_resolve, reject) => {
331 + signal.addEventListener('abort', () => reject(signal.reason), { once: true });
332 + });
333 + });
334 + const repository = yield* ComposioToolkitsRepository;
335 + const fiber = yield* Effect.forkChild(repository[method]());
336 + const requestSignal = yield* Effect.promise(() => started.promise);
337 +
338 + yield* Fiber.interrupt(fiber);
339 +
340 + expect(requestSignal.aborted).toBe(true);
341 + expect(fetchSpy).toHaveBeenCalledTimes(2);
342 + }).pipe(Effect.provide(withRepository))
343 + );
344 + }
345 +
346 + it.effect('fetches every toolkit page, sorted by slug, and counts each request', () =>
347 + Effect.gen(function* () {
348 + const fetchSpy = vi
349 + .spyOn(globalThis, 'fetch')
350 + .mockResolvedValueOnce(
351 + jsonResponse({
352 + items: [toolkitListItem('slack'), toolkitListItem('gmail')],
353 + next_cursor: 'page_2',
354 + total_pages: 2,
355 + current_page: 1,
356 + total_items: 3,
357 + })
358 + )
359 + .mockResolvedValueOnce(
360 + jsonResponse({
361 + items: [toolkitListItem('asana')],
362 + next_cursor: null,
363 + total_pages: 2,
364 + current_page: 2,
365 + total_items: 3,
366 + })
367 + );
368 + const repository = yield* ComposioToolkitsRepository;
369 +
370 + const toolkits = yield* repository.getToolkits();
371 +
372 + expect(toolkits.map(t => t.slug)).toEqual(['asana', 'gmail', 'slack']);
373 + expect(fetchSpy).toHaveBeenCalledTimes(2);
374 + expect(requestOf(fetchSpy.mock.calls[0]).url.searchParams.get('limit')).toBe('1000');
375 + expect(requestOf(fetchSpy.mock.calls[1]).url.searchParams.get('cursor')).toBe('page_2');
376 + const metrics = yield* repository.getMetrics();
377 + expect(metrics.requests).toBe(2);
378 + expect(metrics.byteSize).toBeGreaterThan(0);
379 + }).pipe(Effect.provide(withRepository))
380 + );
381 +
382 + it.effect('a list item that breaks the catalog contract fails with HttpDecodingError', () =>
383 + Effect.gen(function* () {
384 + const { meta: _meta, ...withoutMeta } = toolkitListItem('gmail');
385 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
386 + jsonResponse({ items: [withoutMeta], next_cursor: null, total_pages: 1 })
387 + );
388 + const repository = yield* ComposioToolkitsRepository;
389 +
390 + const error = yield* repository.getToolkits().pipe(Effect.flip);
391 +
392 + expect(error._tag).toBe('services/HttpDecodingError');
393 + }).pipe(Effect.provide(withRepository))
394 + );
395 +
396 + it.effect('an API error envelope maps onto status, details, and suggestedFix', () =>
397 + Effect.gen(function* () {
398 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
399 + errorResponse(
400 + 404,
401 + errorEnvelope({ message: 'Not found', code: 404, suggested_fix: 'Check the id' })
402 + )
403 + );
404 + const repository = yield* ComposioToolkitsRepository;
405 +
406 + const error = yield* repository.getAuthConfig('ac_missing').pipe(Effect.flip);
407 +
408 + expect(error).toBeInstanceOf(HttpServerError);
409 + expect(error).toMatchObject({
410 + status: 404,
411 + details: { message: 'Not found', code: 404, suggestedFix: 'Check the id' },
412 + });
413 + }).pipe(Effect.provide(withRepository))
414 + );
415 +
416 + it.effect('a non-envelope error body keeps the status and leaves details undefined', () =>
417 + Effect.gen(function* () {
418 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
419 + errorResponse(502, { message: 'Bad gateway' })
420 + );
421 + const repository = yield* ComposioToolkitsRepository;
422 +
423 + const error = yield* repository.getAuthConfig('ac_1').pipe(Effect.flip);
424 +
425 + expect(error).toMatchObject({ status: 502, details: undefined });
426 + }).pipe(Effect.provide(withRepository))
427 + );
428 +
429 + it.effect('an envelope without suggested_fix renders without a suggested-fix line', () =>
430 + Effect.gen(function* () {
431 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
432 + errorResponse(400, errorEnvelope({ message: 'Bad input', code: 1001 }))
433 + );
434 + const repository = yield* ComposioToolkitsRepository;
435 + const error = yield* repository.getAuthConfig('ac_1').pipe(Effect.flip);
436 + expect(error).toMatchObject({
437 + details: { message: 'Bad input', code: 1001, suggestedFix: undefined },
438 + });
439 +
440 + const errors: string[] = [];
441 + const steps: string[] = [];
442 + const ui = TerminalUI.of({
443 + ...terminalUITestImpl,
444 + log: {
445 + ...terminalUITestImpl.log,
446 + error: message => Effect.sync(() => void errors.push(message)),
447 + step: message => Effect.sync(() => void steps.push(message)),
448 + },
449 + });
450 + const previousExitCode = process.exitCode;
451 + yield* handleHttpServerError(ui, {
452 + fallbackMessage: 'fallback',
453 + hint: 'hint',
454 + fallbackValue: undefined,
455 + })(error as HttpServerError);
456 + process.exitCode = previousExitCode;
457 +
458 + expect(errors).toEqual(['Bad input']);
459 + expect(steps).toEqual(['hint']);
460 + }).pipe(Effect.provide(withRepository))
461 + );
462 +
463 + it.effect('drops credential-bearing fields from auth configs and connected accounts', () =>
464 + Effect.gen(function* () {
465 + const authConfig = {
466 + id: 'ac_1',
467 + uuid: 'uuid_ac_1',
468 + name: 'Gmail auth',
469 + no_of_connections: 0,
470 + status: 'ENABLED',
471 + type: 'default',
472 + toolkit: { slug: 'gmail', logo: '' },
473 + auth_scheme: 'OAUTH2',
474 + is_composio_managed: true,
475 + credentials: { client_secret: 'secret_credentials' },
476 + shared_credentials: { token: 'secret_shared' },
477 + proxy_config: { url: 'https://proxy', api_key: 'secret_proxy' },
478 + deprecated: { secret: 'secret_deprecated' },
479 + };
480 + const connectedAccount = {
481 + id: 'con_1',
482 + status: 'ACTIVE',
483 + status_reason: null,
484 + is_disabled: false,
485 + user_id: 'default',
486 + toolkit: { slug: 'gmail' },
487 + auth_config: {
488 + id: 'ac_1',
489 + auth_scheme: 'OAUTH2',
490 + is_composio_managed: true,
491 + is_disabled: false,
492 + },
493 + created_at: '2026-01-01T00:00:00Z',
494 + updated_at: '2026-01-01T00:00:00Z',
495 + test_request_endpoint: '',
496 + state: { val: { access_token: 'secret_state' } },
497 + data: { access_token: 'secret_data' },
498 + params: { refresh_token: 'secret_params' },
499 + };
500 + vi.spyOn(globalThis, 'fetch')
501 + .mockResolvedValueOnce(jsonResponse(authConfig))
502 + .mockResolvedValueOnce(
503 + jsonResponse({
504 + items: [connectedAccount],
505 + total_items: 1,
506 + total_pages: 1,
507 + current_page: 1,
508 + next_cursor: null,
509 + })
510 + );
511 + const repository = yield* ComposioToolkitsRepository;
512 +
513 + const decodedAuthConfig = yield* repository.getAuthConfig('ac_1');
514 + const accounts = yield* repository.listConnectedAccounts({});
515 +
516 + expect(JSON.stringify(decodedAuthConfig)).not.toContain('secret');
517 + expect(JSON.stringify(accounts)).not.toContain('secret');
518 + expect(accounts.items.map(item => item.id)).toEqual(['con_1']);
519 + }).pipe(Effect.provide(withRepository))
520 + );
521 +
522 + it.effect('getToolkitsBySlugs turns a 404 into InvalidToolkitsError naming the slug', () =>
523 + Effect.gen(function* () {
524 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
525 + errorResponse(404, errorEnvelope({ message: 'Toolkit not found', code: 404 }))
526 + );
527 + const repository = yield* ComposioToolkitsRepository;
528 +
529 + const error = yield* repository.getToolkitsBySlugs(['ghost']).pipe(Effect.flip);
530 +
531 + expect(error).toBeInstanceOf(InvalidToolkitsError);
532 + expect((error as InvalidToolkitsError).invalidToolkits).toEqual(['ghost']);
533 + }).pipe(Effect.provide(withRepository))
534 + );
535 +
536 + it.effect('getToolkitsBySlugs propagates a 500 as HttpServerError', () =>
537 + Effect.gen(function* () {
538 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
539 + errorResponse(500, errorEnvelope({ message: 'Server error', code: 500 }))
540 + );
541 + const repository = yield* ComposioToolkitsRepository;
542 +
543 + const error = yield* repository.getToolkitsBySlugs(['gmail']).pipe(Effect.flip);
544 +
545 + expect(error).toBeInstanceOf(HttpServerError);
546 + expect((error as HttpServerError).status).toBe(500);
547 + }).pipe(Effect.provide(withRepository))
548 + );
549 +
550 + it.effect('validateToolkitVersions ignores an override outside the filter', () =>
551 + Effect.gen(function* () {
552 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
553 + const repository = yield* ComposioToolkitsRepository;
554 +
555 + const result = yield* repository.validateToolkitVersions(
556 + new Map([['slack', '20250101_00']]),
557 + ['gmail']
558 + );
559 +
560 + expect(result.validatedOverrides.size).toBe(0);
561 + expect(result.warnings).toEqual([
562 + 'Version override for "slack" will be ignored (toolkit not in --toolkits filter)',
563 + ]);
564 + expect(fetchSpy).not.toHaveBeenCalled();
565 + }).pipe(Effect.provide(withRepository))
566 + );
567 + });
568 });
569
570 describe('ComposioToolkitsRepository toolkit lists', () => {
ts/packages/cli/test/src/services/composio-error-overrides.test.ts
+64 -53
@@ -1,3 +1,4 @@
1 +import { APIError } from '@composio/client';
2 import { describe, expect, it } from 'vitest';
3
4 import {
@@ -6,34 +7,43 @@ import {
7 mapOnlyComposioOverrideError,
8 } from 'src/services/composio-error-overrides';
9
10 +const apiError = (
11 + status: number,
12 + envelope: { code: number; slug: string; message: string } | Record<string, unknown>
13 +) =>
14 + APIError.generate(
15 + status,
16 + 'code' in envelope ? { error: { status, ...envelope } } : envelope,
17 + undefined,
18 + new Headers({ 'x-request-id': 'req_test' })
19 + );
20 +
21 describe('composio-error-overrides', () => {
10 - it('rewrites tool-router no-active-connection errors by toolkit', () => {
22 + it('rewrites a 4302 API error by toolkit', () => {
23 const result = mapComposioError({
24 toolkit: 'gmail',
13 - error: {
14 - details: {
15 - code: 4302,
16 - slug: 'ToolRouterV2_NoActiveConnection',
17 - message: 'No active connection',
18 - },
19 - },
25 + error: apiError(400, {
26 + code: 4302,
27 + slug: 'SomethingElse',
28 + message: 'No active connection',
29 + }),
30 });
31
32 expect(result.normalized).toBeInstanceOf(ComposioNoActiveConnectionError);
33 expect(result.message).toBe(
34 'No active connection found for toolkit "gmail". Run `composio link gmail`, then retry.'
35 );
36 + expect(result.apiDetails).toMatchObject({ code: 4302, status: 400, request_id: 'req_test' });
37 });
38
28 - it('rewrites execute no-connection errors by tool slug', () => {
39 + it('rewrites an execute no-connection slug by tool slug', () => {
40 const result = mapComposioError({
41 toolSlug: 'SLACK_SEND_MESSAGE',
31 - error: {
32 - error: {
33 - slug: 'ActionExecute_ConnectedAccountNotFound',
34 - message: 'Missing connected account',
35 - },
36 - },
42 + error: apiError(400, {
43 + code: 1,
44 + slug: 'ActionExecute_ConnectedAccountNotFound',
45 + message: 'Missing connected account',
46 + }),
47 });
48
49 expect(result.normalized).toBeInstanceOf(ComposioNoActiveConnectionError);
@@ -42,54 +52,56 @@ describe('composio-error-overrides', () => {
52 );
53 });
54
55 + it('still recognizes an API error wrapped in an Effect cause chain', () => {
56 + const result = mapComposioError({
57 + toolkit: 'gmail',
58 + error: {
59 + _tag: 'UnknownException',
60 + cause: apiError(400, {
61 + code: 1,
62 + slug: 'ToolRouterV2_NoActiveConnection',
63 + message: 'No active connection',
64 + }),
65 + },
66 + });
67 +
68 + expect(result.normalized).toBeInstanceOf(ComposioNoActiveConnectionError);
69 + expect(result.slugValue).toBe('ToolRouterV2_NoActiveConnection');
70 + });
71 +
72 it('passes through unrelated errors', () => {
46 - const error = new Error('Something else broke');
73 + const error = new Error('boom');
74
75 const result = mapComposioError({ error });
76
77 expect(result.normalized).toBe(error);
78 expect(result.override).toBeNull();
52 - expect(result.message).toBe('Something else broke');
79 + expect(result.message).toBe('boom');
80 });
81
55 - it('does not trust malformed API error fields but keeps the valid ones', () => {
56 - const error = {
57 - details: {
58 - code: '4302',
59 - slug: 4302,
60 - message: 'Malformed API error',
61 - },
62 - };
82 + it('keeps a non-envelope API error unmapped, with the error message', () => {
83 + const error = apiError(502, { message: 'Bad gateway' });
84
85 const result = mapComposioError({ error });
86
66 - expect(result.normalized).toBe(error);
67 - expect(result.apiDetails?.message).toBe('Malformed API error');
68 - expect(result.apiDetails?.code).toBeUndefined();
69 - expect(result.apiDetails?.slug).toBeUndefined();
87 expect(result.override).toBeNull();
71 - expect(result.message).toBe('Malformed API error');
88 + expect(result.apiDetails).toMatchObject({ status: 502, code: undefined, slug: undefined });
89 + expect(result.message).toBe(error.message);
90 });
91
74 - it('skips UnknownException wrappers while decoding their causes', () => {
75 - const result = mapComposioError({
76 - toolkit: 'gmail',
77 - error: {
78 - _tag: 'UnknownException',
79 - cause: {
80 - code: 4302,
81 - slug: 'ToolRouterV2_NoActiveConnection',
82 - message: 'No active connection',
83 - },
92 + it('does not classify look-alike plain objects as API errors', () => {
93 + const error = {
94 + details: {
95 + code: 4302,
96 + slug: 'ToolRouterV2_NoActiveConnection',
97 + message: 'Looks like an API error',
98 },
85 - });
99 + };
100
87 - expect(result.normalized).toBeInstanceOf(ComposioNoActiveConnectionError);
88 - expect(result.apiDetails).toEqual({
89 - code: 4302,
90 - slug: 'ToolRouterV2_NoActiveConnection',
91 - message: 'No active connection',
92 - });
101 + const result = mapComposioError({ toolkit: 'gmail', error });
102 +
103 + expect(result.override).toBeNull();
104 + expect(result.apiDetails).toBeUndefined();
105 });
106
107 it('preserves original generic errors for top-level CLI handling', () => {
@@ -104,12 +116,11 @@ describe('composio-error-overrides', () => {
116 it('still rewrites override-class Composio errors at the top level', () => {
117 const mapped = mapOnlyComposioOverrideError({
118 toolkit: 'gmail',
107 - error: {
108 - details: {
109 - code: 4302,
110 - slug: 'ToolRouterV2_NoActiveConnection',
111 - },
112 - },
119 + error: apiError(400, {
120 + code: 4302,
121 + slug: 'ToolRouterV2_NoActiveConnection',
122 + message: 'No active connection',
123 + }),
124 });
125
126 expect(mapped).toBeInstanceOf(ComposioNoActiveConnectionError);
ts/packages/cli/test/src/services/test-layer.test.ts
+38 -6
@@ -1,9 +1,16 @@
1 import { describe, expect, it, vi } from '@effect/vitest';
2 import { Effect } from 'effect';
3 +import {
4 + getSessionInfoByUserApiKey,
5 + HttpServerError,
6 + listOrganizations,
7 + resolveConsumerProject,
8 +} from 'src/services/composio-clients';
9 import { TestLive } from 'test/__utils__';
10 +import { makeSessionInfo } from 'test/__utils__/models/account';
11
12 describe('TestLayer', () => {
6 - it.effect('restores globalThis.fetch after the layer scope closes', () =>
13 + it.effect('leaves globalThis.fetch untouched', () =>
14 Effect.gen(function* () {
15 const originalFetch = globalThis.fetch;
16
@@ -13,16 +20,41 @@ describe('TestLayer', () => {
20 })
21 );
22
16 - it.effect('does not leak the fetch mock into later spy restore cycles', () =>
23 + it.effect('serves account endpoints from the mock client without calling fetch', () =>
24 Effect.gen(function* () {
18 - const originalFetch = globalThis.fetch;
25 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
26
20 - yield* Effect.provide(Effect.void, TestLive()).pipe(Effect.scoped);
27 + const [sessionInfo, consumerProject] = yield* Effect.all([
28 + getSessionInfoByUserApiKey({ userApiKey: 'uak_test', orgId: 'org_selected' }),
29 + resolveConsumerProject({ apiKey: 'uak_test', orgId: 'org_selected' }),
30 + ]).pipe(
31 + Effect.provide(
32 + TestLive({
33 + accountData: {
34 + sessionInfo: scope => makeSessionInfo({ orgId: scope.orgId }),
35 + },
36 + })
37 + ),
38 + Effect.scoped
39 + );
40
22 - vi.spyOn(globalThis, 'fetch');
41 + expect(sessionInfo.project.org.id).toBe('org_selected');
42 + expect(consumerProject.consumer_user_id).toBe('consumer-user-org_selected');
43 + expect(fetchSpy).not.toHaveBeenCalled();
44 vi.restoreAllMocks();
45 + })
46 + );
47
25 - expect(globalThis.fetch).toBe(originalFetch);
48 + it.effect('rejects an account endpoint without data as an unreachable backend would', () =>
49 + Effect.gen(function* () {
50 + const error = yield* listOrganizations({ apiKey: 'uak_test' }).pipe(
51 + Effect.provide(TestLive()),
52 + Effect.scoped,
53 + Effect.flip
54 + );
55 +
56 + expect(error).toBeInstanceOf(HttpServerError);
57 + expect((error as HttpServerError).status).toBeUndefined();
58 })
59 );
60 });
ts/packages/cli/test/src/services/tool-permissions.test.ts
+135 -1
@@ -2,18 +2,33 @@ import * as FileSystem from 'effect/FileSystem';
2 import * as Path from 'effect/Path';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import * as BunPath from '@effect/platform-bun/BunPath';
5 -import { afterEach, beforeEach, describe, expect, it, vi } from '@effect/vitest';
5 +import { afterEach, beforeEach, describe, expect, it } from '@effect/vitest';
6 +import { vi } from 'vitest';
7 import { Config, ConfigProvider, Effect, Layer, Option } from 'effect';
8 +import { Composio as RawComposioClient } from '@composio/client';
9 +
10 +// Enhanced controls are disabled on darwin-x64, so pin the platform: these
11 +// scenarios are about the transport, not about where the CLI runs.
12 +vi.mock('@composio/cli-local-tools', async importOriginal => ({
13 + ...(await importOriginal<typeof import('@composio/cli-local-tools')>()),
14 + detectCliPlatform: () => 'linux-x64',
15 +}));
16 import {
17 decodeCacheFileTolerant,
18 decodeToolRouterPermissionsConfig,
19 gateToolExecution,
20 + refreshConsumerPermissionSnapshot,
21 resolveGateState,
22 ToolPermissionDeniedError,
23 type ConsumerPermissionSnapshot,
24 } from 'src/services/tool-permissions';
25 import { extendConfigProvider } from 'src/services/config';
26 import { NodeOs } from 'src/services/node-os';
27 +import {
28 + ComposioClientConfigurationError,
29 + ComposioClientSingleton,
30 +} from 'src/services/composio-clients';
31 +import { ComposioUserContext } from 'src/services/user-context';
32
33 // Pinned wall clock for deterministic fixtures. The SUT reads the real
34 // `Date.now()` (snapshot TTL, allow-decision expiry), so every timestamp
@@ -43,6 +58,76 @@ const snapshotFixture = (
58 ...overrides,
59 });
60
61 +/**
62 + * The consumer endpoints the permission snapshot reads. Both are absent from
63 + * the v3.1 spec, so production calls them through the client's generic
64 + * `get`/`post`; the double answers at that same boundary.
65 + */
66 +const permissionsClientLayer = (responses: {
67 + readonly config?: unknown;
68 + readonly permissions?: unknown;
69 + readonly clientUnavailable?: boolean;
70 +}) => {
71 + const paths: string[] = [];
72 + const client = {
73 + get: async (path: string) => {
74 + paths.push(`GET ${path}`);
75 + if (responses.config === undefined) throw new Error(`no stub for GET ${path}`);
76 + return responses.config;
77 + },
78 + post: async (path: string) => {
79 + paths.push(`POST ${path}`);
80 + if (responses.permissions === undefined) throw new Error(`no stub for POST ${path}`);
81 + return responses.permissions;
82 + },
83 + } as unknown as RawComposioClient;
84 +
85 + const layer = Layer.mergeAll(
86 + Layer.succeed(
87 + ComposioClientSingleton,
88 + ComposioClientSingleton.of({
89 + get: () => Effect.succeed(client),
90 + getFor: () =>
91 + responses.clientUnavailable === true
92 + ? Effect.fail(
93 + new ComposioClientConfigurationError({
94 + message: 'invalid base URL',
95 + cause: null,
96 + })
97 + )
98 + : Effect.succeed(client),
99 + getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
100 + })
101 + ),
102 + Layer.succeed(
103 + ComposioUserContext,
104 + ComposioUserContext.of({
105 + data: {
106 + apiKey: Option.some('uak_permissions_test'),
107 + baseURL: 'https://backend.composio.dev',
108 + webURL: 'https://app.composio.dev',
109 + orgId: Option.some('org_test'),
110 + projectId: Option.none(),
111 + testUserId: Option.none(),
112 + },
113 + isLoggedIn: () => true,
114 + logout: Effect.void,
115 + login: () => Effect.void,
116 + update: () => Effect.void,
117 + })
118 + )
119 + );
120 +
121 + return { layer, paths };
122 +};
123 +
124 +const refreshParams = {
125 + orgId: 'org_test',
126 + projectId: 'project_test',
127 + consumerUserId: 'user_test',
128 + connectedAccountIds: ['ca_one'],
129 +};
130 +
131 describe('tool permissions', () => {
132 beforeEach(() => {
133 // Fake ONLY `Date`: the SUT's cache reads/writes run on the live Effect
@@ -224,4 +309,53 @@ describe('tool permissions', () => {
309 expect(result).toStrictEqual({ approvalStatus: 'cached_approved' });
310 }).pipe(Effect.provide(ToolPermissionsTest))
311 );
312 +
313 + describe('consumer permission snapshot over the owned client', () => {
314 + it.effect('reads the policy through the client and keeps it in the snapshot', () =>
315 + Effect.gen(function* () {
316 + const stub = permissionsClientLayer({
317 + config: { enhanced_controls: true },
318 + permissions: { experimental: { permissions: { default: 'allow_all', overrides: {} } } },
319 + });
320 +
321 + const snapshot = yield* refreshConsumerPermissionSnapshot(refreshParams).pipe(
322 + Effect.provide(stub.layer)
323 + );
324 +
325 + expect(stub.paths).toEqual([
326 + 'GET /api/v3.1/org/consumer/config',
327 + 'POST /api/v3.1/consumer/permissions/resolve',
328 + ]);
329 + expect(snapshot?.enhancedControlsEnabled).toBe(true);
330 + expect(snapshot?.permissions).toEqual({ default: 'allow_all', overrides: {} });
331 + }).pipe(Effect.provide(ToolPermissionsTest))
332 + );
333 +
334 + it.effect('fails closed to ask_every_call when the policy call fails', () =>
335 + Effect.gen(function* () {
336 + const stub = permissionsClientLayer({ config: { enhanced_controls: true } });
337 +
338 + const snapshot = yield* refreshConsumerPermissionSnapshot(refreshParams).pipe(
339 + Effect.provide(stub.layer)
340 + );
341 +
342 + expect(snapshot?.enhancedControlsEnabled).toBe(true);
343 + expect(snapshot?.permissions).toEqual({ default: 'ask_every_call' });
344 + expect(resolveGateState({ snapshot, toolSlug: 'GMAIL_SEND_EMAIL' })).toBe('ask_every_call');
345 + }).pipe(Effect.provide(ToolPermissionsTest))
346 + );
347 +
348 + it.effect('returns no snapshot when a client cannot be built', () =>
349 + Effect.gen(function* () {
350 + const stub = permissionsClientLayer({ clientUnavailable: true });
351 +
352 + const snapshot = yield* refreshConsumerPermissionSnapshot(refreshParams).pipe(
353 + Effect.provide(stub.layer)
354 + );
355 +
356 + expect(snapshot).toBeUndefined();
357 + expect(stub.paths).toEqual([]);
358 + }).pipe(Effect.provide(ToolPermissionsTest))
359 + );
360 + });
361 });
ts/packages/cli/test/src/utils/api-error-extraction.test.ts
+46 -40
@@ -1,62 +1,68 @@
1 +import { APIConnectionError, APIError } from '@composio/client';
2 import { describe, expect, it } from 'vitest';
2 -import { extractApiErrorDetails } from 'src/utils/api-error-extraction';
3 +import { extractApiErrorDetails, findApiError } from 'src/utils/api-error-extraction';
4 +
5 +const envelope = {
6 + error: {
7 + message: 'Rate limited',
8 + code: 42901,
9 + slug: 'rate_limited',
10 + status: 429,
11 + request_id: 'req_body',
12 + suggested_fix: 'Slow down',
13 + },
14 +};
15
16 describe('extractApiErrorDetails', () => {
5 - it('extracts details from a well-formed API error body', () => {
6 - const details = extractApiErrorDetails({
7 - error: {
8 - message: 'Rate limited',
9 - slug: 'rate_limited',
10 - request_id: 'req_abc',
11 - code: 42901,
12 - },
13 - });
17 + it('reads the envelope, status, and header request id from an APIError', () => {
18 + const error = APIError.generate(
19 + 429,
20 + envelope,
21 + undefined,
22 + new Headers({ 'x-request-id': 'req_header' })
23 + );
24
15 - expect(details).toMatchObject({
25 + expect(extractApiErrorDetails(error)).toEqual({
26 message: 'Rate limited',
17 - slug: 'rate_limited',
18 - request_id: 'req_abc',
27 code: 42901,
28 + slug: 'rate_limited',
29 + status: 429,
30 + request_id: 'req_header',
31 + suggested_fix: 'Slow down',
32 });
33 });
34
23 - it('keeps well-typed fields when a sibling field has an unexpected type', () => {
24 - const details = extractApiErrorDetails({
25 - error: {
26 - message: 42901,
27 - slug: 'rate_limited',
28 - request_id: 'req_abc',
29 - },
35 + it('follows the cause chain to the first APIError', () => {
36 + const error = APIError.generate(429, envelope, undefined, new Headers());
37 + const wrapper = Object.assign(new Error('generic wrapper'), {
38 + cause: { _tag: 'UnknownException', cause: error },
39 });
40
32 - expect(details?.slug).toBe('rate_limited');
33 - expect(details?.request_id).toBe('req_abc');
34 - expect(details?.message).toBeUndefined();
41 + expect(findApiError(wrapper)).toBe(error);
42 + expect(extractApiErrorDetails(wrapper)?.slug).toBe('rate_limited');
43 });
44
37 - it('prefers a node with strong fields over a weaker shallower node', () => {
38 - const details = extractApiErrorDetails({
39 - message: 'outer wrapper',
40 - error: {
41 - message: 'API says no',
42 - slug: 'tool_not_found',
43 - },
44 - });
45 + it('falls back to the error message when the body is not the envelope', () => {
46 + const error = APIError.generate(502, { message: 'Bad gateway' }, undefined, new Headers());
47
46 - expect(details?.slug).toBe('tool_not_found');
47 - expect(details?.message).toBe('API says no');
48 + expect(extractApiErrorDetails(error)).toMatchObject({
49 + message: error.message,
50 + status: 502,
51 + code: undefined,
52 + slug: undefined,
53 + });
54 });
55
50 - it('skips Error wrappers but follows their cause chain', () => {
51 - const inner = { slug: 'expired_key', message: 'Key expired' };
52 - const wrapper = new Error('generic wrapper');
53 - Object.assign(wrapper, { cause: inner });
56 + it('reports a connection error without a status', () => {
57 + const details = extractApiErrorDetails(new APIConnectionError({ message: 'offline' }));
58
55 - expect(extractApiErrorDetails(wrapper)?.slug).toBe('expired_key');
59 + expect(details?.status).toBeUndefined();
60 + expect(details?.message).toBe('offline');
61 });
62
58 - it('returns undefined when nothing in the chain carries API fields', () => {
59 - expect(extractApiErrorDetails({ foo: 'bar' })).toBeUndefined();
63 + it('returns undefined when no APIError is in the chain', () => {
64 + expect(extractApiErrorDetails({ error: envelope.error })).toBeUndefined();
65 + expect(extractApiErrorDetails(new Error('plain'))).toBeUndefined();
66 expect(extractApiErrorDetails(undefined)).toBeUndefined();
67 expect(extractApiErrorDetails('plain string')).toBeUndefined();
68 });