@devries-cameron20 / composio-1 / commits / d96a8694b
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): provide the command surface and share the dev group's flags (#4900)

This PR: - adds `CommandSurface` (`src/commands/surface.ts`): the root tree provides `{ tree: 'root' }`, the `dev` group provides `{ tree: 'dev', userId, projectName }` from its new shared `--user-id` and `--project-name` flags (`Command.withSharedFlags` + `Command.provide` on `dev.cmd.ts`), accepted before or after the subcommand name - defines each dual command once and moves it to the directory shape: `search` (`tools/search/`, the never-registered dev variant `toolsCmd$Search` is gone), `link` (`connected-accounts/link/`), `triggers list` and `triggers info` (`triggers/list/`, `triggers/info/`; the per-tree hints come from the surface), `toolkits info` (`toolkits/info/`); their handlers read the surface instead of a `rootOnly` parameter - keeps two registrations for `execute` / `playground-execute` because the names differ, over one handler that reads `--user-id`/`--project-name` from the surface - drops the private `--user-id` of `connected-accounts list`, `toolkits list` and `triggers listen`, which `withSharedFlags` rejects as duplicates on a direct `dev` subcommand; they read the surface and stay in the legacy shape until their own units - makes every `dev` command either honor each shared flag or reject it: `connected-accounts list`, `toolkits list`, `toolkits info`, `listen` and `triggers listen` resolve the named project (`resolveSurfaceProject`, `namedProjectClient`); the commands that cannot honor a flag yet (`init`, `auth-configs`, `projects`, `toolkits search|version`, `connected-accounts info|whoami`, `triggers list|info|status|create|enable|disable` for both flags, `logs` for `--project-name` only) pipe `rejectsSharedFlags`, and the group's own `dev --mode` toggle calls `rejectSharedFlags`, so each fails with a `CommandInputError` instead of accepting and ignoring the flag - keeps a named project from borrowing the directory's test user: without `--user-id`, `playground-execute`, `connected-accounts link` (`--list`, `--auth-config`), `toolkits info` and `toolkits list` use the directory's `test_user_id` only when `--project-name` is absent or names the directory's own project, and otherwise fall back to the global test user (`directoryTestUserId` in `surface.ts`); with no test user at all, the missing-user error points at `--user-id` or `composio login` instead of `composio dev init` - `dev logs tools` and `dev logs triggers` read their comma-separated `--user-id` filter from the surface, since the shared flag takes every `--user-id` under `dev`; `playground-execute --parallel` falls back to the surface's `--user-id`/`--project-name` when they come before the command name, and finds its command name past a flag value that spells the same word - adds `test/src/commands/surface.test.ts`: both shared rows on every `dev` page and on none of the root pages, the flags reaching a handler before and after the subcommand name, `--project-name` reaching the project resolver for every command that honors it (and `playground-execute --parallel` before and after the command name, including a `--user-id`/`--project-name` value spelled `playground-execute`), each shared flag rejected on the commands that cannot honor it and on the `dev --mode` toggle (which still toggles without them), the test-user fallback for another project, the directory's own project, and no `--project-name` on each of those four commands, and `search --user-id` rejected on the root tree; the `dev logs` client suites check the `user_id` search params before and after the subcommand name - documents the layout rule in `ts/packages/cli/AGENTS.md` and the user-visible change in `CHANGELOG.md` ## Context Unit U1 of the command-layout series (`CommandSurface` as a service, chosen over per-command factories). Two facts of `effect@4.0.3`, checked against the vendored source and a probe, made a help change unavoidable: a direct subcommand may not redeclare a shared flag, and help prepends an ancestor's shared flags to every descendant page. The deliberate help changes, agreed before implementation: - every `dev` page lists `--user-id` and `--project-name` once, with one description each; the dual commands lose their own copies of the two rows - `dev logs tools` and `dev logs triggers` keep their comma-separated `--user-id` filter (allowed below a group entry), which their page shows in place of the shared row - `composio link --help` lists `--auth-config` (one `Command` value); the root command still rejects it with the same `CommandInputError` as before - `composio dev connected-accounts link --help` shows the root examples (`composio link …`), since examples live on the one `Command` value Help diff against `next` (refreshed for the final `--user-id` description, which also covers the commands that use it as a filter), captured through the test harness for 20 pages (`execute`, `search`, `toolkits info`, `tools list`, `triggers list`, `triggers info` are byte-identical; only the rows below changed, plus column re-padding): ```diff === dev.txt > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory === dev_auth-configs_create.txt > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory === dev_connected-accounts_link.txt > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory < --user-id string Developer-project user ID override < --project-name string Developer project name override for this command < composio dev connected-accounts link github < composio dev connected-accounts link gmail --alias work < composio dev connected-accounts link github --list > composio link github > composio link gmail --alias work > composio link github --list === dev_connected-accounts_list.txt < --user-id string Filter by user ID > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory === dev_init.txt > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory === dev_logs.txt > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory === dev_playground-execute.txt > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory < --user-id string Developer-project user ID override < --project-name string Developer project name override for this command === dev_projects_list.txt > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory === dev_toolkits_info.txt < --user-id string User ID for connection status (falls back to project/global test_user_id, then "default") > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory === dev_toolkits_list.txt < --user-id string User ID for connection status (falls back to project/global test_user_id) > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory === dev_triggers_info.txt > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory === dev_triggers_list.txt > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory === dev_triggers_listen.txt > --user-id string User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one. > --project-name string Developer project to use instead of the one configured in this directory < --user-id string Filter by user id === link.txt > --auth-config string Auth config ID (e.g. "ac_..."). Uses legacy flow (no Tool Router). ``` Argv behaviour, exit codes and stdout/stderr lines are unchanged, with two exceptions: a shared flag on a `dev` command that cannot honor it exits 1 with a usage error naming the flag, after the login check (before this PR the flag did not exist there and failed as unknown at parse time, so it stays loud), and root `composio link --auth-config` fails with the consumer-only usage message after the login check instead of as an unrecognized flag. Every pre-existing suite passes as is after the moves (the `dev … --user-id` tests parse through the shared flag). Left for later units: `execute`'s internal `surface`/`projectMode` fields (U4), the `link` handler split into three functions (U5), `connected-accounts list`, `toolkits list` and `triggers listen` moving to the directory shape (U8, U9). ## Deferred - `triggers listen` stays in `COMMAND_TEST_EXEMPTIONS` until U8 adds its mirrored test; this PR does not touch the list, which may only shrink. - The plan's KTD2 (`ResolvedCommandProject` as a cached service) is not done here: each handler that needs a project resolves it once through `resolveSurfaceProject` with the surface's `projectName`, so nothing resolves twice yet. - Per-command `--help` snapshot files are not added; the help diff against `next` was captured through the test harness and is pasted above instead. Rebased on `next` after #4901, #4905, #4909 and #4906 (CHANGELOG entries kept side by side). Verified locally on the branch tip: `pnpm typecheck`; the CLI suite (153 files, 1812 passed, 1 skipped; `validate:command-tests` at 18 exemptions, `validate:boundaries` unchanged); `lint:effect` 0 diagnostics; `oxlint` and prettier clean on every touched file, `validate:agent-skills` and `validate:skill-routing` pass. Binary smoke (`build` + `build:binary`, isolated `HOME`, developer mode on, logged out): `--version` exits 0; `dev --mode off --project-name x`, `dev --user-id a --mode on` and `dev init --user-id a` exit 1 with the usage message and leave developer mode on; `dev toolkits search email --project-name x`, `dev toolkits list --project-name x` and `link gmail --auth-config ac_1` exit 1 with the login hint; `search email --user-id x` exits 1 with `Unrecognized flag: --user-id in command composio search`; `dev toolkits info --help` lists both shared flags once. The logged-in transcript needs a real account and was not run.

Alberto Schiabel committed Oct 16, 2026 at 01:21 UTC d96a8694b5b07b7dc92e5b0281438009068c7627
43 files changed +1823 -924
ts/packages/cli/AGENTS.md
+2 -1
@@ -70,6 +70,7 @@ src/commands/
70 index.ts root command tree, argv contract with cli-main.ts
71 $default.cmd.ts root command: shared flags and description
72 errors.ts CommandInputError, the one usage error every command raises
73 + surface.ts CommandSurface: the tree a command runs in and the dev group's shared flags
74 <group>/<group>.cmd.ts group entry: Command.make(name) + withSubcommands, nothing else
75 <group>/<name>/<group>.<name>.cmd.ts flags, arguments, description, examples, Command.make
76 <group>/<name>/<group>.<name>.handler.ts (params) => Effect; imports nothing from effect/cli
@@ -83,7 +84,7 @@ Rules:
84
85 - `<group>.<name>.cmd.ts` declares the surface and nothing else: flag and argument constants, `Command.withDescription`, `Command.withExamples`, and the three-argument `Command.make(name, flags, handler)` with the handler imported from the sibling `.handler.ts`. It yields no service and contains no branching. `Command.withHandler` is reserved for `src/commands/index.ts`, where the root handler is attached at assembly time.
86 - `<group>.<name>.handler.ts` exports the handler as a function of a plain params type it declares itself; the command proves it provides those params when it passes the handler to `Command.make`. Do not derive the params type from the `Command` value (no phantom commands, no `GetCmdParams`).
86 -- A command that exists in both the root tree and the `dev` tree is defined once. The group supplies what differs between the two surfaces through `Command.withSharedFlags` and `Command.provide`, not through a second `Command.make` with a copied description.
87 +- A command that exists in both the root tree and the `dev` tree is defined once. The group supplies what differs between the two surfaces through `Command.withSharedFlags` and `Command.provide`, not through a second `Command.make` with a copied description. `--user-id` and `--project-name` are shared flags of the `dev` group (`dev.cmd.ts`), accepted before or after the subcommand name and documented once on every `dev` page; a handler reads them, and the tree it runs in, from `CommandSurface` (`surface.ts`) and never declares either flag itself, since `withSharedFlags` rejects a duplicate on a direct subcommand. A `dev` command that cannot honor one of them yet (it cannot target another project, or it does not act for a user) pipes `rejectsSharedFlags` (`surface.ts`), and the `dev` group's own `--mode` toggle calls `rejectSharedFlags`, so the flag fails with a `CommandInputError` instead of being ignored. `execute` and `playground-execute` keep two registrations because their names differ; they share one handler.
88 - Logic shared across groups belongs in `src/effects/` or `src/services/`, never in another command's directory.
89 - A command that needs a logged-in user pipes `requireLogin` (`src/effects/require-auth.ts`) on itself or on its group entry, after `Command.withSubcommands`. Handlers never check `apiKey` or print a login hint; a missing login fails with `NotLoggedInError` and exits 1. Project context comes from `resolveCommandProject`, which fails with `ProjectResolutionError`; never flatten it into a plain `Error`.
90 - A group entry is recognised by its place in the tree: `<dir>/<dir>.cmd.ts` or `<dir>/root-<dir>.cmd.ts` with other `.cmd.ts` files below `<dir>/`. The same name with nothing below it (`logout/logout.cmd.ts`) is a top-level command. Every command needs a test; a group entry does not, though one with a default action (`generate`) still gets one.
ts/packages/cli/CHANGELOG.md
+23
@@ -9,6 +9,29 @@
9 - API requests now carry the CLI's product, version and runtime headers through
10 the API client's `identity` option instead of default headers. The headers
11 sent are unchanged.
12 +- `--user-id` and `--project-name` are now flags of the `composio dev` group,
13 + accepted before or after the subcommand name (`composio dev --user-id alice
14 +toolkits info gmail` and `composio dev toolkits info gmail --user-id alice`
15 + both work) and documented once, with one description each, on every `dev`
16 + page. `dev playground-execute` (including `--parallel`),
17 + `dev connected-accounts link`, `dev connected-accounts list`,
18 + `dev toolkits info`, `dev toolkits list`, `dev listen` and
19 + `dev triggers listen` read them from the group instead of declaring their
20 + own; `dev logs tools` and `dev logs triggers` read the group's `--user-id` as
21 + their comma-separated filter. The other `dev` commands still fail with exit 1
22 + on a flag they cannot honor, now with a usage error naming it instead of an
23 + unrecognized-flag error: `--project-name` on all of them, `--user-id` on all
24 + but `dev logs`. `composio dev --mode` rejects both.
25 + Without `--user-id`, a `dev` command given `--project-name` for another
26 + project falls back to the global test user instead of the directory's
27 + `test_user_id`, which belongs to the directory's project:
28 + `dev playground-execute`, `dev connected-accounts link`,
29 + `dev toolkits info` and `dev toolkits list`. With neither test user set,
30 + the missing-user error now points at `--user-id` or `composio login`.
31 +- `composio link --help` now lists `--auth-config`. The root command still
32 + rejects it, now with the message ``Top-level `composio link` is
33 +consumer-only and does not accept `--auth-config`.`` (exit 1) after the login
34 + check, where it used to fail as an unrecognized flag.
35
36 ## 0.4.4
37
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts
+5 -11
@@ -6,7 +6,7 @@ import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-conne
6 import { failedWith, requestError } from 'src/effects/request-error';
7 import { clampLimit } from 'src/ui/clamp-limit';
8 import { redact } from 'src/ui/redact';
9 -import { resolveCommandProject } from 'src/services/command-project';
9 +import { CommandSurface, resolveSurfaceProject } from 'src/commands/surface';
10 import { formatConnectedAccountsTable, formatConnectedAccountsJson } from '../format';
11 import { idempotent } from 'src/services/composio-request';
12
@@ -19,11 +19,6 @@ const toolkits = Flag.String('toolkits').pipe(
19 Flag.optional
20 );
21
22 -const userId = Flag.String('user-id').pipe(
23 - Flag.withDescription('Filter by user ID'),
24 - Flag.optional
25 -);
26 -
22 const status = Flag.Literals('status', [
23 'INITIALIZING',
24 'INITIATED',
@@ -51,18 +46,17 @@ const limit = Flag.Int('limit').pipe(
46 */
47 export const connectedAccountsCmd$List = Command.make(
48 'list',
54 - { toolkits, userId, status, limit },
55 - ({ toolkits, userId, status, limit }) =>
49 + { toolkits, status, limit },
50 + ({ toolkits, status, limit }) =>
51 Effect.gen(function* () {
52 + const { userId } = yield* CommandSurface;
53 const ui = yield* TerminalUI;
54 const clientSingleton = yield* ComposioClientSingleton;
55
56 const toolkitSlugs = Option.isSome(toolkits)
57 ? toolkits.value.split(',').map(s => s.trim())
58 : undefined;
63 - const resolvedProject = yield* resolveCommandProject({
64 - mode: 'developer',
65 - });
59 + const resolvedProject = yield* resolveSurfaceProject('developer');
60 const client = yield* clientSingleton.getFor({
61 orgId: resolvedProject.orgId,
62 projectId: resolvedProject.projectId,
ts/packages/cli/src/commands/connected-accounts/connected-accounts.cmd.ts
+4 -3
@@ -1,9 +1,10 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 +import { rejectsSharedFlags } from 'src/commands/surface';
4 import { connectedAccountsCmd$List } from './commands/connected-accounts.list.cmd';
5 import { connectedAccountsCmd$Info } from './commands/connected-accounts.info.cmd';
6 import { connectedAccountsCmd$Whoami } from './commands/connected-accounts.whoami.cmd';
6 -import { connectedAccountsCmd$Link } from './commands/connected-accounts.link.cmd';
7 +import { connectedAccountsCmd$Link } from './link/connected-accounts.link.cmd';
8
9 /**
10 * CLI entry point for connected account management commands.
@@ -18,8 +19,8 @@ export const connectedAccountsCmd = Command.make('connected-accounts').pipe(
19 Command.withSubcommands([
20 connectedAccountsCmd$Link,
21 connectedAccountsCmd$List,
21 - connectedAccountsCmd$Info,
22 - connectedAccountsCmd$Whoami,
22 + connectedAccountsCmd$Info.pipe(rejectsSharedFlags('dev connected-accounts info')),
23 + connectedAccountsCmd$Whoami.pipe(rejectsSharedFlags('dev connected-accounts whoami')),
24 ]),
25 requireLogin
26 );
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.cmd.ts new
+64
@@ -0,0 +1,64 @@
1 +import { Argument, Command, Flag } from 'effect/cli';
2 +import { requireLogin } from 'src/effects/require-auth';
3 +import { runConnectedAccountsLink } from './connected-accounts.link.handler';
4 +
5 +const toolkit = Argument.String('toolkit').pipe(
6 + Argument.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
7 + Argument.optional
8 +);
9 +
10 +const authConfig = Flag.String('auth-config').pipe(
11 + Flag.withDescription('Auth config ID (e.g. "ac_..."). Uses legacy flow (no Tool Router).'),
12 + Flag.optional
13 +);
14 +
15 +const noWait = Flag.Boolean('no-wait').pipe(
16 + Flag.withDefault(false),
17 + Flag.withDescription('Do not wait for authorization; only print link info')
18 +);
19 +
20 +const noBrowser = Flag.Boolean('no-browser').pipe(
21 + Flag.withDefault(false),
22 + Flag.withDescription('Do not open the browser automatically; print the URL to open manually')
23 +);
24 +
25 +const alias = Flag.String('alias').pipe(
26 + Flag.withDescription(
27 + 'Alias to assign to the connected account. Required when creating an additional account for the same toolkit/auth config.'
28 + ),
29 + Flag.optional
30 +);
31 +
32 +const list = Flag.Boolean('list').pipe(
33 + Flag.withDefault(false),
34 + Flag.withDescription(
35 + 'List existing connected accounts for the toolkit instead of creating a new link'
36 + )
37 +);
38 +
39 +const linkExamples = [
40 + {
41 + command: 'composio link github',
42 + },
43 + {
44 + command: 'composio link gmail --alias work',
45 + },
46 + {
47 + command: 'composio link github --list',
48 + },
49 +];
50 +
51 +export const connectedAccountsCmd$Link = Command.make(
52 + 'link',
53 + { toolkit, authConfig, noWait, noBrowser, alias, list },
54 + runConnectedAccountsLink
55 +).pipe(
56 + Command.withDescription(
57 + 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.\nOpens a browser for OAuth authorization and waits for confirmation.'
58 + ),
59 + Command.withShortDescription(
60 + 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.'
61 + ),
62 + Command.withExamples(linkExamples),
63 + requireLogin
64 +);
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.errors.ts new
+29
@@ -0,0 +1,29 @@
1 +import { Data } from 'effect';
2 +import { requestError } from 'src/effects/request-error';
3 +
4 +export class ConnectionPollingError extends Data.TaggedError('commands/ConnectionPollingError')<{
5 + readonly message: string;
6 + readonly connectedAccountId: string;
7 + readonly status: string;
8 +}> {}
9 +
10 +export class MissingLinkUserIdError extends Data.TaggedError('commands/MissingLinkUserIdError')<{
11 + readonly message: string;
12 + readonly flow: 'list' | 'legacy' | 'tool-router';
13 +}> {}
14 +
15 +export class ConnectedAccountsDecodeError extends Data.TaggedError(
16 + 'commands/ConnectedAccountsDecodeError'
17 +)<{
18 + readonly message: string;
19 + readonly cause: unknown;
20 +}> {}
21 +
22 +export class ConnectedAccountsRequestError extends requestError(
23 + 'commands/ConnectedAccountsRequestError'
24 +) {}
25 +
26 +export class BrowserOpenError extends Data.TaggedError('commands/BrowserOpenError')<{
27 + readonly message: string;
28 + readonly cause: unknown;
29 +}> {}
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.handler.ts renamed
+66 -177
@@ -1,12 +1,16 @@
1 -import { requireLogin } from 'src/effects/require-auth';
2 -import { commandInputError } from 'src/commands/errors';
3 -import { Argument, Command, Flag } from 'effect/cli';
4 -import { Data, Effect, Option, Schedule } from 'effect';
1 +import { Effect, Option, Schedule } from 'effect';
2 import type { ComposioClientShape } from '@composio/client/effect';
3 import open from 'open';
4 +import { commandInputError } from 'src/commands/errors';
5 +import {
6 + CommandSurface,
7 + directoryTestUserId,
8 + missingUserIdMessage,
9 + type CommandTree,
10 +} from 'src/commands/surface';
11 import { ComposioUserContext } from 'src/services/user-context';
12 import { TerminalUI } from 'src/services/terminal-ui';
9 -import { failedWith, requestError } from 'src/effects/request-error';
13 +import { failedWith } from 'src/effects/request-error';
14 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
15 import { extractApiErrorDetails, extractMessage } from 'src/utils/api-error-extraction';
16 import { ProjectContext } from 'src/services/project-context';
@@ -26,80 +30,25 @@ import {
30 } from 'src/services/connected-account-selection';
31 import { decodeConnectedAccountItems } from 'src/effects/decode-connected-account-list';
32 import { idempotent } from 'src/services/composio-request';
29 -
30 -class ConnectionPollingError extends Data.TaggedError('commands/ConnectionPollingError')<{
31 - readonly message: string;
32 - readonly connectedAccountId: string;
33 - readonly status: string;
34 -}> {}
35 -
36 -class MissingLinkUserIdError extends Data.TaggedError('commands/MissingLinkUserIdError')<{
37 - readonly message: string;
38 - readonly flow: 'list' | 'legacy' | 'tool-router';
39 -}> {}
40 -
41 -class ConnectedAccountsDecodeError extends Data.TaggedError(
42 - 'commands/ConnectedAccountsDecodeError'
43 -)<{
44 - readonly message: string;
45 - readonly cause: unknown;
46 -}> {}
47 -
48 -class ConnectedAccountsRequestError extends requestError(
49 - 'commands/ConnectedAccountsRequestError'
50 -) {}
51 -
52 -class BrowserOpenError extends Data.TaggedError('commands/BrowserOpenError')<{
53 - readonly message: string;
54 - readonly cause: unknown;
55 -}> {}
33 +import {
34 + BrowserOpenError,
35 + ConnectedAccountsDecodeError,
36 + ConnectedAccountsRequestError,
37 + ConnectionPollingError,
38 + MissingLinkUserIdError,
39 +} from './connected-accounts.link.errors';
40 +
41 +export type ConnectedAccountsLinkParams = {
42 + readonly toolkit: Option.Option<string>;
43 + readonly authConfig: Option.Option<string>;
44 + readonly noWait: boolean;
45 + readonly noBrowser: boolean;
46 + readonly alias: Option.Option<string>;
47 + readonly list: boolean;
48 +};
49
50 const invalidOptionValue = commandInputError('link');
51
59 -const toolkit = Argument.String('toolkit').pipe(
60 - Argument.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
61 - Argument.optional
62 -);
63 -
64 -const authConfig = Flag.String('auth-config').pipe(
65 - Flag.withDescription('Auth config ID (e.g. "ac_..."). Uses legacy flow (no Tool Router).'),
66 - Flag.optional
67 -);
68 -
69 -const userId = Flag.String('user-id').pipe(
70 - Flag.withDescription('Developer-project user ID override'),
71 - Flag.optional
72 -);
73 -
74 -const projectName = Flag.String('project-name').pipe(
75 - Flag.optional,
76 - Flag.withDescription('Developer project name override for this command')
77 -);
78 -
79 -const noWait = Flag.Boolean('no-wait').pipe(
80 - Flag.withDefault(false),
81 - Flag.withDescription('Do not wait for authorization; only print link info')
82 -);
83 -
84 -const noBrowser = Flag.Boolean('no-browser').pipe(
85 - Flag.withDefault(false),
86 - Flag.withDescription('Do not open the browser automatically; print the URL to open manually')
87 -);
88 -
89 -const alias = Flag.String('alias').pipe(
90 - Flag.withDescription(
91 - 'Alias to assign to the connected account. Required when creating an additional account for the same toolkit/auth config.'
92 - ),
93 - Flag.optional
94 -);
95 -
96 -const list = Flag.Boolean('list').pipe(
97 - Flag.withDefault(false),
98 - Flag.withDescription(
99 - 'List existing connected accounts for the toolkit instead of creating a new link'
100 - )
101 -);
102 -
52 const showRedirectUrl = (
53 ui: TerminalUI,
54 redirectUrl: string,
@@ -420,9 +369,11 @@ const resolveLinkUserId = (params: {
369 readonly consumerUserId?: string;
370 };
371 readonly requestedUserId: Option.Option<string>;
372 + /** The project `--project-name` resolved to, or none without the flag. */
373 + readonly namedProjectId: Option.Option<string>;
374 readonly projectContext: {
375 readonly resolve: Effect.Effect<
425 - Option.Option<{ readonly testUserId: Option.Option<string> }>,
376 + Option.Option<{ readonly projectId: string; readonly testUserId: Option.Option<string> }>,
377 unknown
378 >;
379 };
@@ -437,7 +388,7 @@ const resolveLinkUserId = (params: {
388 Effect.option,
389 Effect.map(Option.flatten)
390 );
440 - const localTestUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
391 + const localTestUserId = directoryTestUserId(resolvedProjectContext, params.namedProjectId);
392
393 const resolvedUserId =
394 params.resolvedProject.projectType === 'CONSUMER'
@@ -457,7 +408,7 @@ const resolveLinkUserId = (params: {
408 const handleListConnectedAccounts = (params: {
409 readonly toolkit: Option.Option<string>;
410 readonly authConfig: Option.Option<string>;
460 - readonly rootOnly: boolean;
411 + readonly tree: CommandTree;
412 readonly projectName: Option.Option<string>;
413 readonly userId: Option.Option<string>;
414 readonly ui: TerminalUI;
@@ -469,7 +420,7 @@ const handleListConnectedAccounts = (params: {
420 };
421 readonly projectContext: {
422 readonly resolve: Effect.Effect<
472 - Option.Option<{ readonly testUserId: Option.Option<string> }>,
423 + Option.Option<{ readonly projectId: string; readonly testUserId: Option.Option<string> }>,
424 unknown
425 >;
426 };
@@ -494,7 +445,7 @@ const handleListConnectedAccounts = (params: {
445 const toolkitSlug = params.toolkit.value;
446 const resolvedProject = yield* resolveCommandProject({
447 mode: 'consumer',
497 - projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
448 + projectName: Option.getOrUndefined(params.projectName),
449 });
450 const client = yield* params.clientSingleton.getFor({
451 orgId: resolvedProject.orgId,
@@ -503,13 +454,17 @@ const handleListConnectedAccounts = (params: {
454 const { resolvedUserId } = yield* resolveLinkUserId({
455 resolvedProject,
456 requestedUserId: params.userId,
457 + namedProjectId: Option.as(params.projectName, resolvedProject.projectId),
458 projectContext: params.projectContext,
459 userContext: params.userContext,
460 });
461
462 if (Option.isNone(resolvedUserId)) {
463 return yield* new MissingLinkUserIdError({
512 - message: 'Missing user id. Provide --user-id or run composio dev init/login first.',
464 + message: missingUserIdMessage(
465 + params.projectName,
466 + 'Missing user id. Provide --user-id or run composio dev init/login first.'
467 + ),
468 flow: 'list',
469 });
470 }
@@ -598,7 +553,7 @@ const handleLegacyAuthConfigLink = (params: {
553 };
554 readonly projectContext: {
555 readonly resolve: Effect.Effect<
601 - Option.Option<{ readonly testUserId: Option.Option<string> }>,
556 + Option.Option<{ readonly projectId: string; readonly testUserId: Option.Option<string> }>,
557 unknown
558 >;
559 };
@@ -613,7 +568,16 @@ const handleLegacyAuthConfigLink = (params: {
568 Effect.option,
569 Effect.map(Option.flatten)
570 );
616 - const localTestUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
571 + // A named project is looked up first: its id decides whether the directory's test user applies.
572 + const namedResolvedProject = yield* Effect.transposeOption(
573 + Option.map(params.projectName, projectName =>
574 + resolveCommandProject({ mode: 'developer', projectName })
575 + )
576 + );
577 + const localTestUserId = directoryTestUserId(
578 + resolvedProjectContext,
579 + Option.map(namedResolvedProject, project => project.projectId)
580 + );
581 const globalTestUserId = params.userContext.data.testUserId;
582 const resolvedUserId = Option.match(params.requestedUserId, {
583 onSome: value => Option.some(value),
@@ -622,7 +586,10 @@ const handleLegacyAuthConfigLink = (params: {
586
587 if (Option.isNone(resolvedUserId)) {
588 return yield* new MissingLinkUserIdError({
625 - message: 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.',
589 + message: missingUserIdMessage(
590 + params.projectName,
591 + 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'
592 + ),
593 flow: 'legacy',
594 });
595 }
@@ -638,9 +605,9 @@ const handleLegacyAuthConfigLink = (params: {
605 yield* params.ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
606 }
607
641 - const resolvedProject = yield* resolveCommandProject({
642 - mode: 'developer',
643 - projectName: Option.getOrUndefined(params.projectName),
608 + const resolvedProject = yield* Option.match(namedResolvedProject, {
609 + onSome: Effect.succeed,
610 + onNone: () => resolveCommandProject({ mode: 'developer' }),
611 });
612 const client = yield* params.clientSingleton.getFor({
613 orgId: resolvedProject.orgId,
@@ -733,17 +700,7 @@ const handleLegacyAuthConfigLink = (params: {
700 );
701 });
702
736 -const runConnectedAccountsLink = (params: {
737 - toolkit: Option.Option<string>;
738 - authConfig: Option.Option<string>;
739 - userId: Option.Option<string>;
740 - projectName: Option.Option<string>;
741 - noWait: boolean;
742 - noBrowser: boolean;
743 - alias: Option.Option<string>;
744 - list: boolean;
745 - rootOnly: boolean;
746 -}) =>
703 +export const runConnectedAccountsLink = (params: ConnectedAccountsLinkParams) =>
704 Effect.gen(function* () {
705 const normalizedAliasOption = yield* resolveNormalizedAliasOption(params.alias);
706
@@ -751,8 +708,9 @@ const runConnectedAccountsLink = (params: {
708 const clientSingleton = yield* ComposioClientSingleton;
709 const projectContext = yield* ProjectContext;
710 const userContext = yield* ComposioUserContext;
711 + const { tree, userId, projectName } = yield* CommandSurface;
712
755 - if (params.rootOnly) {
713 + if (tree === 'root') {
714 if (Option.isSome(params.authConfig)) {
715 return yield* Effect.fail(
716 invalidOptionValue(
@@ -774,7 +732,7 @@ const runConnectedAccountsLink = (params: {
732
733 if (Option.isNone(params.toolkit) && Option.isNone(params.authConfig)) {
734 yield* ui.log.error(
777 - params.rootOnly
735 + tree === 'root'
736 ? 'Missing argument. Provide a toolkit slug:\n composio link github'
737 : 'Missing argument. Provide a toolkit slug or --auth-config:\n' +
738 ' composio dev connected-accounts link github\n' +
@@ -787,9 +745,9 @@ const runConnectedAccountsLink = (params: {
745 yield* handleListConnectedAccounts({
746 toolkit: params.toolkit,
747 authConfig: params.authConfig,
790 - rootOnly: params.rootOnly,
791 - projectName: params.projectName,
792 - userId: params.userId,
748 + tree,
749 + projectName: projectName,
750 + userId: userId,
751 ui,
752 clientSingleton,
753 projectContext,
@@ -801,8 +759,8 @@ const runConnectedAccountsLink = (params: {
759 if (Option.isSome(params.authConfig)) {
760 yield* handleLegacyAuthConfigLink({
761 authConfigId: params.authConfig.value,
804 - requestedUserId: params.userId,
805 - projectName: params.projectName,
762 + requestedUserId: userId,
763 + projectName: projectName,
764 noWait: params.noWait,
765 noBrowser: params.noBrowser,
766 alias: params.alias,
@@ -818,12 +776,12 @@ const runConnectedAccountsLink = (params: {
776 const toolkitSlug = params.toolkit.value;
777 const resolvedProject = yield* resolveCommandProject({
778 mode: 'consumer',
821 - projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
779 + projectName: Option.getOrUndefined(projectName),
780 });
781 const resolvedUserId =
782 resolvedProject.projectType === 'CONSUMER'
783 ? Option.fromNullishOr(resolvedProject.consumerUserId)
826 - : Option.match(params.userId, {
784 + : Option.match(userId, {
785 onSome: value => Option.some(value),
786 onNone: () => userContext.data.testUserId,
787 });
@@ -967,72 +925,3 @@ const runConnectedAccountsLink = (params: {
925 }).pipe(Effect.ignore);
926 }
927 });
970 -
971 -const linkExamples = [
972 - {
973 - command: 'composio link github',
974 - },
975 - {
976 - command: 'composio link gmail --alias work',
977 - },
978 - {
979 - command: 'composio link github --list',
980 - },
981 -];
982 -
983 -export const connectedAccountsCmd$Link = Command.make(
984 - 'link',
985 - { toolkit, authConfig, userId, projectName, noWait, noBrowser, alias, list },
986 - ({ toolkit, authConfig, userId, projectName, noWait, noBrowser, alias, list }) =>
987 - runConnectedAccountsLink({
988 - toolkit,
989 - authConfig,
990 - userId,
991 - projectName,
992 - noWait,
993 - noBrowser,
994 - alias,
995 - list,
996 - rootOnly: false,
997 - })
998 -).pipe(
999 - Command.withDescription(
1000 - 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.\nOpens a browser for OAuth authorization and waits for confirmation.'
1001 - ),
1002 - Command.withShortDescription(
1003 - 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.'
1004 - ),
1005 - Command.withExamples(
1006 - linkExamples.map(example => ({
1007 - ...example,
1008 - command: example.command.replace('composio link', 'composio dev connected-accounts link'),
1009 - }))
1010 - ),
1011 - requireLogin
1012 -);
1013 -
1014 -export const rootConnectedAccountsCmd$Link = Command.make(
1015 - 'link',
1016 - { toolkit, noWait, noBrowser, alias, list },
1017 - ({ toolkit, noWait, noBrowser, alias, list }) =>
1018 - runConnectedAccountsLink({
1019 - toolkit,
1020 - authConfig: Option.none(),
1021 - userId: Option.none(),
1022 - projectName: Option.none(),
1023 - noWait,
1024 - noBrowser,
1025 - alias,
1026 - list,
1027 - rootOnly: true,
1028 - })
1029 -).pipe(
1030 - Command.withDescription(
1031 - 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.\nOpens a browser for OAuth authorization and waits for confirmation.'
1032 - ),
1033 - Command.withShortDescription(
1034 - 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.'
1035 - ),
1036 - Command.withExamples(linkExamples),
1037 - requireLogin
1038 -);
ts/packages/cli/src/commands/dev.cmd.ts
+53 -13
@@ -15,22 +15,40 @@ import { ComposioCliUserConfig, resolveCliConfigPath } from 'src/services/cli-us
15 import { Stdin } from 'src/services/stdin';
16 import { TerminalUI } from 'src/services/terminal-ui';
17 import type { CommandVisibility } from './feature-tags';
18 +import { CommandSurface, rejectSharedFlags, rejectsSharedFlags } from './surface';
19
20 const devMode = Flag.Literals('mode', ['on', 'off'] as const).pipe(
21 Flag.withDescription('Set developer mode on or off.'),
22 Flag.optional
23 );
24
25 +/**
26 + * Flags every `dev` subcommand accepts, before or after the subcommand name.
27 + * A handler reads them through `CommandSurface`; a subcommand must not declare
28 + * a flag of the same name, `withSharedFlags` rejects the duplicate.
29 + */
30 +const userId = Flag.String('user-id').pipe(
31 + Flag.optional,
32 + Flag.withDescription(
33 + 'User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one.'
34 + )
35 +);
36 +
37 +const projectName = Flag.String('project-name').pipe(
38 + Flag.optional,
39 + Flag.withDescription('Developer project to use instead of the one configured in this directory')
40 +);
41 +
42 export const devSubcommands = [
25 - initCmd,
43 + initCmd.pipe(rejectsSharedFlags('dev init')),
44 devToolsCmd$Execute,
45 triggersCmd$Listen.pipe(requireLogin),
28 - logsCmd,
46 + logsCmd.pipe(rejectsSharedFlags('dev logs', ['--project-name'])),
47 toolkitsCmd,
30 - authConfigsCmd,
48 + authConfigsCmd.pipe(rejectsSharedFlags('dev auth-configs')),
49 connectedAccountsCmd,
50 triggersCmd,
33 - projectsCmd,
51 + projectsCmd.pipe(rejectsSharedFlags('dev projects')),
52 ] as const;
53
54 const describeCurrentMode = (enabled: boolean) =>
@@ -124,8 +142,17 @@ const promptForDeveloperMode = () =>
142 yield* applyDeveloperModeChange(next === 'on');
143 });
144
127 -export const buildDevCommand = (visibility: CommandVisibility) => {
128 - const cmd = Command.make('dev', { devMode }).pipe(
145 +const developerModeHandler = ({ devMode }: { readonly devMode: Option.Option<'on' | 'off'> }) =>
146 + Option.match(devMode, {
147 + onNone: () => promptForDeveloperMode(),
148 + onSome: value => applyDeveloperModeChange(value === 'on'),
149 + });
150 +
151 +const makeDevCommand = <E, R>(
152 + visibility: CommandVisibility,
153 + handler: (input: { readonly devMode: Option.Option<'on' | 'off'> }) => Effect.Effect<void, E, R>
154 +) =>
155 + Command.make('dev', { devMode }).pipe(
156 Command.withDescription(
157 visibility.isDevModeEnabled
158 ? 'Developer workflows: init, playground execution, logs, projects, toolkits, accounts, and triggers.'
@@ -135,13 +162,26 @@ export const buildDevCommand = (visibility: CommandVisibility) => {
162 { command: 'composio dev --mode on' },
163 { command: 'composio dev --mode off' },
164 ]),
138 - Command.withHandler(({ devMode }) =>
139 - Option.match(devMode, {
140 - onNone: () => promptForDeveloperMode(),
141 - onSome: value => applyDeveloperModeChange(value === 'on'),
142 - })
143 - )
165 + Command.withHandler(handler)
166 );
167
146 - return visibility.isDevModeEnabled ? cmd.pipe(Command.withSubcommands([...devSubcommands])) : cmd;
168 +// The developer-mode toggle changes a global setting, for no user and no project.
169 +const toggleRejections = {
170 + '--project-name':
171 + '`composio dev --mode` changes a global setting, so --project-name does not apply. Remove it.',
172 + '--user-id':
173 + '`composio dev --mode` changes a global setting, so --user-id does not apply. Remove it.',
174 };
175 +
176 +export const buildDevCommand = (visibility: CommandVisibility) =>
177 + visibility.isDevModeEnabled
178 + ? makeDevCommand(visibility, input =>
179 + rejectSharedFlags('dev', undefined, toggleRejections).pipe(
180 + Effect.andThen(developerModeHandler(input))
181 + )
182 + ).pipe(
183 + Command.withSubcommands([...devSubcommands]),
184 + Command.withSharedFlags({ userId, projectName }),
185 + Command.provide(({ userId, projectName }) => CommandSurface.dev({ userId, projectName }))
186 + )
187 + : makeDevCommand(visibility, developerModeHandler);
ts/packages/cli/src/commands/index.ts
+8 -5
@@ -24,11 +24,11 @@ import {
24 RootHelpContext,
25 showCommandHelp,
26 } from './root-help';
27 -import { rootToolsCmd$Search } from './tools/commands/tools.search.cmd';
27 +import { toolsCmd$Search } from './tools/search/tools.search.cmd';
28 import { rootToolsCmd$Execute } from './tools/commands/tools.execute.cmd';
29 import { rootToolsCmd } from './tools/tools.cmd';
30 import { rootTriggersCmd } from './triggers/root-triggers.cmd';
31 -import { rootConnectedAccountsCmd$Link } from './connected-accounts/commands/connected-accounts.link.cmd';
31 +import { connectedAccountsCmd$Link } from './connected-accounts/link/connected-accounts.link.cmd';
32 import { orgsCmd } from './orgs/orgs.cmd';
33 import { configCmd } from './config/config.cmd';
34 import { rootConnectionsCmd } from './connections/connections.cmd';
@@ -42,6 +42,7 @@ import { withBackgroundUpdateCheck } from './background-update-check';
42 import { debugCmd } from './debug.cmd';
43 import { normalizeListenStreamFlag, normalizeRunScriptArgs } from './argv-compat';
44 import { configureCliAnalyticsReleaseVersion } from 'src/analytics/events';
45 +import { CommandSurface } from './surface';
46
47 const ROOT_COMMANDS = [
48 tagged(debugCmd),
@@ -60,8 +61,8 @@ const ROOT_COMMANDS = [
61 tagged(installCmd),
62 tagged(rootToolsCmd),
63 tagged(rootTriggersCmd),
63 - tagged(rootToolsCmd$Search),
64 - tagged(rootConnectedAccountsCmd$Link),
64 + tagged(toolsCmd$Search),
65 + tagged(connectedAccountsCmd$Link),
66 tagged(rootToolsCmd$Execute),
67 tagged(rootConnectionsCmd),
68 tagged(generateCmd),
@@ -85,7 +86,9 @@ export const buildRootCommand = (visibility: CommandVisibility) => {
86 ]).pipe(
87 Command.annotate(RootHelpMarker, true),
88 Command.withGlobalFlags(CLI_DEBUG_GLOBAL_FLAGS),
88 - withRootLogLevel
89 + withRootLogLevel,
90 + // The `dev` group provides its own surface around its subcommands; everything else is root.
91 + Command.provide(CommandSurface.root)
92 );
93 };
94
ts/packages/cli/src/commands/logs/commands/logs.tools.cmd.ts
+6 -1
@@ -2,6 +2,7 @@ import { Argument, Command, Flag } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { failedWith, requestError } from 'src/effects/request-error';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 +import { CommandSurface } from 'src/commands/surface';
6 import { ComposioClientSingleton } from 'src/services/composio-clients';
7 import { idempotent } from 'src/services/composio-request';
8 import { clampLimit } from 'src/ui/clamp-limit';
@@ -92,6 +93,9 @@ const status = Flag.String('status').pipe(
93 Flag.optional
94 );
95
96 +// Declared for its help row, which documents the comma-separated filter in place of the `dev`
97 +// group's shared row. The parser hands every `--user-id` under `dev` to the shared flag, so
98 +// the value is read from `CommandSurface`.
99 const userId = Flag.String('user-id').pipe(
100 Flag.withDescription('Filter by user id(s), comma-separated'),
101 Flag.optional
@@ -167,6 +171,7 @@ export const logsCmd$Tools = Command.make(
171 sessionId,
172 }) =>
173 Effect.gen(function* () {
174 + const userIdFilter = Option.orElse((yield* CommandSurface).userId, () => userId);
175 const ui = yield* TerminalUI;
176 const clientSingleton = yield* ComposioClientSingleton;
177 const client = yield* clientSingleton.get();
@@ -177,7 +182,7 @@ export const logsCmd$Tools = Command.make(
182 connectedAccountId: Option.getOrUndefined(connectedAccountId),
183 authConfigId: Option.getOrUndefined(authConfigId),
184 status: Option.getOrUndefined(status),
180 - userId: Option.getOrUndefined(userId),
185 + userId: Option.getOrUndefined(userIdFilter),
186 logId: Option.getOrUndefined(logIdFilter),
187 toolRouterSessionId: Option.getOrUndefined(toolRouterSessionId),
188 sessionId: Option.getOrUndefined(sessionId),
ts/packages/cli/src/commands/logs/commands/logs.triggers.cmd.ts
+7 -2
@@ -2,6 +2,7 @@ import { Argument, Command, Flag } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { failedWith, requestError } from 'src/effects/request-error';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 +import { CommandSurface } from 'src/commands/surface';
6 import { ComposioClientSingleton } from 'src/services/composio-clients';
7 import { clampLimit } from 'src/ui/clamp-limit';
8 import { nonEmptyOrUndefined, optionalParams } from 'src/utils/optional-params';
@@ -19,6 +20,9 @@ const cursor = Flag.String('cursor').pipe(
20 Flag.optional
21 );
22
23 +// Declared for its help row, which documents the comma-separated filter in place of the `dev`
24 +// group's shared row. The parser hands every `--user-id` under `dev` to the shared flag, so
25 +// the value is read from `CommandSurface`.
26 const userId = Flag.String('user-id').pipe(
27 Flag.withDescription('Filter by user id'),
28 Flag.optional
@@ -124,6 +128,7 @@ export const logsCmd$Triggers = Command.make(
128 includePayload,
129 }) =>
130 Effect.gen(function* () {
131 + const userIdFilter = Option.orElse((yield* CommandSurface).userId, () => userId);
132 const ui = yield* TerminalUI;
133 const clientSingleton = yield* ComposioClientSingleton;
134 const client = yield* clientSingleton.get();
@@ -135,8 +140,8 @@ export const logsCmd$Triggers = Command.make(
140 ...(Option.isSome(triggerId)
141 ? parseCsv(triggerId.value).map(value => toSearchParam('trigger_id', value))
142 : []),
138 - ...(Option.isSome(userId)
139 - ? parseCsv(userId.value).map(value => toSearchParam('user_id', value))
143 + ...(Option.isSome(userIdFilter)
144 + ? parseCsv(userIdFilter.value).map(value => toSearchParam('user_id', value))
145 : []),
146 ...(Option.isSome(connectedAccountId)
147 ? parseCsv(connectedAccountId.value).map(value =>
ts/packages/cli/src/commands/surface.ts new
+142
@@ -0,0 +1,142 @@
1 +import { Context, Effect, Layer, Option, pipe } from 'effect';
2 +import { Command } from 'effect/cli';
3 +import { commandInputError } from 'src/commands/errors';
4 +import { resolveCommandProject, type ProjectMode } from 'src/services/command-project';
5 +import { ComposioClientSingleton } from 'src/services/composio-clients';
6 +
7 +/** The command tree a command was invoked from. */
8 +export type CommandTree = 'root' | 'dev';
9 +
10 +export interface CommandSurfaceShape {
11 + readonly tree: CommandTree;
12 + /** `--user-id` of the `dev` group; always none on the root tree. */
13 + readonly userId: Option.Option<string>;
14 + /** `--project-name` of the `dev` group; always none on the root tree. */
15 + readonly projectName: Option.Option<string>;
16 +}
17 +
18 +/**
19 + * What differs between the root tree and the `dev` tree for a command that
20 + * exists in both: each group provides this service around its subcommands, so
21 + * one `Command` value serves both and its handler reads the surface instead of
22 + * taking a `rootOnly` parameter.
23 + */
24 +export class CommandSurface extends Context.Service<CommandSurface, CommandSurfaceShape>()(
25 + 'commands/CommandSurface'
26 +) {
27 + static readonly root: Layer.Layer<CommandSurface> = Layer.succeed(
28 + CommandSurface,
29 + CommandSurface.of({ tree: 'root', userId: Option.none(), projectName: Option.none() })
30 + );
31 +
32 + static readonly dev = (flags: {
33 + readonly userId: Option.Option<string>;
34 + readonly projectName: Option.Option<string>;
35 + }): Layer.Layer<CommandSurface> =>
36 + Layer.succeed(CommandSurface, CommandSurface.of({ tree: 'dev', ...flags }));
37 +}
38 +
39 +/**
40 + * Resolves the command's project for the surface it runs in: the `dev` group's
41 + * `--project-name` picks the developer project, the root tree never has one.
42 + */
43 +export const resolveSurfaceProject = (mode: ProjectMode) =>
44 + Effect.gen(function* () {
45 + const surface = yield* CommandSurface;
46 + return yield* resolveCommandProject({
47 + mode,
48 + projectName: Option.getOrUndefined(surface.projectName),
49 + });
50 + });
51 +
52 +/**
53 + * The developer project the `dev` group's `--project-name` names, with its client, or none when
54 + * the flag is absent and the command keeps the directory's project and its default client.
55 + */
56 +export const namedProject = Effect.gen(function* () {
57 + const surface = yield* CommandSurface;
58 + if (Option.isNone(surface.projectName)) {
59 + return Option.none();
60 + }
61 + const project = yield* resolveSurfaceProject('developer');
62 + const clientSingleton = yield* ComposioClientSingleton;
63 + const client = yield* clientSingleton.getFor({
64 + orgId: project.orgId,
65 + projectId: project.projectId,
66 + });
67 + return Option.some({ projectId: project.projectId, client });
68 +});
69 +
70 +/**
71 + * The test user the directory configures (`.composio/project.json`), for a command that runs
72 + * against the directory's project. A `--project-name` that names another project does not
73 + * borrow it, so the command falls back to the global test user; `namedProjectId` is the id of
74 + * the project `--project-name` resolved to, or none without the flag.
75 + */
76 +export const directoryTestUserId = (
77 + directoryProject: Option.Option<{
78 + readonly projectId: string;
79 + readonly testUserId: Option.Option<string>;
80 + }>,
81 + namedProjectId: Option.Option<string>
82 +): Option.Option<string> =>
83 + pipe(
84 + directoryProject,
85 + Option.filter(
86 + keys => Option.isNone(namedProjectId) || Option.contains(namedProjectId, keys.projectId)
87 + ),
88 + Option.flatMap(keys => keys.testUserId)
89 + );
90 +
91 +/**
92 + * The missing-user message for a command, given its `--project-name`. With the flag the
93 + * directory's test user does not carry over to another project, so the message points at
94 + * `--user-id` and `composio login` instead of `composio dev init`.
95 + */
96 +export const missingUserIdMessage = (projectName: Option.Option<string>, otherwise: string) =>
97 + Option.match(projectName, {
98 + onNone: () => otherwise,
99 + onSome: () =>
100 + 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
101 + });
102 +
103 +/** A shared flag of the `dev` group. */
104 +export type SharedFlag = '--user-id' | '--project-name';
105 +
106 +const unsupportedSharedFlag = (command: string): Record<SharedFlag, string> => ({
107 + '--project-name': `\`composio ${command}\` cannot target another project yet. Remove --project-name, or run it from that project's directory.`,
108 + '--user-id': `\`composio ${command}\` does not act as a user. Remove --user-id.`,
109 +});
110 +
111 +/**
112 + * Fails with a `CommandInputError` when the surface carries one of `flags`, for a `dev` command
113 + * that cannot honor it. Without it the flag would be accepted and ignored. `messages` defaults
114 + * to the wording for a command that runs against the directory's project.
115 + */
116 +export const rejectSharedFlags = (
117 + command: string,
118 + flags: ReadonlyArray<SharedFlag> = ['--project-name', '--user-id'],
119 + messages: Record<SharedFlag, string> = unsupportedSharedFlag(command)
120 +) =>
121 + Effect.gen(function* () {
122 + const surface = yield* CommandSurface;
123 + const values: Record<SharedFlag, Option.Option<string>> = {
124 + '--project-name': surface.projectName,
125 + '--user-id': surface.userId,
126 + };
127 + const given = flags.find(flag => Option.isSome(values[flag]));
128 + if (given !== undefined) {
129 + return yield* commandInputError(command)(messages[given], given);
130 + }
131 + });
132 +
133 +/**
134 + * Applies `rejectSharedFlags` to a `dev` command, or to a group entry and every subcommand
135 + * under it. `flags` defaults to both.
136 + */
137 +export const rejectsSharedFlags =
138 + (command: string, flags?: ReadonlyArray<SharedFlag>) =>
139 + <const Name extends string, Input, ContextInput, E, R>(
140 + self: Command.Command<Name, Input, ContextInput, E, R>
141 + ) =>
142 + Command.provideEffectDiscard(self, rejectSharedFlags(command, flags));
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts deleted
-173
@@ -1,173 +0,0 @@
1 -import { Argument, Command, Flag } from 'effect/cli';
2 -import { Effect, Option } from 'effect';
3 -import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
4 -import { TerminalUI } from 'src/services/terminal-ui';
5 -import { idempotent } from 'src/services/composio-request';
6 -import { failedWith, requestError } from 'src/effects/request-error';
7 -import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
8 -import { extractMessage } from 'src/utils/api-error-extraction';
9 -import { ProjectContext } from 'src/services/project-context';
10 -import { ComposioUserContext } from 'src/services/user-context';
11 -import { formatToolkitInfo, formatToolkitInfoJson } from '../format';
12 -
13 -class ToolkitsInfoRequestError extends requestError('commands/ToolkitsInfoRequestError') {}
14 -
15 -const slug = Argument.String('slug').pipe(
16 - Argument.withDescription('Toolkit slug (e.g. "gmail")'),
17 - Argument.optional
18 -);
19 -
20 -const userId = Flag.String('user-id').pipe(
21 - Flag.optional,
22 - Flag.withDescription(
23 - 'User ID for connection status (falls back to project/global test_user_id, then "default")'
24 - )
25 -);
26 -
27 -const allDetails = Flag.Boolean('all').pipe(
28 - Flag.withAlias('a'),
29 - Flag.withDefault(false),
30 - Flag.withDescription('Show all available toolkit details, including auth config fields')
31 -);
32 -
33 -/**
34 - * View details of a specific toolkit including connection status.
35 - *
36 - * @example
37 - * ```bash
38 - * composio dev toolkits info "gmail"
39 - * composio dev toolkits info "github" --user-id "alice"
40 - * ```
41 - */
42 -export const toolkitsCmd$Info = Command.make(
43 - 'info',
44 - { slug, userId, allDetails },
45 - ({ slug, userId, allDetails }) =>
46 - Effect.gen(function* () {
47 - const ui = yield* TerminalUI;
48 - const projectContext = yield* ProjectContext;
49 - const userContext = yield* ComposioUserContext;
50 - const clientSingleton = yield* ComposioClientSingleton;
51 -
52 - // Missing slug guard
53 - if (Option.isNone(slug)) {
54 - yield* ui.log.warn('Missing required argument: <slug>');
55 - yield* ui.log.step(
56 - 'Try specifying a toolkit slug, e.g.:\n> composio dev toolkits info "gmail"'
57 - );
58 - return;
59 - }
60 -
61 - const slugValue = slug.value;
62 - const repo = yield* ComposioToolkitsRepository;
63 - const resolvedProjectContext = yield* projectContext.resolve;
64 - const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
65 - const globalTestUserId = userContext.data.testUserId;
66 - const resolvedUserId = Option.match(userId, {
67 - onSome: value => Option.some(value),
68 - onNone: () => Option.orElse(testUserId, () => globalTestUserId),
69 - });
70 -
71 - if (Option.isNone(userId) && Option.isSome(testUserId)) {
72 - yield* ui.log.warn(`Using test user id "${testUserId.value}"`);
73 - } else if (Option.isNone(userId) && Option.isSome(globalTestUserId)) {
74 - yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
75 - } else if (Option.isNone(userId)) {
76 - yield* ui.log.info(
77 - 'No test user id found; showing toolkit details without connection status.'
78 - );
79 - }
80 -
81 - const resultOpt = yield* ui
82 - .withSpinner(
83 - `Fetching toolkit "${slugValue}"...`,
84 - Effect.gen(function* () {
85 - const detailedToolkitOpt = yield* repo
86 - .getToolkitDetailed(slugValue)
87 - .pipe(Effect.option);
88 -
89 - if (Option.isSome(resolvedUserId)) {
90 - const client = yield* clientSingleton.get();
91 - const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);
92 - const sessionToolkits = yield* client.toolRouter.session
93 - // Only the first item is read, and only a few of its fields.
94 - .toolkits(sessionId, { toolkits: [slugValue] }, idempotent)
95 - .pipe(
96 - failedWith(ToolkitsInfoRequestError, `Failed to fetch toolkit "${slugValue}".`)
97 - );
98 - return { toolkit: sessionToolkits.items[0], detailedToolkitOpt };
99 - }
100 -
101 - const toolkit = Option.match(detailedToolkitOpt, {
102 - onNone: () => undefined,
103 - onSome: detailed => ({
104 - slug: detailed.slug,
105 - name: detailed.name,
106 - meta: {
107 - description: detailed.meta.description,
108 - logo: '',
109 - },
110 - is_no_auth: detailed.no_auth,
111 - enabled: true,
112 - connected_account: null,
113 - composio_managed_auth_schemes: [...detailed.composio_managed_auth_schemes],
114 - }),
115 - });
116 - return { toolkit, detailedToolkitOpt };
117 - })
118 - )
119 - .pipe(
120 - Effect.asSome,
121 - Effect.catch(error =>
122 - Effect.gen(function* () {
123 - const message = extractMessage(error) ?? `Failed to fetch toolkit "${slugValue}".`;
124 - yield* ui.log.error(message);
125 - yield* Effect.logDebug('Toolkit info error:', error);
126 - yield* ui.log.step('Browse available toolkits:\n> composio dev toolkits list');
127 - return Option.none();
128 - })
129 - )
130 - );
131 -
132 - if (Option.isNone(resultOpt)) {
133 - return;
134 - }
135 -
136 - const result = resultOpt.value;
137 - const toolkit = result.toolkit;
138 - const detailedToolkit = Option.getOrUndefined(result.detailedToolkitOpt);
139 -
140 - if (!toolkit) {
141 - yield* ui.log.warn(`Toolkit "${slugValue}" not found.`);
142 -
143 - // "Did you mean?" suggestions via legacy search
144 - const suggestions = yield* repo.searchToolkits({ search: slugValue, limit: 3 }).pipe(
145 - Effect.map(r =>
146 - r.items.map(s => ({
147 - label: `${s.slug} — ${s.meta.description}`,
148 - command: `> composio dev toolkits info "${s.slug}"`,
149 - }))
150 - ),
151 - Effect.catch(() => Effect.succeed([] as { label: string; command: string }[]))
152 - );
153 -
154 - const [first] = suggestions;
155 - if (first) {
156 - const lines = suggestions.map(s => ` ${s.label}`).join('\n');
157 - yield* ui.log.step(`Did you mean?\n${lines}\n\n${first.command}`);
158 - } else {
159 - yield* ui.log.step('Browse available toolkits:\n> composio dev toolkits list');
160 - }
161 - return;
162 - }
163 -
164 - yield* ui.log.message(
165 - `Toolkit: ${toolkit.name}\n\n${formatToolkitInfo(toolkit, detailedToolkit, allDetails)}`
166 - );
167 -
168 - // Next step hint
169 - yield* ui.log.step(`To list tools in this toolkit:\n> composio tools list "${toolkit.slug}"`);
170 -
171 - yield* ui.output(formatToolkitInfoJson(toolkit, detailedToolkit, allDetails));
172 - })
173 -).pipe(Command.withDescription('View details of a specific toolkit.'));
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+13 -9
@@ -7,6 +7,7 @@ import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/service
7 import { idempotent } from 'src/services/composio-request';
8 import { ProjectContext } from 'src/services/project-context';
9 import { ComposioUserContext } from 'src/services/user-context';
10 +import { CommandSurface, directoryTestUserId, namedProject } from 'src/commands/surface';
11 import { clampLimit } from 'src/ui/clamp-limit';
12 import { extractMessage } from 'src/utils/api-error-extraction';
13 import { mergeToolkitData, formatToolkitsJson, formatToolkitsTable } from '../format';
@@ -26,11 +27,6 @@ const connected = Flag.Boolean('connected').pipe(
27 Flag.optional
28 );
29
29 -const userId = Flag.String('user-id').pipe(
30 - Flag.optional,
31 - Flag.withDescription('User ID for connection status (falls back to project/global test_user_id)')
32 -);
33 -
30 /**
31 * List available toolkits with connection status.
32 *
@@ -48,9 +44,10 @@ const userId = Flag.String('user-id').pipe(
44 */
45 export const toolkitsCmd$List = Command.make(
46 'list',
51 - { query, limit, connected, userId },
52 - ({ query, limit, connected, userId }) =>
47 + { query, limit, connected },
48 + ({ query, limit, connected }) =>
49 Effect.gen(function* () {
50 + const { userId } = yield* CommandSurface;
51 const ui = yield* TerminalUI;
52 const repo = yield* ComposioToolkitsRepository;
53 const clientSingleton = yield* ComposioClientSingleton;
@@ -58,8 +55,13 @@ export const toolkitsCmd$List = Command.make(
55 const userContext = yield* ComposioUserContext;
56
57 const clampedLimit = clampLimit(limit);
58 + // Resolved outside the session lookup, whose failures only drop the connection status.
59 + const project = yield* namedProject;
60 const resolvedProjectContext = yield* projectContext.resolve;
62 - const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
61 + const testUserId = directoryTestUserId(
62 + resolvedProjectContext,
63 + Option.map(project, named => named.projectId)
64 + );
65 const globalTestUserId = userContext.data.testUserId;
66 const resolvedUserId = Option.match(userId, {
67 onSome: value => Option.some(value),
@@ -93,7 +95,9 @@ export const toolkitsCmd$List = Command.make(
95 // Resolve session context in parallel with catalog fetch (saves one round trip).
96 const sessionContextEffect = Option.isSome(resolvedUserId)
97 ? Effect.gen(function* () {
96 - const client = yield* clientSingleton.get();
98 + const client = Option.isSome(project)
99 + ? project.value.client
100 + : yield* clientSingleton.get();
101 const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);
102 return { client, sessionId };
103 }).pipe(
ts/packages/cli/src/commands/toolkits/info/toolkits.info.cmd.ts new
+26
@@ -0,0 +1,26 @@
1 +import { Argument, Command, Flag } from 'effect/cli';
2 +import { runToolkitsInfo } from './toolkits.info.handler';
3 +
4 +const slug = Argument.String('slug').pipe(
5 + Argument.withDescription('Toolkit slug (e.g. "gmail")'),
6 + Argument.optional
7 +);
8 +
9 +const allDetails = Flag.Boolean('all').pipe(
10 + Flag.withAlias('a'),
11 + Flag.withDefault(false),
12 + Flag.withDescription('Show all available toolkit details, including auth config fields')
13 +);
14 +
15 +/**
16 + * View details of a specific toolkit including connection status.
17 + *
18 + * @example
19 + * ```bash
20 + * composio dev toolkits info "gmail"
21 + * composio dev toolkits info "github" --user-id "alice"
22 + * ```
23 + */
24 +export const toolkitsCmd$Info = Command.make('info', { slug, allDetails }, runToolkitsInfo).pipe(
25 + Command.withDescription('View details of a specific toolkit.')
26 +);
ts/packages/cli/src/commands/toolkits/info/toolkits.info.errors.ts new
+3
@@ -0,0 +1,3 @@
1 +import { requestError } from 'src/effects/request-error';
2 +
3 +export class ToolkitsInfoRequestError extends requestError('commands/ToolkitsInfoRequestError') {}
ts/packages/cli/src/commands/toolkits/info/toolkits.info.handler.ts new
+156
@@ -0,0 +1,156 @@
1 +import { Effect, Option } from 'effect';
2 +import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
3 +import { TerminalUI } from 'src/services/terminal-ui';
4 +import { idempotent } from 'src/services/composio-request';
5 +import { failedWith } from 'src/effects/request-error';
6 +import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
7 +import { extractMessage } from 'src/utils/api-error-extraction';
8 +import { ProjectContext } from 'src/services/project-context';
9 +import { ComposioUserContext } from 'src/services/user-context';
10 +import { CommandSurface, directoryTestUserId, namedProject } from 'src/commands/surface';
11 +import { formatToolkitInfo, formatToolkitInfoJson } from '../format';
12 +import { ToolkitsInfoRequestError } from './toolkits.info.errors';
13 +
14 +export type ToolkitsInfoParams = {
15 + readonly slug: Option.Option<string>;
16 + readonly allDetails: boolean;
17 +};
18 +
19 +/**
20 + * Shows a toolkit with its connection status for the surface's user: the `dev`
21 + * group's `--user-id`, then the project test user id, then the global one.
22 + */
23 +export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
24 + Effect.gen(function* () {
25 + const { userId } = yield* CommandSurface;
26 + const ui = yield* TerminalUI;
27 + const projectContext = yield* ProjectContext;
28 + const userContext = yield* ComposioUserContext;
29 + const clientSingleton = yield* ComposioClientSingleton;
30 +
31 + // Missing slug guard
32 + if (Option.isNone(slug)) {
33 + yield* ui.log.warn('Missing required argument: <slug>');
34 + yield* ui.log.step(
35 + 'Try specifying a toolkit slug, e.g.:\n> composio dev toolkits info "gmail"'
36 + );
37 + return;
38 + }
39 +
40 + const slugValue = slug.value;
41 + // Resolved outside the session lookup, whose failures only drop the connection status.
42 + const project = yield* namedProject;
43 + const repo = yield* ComposioToolkitsRepository;
44 + const resolvedProjectContext = yield* projectContext.resolve;
45 + const testUserId = directoryTestUserId(
46 + resolvedProjectContext,
47 + Option.map(project, named => named.projectId)
48 + );
49 + const globalTestUserId = userContext.data.testUserId;
50 + const resolvedUserId = Option.match(userId, {
51 + onSome: value => Option.some(value),
52 + onNone: () => Option.orElse(testUserId, () => globalTestUserId),
53 + });
54 +
55 + if (Option.isNone(userId) && Option.isSome(testUserId)) {
56 + yield* ui.log.warn(`Using test user id "${testUserId.value}"`);
57 + } else if (Option.isNone(userId) && Option.isSome(globalTestUserId)) {
58 + yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
59 + } else if (Option.isNone(userId)) {
60 + yield* ui.log.info(
61 + 'No test user id found; showing toolkit details without connection status.'
62 + );
63 + }
64 +
65 + const resultOpt = yield* ui
66 + .withSpinner(
67 + `Fetching toolkit "${slugValue}"...`,
68 + Effect.gen(function* () {
69 + const detailedToolkitOpt = yield* repo.getToolkitDetailed(slugValue).pipe(Effect.option);
70 +
71 + if (Option.isSome(resolvedUserId)) {
72 + const client = Option.isSome(project)
73 + ? project.value.client
74 + : yield* clientSingleton.get();
75 + const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);
76 + const sessionToolkits = yield* client.toolRouter.session
77 + // Only the first item is read, and only a few of its fields.
78 + .toolkits(sessionId, { toolkits: [slugValue] }, idempotent)
79 + .pipe(
80 + failedWith(ToolkitsInfoRequestError, `Failed to fetch toolkit "${slugValue}".`)
81 + );
82 + return { toolkit: sessionToolkits.items[0], detailedToolkitOpt };
83 + }
84 +
85 + const toolkit = Option.match(detailedToolkitOpt, {
86 + onNone: () => undefined,
87 + onSome: detailed => ({
88 + slug: detailed.slug,
89 + name: detailed.name,
90 + meta: {
91 + description: detailed.meta.description,
92 + logo: '',
93 + },
94 + is_no_auth: detailed.no_auth,
95 + enabled: true,
96 + connected_account: null,
97 + composio_managed_auth_schemes: [...detailed.composio_managed_auth_schemes],
98 + }),
99 + });
100 + return { toolkit, detailedToolkitOpt };
101 + })
102 + )
103 + .pipe(
104 + Effect.asSome,
105 + Effect.catch(error =>
106 + Effect.gen(function* () {
107 + const message = extractMessage(error) ?? `Failed to fetch toolkit "${slugValue}".`;
108 + yield* ui.log.error(message);
109 + yield* Effect.logDebug('Toolkit info error:', error);
110 + yield* ui.log.step('Browse available toolkits:\n> composio dev toolkits list');
111 + return Option.none();
112 + })
113 + )
114 + );
115 +
116 + if (Option.isNone(resultOpt)) {
117 + return;
118 + }
119 +
120 + const result = resultOpt.value;
121 + const toolkit = result.toolkit;
122 + const detailedToolkit = Option.getOrUndefined(result.detailedToolkitOpt);
123 +
124 + if (!toolkit) {
125 + yield* ui.log.warn(`Toolkit "${slugValue}" not found.`);
126 +
127 + // "Did you mean?" suggestions via legacy search
128 + const suggestions = yield* repo.searchToolkits({ search: slugValue, limit: 3 }).pipe(
129 + Effect.map(r =>
130 + r.items.map(s => ({
131 + label: `${s.slug} — ${s.meta.description}`,
132 + command: `> composio dev toolkits info "${s.slug}"`,
133 + }))
134 + ),
135 + Effect.catch(() => Effect.succeed([] as { label: string; command: string }[]))
136 + );
137 +
138 + const [first] = suggestions;
139 + if (first) {
140 + const lines = suggestions.map(s => ` ${s.label}`).join('\n');
141 + yield* ui.log.step(`Did you mean?\n${lines}\n\n${first.command}`);
142 + } else {
143 + yield* ui.log.step('Browse available toolkits:\n> composio dev toolkits list');
144 + }
145 + return;
146 + }
147 +
148 + yield* ui.log.message(
149 + `Toolkit: ${toolkit.name}\n\n${formatToolkitInfo(toolkit, detailedToolkit, allDetails)}`
150 + );
151 +
152 + // Next step hint
153 + yield* ui.log.step(`To list tools in this toolkit:\n> composio tools list "${toolkit.slug}"`);
154 +
155 + yield* ui.output(formatToolkitInfoJson(toolkit, detailedToolkit, allDetails));
156 + });
ts/packages/cli/src/commands/toolkits/toolkits.cmd.ts
+4 -3
@@ -1,7 +1,8 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 +import { rejectsSharedFlags } from 'src/commands/surface';
4 import { toolkitsCmd$List } from './commands/toolkits.list.cmd';
4 -import { toolkitsCmd$Info } from './commands/toolkits.info.cmd';
5 +import { toolkitsCmd$Info } from './info/toolkits.info.cmd';
6 import { toolkitsCmd$Search } from './commands/toolkits.search.cmd';
7 import { toolkitsCmd$Version } from './commands/toolkits.version.cmd';
8
@@ -18,8 +19,8 @@ export const toolkitsCmd = Command.make('toolkits').pipe(
19 Command.withSubcommands([
20 toolkitsCmd$List,
21 toolkitsCmd$Info,
21 - toolkitsCmd$Search,
22 - toolkitsCmd$Version,
22 + toolkitsCmd$Search.pipe(rejectsSharedFlags('dev toolkits search')),
23 + toolkitsCmd$Version.pipe(rejectsSharedFlags('dev toolkits version')),
24 ]),
25 requireLogin
26 );
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+38 -21
@@ -1,4 +1,5 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 +import { CommandSurface, directoryTestUserId, missingUserIdMessage } from 'src/commands/surface';
3 import { commandInputError } from 'src/commands/errors';
4 import { Argument, Command, Flag } from 'effect/cli';
5 import util from 'node:util';
@@ -92,16 +93,6 @@ const accountOption = Flag.String('account').pipe(
93 Flag.optional
94 );
95
95 -const userId = Flag.String('user-id').pipe(
96 - Flag.optional,
97 - Flag.withDescription('Developer-project user ID override')
98 -);
99 -
100 -const projectName = Flag.String('project-name').pipe(
101 - Flag.optional,
102 - Flag.withDescription('Developer project name override for this command')
103 -);
104 -
96 const getSchema = Flag.Boolean('get-schema').pipe(
97 Flag.withDescription('Fetch and print the CLI-facing input schema without executing'),
98 Flag.withDefault(false)
@@ -852,10 +843,11 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
843 const parsedArgs = yield* parseArguments(input);
844 const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;
845
846 + // The root tree has no --project-name.
847 + const projectName = Option.filter(params.projectName, () => params.surface !== 'root');
848 const resolvedProject = yield* resolveCommandProject({
849 mode: params.projectMode,
857 - projectName:
858 - params.surface === 'root' ? undefined : Option.getOrUndefined(params.projectName),
850 + projectName: Option.getOrUndefined(projectName),
851 });
852 const clientSingleton = yield* ComposioClientSingleton;
853 const userContext = yield* ComposioUserContext;
@@ -864,7 +856,10 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
856 const localProjectContext = yield* projectContext.resolve.pipe(
857 Effect.catch(() => Effect.succeed(Option.none()))
858 );
867 - const localTestUserId = Option.flatMap(localProjectContext, keys => keys.testUserId);
859 + const localTestUserId = directoryTestUserId(
860 + localProjectContext,
861 + Option.as(projectName, resolvedProject.projectId)
862 + );
863 const resolvedUserId =
864 resolvedProject.projectType === 'CONSUMER'
865 ? Option.fromNullishOr(resolvedProject.consumerUserId)
@@ -877,10 +872,12 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
872 return yield* new ToolExecutionError({
873 reason: 'missing_user_id',
874 toolSlug: params.slug,
880 - message:
875 + message: missingUserIdMessage(
876 + projectName,
877 params.projectMode === 'developer'
878 ? 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.'
883 - : 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
879 + : 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
880 + ),
881 });
882 }
883
@@ -1873,6 +1870,21 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
1870 }
1871 });
1872
1873 +// Flags that can precede the command name and take the next token as their value
1874 +// (`$default.cmd.ts`, `dev.cmd.ts`), so a value equal to the command name is not the command.
1875 +const VALUE_FLAGS_BEFORE_COMMAND = new Set([
1876 + '--log-level',
1877 + '--mode',
1878 + '--user-id',
1879 + '--project-name',
1880 +]);
1881 +
1882 +/** The index of the command name in argv, skipping a flag value that spells the same word. */
1883 +const commandNameIndex = (argv: ReadonlyArray<string>, name: string) =>
1884 + argv.findIndex(
1885 + (token, index) => token === name && !VALUE_FLAGS_BEFORE_COMMAND.has(argv[index - 1] ?? '')
1886 + );
1887 +
1888 const runParallelFromCommand = (config: {
1889 readonly surface: 'root' | 'dev';
1890 readonly projectMode: 'consumer' | 'developer';
@@ -1885,13 +1897,21 @@ const runParallelFromCommand = (config: {
1897 Effect.gen(function* () {
1898 const argv = yield* ExecuteInvocationArgs;
1899 const name = config.surface === 'root' ? 'execute' : 'playground-execute';
1888 - const tail = argv.slice(argv.indexOf(name) + 1);
1900 + const tail = argv.slice(commandNameIndex(argv, name) + 1);
1901 const parsed = yield* parseParallelExecuteArgs(tail, {
1902 ...config,
1903 allowUserId: config.surface === 'dev',
1904 allowProjectName: config.surface === 'dev',
1905 });
1894 - return yield* runParallelToolsExecuteFromParsed({ ...parsed, ...config });
1906 + // The tail starts after the command name, so the `dev` group's shared flags given before
1907 + // it reach the command only through the surface.
1908 + const surface = yield* CommandSurface;
1909 + return yield* runParallelToolsExecuteFromParsed({
1910 + ...parsed,
1911 + ...config,
1912 + userId: Option.orElse(parsed.userId, () => surface.userId),
1913 + projectName: Option.orElse(parsed.projectName, () => surface.projectName),
1914 + });
1915 });
1916
1917 const executeExamples = [
@@ -2004,8 +2024,6 @@ export const devToolsCmd$Execute = Command.make(
2024 data,
2025 file,
2026 account: accountOption,
2007 - userId,
2008 - projectName,
2027 getSchema,
2028 dryRun,
2029 skipConnectionCheck,
@@ -2019,8 +2037,6 @@ export const devToolsCmd$Execute = Command.make(
2037 data,
2038 file,
2039 account,
2022 - userId,
2023 - projectName,
2040 getSchema,
2041 dryRun,
2042 skipConnectionCheck,
@@ -2028,6 +2044,7 @@ export const devToolsCmd$Execute = Command.make(
2044 skipChecks,
2045 }) =>
2046 Effect.gen(function* () {
2047 + const { userId, projectName } = yield* CommandSurface;
2048 if (parallel) {
2049 return yield* runParallelFromCommand({
2050 surface: 'dev',
ts/packages/cli/src/commands/tools/search/tools.search.cmd.ts new
+73
@@ -0,0 +1,73 @@
1 +import { Argument, Command, Flag } from 'effect/cli';
2 +import { requireLogin } from 'src/effects/require-auth';
3 +import { runToolsSearch } from './tools.search.handler';
4 +
5 +const query = Argument.String('query').pipe(
6 + Argument.variadic(),
7 + Argument.withDescription(
8 + 'One or more semantic use-case queries (e.g. "onboard a new GitHub repo", "notify Slack").'
9 + )
10 +);
11 +
12 +const toolkits = Flag.String('toolkits').pipe(
13 + Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail,outlook")'),
14 + Flag.optional
15 +);
16 +
17 +const limit = Flag.Int('limit').pipe(
18 + Flag.withDefault(10),
19 + Flag.withDescription('Number of results per page (1-1000)')
20 +);
21 +
22 +const json = Flag.Boolean('json').pipe(
23 + Flag.withDefault(false),
24 + Flag.withDescription('Print the full search response as JSON (default behavior)')
25 +);
26 +
27 +const human = Flag.Boolean('human').pipe(
28 + Flag.withDefault(false),
29 + Flag.withDescription('Show formatted human-readable search output')
30 +);
31 +
32 +export const toolsCmd$Search = Command.make(
33 + 'search',
34 + { query, toolkits, limit, json, human },
35 + runToolsSearch
36 +).pipe(
37 + Command.withDescription(
38 + 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.'
39 + ),
40 + Command.withShortDescription(
41 + 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.'
42 + ),
43 + Command.withExamples([
44 + {
45 + command: 'composio search "send an email"',
46 + description: 'Find tools for a use case',
47 + },
48 + {
49 + command: 'composio search "send an email" "create github issue"',
50 + },
51 + {
52 + command: 'composio search "my emails" "my github issues" --toolkits gmail,github',
53 + },
54 + {
55 + command: 'composio search "create issue" --toolkits github',
56 + },
57 + {
58 + command: 'composio search "send an email" --human',
59 + },
60 + {
61 + command: 'composio search "post a message to a slack channel"',
62 + description: 'Cross-app workflow discovery',
63 + },
64 + {
65 + command: 'composio search "add a row to google sheet"',
66 + },
67 + {
68 + command: 'composio search "list calendar events" --toolkits google_calendar --limit 5',
69 + description: 'Narrow results to a specific toolkit',
70 + },
71 + ]),
72 + requireLogin
73 +);
ts/packages/cli/src/commands/tools/search/tools.search.errors.ts new
+3
@@ -0,0 +1,3 @@
1 +import { requestError } from 'src/effects/request-error';
2 +
3 +export class ToolsSearchRequestError extends requestError('commands/ToolsSearchRequestError') {}
ts/packages/cli/src/commands/tools/search/tools.search.format.ts new
+173
@@ -0,0 +1,173 @@
1 +import type { SessionSearchResponse } from '@composio/client/resources/tool-router';
2 +import { Effect } from 'effect';
3 +import type { Tool } from 'src/models/tools';
4 +import type { TerminalUI } from 'src/services/terminal-ui';
5 +import type { CommandTree } from 'src/commands/surface';
6 +import { commandHintExample, commandHintStep } from 'src/services/command-hints';
7 +import { formatToolsTable } from '../format';
8 +
9 +export type SearchToolSchema = SessionSearchResponse.ToolSchemas;
10 +export type SearchResultRecord = SessionSearchResponse.Result;
11 +export type SearchResponseRecord = Pick<
12 + SessionSearchResponse,
13 + 'results' | 'toolkit_connection_statuses' | 'tool_schemas' | 'next_steps_guidance' | 'error'
14 +>;
15 +
16 +export const stripSearchResultMetadata = <
17 + T extends { reference_workbench_snippets?: unknown; plan_id?: unknown },
18 +>(
19 + result: T
20 +) => {
21 + const {
22 + reference_workbench_snippets: _referenceWorkbenchSnippets,
23 + plan_id: _planId,
24 + ...rest
25 + } = result;
26 + return rest;
27 +};
28 +
29 +export const TOOL_SCHEMA_PATH_FORMAT = '~/.composio/tool_definitions/<TOOL_SLUG>.json';
30 +
31 +export const toHomeRelativePath = (cacheDir: string, absolutePath: string) =>
32 + absolutePath.startsWith(cacheDir) ? absolutePath.replace(cacheDir, '~/.composio') : absolutePath;
33 +
34 +export const collectToolsForResult = (params: {
35 + result: {
36 + primary_tool_slugs: string[];
37 + related_tool_slugs: string[];
38 + };
39 + toolSchemas: Record<string, SearchToolSchema>;
40 + toolkitSet?: Set<string>;
41 + limit: number;
42 +}): Tool[] => {
43 + const mergedSlugs: string[] = [];
44 + const seen = new Set<string>();
45 + for (const slug of [...params.result.primary_tool_slugs, ...params.result.related_tool_slugs]) {
46 + if (!seen.has(slug)) {
47 + seen.add(slug);
48 + mergedSlugs.push(slug);
49 + }
50 + }
51 +
52 + const toolsList: Tool[] = [];
53 + for (const slug of mergedSlugs) {
54 + const schema = params.toolSchemas[slug];
55 + if (!schema) continue;
56 + if (params.toolkitSet && !params.toolkitSet.has(schema.toolkit.toLowerCase())) continue;
57 +
58 + toolsList.push({
59 + slug: schema.tool_slug,
60 + name: schema.tool_slug,
61 + description: schema.description ?? '',
62 + tags: [],
63 + available_versions: [],
64 + input_parameters: schema.input_schema ?? {},
65 + output_parameters: schema.output_schema ?? {},
66 + });
67 +
68 + if (toolsList.length >= params.limit) break;
69 + }
70 +
71 + return toolsList;
72 +};
73 +
74 +export const buildSearchNextSteps = (params: {
75 + firstSlug?: string;
76 + firstToolkit?: string;
77 + firstDataArg: string;
78 + tree: CommandTree;
79 +}) => {
80 + const steps: Array<{ action: string; command: string }> = [];
81 + if (params.firstToolkit) {
82 + steps.push({
83 + action: 'Link a user account',
84 + command:
85 + params.tree === 'root'
86 + ? commandHintExample('root.link', { toolkit: String(params.firstToolkit).toLowerCase() })
87 + : commandHintExample('dev.connectedAccounts.link', {
88 + toolkit: String(params.firstToolkit).toLowerCase(),
89 + userId: '<user-id>',
90 + }),
91 + });
92 + }
93 + if (params.firstSlug) {
94 + steps.push({
95 + action: 'Execute a tool',
96 + command:
97 + params.tree === 'root'
98 + ? commandHintExample('root.execute', {
99 + slug: params.firstSlug,
100 + data: params.firstDataArg,
101 + })
102 + : commandHintExample('dev.playgroundExecute', {
103 + slug: params.firstSlug,
104 + userId: '<user-id>',
105 + data: params.firstDataArg,
106 + }),
107 + });
108 + }
109 + return steps;
110 +};
111 +
112 +export const emitHumanSearchOutput = (params: {
113 + ui: TerminalUI;
114 + queries: ReadonlyArray<string>;
115 + resultsWithTools: Array<{ result: SearchResultRecord; tools: Tool[] }>;
116 + nextStepsGuidance: ReadonlyArray<string>;
117 + firstSlug?: string;
118 + firstDataArg: string;
119 + tree: CommandTree;
120 + error: string | null;
121 +}) =>
122 + Effect.gen(function* () {
123 + for (const { result, tools } of params.resultsWithTools) {
124 + if (params.queries.length > 1) {
125 + yield* params.ui.log.info(`Results for "${result.use_case}"`);
126 + }
127 +
128 + if (tools.length === 0) {
129 + yield* params.ui.log.warn(`No tools found for "${result.use_case}".`);
130 + continue;
131 + }
132 +
133 + yield* params.ui.log.info(`Found ${tools.length} tools\n\n${formatToolsTable(tools)}`);
134 +
135 + const planSteps = Array.from(new Set(result.recommended_plan_steps ?? []));
136 + if (planSteps.length > 0) {
137 + yield* params.ui.log.info(
138 + `Plan:\n${planSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}`
139 + );
140 + } else if (params.queries.length === 1 && params.nextStepsGuidance.length > 0) {
141 + yield* params.ui.log.info(
142 + `Plan:\n${params.nextStepsGuidance.map((step, i) => `${i + 1}. ${step}`).join('\n')}`
143 + );
144 + }
145 + }
146 +
147 + if (params.firstSlug) {
148 + const linkHint =
149 + params.tree === 'root'
150 + ? commandHintStep('Link an account', 'root.link', { toolkit: '<toolkit>' })
151 + : commandHintStep('Link an account', 'dev.connectedAccounts.link', {
152 + toolkit: '<toolkit>',
153 + userId: '<user-id>',
154 + });
155 + const executeHint =
156 + params.tree === 'root'
157 + ? commandHintStep('Execute a tool', 'root.execute', {
158 + slug: params.firstSlug,
159 + data: params.firstDataArg,
160 + })
161 + : commandHintStep('Test a tool against a playground user', 'dev.playgroundExecute', {
162 + slug: params.firstSlug,
163 + userId: '<user-id>',
164 + data: params.firstDataArg,
165 + });
166 + const steps = params.firstSlug.startsWith('LOCAL_') ? [executeHint] : [linkHint, executeHint];
167 + yield* params.ui.log.step(steps.join('\n'));
168 + }
169 +
170 + if (params.error) {
171 + yield* params.ui.log.warn(params.error);
172 + }
173 + });
ts/packages/cli/src/commands/tools/search/tools.search.handler.ts renamed
+28 -299
@@ -1,21 +1,16 @@
1 -import { requireLogin } from 'src/effects/require-auth';
2 -import { commandInputError } from 'src/commands/errors';
3 -import { Argument, Command, Flag } from 'effect/cli';
4 -import type { SessionSearchResponse } from '@composio/client/resources/tool-router';
1 import { Effect, Option } from 'effect';
2 +import { commandInputError } from 'src/commands/errors';
3 +import { CommandSurface } from 'src/commands/surface';
4 import { TerminalUI } from 'src/services/terminal-ui';
7 -import { failedWith, requestError } from 'src/effects/request-error';
5 +import { failedWith } from 'src/effects/request-error';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 import { clampLimit } from 'src/ui/clamp-limit';
8 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
9 import { buildMinimalPayloadFromSchema } from 'src/ui/build-minimal-payload';
12 -import { formatToolsTable } from '../format';
13 -import type { Tool } from 'src/models/tools';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { ComposioClientSingleton } from 'src/services/composio-clients';
12 import { idempotent } from 'src/services/composio-request';
13 import { resolveCommandProject } from 'src/services/command-project';
18 -import { commandHintExample, commandHintStep } from 'src/services/command-hints';
14 import { isRemoteCustomToolSlug } from 'src/utils/remote-custom-toolkit';
15 import { toolInputRequiredError } from 'src/utils/tool-input-required';
16 import {
@@ -27,145 +22,27 @@ import {
22 cacheToolInputDefinition,
23 getOrFetchToolInputDefinition,
24 } from 'src/services/tool-input-validation';
30 -
31 -const query = Argument.String('query').pipe(
32 - Argument.variadic(),
33 - Argument.withDescription(
34 - 'One or more semantic use-case queries (e.g. "onboard a new GitHub repo", "notify Slack").'
35 - )
36 -);
37 -
38 -const toolkits = Flag.String('toolkits').pipe(
39 - Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail,outlook")'),
40 - Flag.optional
41 -);
42 -
43 -const userId = Flag.String('user-id').pipe(
44 - Flag.optional,
45 - Flag.withDescription('Developer-project user ID override')
46 -);
47 -
48 -const projectName = Flag.String('project-name').pipe(
49 - Flag.optional,
50 - Flag.withDescription('Developer project name override for this command')
51 -);
52 -
53 -const limit = Flag.Int('limit').pipe(
54 - Flag.withDefault(10),
55 - Flag.withDescription('Number of results per page (1-1000)')
56 -);
57 -
58 -const json = Flag.Boolean('json').pipe(
59 - Flag.withDefault(false),
60 - Flag.withDescription('Print the full search response as JSON (default behavior)')
61 -);
62 -
63 -const human = Flag.Boolean('human').pipe(
64 - Flag.withDefault(false),
65 - Flag.withDescription('Show formatted human-readable search output')
66 -);
67 -
68 -type SearchToolSchema = SessionSearchResponse.ToolSchemas;
69 -type SearchResultRecord = SessionSearchResponse.Result;
70 -type SearchResponseRecord = Pick<
71 - SessionSearchResponse,
72 - 'results' | 'toolkit_connection_statuses' | 'tool_schemas' | 'next_steps_guidance' | 'error'
73 ->;
74 -
75 -const invalidSearchInput = commandInputError('search');
76 -
77 -class ToolsSearchRequestError extends requestError('commands/ToolsSearchRequestError') {}
78 -
79 -const stripSearchResultMetadata = <
80 - T extends { reference_workbench_snippets?: unknown; plan_id?: unknown },
81 ->(
82 - result: T
83 -) => {
84 - const {
85 - reference_workbench_snippets: _referenceWorkbenchSnippets,
86 - plan_id: _planId,
87 - ...rest
88 - } = result;
89 - return rest;
90 -};
91 -
92 -const TOOL_SCHEMA_PATH_FORMAT = '~/.composio/tool_definitions/<TOOL_SLUG>.json';
93 -
94 -const toHomeRelativePath = (cacheDir: string, absolutePath: string) =>
95 - absolutePath.startsWith(cacheDir) ? absolutePath.replace(cacheDir, '~/.composio') : absolutePath;
96 -
97 -const collectToolsForResult = (params: {
98 - result: {
99 - primary_tool_slugs: string[];
100 - related_tool_slugs: string[];
101 - };
102 - toolSchemas: Record<string, SearchToolSchema>;
103 - toolkitSet?: Set<string>;
104 - limit: number;
105 -}): Tool[] => {
106 - const mergedSlugs: string[] = [];
107 - const seen = new Set<string>();
108 - for (const slug of [...params.result.primary_tool_slugs, ...params.result.related_tool_slugs]) {
109 - if (!seen.has(slug)) {
110 - seen.add(slug);
111 - mergedSlugs.push(slug);
112 - }
113 - }
114 -
115 - const toolsList: Tool[] = [];
116 - for (const slug of mergedSlugs) {
117 - const schema = params.toolSchemas[slug];
118 - if (!schema) continue;
119 - if (params.toolkitSet && !params.toolkitSet.has(schema.toolkit.toLowerCase())) continue;
120 -
121 - toolsList.push({
122 - slug: schema.tool_slug,
123 - name: schema.tool_slug,
124 - description: schema.description ?? '',
125 - tags: [],
126 - available_versions: [],
127 - input_parameters: schema.input_schema ?? {},
128 - output_parameters: schema.output_schema ?? {},
129 - });
130 -
131 - if (toolsList.length >= params.limit) break;
132 - }
133 -
134 - return toolsList;
25 +import { ToolsSearchRequestError } from './tools.search.errors';
26 +import {
27 + buildSearchNextSteps,
28 + collectToolsForResult,
29 + emitHumanSearchOutput,
30 + stripSearchResultMetadata,
31 + toHomeRelativePath,
32 + TOOL_SCHEMA_PATH_FORMAT,
33 + type SearchResponseRecord,
34 + type SearchToolSchema,
35 +} from './tools.search.format';
36 +
37 +export type ToolsSearchParams = {
38 + readonly query: ReadonlyArray<string>;
39 + readonly toolkits: Option.Option<string>;
40 + readonly limit: number;
41 + readonly json: boolean;
42 + readonly human: boolean;
43 };
44
137 -const buildSearchNextSteps = (params: {
138 - firstSlug?: string;
139 - firstToolkit?: string;
140 - firstDataArg: string;
141 - rootOnly: boolean;
142 -}) => {
143 - const steps: Array<{ action: string; command: string }> = [];
144 - if (params.firstToolkit) {
145 - steps.push({
146 - action: 'Link a user account',
147 - command: params.rootOnly
148 - ? commandHintExample('root.link', { toolkit: String(params.firstToolkit).toLowerCase() })
149 - : commandHintExample('dev.connectedAccounts.link', {
150 - toolkit: String(params.firstToolkit).toLowerCase(),
151 - userId: '<user-id>',
152 - }),
153 - });
154 - }
155 - if (params.firstSlug) {
156 - steps.push({
157 - action: 'Execute a tool',
158 - command: params.rootOnly
159 - ? commandHintExample('root.execute', { slug: params.firstSlug, data: params.firstDataArg })
160 - : commandHintExample('dev.playgroundExecute', {
161 - slug: params.firstSlug,
162 - userId: '<user-id>',
163 - data: params.firstDataArg,
164 - }),
165 - });
166 - }
167 - return steps;
168 -};
45 +const invalidSearchInput = commandInputError('search');
46
47 const buildSearchJsonPayload = (params: {
48 searchResponse: SearchResponseRecord;
@@ -228,79 +105,10 @@ const buildSearchJsonPayload = (params: {
105 };
106 });
107
231 -const emitHumanSearchOutput = (params: {
232 - ui: TerminalUI;
233 - queries: ReadonlyArray<string>;
234 - resultsWithTools: Array<{ result: SearchResultRecord; tools: Tool[] }>;
235 - nextStepsGuidance: ReadonlyArray<string>;
236 - firstSlug?: string;
237 - firstDataArg: string;
238 - rootOnly: boolean;
239 - error: string | null;
240 -}) =>
241 - Effect.gen(function* () {
242 - for (const { result, tools } of params.resultsWithTools) {
243 - if (params.queries.length > 1) {
244 - yield* params.ui.log.info(`Results for "${result.use_case}"`);
245 - }
246 -
247 - if (tools.length === 0) {
248 - yield* params.ui.log.warn(`No tools found for "${result.use_case}".`);
249 - continue;
250 - }
251 -
252 - yield* params.ui.log.info(`Found ${tools.length} tools\n\n${formatToolsTable(tools)}`);
253 -
254 - const planSteps = Array.from(new Set(result.recommended_plan_steps ?? []));
255 - if (planSteps.length > 0) {
256 - yield* params.ui.log.info(
257 - `Plan:\n${planSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}`
258 - );
259 - } else if (params.queries.length === 1 && params.nextStepsGuidance.length > 0) {
260 - yield* params.ui.log.info(
261 - `Plan:\n${params.nextStepsGuidance.map((step, i) => `${i + 1}. ${step}`).join('\n')}`
262 - );
263 - }
264 - }
265 -
266 - if (params.firstSlug) {
267 - const linkHint = params.rootOnly
268 - ? commandHintStep('Link an account', 'root.link', { toolkit: '<toolkit>' })
269 - : commandHintStep('Link an account', 'dev.connectedAccounts.link', {
270 - toolkit: '<toolkit>',
271 - userId: '<user-id>',
272 - });
273 - const executeHint = params.rootOnly
274 - ? commandHintStep('Execute a tool', 'root.execute', {
275 - slug: params.firstSlug,
276 - data: params.firstDataArg,
277 - })
278 - : commandHintStep('Test a tool against a playground user', 'dev.playgroundExecute', {
279 - slug: params.firstSlug,
280 - userId: '<user-id>',
281 - data: params.firstDataArg,
282 - });
283 - const steps = params.firstSlug.startsWith('LOCAL_') ? [executeHint] : [linkHint, executeHint];
284 - yield* params.ui.log.step(steps.join('\n'));
285 - }
286 -
287 - if (params.error) {
288 - yield* params.ui.log.warn(params.error);
289 - }
290 - });
291 -
292 -const runToolsSearch = (params: {
293 - query: ReadonlyArray<string>;
294 - toolkits: Option.Option<string>;
295 - userId: Option.Option<string>;
296 - projectName: Option.Option<string>;
297 - limit: number;
298 - json: boolean;
299 - human: boolean;
300 - rootOnly: boolean;
301 -}) =>
108 +export const runToolsSearch = (params: ToolsSearchParams) =>
109 Effect.gen(function* () {
110 const ui = yield* TerminalUI;
111 + const { tree, userId, projectName } = yield* CommandSurface;
112 const userContext = yield* ComposioUserContext;
113
114 const clampedLimit = clampLimit(params.limit);
@@ -322,12 +130,12 @@ const runToolsSearch = (params: {
130 const runSearchRequest = Effect.gen(function* () {
131 const resolvedProject = yield* resolveCommandProject({
132 mode: 'consumer',
325 - projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
133 + projectName: Option.getOrUndefined(projectName),
134 });
135 const resolvedUserId =
136 resolvedProject.projectType === 'CONSUMER'
137 ? Option.fromNullishOr(resolvedProject.consumerUserId)
330 - : Option.match(params.userId, {
138 + : Option.match(userId, {
139 onSome: value => Option.some(value),
140 onNone: () => userContext.data.testUserId,
141 });
@@ -480,7 +288,7 @@ const runToolsSearch = (params: {
288 firstSlug,
289 firstToolkit,
290 firstDataArg,
483 - rootOnly: params.rootOnly,
291 + tree,
292 });
293
294 const outputForJq = yield* buildSearchJsonPayload({
@@ -516,7 +324,7 @@ const runToolsSearch = (params: {
324 nextStepsGuidance: searchResponse.next_steps_guidance,
325 firstSlug,
326 firstDataArg,
519 - rootOnly: params.rootOnly,
327 + tree,
328 error: searchResponse.error,
329 });
330 } else if (emitJson) {
@@ -525,82 +333,3 @@ const runToolsSearch = (params: {
333 yield* ui.output(outputJson);
334 }
335 });
528 -
529 -export const toolsCmd$Search = Command.make(
530 - 'search',
531 - { query, toolkits, userId, projectName, limit, json, human },
532 - ({ query, toolkits, userId, projectName, limit, json, human }) =>
533 - runToolsSearch({ query, toolkits, userId, projectName, limit, json, human, rootOnly: false })
534 -).pipe(
535 - Command.withDescription(
536 - [
537 - 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.',
538 - '',
539 - 'Examples:',
540 - ' composio search "send an email"',
541 - ' composio search "send an email" "create a github issue"',
542 - ' composio search "create issue" --toolkits github',
543 - ' composio search "send an email" --human',
544 - ' composio search "list calendar events" --limit 5',
545 - '',
546 - 'Next steps:',
547 - ' composio link <toolkit> Connect an account before executing tools',
548 - " composio execute <slug> -d '{ ... }' Run a tool from the results",
549 - " composio tools info <slug> Inspect a tool's schema before executing",
550 - ].join('\n')
551 - ),
552 - requireLogin
553 -);
554 -
555 -export const rootToolsCmd$Search = Command.make(
556 - 'search',
557 - { query, toolkits, limit, json, human },
558 - ({ query, toolkits, limit, json, human }) =>
559 - runToolsSearch({
560 - query,
561 - toolkits,
562 - userId: Option.none(),
563 - projectName: Option.none(),
564 - limit,
565 - json,
566 - human,
567 - rootOnly: true,
568 - })
569 -).pipe(
570 - Command.withDescription(
571 - 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.'
572 - ),
573 - Command.withShortDescription(
574 - 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.'
575 - ),
576 - Command.withExamples([
577 - {
578 - command: 'composio search "send an email"',
579 - description: 'Find tools for a use case',
580 - },
581 - {
582 - command: 'composio search "send an email" "create github issue"',
583 - },
584 - {
585 - command: 'composio search "my emails" "my github issues" --toolkits gmail,github',
586 - },
587 - {
588 - command: 'composio search "create issue" --toolkits github',
589 - },
590 - {
591 - command: 'composio search "send an email" --human',
592 - },
593 - {
594 - command: 'composio search "post a message to a slack channel"',
595 - description: 'Cross-app workflow discovery',
596 - },
597 - {
598 - command: 'composio search "add a row to google sheet"',
599 - },
600 - {
601 - command: 'composio search "list calendar events" --toolkits google_calendar --limit 5',
602 - description: 'Narrow results to a specific toolkit',
603 - },
604 - ]),
605 - requireLogin
606 -);
ts/packages/cli/src/commands/triggers/commands/triggers.info.cmd.ts deleted
-89
@@ -1,89 +0,0 @@
1 -import { Argument, Command } from 'effect/cli';
2 -import { Effect, Option } from 'effect';
3 -import { handleClientApiError } from 'src/effects/handle-http-error';
4 -import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
5 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 -import { TerminalUI } from 'src/services/terminal-ui';
7 -import { formatTriggerTypeInfo } from '../format';
8 -
9 -type TriggersInfoCommandConfig = {
10 - readonly exampleCommand: string;
11 - readonly listCommand: string;
12 - readonly listCommandPlaceholder: string;
13 -};
14 -
15 -const slug = Argument.String('slug').pipe(
16 - Argument.withDescription('Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")'),
17 - Argument.optional
18 -);
19 -
20 -/**
21 - * View details of a specific trigger type including config and payload schemas.
22 - *
23 - * @example
24 - * ```bash
25 - * composio dev triggers info "GMAIL_NEW_GMAIL_MESSAGE"
26 - * ```
27 - */
28 -const makeTriggersInfoCommand = ({
29 - exampleCommand,
30 - listCommand,
31 - listCommandPlaceholder,
32 -}: TriggersInfoCommandConfig) =>
33 - Command.make('info', { slug }, ({ slug }) =>
34 - Effect.gen(function* () {
35 - const ui = yield* TerminalUI;
36 - const repo = yield* ComposioToolkitsRepository;
37 -
38 - if (Option.isNone(slug)) {
39 - yield* ui.log.warn('Missing required argument: <slug>');
40 - yield* ui.log.step(
41 - `Try specifying a trigger slug, e.g.:\n> ${exampleCommand} "GMAIL_NEW_GMAIL_MESSAGE"`
42 - );
43 - return;
44 - }
45 -
46 - const slugValue = slug.value;
47 -
48 - const triggerTypeOpt = yield* ui
49 - .withSpinner('Fetching trigger type details...', repo.getTriggerTypeDetailed(slugValue))
50 - .pipe(
51 - Effect.asSome,
52 - Effect.catchTag(
53 - CLIENT_API_ERROR_TAGS,
54 - handleClientApiError(ui, {
55 - fallbackMessage: `Trigger "${slugValue}" not found.`,
56 - hint: `Browse available trigger types:\n> ${listCommandPlaceholder}`,
57 - fallbackValue: Option.none(),
58 - })
59 - )
60 - );
61 -
62 - if (Option.isNone(triggerTypeOpt)) return;
63 -
64 - const triggerType = triggerTypeOpt.value;
65 -
66 - yield* ui.note(formatTriggerTypeInfo(triggerType), `Trigger: ${triggerType.name}`);
67 -
68 - const toolkitSlug = triggerType.toolkit?.slug?.toLowerCase();
69 - if (toolkitSlug) {
70 - yield* ui.log.step(
71 - `To list more trigger types in this toolkit:\n> ${listCommand} "${toolkitSlug}"`
72 - );
73 - }
74 -
75 - yield* ui.output(JSON.stringify(triggerType, null, 2));
76 - })
77 - ).pipe(Command.withDescription('View details of a specific trigger type.'));
78 -
79 -export const triggersCmd$Info = makeTriggersInfoCommand({
80 - exampleCommand: 'composio dev triggers info',
81 - listCommand: 'composio dev triggers list',
82 - listCommandPlaceholder: 'composio dev triggers list "<toolkit>"',
83 -});
84 -
85 -export const rootTriggersCmd$Info = makeTriggersInfoCommand({
86 - exampleCommand: 'composio triggers info',
87 - listCommand: 'composio triggers list',
88 - listCommandPlaceholder: 'composio triggers list "<toolkit>"',
89 -});
ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts deleted
-92
@@ -1,92 +0,0 @@
1 -import { commandInputError } from 'src/commands/errors';
2 -import { Argument, Command, Flag } from 'effect/cli';
3 -import { Effect } from 'effect';
4 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 -import { TerminalUI } from 'src/services/terminal-ui';
6 -import { clampLimit } from 'src/ui/clamp-limit';
7 -import { formatTriggerTypesJson, formatTriggerTypesTable } from '../format';
8 -
9 -type TriggersListCommandConfig = {
10 - readonly noResultsCommand: string;
11 - readonly infoCommand: string;
12 -};
13 -
14 -const invalidToolkit = commandInputError('triggers list');
15 -
16 -const toolkit = Argument.String('toolkit').pipe(
17 - Argument.withDescription('Toolkit slug to list trigger types for (e.g. "gmail")')
18 -);
19 -
20 -const limit = Flag.Int('limit').pipe(
21 - Flag.withDefault(30),
22 - Flag.withDescription('Maximum number of trigger types to show (1-1000)')
23 -);
24 -
25 -/**
26 - * List available trigger types with optional toolkit filters.
27 - *
28 - * @example
29 - * ```bash
30 - * composio dev triggers list gmail
31 - * composio dev triggers list slack --limit 10
32 - * ```
33 - */
34 -const makeTriggersListCommand = ({ noResultsCommand, infoCommand }: TriggersListCommandConfig) =>
35 - Command.make('list', { toolkit, limit }, ({ toolkit, limit }) =>
36 - Effect.gen(function* () {
37 - const ui = yield* TerminalUI;
38 - const repo = yield* ComposioToolkitsRepository;
39 - const clampedLimit = clampLimit(limit);
40 -
41 - yield* repo.validateToolkits([toolkit]).pipe(
42 - Effect.catchTag('services/InvalidToolkitsError', error =>
43 - Effect.gen(function* () {
44 - const availableExample = error.availableToolkits.slice(0, 8).join(', ');
45 - yield* ui.log.step(`List valid toolkits with:\n> ${noResultsCommand}`);
46 - return yield* Effect.fail(
47 - invalidToolkit(
48 - `Toolkit "${toolkit}" is not available. ${availableExample ? `Examples: ${availableExample}` : ''}`,
49 - '<toolkit>'
50 - )
51 - );
52 - })
53 - )
54 - );
55 -
56 - const allTriggerTypes = yield* ui.withSpinner(
57 - 'Fetching trigger types...',
58 - repo.getTriggerTypes([toolkit])
59 - );
60 - const triggerTypes = allTriggerTypes.slice(0, clampedLimit);
61 -
62 - if (triggerTypes.length === 0) {
63 - yield* ui.log.warn(
64 - `No trigger types found in toolkit "${toolkit}". Verify the toolkit slug with:\n> ${noResultsCommand}`
65 - );
66 - return;
67 - }
68 -
69 - const count = triggerTypes.length;
70 - yield* ui.note(
71 - formatTriggerTypesTable(triggerTypes),
72 - `Listing ${count} trigger type${count === 1 ? '' : 's'}`
73 - );
74 -
75 - const firstSlug = triggerTypes[0]?.slug;
76 - if (firstSlug) {
77 - yield* ui.log.step(`To view details of a trigger type:\n> ${infoCommand} "${firstSlug}"`);
78 - }
79 -
80 - yield* ui.output(formatTriggerTypesJson(triggerTypes));
81 - })
82 - ).pipe(Command.withDescription('List available trigger types.'));
83 -
84 -export const triggersCmd$List = makeTriggersListCommand({
85 - noResultsCommand: 'composio dev toolkits list',
86 - infoCommand: 'composio dev triggers info',
87 -});
88 -
89 -export const rootTriggersCmd$List = makeTriggersListCommand({
90 - noResultsCommand: 'composio toolkits list',
91 - infoCommand: 'composio triggers info',
92 -});
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+15 -14
@@ -4,6 +4,7 @@ import * as FileSystem from 'effect/FileSystem';
4 import * as Path from 'effect/Path';
5 import { Deferred, Effect, Option } from 'effect';
6 import { APP_CONFIG } from 'src/config';
7 +import { CommandSurface, resolveSurfaceProject } from 'src/commands/surface';
8 import { TerminalUI } from 'src/services/terminal-ui';
9 import { TriggersRealtime } from 'src/services/triggers-realtime';
10 import { matchesTriggerListenFilters } from '../filter';
@@ -15,7 +16,6 @@ import {
16 import { parseCsv } from '../parse-csv';
17 import { parseTriggerListenEvent } from '../parse';
18 import type { TriggerListenFilters } from '../types';
18 -import { resolveCommandProject } from 'src/services/command-project';
19
20 const toolkits = Flag.String('toolkits').pipe(
21 Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'),
@@ -37,11 +37,6 @@ const triggerSlug = Flag.String('trigger-slug').pipe(
37 Flag.optional
38 );
39
40 -const userId = Flag.String('user-id').pipe(
41 - Flag.withDescription('Filter by user id'),
42 - Flag.optional
43 -);
44 -
40 const json = Flag.Boolean('json').pipe(
41 Flag.withDefault(false),
42 Flag.withDescription('Show raw event payload as JSON in interactive mode')
@@ -147,7 +142,6 @@ export const triggersCmd$Listen = Command.make(
142 triggerId,
143 connectedAccountId,
144 triggerSlug,
150 - userId,
145 json,
146 table,
147 maxEvents,
@@ -159,7 +153,6 @@ export const triggersCmd$Listen = Command.make(
153 triggerId,
154 connectedAccountId,
155 triggerSlug,
162 - userId,
156 json,
157 table,
158 maxEvents,
@@ -167,8 +160,10 @@ export const triggersCmd$Listen = Command.make(
160 out,
161 }) =>
162 Effect.gen(function* () {
163 + const surface = yield* CommandSurface;
164 + const { userId } = surface;
165 const ui = yield* TerminalUI;
171 - yield* resolveCommandProject({ mode: 'developer' });
166 + const project = yield* resolveSurfaceProject('developer');
167 const fs = yield* FileSystem.FileSystem;
168 const path = yield* Path.Path;
169 const realtime = yield* TriggersRealtime;
@@ -318,11 +313,17 @@ export const triggersCmd$Listen = Command.make(
313 );
314 };
315
321 - const listenEffect = realtime
322 - .listen(onEvent)
323 - .pipe(
324 - Effect.onInterrupt(() => ui.log.info('Stopped listening for realtime trigger events.'))
325 - );
316 + // The default credentials serve the configured project; a named one needs its own.
317 + const listenEffect = (
318 + Option.isSome(surface.projectName)
319 + ? realtime.listenInProject(
320 + { orgId: project.orgId, projectId: project.projectId },
321 + onEvent
322 + )
323 + : realtime.listen(onEvent)
324 + ).pipe(
325 + Effect.onInterrupt(() => ui.log.info('Stopped listening for realtime trigger events.'))
326 + );
327
328 yield* Effect.gen(function* () {
329 if (maxEventsLimit === undefined) {
ts/packages/cli/src/commands/triggers/info/triggers.info.cmd.ts new
+11
@@ -0,0 +1,11 @@
1 +import { Argument, Command } from 'effect/cli';
2 +import { runTriggersInfo } from './triggers.info.handler';
3 +
4 +const slug = Argument.String('slug').pipe(
5 + Argument.withDescription('Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")'),
6 + Argument.optional
7 +);
8 +
9 +export const triggersCmd$Info = Command.make('info', { slug }, runTriggersInfo).pipe(
10 + Command.withDescription('View details of a specific trigger type.')
11 +);
ts/packages/cli/src/commands/triggers/info/triggers.info.handler.ts new
+80
@@ -0,0 +1,80 @@
1 +import { Effect, Option } from 'effect';
2 +import { CommandSurface } from 'src/commands/surface';
3 +import { handleClientApiError } from 'src/effects/handle-http-error';
4 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
5 +import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 +import { TerminalUI } from 'src/services/terminal-ui';
7 +import { formatTriggerTypeInfo } from '../format';
8 +
9 +export type TriggersInfoParams = {
10 + readonly slug: Option.Option<string>;
11 +};
12 +
13 +/** The commands the hints name, on the tree the command runs in. */
14 +const triggersInfoHints = Effect.map(CommandSurface, ({ tree }) =>
15 + tree === 'dev'
16 + ? {
17 + exampleCommand: 'composio dev triggers info',
18 + listCommand: 'composio dev triggers list',
19 + listCommandPlaceholder: 'composio dev triggers list "<toolkit>"',
20 + }
21 + : {
22 + exampleCommand: 'composio triggers info',
23 + listCommand: 'composio triggers list',
24 + listCommandPlaceholder: 'composio triggers list "<toolkit>"',
25 + }
26 +);
27 +
28 +/**
29 + * View details of a specific trigger type including config and payload schemas.
30 + *
31 + * @example
32 + * ```bash
33 + * composio dev triggers info "GMAIL_NEW_GMAIL_MESSAGE"
34 + * ```
35 + */
36 +export const runTriggersInfo = ({ slug }: TriggersInfoParams) =>
37 + Effect.gen(function* () {
38 + const ui = yield* TerminalUI;
39 + const { exampleCommand, listCommand, listCommandPlaceholder } = yield* triggersInfoHints;
40 + const repo = yield* ComposioToolkitsRepository;
41 +
42 + if (Option.isNone(slug)) {
43 + yield* ui.log.warn('Missing required argument: <slug>');
44 + yield* ui.log.step(
45 + `Try specifying a trigger slug, e.g.:\n> ${exampleCommand} "GMAIL_NEW_GMAIL_MESSAGE"`
46 + );
47 + return;
48 + }
49 +
50 + const slugValue = slug.value;
51 +
52 + const triggerTypeOpt = yield* ui
53 + .withSpinner('Fetching trigger type details...', repo.getTriggerTypeDetailed(slugValue))
54 + .pipe(
55 + Effect.asSome,
56 + Effect.catchTag(
57 + CLIENT_API_ERROR_TAGS,
58 + handleClientApiError(ui, {
59 + fallbackMessage: `Trigger "${slugValue}" not found.`,
60 + hint: `Browse available trigger types:\n> ${listCommandPlaceholder}`,
61 + fallbackValue: Option.none(),
62 + })
63 + )
64 + );
65 +
66 + if (Option.isNone(triggerTypeOpt)) return;
67 +
68 + const triggerType = triggerTypeOpt.value;
69 +
70 + yield* ui.note(formatTriggerTypeInfo(triggerType), `Trigger: ${triggerType.name}`);
71 +
72 + const toolkitSlug = triggerType.toolkit?.slug?.toLowerCase();
73 + if (toolkitSlug) {
74 + yield* ui.log.step(
75 + `To list more trigger types in this toolkit:\n> ${listCommand} "${toolkitSlug}"`
76 + );
77 + }
78 +
79 + yield* ui.output(JSON.stringify(triggerType, null, 2));
80 + });
ts/packages/cli/src/commands/triggers/list/triggers.list.cmd.ts new
+15
@@ -0,0 +1,15 @@
1 +import { Argument, Command, Flag } from 'effect/cli';
2 +import { runTriggersList } from './triggers.list.handler';
3 +
4 +const toolkit = Argument.String('toolkit').pipe(
5 + Argument.withDescription('Toolkit slug to list trigger types for (e.g. "gmail")')
6 +);
7 +
8 +const limit = Flag.Int('limit').pipe(
9 + Flag.withDefault(30),
10 + Flag.withDescription('Maximum number of trigger types to show (1-1000)')
11 +);
12 +
13 +export const triggersCmd$List = Command.make('list', { toolkit, limit }, runTriggersList).pipe(
14 + Command.withDescription('List available trigger types.')
15 +);
ts/packages/cli/src/commands/triggers/list/triggers.list.handler.ts new
+79
@@ -0,0 +1,79 @@
1 +import { Effect } from 'effect';
2 +import { commandInputError } from 'src/commands/errors';
3 +import { CommandSurface } from 'src/commands/surface';
4 +import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 +import { TerminalUI } from 'src/services/terminal-ui';
6 +import { clampLimit } from 'src/ui/clamp-limit';
7 +import { formatTriggerTypesJson, formatTriggerTypesTable } from '../format';
8 +
9 +export type TriggersListParams = {
10 + readonly toolkit: string;
11 + readonly limit: number;
12 +};
13 +
14 +const invalidToolkit = commandInputError('triggers list');
15 +
16 +/** The commands the hints name, on the tree the command runs in. */
17 +const triggersListHints = Effect.map(CommandSurface, ({ tree }) =>
18 + tree === 'dev'
19 + ? { noResultsCommand: 'composio dev toolkits list', infoCommand: 'composio dev triggers info' }
20 + : { noResultsCommand: 'composio toolkits list', infoCommand: 'composio triggers info' }
21 +);
22 +
23 +/**
24 + * List available trigger types with optional toolkit filters.
25 + *
26 + * @example
27 + * ```bash
28 + * composio dev triggers list gmail
29 + * composio dev triggers list slack --limit 10
30 + * ```
31 + */
32 +export const runTriggersList = ({ toolkit, limit }: TriggersListParams) =>
33 + Effect.gen(function* () {
34 + const ui = yield* TerminalUI;
35 + const { noResultsCommand, infoCommand } = yield* triggersListHints;
36 + const repo = yield* ComposioToolkitsRepository;
37 + const clampedLimit = clampLimit(limit);
38 +
39 + yield* repo.validateToolkits([toolkit]).pipe(
40 + Effect.catchTag('services/InvalidToolkitsError', error =>
41 + Effect.gen(function* () {
42 + const availableExample = error.availableToolkits.slice(0, 8).join(', ');
43 + yield* ui.log.step(`List valid toolkits with:\n> ${noResultsCommand}`);
44 + return yield* Effect.fail(
45 + invalidToolkit(
46 + `Toolkit "${toolkit}" is not available. ${availableExample ? `Examples: ${availableExample}` : ''}`,
47 + '<toolkit>'
48 + )
49 + );
50 + })
51 + )
52 + );
53 +
54 + const allTriggerTypes = yield* ui.withSpinner(
55 + 'Fetching trigger types...',
56 + repo.getTriggerTypes([toolkit])
57 + );
58 + const triggerTypes = allTriggerTypes.slice(0, clampedLimit);
59 +
60 + if (triggerTypes.length === 0) {
61 + yield* ui.log.warn(
62 + `No trigger types found in toolkit "${toolkit}". Verify the toolkit slug with:\n> ${noResultsCommand}`
63 + );
64 + return;
65 + }
66 +
67 + const count = triggerTypes.length;
68 + yield* ui.note(
69 + formatTriggerTypesTable(triggerTypes),
70 + `Listing ${count} trigger type${count === 1 ? '' : 's'}`
71 + );
72 +
73 + const firstSlug = triggerTypes[0]?.slug;
74 + if (firstSlug) {
75 + yield* ui.log.step(`To view details of a trigger type:\n> ${infoCommand} "${firstSlug}"`);
76 + }
77 +
78 + yield* ui.output(formatTriggerTypesJson(triggerTypes));
79 + });
ts/packages/cli/src/commands/triggers/root-triggers.cmd.ts
+3 -3
@@ -1,10 +1,10 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 -import { rootTriggersCmd$Info } from './commands/triggers.info.cmd';
4 -import { rootTriggersCmd$List } from './commands/triggers.list.cmd';
3 +import { triggersCmd$Info } from './info/triggers.info.cmd';
4 +import { triggersCmd$List } from './list/triggers.list.cmd';
5
6 export const rootTriggersCmd = Command.make('triggers').pipe(
7 Command.withDescription('Browse and inspect trigger types before creating subscriptions.'),
8 - Command.withSubcommands([rootTriggersCmd$List, rootTriggersCmd$Info]),
8 + Command.withSubcommands([triggersCmd$List, triggersCmd$Info]),
9 requireLogin
10 );
ts/packages/cli/src/commands/triggers/triggers.cmd.ts
+9 -8
@@ -1,7 +1,8 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 -import { triggersCmd$Info } from './commands/triggers.info.cmd';
4 -import { triggersCmd$List } from './commands/triggers.list.cmd';
3 +import { rejectsSharedFlags } from 'src/commands/surface';
4 +import { triggersCmd$Info } from './info/triggers.info.cmd';
5 +import { triggersCmd$List } from './list/triggers.list.cmd';
6 import { triggersCmd$Status } from './commands/triggers.status.cmd';
7 import { triggersCmd$Create } from './commands/triggers.create.cmd';
8 import { triggersCmd$Enable } from './commands/triggers.enable.cmd';
@@ -20,12 +21,12 @@ export const triggersCmd = Command.make('triggers').pipe(
21 Command.withDescription('Inspect and subscribe to trigger events.'),
22 Command.withSubcommands([
23 triggersCmd$Listen,
23 - triggersCmd$List,
24 - triggersCmd$Info,
25 - triggersCmd$Status,
26 - triggersCmd$Create,
27 - triggersCmd$Enable,
28 - triggersCmd$Disable,
24 + triggersCmd$List.pipe(rejectsSharedFlags('dev triggers list')),
25 + triggersCmd$Info.pipe(rejectsSharedFlags('dev triggers info')),
26 + triggersCmd$Status.pipe(rejectsSharedFlags('dev triggers status')),
27 + triggersCmd$Create.pipe(rejectsSharedFlags('dev triggers create')),
28 + triggersCmd$Enable.pipe(rejectsSharedFlags('dev triggers enable')),
29 + triggersCmd$Disable.pipe(rejectsSharedFlags('dev triggers disable')),
30 ]),
31 requireLogin
32 );
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.client.cmd.test.ts renamed
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.cmd.test.ts renamed
ts/packages/cli/test/src/commands/logs/logs.tools.client.cmd.test.ts
+29
@@ -75,6 +75,35 @@ describe('CLI: composio dev logs tools over the API client', () => {
75 );
76 });
77
78 + layer(testLayer)('[Given] a comma-separated --user-id filter', it => {
79 + it.effect.each([
80 + {
81 + name: 'after the subcommand',
82 + args: ['dev', 'logs', 'tools', '--user-id', 'user_1,user_2'],
83 + },
84 + {
85 + name: 'before the subcommand',
86 + args: ['dev', '--user-id', 'user_1,user_2', 'logs', 'tools'],
87 + },
88 + ])('[Then] each user id is sent as a search param when passed $name', ({ args }) =>
89 + Effect.gen(function* () {
90 + const stub = stubClientResources(['logs'], () => Response.json({ data: [] }));
91 + yield* cli(args).pipe(Effect.provide(stub.layer));
92 +
93 + expect(stub.requests).toMatchObject([
94 + {
95 + body: {
96 + search_params: [
97 + { field: 'user_id', operation: '==', value: 'user_1' },
98 + { field: 'user_id', operation: '==', value: 'user_2' },
99 + ],
100 + },
101 + },
102 + ]);
103 + })
104 + );
105 + });
106 +
107 layer(testLayer)('[Given] the API rejects the request', it => {
108 it.effect('[Then] the command fails with the status and response body as the cause', () =>
109 Effect.gen(function* () {
ts/packages/cli/test/src/commands/logs/logs.triggers.client.cmd.test.ts
+25
@@ -38,6 +38,31 @@ describe('CLI: composio dev logs triggers over the API client', () => {
38 );
39 });
40
41 + layer(testLayer)('[Given] a comma-separated --user-id filter', it => {
42 + it.effect.each([
43 + {
44 + name: 'after the subcommand',
45 + args: ['dev', 'logs', 'triggers', '--user-id', 'user_1,user_2'],
46 + },
47 + {
48 + name: 'before the subcommand',
49 + args: ['dev', '--user-id', 'user_1,user_2', 'logs', 'triggers'],
50 + },
51 + ])('[Then] each user id is sent as a search param when passed $name', ({ args }) =>
52 + Effect.gen(function* () {
53 + const stub = stubClientResources(['logs'], () => Response.json({ data: [] }));
54 + yield* cli(args).pipe(Effect.provide(stub.layer));
55 +
56 + expect(JSON.stringify(stub.requests)).toContain(
57 + JSON.stringify({ field: 'user_id', operation: '==', value: 'user_1' })
58 + );
59 + expect(JSON.stringify(stub.requests)).toContain(
60 + JSON.stringify({ field: 'user_id', operation: '==', value: 'user_2' })
61 + );
62 + })
63 + );
64 + });
65 +
66 layer(testLayer)('[Given] one trigger log in an older response shape', it => {
67 it.effect('[Then] its details are shown and it is printed as the API returned it', () =>
68 Effect.gen(function* () {
ts/packages/cli/test/src/commands/surface.test.ts new
+631
@@ -0,0 +1,631 @@
1 +import { describe, expect, it, layer } from '@effect/vitest';
2 +import { ConfigProvider, Effect, FileSystem, Path } from 'effect';
3 +import { buildRootCommand } from 'src/commands';
4 +import { CommandInputError } from 'src/commands/errors';
5 +import { ComposioCliUserConfig } from 'src/services/cli-user-config';
6 +import { ProjectResolutionError } from 'src/services/command-project';
7 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
8 +import { NodeProcess } from 'src/services/node-process';
9 +import { ComposioUserContext } from 'src/services/user-context';
10 +import { cli, MockConsole, TestLive } from 'test/__utils__';
11 +import { makeOrgProject } from 'test/__utils__/models/account';
12 +
13 +const SHARED_PROJECT_DESCRIPTION =
14 + 'Developer project to use instead of the one configured in this directory';
15 +const SHARED_USER_DESCRIPTION =
16 + 'User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one.';
17 +// `dev logs tools|triggers` declare a comma-separated `--user-id` filter of their own, which
18 +// `withSharedFlags` accepts below a group entry and the help page shows in place of the shared row.
19 +const OWN_USER_ID_PAGES = ['dev logs tools', 'dev logs triggers'];
20 +
21 +// A fresh layer per page: the mock console keeps every line written under one layer.
22 +const helpPage = (path: ReadonlyArray<string>) =>
23 + Effect.gen(function* () {
24 + yield* Effect.exit(cli([...path, '--help']));
25 + return (yield* MockConsole.getLines({ stripAnsi: true, stream: 'stdout' })).join('\n');
26 + }).pipe(Effect.provide(TestLive()));
27 +
28 +const subcommandPaths = (
29 + command: import('effect/cli').Command.Command.Any,
30 + prefix: ReadonlyArray<string>
31 +): ReadonlyArray<ReadonlyArray<string>> =>
32 + command.subcommands
33 + .flatMap(group => group.commands)
34 + .filter(child => child.name !== 'help' && !child.unlisted)
35 + .flatMap(child => {
36 + const path = [...prefix, child.name];
37 + return [path, ...subcommandPaths(child, path)];
38 + });
39 +
40 +const root = buildRootCommand({ isDevModeEnabled: true, isExperimentalFeatureEnabled: () => true });
41 +const devCommand = root.subcommands.flatMap(group => group.commands).find(c => c.name === 'dev')!;
42 +const devPages = subcommandPaths(devCommand, ['dev']).map(path => ({ path, name: path.join(' ') }));
43 +const rootPages = subcommandPaths(root, [])
44 + .filter(path => path[0] !== 'dev' && path[0] !== 'listen')
45 + .map(path => ({ path, name: path.join(' ') }));
46 +
47 +describe('CommandSurface: the dev group shares --user-id and --project-name', () => {
48 + it.effect.each(devPages)('documents both shared flags once on `$name`', ({ path, name }) =>
49 + Effect.gen(function* () {
50 + const page = yield* helpPage(path);
51 + const rows = page.split('\n').filter(line => line.trimStart().startsWith('--'));
52 + expect(
53 + rows.filter(row => row.includes('--project-name string')),
54 + name
55 + ).toHaveLength(1);
56 + expect(
57 + rows.filter(row => row.includes('--user-id string')),
58 + name
59 + ).toHaveLength(1);
60 + expect(page, name).toContain(SHARED_PROJECT_DESCRIPTION);
61 + if (!OWN_USER_ID_PAGES.includes(name)) {
62 + expect(page, name).toContain(SHARED_USER_DESCRIPTION);
63 + }
64 + })
65 + );
66 +
67 + it.effect.each(rootPages)('keeps the shared flags off the root page `$name`', ({ path }) =>
68 + Effect.gen(function* () {
69 + const page = yield* helpPage(path);
70 + expect(page).not.toContain('--user-id');
71 + expect(page).not.toContain('--project-name');
72 + })
73 + );
74 +
75 + layer(TestLive())(it => {
76 + it.effect('rejects --user-id on a root command, which has no such flag', () =>
77 + Effect.gen(function* () {
78 + const result = yield* Effect.result(cli(['search', 'send an email', '--user-id', 'alice']));
79 + expect(result._tag).toBe('Failure');
80 + const stderr = (yield* MockConsole.getLines({ stripAnsi: true, stream: 'stderr' })).join(
81 + '\n'
82 + );
83 + expect(stderr).toContain('--user-id');
84 + })
85 + );
86 + });
87 +
88 + layer(
89 + TestLive({
90 + baseConfigProvider: ConfigProvider.fromEnv({
91 + env: {
92 + COMPOSIO_USER_API_KEY: 'test_api_key',
93 + COMPOSIO_ORG_ID: 'dev_org_test',
94 + COMPOSIO_PROJECT_ID: 'dev_project_test',
95 + },
96 + }),
97 + connectedAccountsData: {
98 + items: ['alice', 'bob'].map(userId => ({
99 + id: `con_${userId}`,
100 + status: 'ACTIVE',
101 + status_reason: null,
102 + is_disabled: false,
103 + user_id: userId,
104 + toolkit: { slug: 'gmail' },
105 + auth_config: {
106 + id: 'ac_gmail',
107 + auth_scheme: 'OAUTH2',
108 + is_composio_managed: true,
109 + is_disabled: false,
110 + },
111 + created_at: '2026-01-01T00:00:00Z',
112 + updated_at: '2026-01-01T00:00:00Z',
113 + test_request_endpoint: 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
114 + })),
115 + },
116 + })
117 + )(it => {
118 + it.effect.each([
119 + {
120 + name: 'after the subcommand',
121 + args: ['dev', 'connected-accounts', 'list', '--user-id', 'alice'],
122 + },
123 + {
124 + name: 'before the subcommand',
125 + args: ['dev', '--user-id', 'alice', 'connected-accounts', 'list'],
126 + },
127 + ])('reaches the handler when passed $name', ({ args }) =>
128 + Effect.gen(function* () {
129 + const userContext = yield* ComposioUserContext;
130 + yield* userContext.login('test_api_key', 'org_test');
131 + yield* cli(args);
132 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
133 + expect(output).toContain('con_alice');
134 + expect(output).not.toContain('con_bob');
135 + })
136 + );
137 + });
138 +});
139 +
140 +describe('CommandSurface: --project-name reaches the project resolver', () => {
141 + layer(
142 + TestLive({
143 + baseConfigProvider: ConfigProvider.fromEnv({
144 + env: { COMPOSIO_USER_API_KEY: 'test_api_key', COMPOSIO_ORG_ID: 'org_test' },
145 + }),
146 + accountData: { projects: [] },
147 + })
148 + )(it => {
149 + it.effect.each(
150 + [
151 + {
152 + name: 'after the subcommand',
153 + args: ['dev', 'connected-accounts', 'link', 'gmail', '--list', '--project-name', 'nope'],
154 + },
155 + {
156 + name: 'before the subcommand',
157 + args: ['dev', '--project-name', 'nope', 'connected-accounts', 'link', 'gmail', '--list'],
158 + },
159 + { name: 'to connected-accounts list', args: ['dev', 'connected-accounts', 'list'] },
160 + { name: 'to toolkits info', args: ['dev', 'toolkits', 'info', 'gmail'] },
161 + { name: 'to triggers listen', args: ['dev', 'triggers', 'listen'] },
162 + { name: 'to listen', args: ['dev', 'listen'] },
163 + ].map(({ name, args }) =>
164 + args.includes('--project-name')
165 + ? { name, args }
166 + : { name, args: [...args, '--project-name', 'nope'] }
167 + )
168 + )('looks the named project up when passed $name', ({ args }) =>
169 + Effect.gen(function* () {
170 + const userContext = yield* ComposioUserContext;
171 + yield* userContext.login('test_api_key', 'org_test');
172 + const error = yield* Effect.flip(cli(args));
173 + expect(error).toBeInstanceOf(ProjectResolutionError);
174 + expect((error as ProjectResolutionError).message).toContain(
175 + 'Developer project "nope" was not found in org "org_test"'
176 + );
177 + })
178 + );
179 + });
180 +});
181 +
182 +describe('CommandSurface: toolkits list reports the named project it cannot find', () => {
183 + layer(
184 + TestLive({
185 + baseConfigProvider: ConfigProvider.fromEnv({
186 + env: { COMPOSIO_USER_API_KEY: 'test_api_key', COMPOSIO_ORG_ID: 'org_test' },
187 + }),
188 + accountData: { projects: [] },
189 + })
190 + )(it => {
191 + // `toolkits list` reports every failure on stderr and exits 1 rather than failing.
192 + it.effect('looks the named project up', () =>
193 + Effect.gen(function* () {
194 + const userContext = yield* ComposioUserContext;
195 + yield* userContext.login('test_api_key', 'org_test');
196 + yield* cli(['dev', 'toolkits', 'list', '--project-name', 'nope']);
197 + const stderr = (yield* MockConsole.getLines({ stripAnsi: true, stream: 'stderr' })).join(
198 + '\n'
199 + );
200 + expect(stderr).toContain('Developer project "nope" was not found in org "org_test"');
201 + })
202 + );
203 + });
204 +});
205 +
206 +describe('CommandSurface: playground-execute --parallel keeps the shared flags', () => {
207 + layer(
208 + TestLive({
209 + baseConfigProvider: ConfigProvider.fromEnv({
210 + env: { COMPOSIO_USER_API_KEY: 'test_api_key', COMPOSIO_ORG_ID: 'org_test' },
211 + }),
212 + accountData: { projects: [] },
213 + })
214 + )(it => {
215 + it.effect.each([
216 + {
217 + name: 'after the subcommand',
218 + args: ['dev', 'playground-execute', '--parallel', 'GMAIL_SEND_EMAIL', '-d', '{}'],
219 + shared: ['--project-name', 'nope'],
220 + },
221 + {
222 + name: 'before the subcommand',
223 + args: ['dev', '--project-name', 'nope', 'playground-execute', '--parallel'],
224 + shared: ['GMAIL_SEND_EMAIL', '-d', '{}'],
225 + },
226 + ])('looks the named project up when --project-name is passed $name', ({ args, shared }) =>
227 + Effect.gen(function* () {
228 + const userContext = yield* ComposioUserContext;
229 + yield* userContext.login('test_api_key', 'org_test');
230 + const error = yield* Effect.flip(cli([...args, ...shared, '--skip-checks']));
231 + expect(error).toBeInstanceOf(ProjectResolutionError);
232 + expect((error as ProjectResolutionError).message).toContain(
233 + 'Developer project "nope" was not found in org "org_test"'
234 + );
235 + })
236 + );
237 + });
238 +
239 + const sessionUserIds: Array<string> = [];
240 + layer(
241 + TestLive({
242 + baseConfigProvider: ConfigProvider.fromEnv({
243 + env: {
244 + COMPOSIO_USER_API_KEY: 'test_api_key',
245 + COMPOSIO_ORG_ID: 'dev_org_test',
246 + COMPOSIO_PROJECT_ID: 'dev_project_test',
247 + },
248 + }),
249 + fixture: 'global-test-user-id',
250 + stdin: { isTTY: true, data: '' },
251 + toolRouter: {
252 + create: params =>
253 + Effect.sync(() => {
254 + sessionUserIds.push(params.user_id);
255 + return {
256 + session_id: 'trs_test_session',
257 + config: {
258 + user_id: params.user_id,
259 + execute: {},
260 + search: {},
261 + preload: { tools: [] },
262 + instant: false,
263 + },
264 + config_version: 1,
265 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
266 + tool_router_tools: [],
267 + };
268 + }),
269 + },
270 + })
271 + )(it => {
272 + it.effect('runs as the --user-id passed before the subcommand', () =>
273 + Effect.gen(function* () {
274 + const userContext = yield* ComposioUserContext;
275 + yield* userContext.login('test_api_key', 'org_test');
276 + sessionUserIds.length = 0;
277 + yield* cli([
278 + 'dev',
279 + '--user-id',
280 + 'alice',
281 + 'playground-execute',
282 + '--parallel',
283 + '--skip-checks',
284 + 'GMAIL_SEND_EMAIL',
285 + '-d',
286 + '{}',
287 + 'GITHUB_CREATE_ISSUE',
288 + '-d',
289 + '{}',
290 + ]);
291 + expect(sessionUserIds.length).toBeGreaterThan(0);
292 + expect(new Set(sessionUserIds)).toEqual(new Set(['alice']));
293 + })
294 + );
295 + });
296 +});
297 +
298 +describe('CommandSurface: playground-execute --parallel finds its command name', () => {
299 + const executedSlugs: Array<string> = [];
300 + layer(
301 + TestLive({
302 + baseConfigProvider: ConfigProvider.fromEnv({
303 + env: {
304 + COMPOSIO_USER_API_KEY: 'test_api_key',
305 + COMPOSIO_ORG_ID: 'dev_org_test',
306 + COMPOSIO_PROJECT_ID: 'dev_project_test',
307 + },
308 + }),
309 + stdin: { isTTY: true, data: '' },
310 + accountData: {
311 + projects: [
312 + makeOrgProject({ id: 'proj_pe', name: 'playground-execute', orgId: 'org_test' }),
313 + ],
314 + },
315 + toolsExecutor: { onExecute: slug => executedSlugs.push(slug) },
316 + })
317 + )(it => {
318 + it.effect.each([
319 + { flag: '--user-id', args: ['--user-id', 'playground-execute'] },
320 + { flag: '--project-name', args: ['--project-name', 'playground-execute'] },
321 + ])('does not take a $flag value that spells it for the command', ({ args }) =>
322 + Effect.gen(function* () {
323 + yield* (yield* ComposioUserContext).login('test_api_key', 'org_test', 'global_user');
324 + executedSlugs.length = 0;
325 + yield* cli([
326 + 'dev',
327 + ...args,
328 + 'playground-execute',
329 + '--parallel',
330 + '--skip-checks',
331 + 'GMAIL_SEND_EMAIL',
332 + '-d',
333 + '{}',
334 + 'GITHUB_CREATE_ISSUE',
335 + '-d',
336 + '{}',
337 + ]);
338 + expect(executedSlugs.toSorted()).toEqual(['GITHUB_CREATE_ISSUE', 'GMAIL_SEND_EMAIL']);
339 + })
340 + );
341 + });
342 +});
343 +
344 +// `dev logs tools|triggers` honor --user-id as their filter and reject only --project-name.
345 +const rejectingCommands = [
346 + { path: ['init'], flags: ['--project-name', '--user-id'] },
347 + { path: ['logs', 'tools'], flags: ['--project-name'] },
348 + { path: ['logs', 'triggers'], flags: ['--project-name'] },
349 + { path: ['auth-configs', 'list'], flags: ['--project-name', '--user-id'] },
350 + { path: ['projects', 'list'], flags: ['--project-name', '--user-id'] },
351 + { path: ['toolkits', 'search', 'email'], flags: ['--project-name', '--user-id'] },
352 + { path: ['toolkits', 'version', 'gmail'], flags: ['--project-name', '--user-id'] },
353 + { path: ['connected-accounts', 'info', 'ca_1'], flags: ['--project-name', '--user-id'] },
354 + { path: ['connected-accounts', 'whoami', 'ca_1'], flags: ['--project-name', '--user-id'] },
355 + { path: ['triggers', 'list', 'gmail'], flags: ['--project-name', '--user-id'] },
356 + { path: ['triggers', 'info', 'GMAIL_NEW_GMAIL_MESSAGE'], flags: ['--project-name', '--user-id'] },
357 + { path: ['triggers', 'status'], flags: ['--project-name', '--user-id'] },
358 + {
359 + path: ['triggers', 'create', 'GMAIL_NEW_GMAIL_MESSAGE'],
360 + flags: ['--project-name', '--user-id'],
361 + },
362 + { path: ['triggers', 'enable', 'ti_1'], flags: ['--project-name', '--user-id'] },
363 + { path: ['triggers', 'disable', 'ti_1'], flags: ['--project-name', '--user-id'] },
364 +].flatMap(({ path, flags }) =>
365 + flags.map(flag => ({ path, flag, name: `dev ${path.join(' ')} ${flag}` }))
366 +);
367 +
368 +describe('CommandSurface: dev commands that cannot honor a shared flag reject it', () => {
369 + layer(
370 + TestLive({
371 + baseConfigProvider: ConfigProvider.fromEnv({
372 + env: { COMPOSIO_USER_API_KEY: 'test_api_key', COMPOSIO_ORG_ID: 'org_test' },
373 + }),
374 + })
375 + )(it => {
376 + it.effect.each(rejectingCommands)('rejects `$name`', ({ path, flag }) =>
377 + Effect.gen(function* () {
378 + const userContext = yield* ComposioUserContext;
379 + yield* userContext.login('test_api_key', 'org_test');
380 + const error = yield* Effect.flip(cli(['dev', flag, 'other', ...path]));
381 + expect(error).toBeInstanceOf(CommandInputError);
382 + expect(error).toMatchObject({ option: flag });
383 + })
384 + );
385 + });
386 +});
387 +
388 +describe('CommandSurface: the developer-mode toggle rejects the shared flags', () => {
389 + // A fresh layer per case: a toggle that went through would turn developer mode off, and the
390 + // next case would then parse without the shared flags.
391 + it.effect.each([
392 + { args: ['dev', '--mode', 'off', '--project-name', 'other'], flag: '--project-name' },
393 + { args: ['dev', '--user-id', 'alice', '--mode', 'off'], flag: '--user-id' },
394 + ])('rejects `$args` and keeps developer mode on', ({ args, flag }) =>
395 + Effect.gen(function* () {
396 + const error = yield* Effect.flip(cli(args));
397 + expect(error).toBeInstanceOf(CommandInputError);
398 + expect(error).toMatchObject({ command: 'dev', option: flag });
399 + expect((yield* ComposioCliUserConfig).isDevModeEnabled()).toBe(true);
400 + }).pipe(Effect.provide(TestLive()), Effect.scoped)
401 + );
402 +
403 + it.effect('still toggles without them', () =>
404 + Effect.gen(function* () {
405 + yield* cli(['dev', '--mode', 'off']);
406 + expect((yield* ComposioCliUserConfig).isDevModeEnabled()).toBe(false);
407 + }).pipe(Effect.provide(TestLive()), Effect.scoped)
408 + );
409 +});
410 +
411 +describe('CommandSurface: a named project does not borrow the directory test user', () => {
412 + // The directory belongs to `dir-project` and configures its own test user; the global one is
413 + // what login stores. A `--project-name` naming another project must fall back to the global one.
414 + const writeDirectoryProject = Effect.gen(function* () {
415 + const fs = yield* FileSystem.FileSystem;
416 + const path = yield* Path.Path;
417 + const { cwd } = yield* NodeProcess;
418 + yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
419 + yield* fs.writeFileString(
420 + path.join(cwd, '.composio', 'project.json'),
421 + JSON.stringify({ org_id: 'org_test', project_id: 'proj_dir', test_user_id: 'directory_user' })
422 + );
423 + });
424 +
425 + const sessionUser = (args: ReadonlyArray<string>) =>
426 + Effect.gen(function* () {
427 + const userIds: Array<string> = [];
428 + yield* Effect.gen(function* () {
429 + yield* writeDirectoryProject;
430 + yield* (yield* ComposioUserContext).login('test_api_key', 'org_test', 'global_user');
431 + yield* Effect.exit(cli(args));
432 + }).pipe(
433 + Effect.provide(
434 + TestLive({
435 + baseConfigProvider: ConfigProvider.fromEnv({
436 + env: { COMPOSIO_USER_API_KEY: 'test_api_key', COMPOSIO_ORG_ID: 'org_test' },
437 + }),
438 + accountData: { projects },
439 + stdin: { isTTY: true, data: '' },
440 + toolRouter: {
441 + create: params =>
442 + Effect.sync(() => {
443 + userIds.push(params.user_id);
444 + return {
445 + session_id: 'trs_test_session',
446 + config: {
447 + user_id: params.user_id,
448 + execute: {},
449 + search: {},
450 + preload: { tools: [] },
451 + instant: false,
452 + },
453 + config_version: 1,
454 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
455 + tool_router_tools: [],
456 + };
457 + }),
458 + },
459 + })
460 + ),
461 + Effect.scoped
462 + );
463 + return [...new Set(userIds)];
464 + });
465 +
466 + const projects = [
467 + makeOrgProject({ id: 'proj_dir', name: 'dir-project', orgId: 'org_test' }),
468 + makeOrgProject({ id: 'proj_other', name: 'other-project', orgId: 'org_test' }),
469 + ];
470 + const sessionCommands = [
471 + { command: 'toolkits list', args: ['dev', 'toolkits', 'list'] },
472 + { command: 'toolkits info', args: ['dev', 'toolkits', 'info', 'gmail'] },
473 + {
474 + command: 'playground-execute',
475 + args: ['dev', 'playground-execute', 'GMAIL_SEND_EMAIL', '-d', '{}', '--skip-checks'],
476 + },
477 + ];
478 + const projectCases = [
479 + { project: ['--project-name', 'other-project'], expected: 'global_user' },
480 + { project: ['--project-name', 'dir-project'], expected: 'directory_user' },
481 + { project: [], expected: 'directory_user' },
482 + ];
483 +
484 + it.effect.each(
485 + sessionCommands.flatMap(({ command, args }) =>
486 + projectCases.map(({ project, expected }) => ({
487 + args: [...args, ...project],
488 + expected,
489 + name: `${command} ${project.join(' ') || 'without --project-name'}`,
490 + }))
491 + )
492 + )('`$name` opens its session as $expected', ({ args, expected }) =>
493 + Effect.gen(function* () {
494 + expect(yield* sessionUser(args)).toEqual([expected]);
495 + })
496 + );
497 +
498 + const accountFor = (userId: string, id: string): ConnectedAccountItem => ({
499 + id,
500 + alias: id,
501 + word_id: id,
502 + status: 'ACTIVE',
503 + status_reason: null,
504 + is_disabled: false,
505 + user_id: userId,
506 + toolkit: { slug: 'gmail' },
507 + auth_config: {
508 + id: 'ac_gmail_oauth',
509 + auth_scheme: 'OAUTH2',
510 + is_composio_managed: true,
511 + is_disabled: false,
512 + },
513 + created_at: '2026-01-01T00:00:00Z',
514 + updated_at: '2026-01-15T00:00:00Z',
515 + test_request_endpoint: '',
516 + });
517 +
518 + // `link --list` without --project-name resolves the consumer project and its own user, so only
519 + // the named cases apply.
520 + it.effect.each([
521 + { project: 'other-project', expected: 'ca_global', other: 'ca_dir' },
522 + { project: 'dir-project', expected: 'ca_dir', other: 'ca_global' },
523 + ])(
524 + '`connected-accounts link --list --project-name $project` lists $expected',
525 + ({ project, expected, other }) =>
526 + Effect.gen(function* () {
527 + yield* writeDirectoryProject;
528 + yield* (yield* ComposioUserContext).login('test_api_key', 'org_test', 'global_user');
529 + yield* cli([
530 + 'dev',
531 + 'connected-accounts',
532 + 'link',
533 + 'gmail',
534 + '--list',
535 + '--project-name',
536 + project,
537 + ]);
538 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
539 + expect(output).toContain(expected);
540 + expect(output).not.toContain(other);
541 + }).pipe(
542 + Effect.provide(
543 + TestLive({
544 + baseConfigProvider: ConfigProvider.fromEnv({
545 + env: { COMPOSIO_USER_API_KEY: 'test_api_key', COMPOSIO_ORG_ID: 'org_test' },
546 + }),
547 + accountData: { projects },
548 + connectedAccountsData: {
549 + items: [
550 + accountFor('global_user', 'ca_global'),
551 + accountFor('directory_user', 'ca_dir'),
552 + ],
553 + },
554 + })
555 + ),
556 + Effect.scoped
557 + )
558 + );
559 +
560 + it.effect.each([
561 + { project: 'other-project', expected: 'Using global test user id "global_user"' },
562 + { project: 'dir-project', expected: 'Using test user id "directory_user"' },
563 + ])(
564 + '`connected-accounts link --auth-config --project-name $project` warns `$expected`',
565 + ({ project, expected }) =>
566 + Effect.gen(function* () {
567 + yield* writeDirectoryProject;
568 + yield* (yield* ComposioUserContext).login('test_api_key', 'org_test', 'global_user');
569 + yield* Effect.exit(
570 + cli([
571 + 'dev',
572 + 'connected-accounts',
573 + 'link',
574 + '--auth-config',
575 + 'ac_gmail_oauth',
576 + '--no-wait',
577 + '--project-name',
578 + project,
579 + ])
580 + );
581 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
582 + expect(output).toContain(expected);
583 + }).pipe(
584 + Effect.provide(
585 + TestLive({
586 + baseConfigProvider: ConfigProvider.fromEnv({
587 + env: { COMPOSIO_USER_API_KEY: 'test_api_key', COMPOSIO_ORG_ID: 'org_test' },
588 + }),
589 + accountData: { projects },
590 + })
591 + ),
592 + Effect.scoped
593 + )
594 + );
595 + // A login without session info stores no global test user; the directory's does not carry over.
596 + it.effect.each([
597 + {
598 + command: 'playground-execute',
599 + args: ['dev', 'playground-execute', 'GMAIL_SEND_EMAIL', '-d', '{}', '--skip-checks'],
600 + },
601 + {
602 + command: 'connected-accounts link --list',
603 + args: ['dev', 'connected-accounts', 'link', 'gmail', '--list'],
604 + },
605 + {
606 + command: 'connected-accounts link --auth-config',
607 + args: ['dev', 'connected-accounts', 'link', '--auth-config', 'ac_gmail_oauth', '--no-wait'],
608 + },
609 + ])('`$command --project-name` without any test user points at --user-id and login', ({ args }) =>
610 + Effect.gen(function* () {
611 + yield* writeDirectoryProject;
612 + yield* (yield* ComposioUserContext).login('test_api_key', 'org_test');
613 + const error = yield* Effect.flip(cli([...args, '--project-name', 'other-project']));
614 + expect(error).toMatchObject({
615 + message:
616 + 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
617 + });
618 + }).pipe(
619 + Effect.provide(
620 + TestLive({
621 + baseConfigProvider: ConfigProvider.fromEnv({
622 + env: { COMPOSIO_USER_API_KEY: 'test_api_key', COMPOSIO_ORG_ID: 'org_test' },
623 + }),
624 + accountData: { projects },
625 + stdin: { isTTY: true, data: '' },
626 + })
627 + ),
628 + Effect.scoped
629 + )
630 + );
631 +});
ts/packages/cli/test/src/commands/toolkits/info/toolkits.info.client.cmd.test.ts renamed
ts/packages/cli/test/src/commands/toolkits/info/toolkits.info.cmd.test.ts renamed
ts/packages/cli/test/src/commands/tools/search/tools.search.client.cmd.test.ts renamed
ts/packages/cli/test/src/commands/tools/search/tools.search.cmd.test.ts renamed
ts/packages/cli/test/src/commands/triggers/info/triggers.info.cmd.test.ts renamed
ts/packages/cli/test/src/commands/triggers/list/triggers.list.cmd.test.ts renamed