@devries-cameron20 / composio-1 / commits / e1e1c8471
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): move `orgs list` into the directory shape (#4972)

This PR: - moves `orgs list` from `orgs/commands/orgs.list.cmd.ts` to `orgs/list/orgs.list.{cmd,handler,format}.ts`. The command file only declares `--limit` and passes `runOrgsList` to `Command.make` - puts the intro, spinner, and outro strings, the marked org lines, and the stdout JSON in `orgs.list.format.ts`; the current org is matched with `Option.contains` and the empty case with `Array.match` - replaces the handler's own "No user API key found" warning with `Effect.fromOption(ctx.data.apiKey, notLoggedIn)`. The `orgs` group already pipes `requireLogin`, so through the CLI the branch was unreachable and the logged-out exit is unchanged (`NotLoggedInError`, exit 1) - adds `orgs.list.cmd.test.ts` (logged out, stdout JSON and stderr lines with a current org, `--limit` clamping, no orgs) and `orgs.list.handler.test.ts` (selection, clamp table, empty list, missing key) over `layers/accounts.ts` doubles - removes `orgs/commands/orgs.list.cmd.ts` from `COMMAND_TEST_EXEMPTIONS` (15 to 14) Part of U9 of the CLI command-layout series. No user-visible change, so no CHANGELOG entry. Verified locally on the branch tip: | Check | Result | | --- | --- | | `pnpm --filter @composio/cli typecheck` | passes | | `pnpm --filter @composio/cli test` (skills, boundaries, command tests, Vitest) | 162 files, 1910 passed, 1 skipped | | `validate:command-tests` | 14 exemptions (was 15) | | `lint:effect` | 0 diagnostics | | `oxlint`, prettier on touched files | clean | | Binary smoke | `orgs --help`, `orgs list --help`, logged-out `orgs list` and `orgs list --limit 3`, root `--help`: stdout, stderr, and exit codes identical to an `origin/next` (231122de1) binary | `orgs switch` stays in the legacy shape; it has its test already.

Alberto Schiabel committed Oct 20, 2026 at 15:36 UTC e1e1c84712d7b4ce4706442d4db9475a6a70727a
8 files changed +365 -66
ts/packages/cli/scripts/command-tests.ts
-1
@@ -21,7 +21,6 @@ export const COMMAND_TEST_EXEMPTIONS: readonly CommandTestExemption[] = [
21 { command: 'artifacts.cmd.ts', reason: 'no test yet' },
22 { command: 'connections/commands/connections.remove.cmd.ts', reason: 'no test yet' },
23 { command: 'debug.cmd.ts', reason: 'no test yet' },
24 - { command: 'orgs/commands/orgs.list.cmd.ts', reason: 'no test yet' },
24 { command: 'signup.cmd.ts', reason: 'no test yet' },
25 { command: 'triggers/commands/triggers.listen.cmd.ts', reason: 'no test yet' },
26 { command: 'upgrade.cmd.ts', reason: 'no test yet' },
ts/packages/cli/src/commands/orgs/commands/orgs.list.cmd.ts deleted
-64
@@ -1,64 +0,0 @@
1 -import { Command, Flag } from 'effect/cli';
2 -import { Effect, Option } from 'effect';
3 -import { TerminalUI } from 'src/services/terminal-ui';
4 -import { listOrganizations } from 'src/services/composio-account';
5 -import { ComposioUserContext } from 'src/services/user-context';
6 -import { clampLimit } from 'src/ui/clamp-limit';
7 -
8 -const limit = Flag.Int('limit').pipe(
9 - Flag.withDefault(50),
10 - Flag.withDescription('Max organizations to fetch from API (default: 50)')
11 -);
12 -
13 -export const orgsCmd$List = Command.make('list', { limit }, ({ limit }) =>
14 - Effect.gen(function* () {
15 - const ui = yield* TerminalUI;
16 - const ctx = yield* ComposioUserContext;
17 - const apiKey = Option.getOrUndefined(ctx.data.apiKey);
18 - if (!apiKey) {
19 - yield* ui.log.warn('No user API key found. Run `composio login` first.');
20 - return;
21 - }
22 -
23 - const clampedLimit = clampLimit(limit);
24 - const defaultOrgId = Option.getOrUndefined(ctx.data.orgId);
25 -
26 - yield* ui.intro(`composio dev orgs list`);
27 -
28 - const organizations = yield* ui.withSpinner(
29 - 'Loading organizations...',
30 - listOrganizations({
31 - apiKey,
32 - limit: clampedLimit,
33 - }),
34 - {
35 - successMessage: result => `Loaded ${result.data.length} orgs`,
36 - errorMessage: 'Failed to fetch organizations',
37 - }
38 - );
39 -
40 - if (organizations.data.length === 0) {
41 - yield* ui.log.warn('No organizations found.');
42 - return;
43 - }
44 -
45 - const lines = organizations.data.map(org => {
46 - const isSelected = defaultOrgId === org.id;
47 - return `${isSelected ? '✓' : ' '} ${org.name} (${org.id})`;
48 - });
49 - yield* ui.log.info(lines.join('\n'));
50 - yield* ui.outro(
51 - 'Hint: run `composio dev orgs switch` to switch the default global org/project.'
52 - );
53 -
54 - yield* ui.output(
55 - JSON.stringify(
56 - organizations.data.map(org => ({
57 - id: org.id,
58 - name: org.name,
59 - is_selected_global_org: defaultOrgId === org.id,
60 - }))
61 - )
62 - );
63 - })
64 -).pipe(Command.withDescription('List organizations and show current global selection.'));
ts/packages/cli/src/commands/orgs/list/orgs.list.cmd.ts new
+11
@@ -0,0 +1,11 @@
1 +import { Command, Flag } from 'effect/cli';
2 +import { runOrgsList } from './orgs.list.handler';
3 +
4 +const limit = Flag.Int('limit').pipe(
5 + Flag.withDefault(50),
6 + Flag.withDescription('Max organizations to fetch from API (default: 50)')
7 +);
8 +
9 +export const orgsCmd$List = Command.make('list', { limit }, runOrgsList).pipe(
10 + Command.withDescription('List organizations and show current global selection.')
11 +);
ts/packages/cli/src/commands/orgs/list/orgs.list.format.ts new
+41
@@ -0,0 +1,41 @@
1 +import { Option } from 'effect';
2 +import type { OrganizationSummary } from 'src/services/composio-account';
3 +
4 +// --- stderr -----------------------------------------------------------------------------------
5 +
6 +/** The intro both trees print; `orgs list` is reachable from the root as well. */
7 +export const ORGS_LIST_INTRO = 'composio dev orgs list';
8 +export const LOADING_ORGANIZATIONS_MESSAGE = 'Loading organizations...';
9 +export const FETCH_ORGANIZATIONS_FAILED_MESSAGE = 'Failed to fetch organizations';
10 +export const NO_ORGANIZATIONS_MESSAGE = 'No organizations found.';
11 +export const ORGS_LIST_OUTRO =
12 + 'Hint: run `composio dev orgs switch` to switch the default global org/project.';
13 +
14 +export const loadedOrganizationsMessage = (count: number) => `Loaded ${count} orgs`;
15 +
16 +const isSelected = (org: OrganizationSummary, currentOrgId: Option.Option<string>) =>
17 + Option.contains(currentOrgId, org.id);
18 +
19 +/** One line per organization, the current one marked with `✓`. */
20 +export const formatOrganizationLines = (
21 + organizations: ReadonlyArray<OrganizationSummary>,
22 + currentOrgId: Option.Option<string>
23 +) =>
24 + organizations
25 + .map(org => `${isSelected(org, currentOrgId) ? '✓' : ' '} ${org.name} (${org.id})`)
26 + .join('\n');
27 +
28 +// --- stdout -----------------------------------------------------------------------------------
29 +
30 +/** The organizations as JSON, each flagged when it is the current global org. */
31 +export const formatOrganizationsJson = (
32 + organizations: ReadonlyArray<OrganizationSummary>,
33 + currentOrgId: Option.Option<string>
34 +) =>
35 + JSON.stringify(
36 + organizations.map(org => ({
37 + id: org.id,
38 + name: org.name,
39 + is_selected_global_org: isSelected(org, currentOrgId),
40 + }))
41 + );
ts/packages/cli/src/commands/orgs/list/orgs.list.handler.ts new
+52
@@ -0,0 +1,52 @@
1 +import { Array as Arr, Effect } from 'effect';
2 +import { notLoggedIn } from 'src/commands/errors';
3 +import { listOrganizations } from 'src/services/composio-account';
4 +import { TerminalUI } from 'src/services/terminal-ui';
5 +import { ComposioUserContext } from 'src/services/user-context';
6 +import { clampLimit } from 'src/ui/clamp-limit';
7 +import {
8 + FETCH_ORGANIZATIONS_FAILED_MESSAGE,
9 + LOADING_ORGANIZATIONS_MESSAGE,
10 + NO_ORGANIZATIONS_MESSAGE,
11 + ORGS_LIST_INTRO,
12 + ORGS_LIST_OUTRO,
13 + formatOrganizationLines,
14 + formatOrganizationsJson,
15 + loadedOrganizationsMessage,
16 +} from './orgs.list.format';
17 +
18 +/** The flags of `composio orgs list`. */
19 +export type OrgsListParams = {
20 + readonly limit: number;
21 +};
22 +
23 +/** Lists the user's organizations and marks the current global one. */
24 +export const runOrgsList = ({ limit }: OrgsListParams) =>
25 + Effect.gen(function* () {
26 + const ui = yield* TerminalUI;
27 + const ctx = yield* ComposioUserContext;
28 + // `requireLogin` on the `orgs` group has already proven the key is there.
29 + const apiKey = yield* Effect.fromOption(ctx.data.apiKey, notLoggedIn);
30 + const currentOrgId = ctx.data.orgId;
31 +
32 + yield* ui.intro(ORGS_LIST_INTRO);
33 +
34 + const organizations = yield* ui.withSpinner(
35 + LOADING_ORGANIZATIONS_MESSAGE,
36 + listOrganizations({ apiKey, limit: clampLimit(limit) }),
37 + {
38 + successMessage: result => loadedOrganizationsMessage(result.data.length),
39 + errorMessage: FETCH_ORGANIZATIONS_FAILED_MESSAGE,
40 + }
41 + );
42 +
43 + yield* Arr.match(organizations.data, {
44 + onEmpty: () => ui.log.warn(NO_ORGANIZATIONS_MESSAGE),
45 + onNonEmpty: data =>
46 + Effect.gen(function* () {
47 + yield* ui.log.info(formatOrganizationLines(data, currentOrgId));
48 + yield* ui.outro(ORGS_LIST_OUTRO);
49 + yield* ui.output(formatOrganizationsJson(data, currentOrgId));
50 + }),
51 + });
52 + });
ts/packages/cli/src/commands/orgs/orgs.cmd.ts
+1 -1
@@ -1,6 +1,6 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 -import { orgsCmd$List } from './commands/orgs.list.cmd';
3 +import { orgsCmd$List } from './list/orgs.list.cmd';
4 import { orgsCmd$Switch } from './commands/orgs.switch.cmd';
5
6 /**
ts/packages/cli/test/src/commands/orgs/list/orgs.list.cmd.test.ts new
+100
@@ -0,0 +1,100 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { cli, MockConsole, TestLive } from 'test/__utils__';
4 +import type { MockAccountRequest } from 'test/__utils__/services/test-layer';
5 +
6 +// The fixture stores a login whose current org is `org_1`.
7 +const LOGGED_IN_FIXTURE = 'user-config-with-global-context';
8 +
9 +const ORGANIZATIONS = [
10 + { id: 'org_0', name: 'Other Org' },
11 + { id: 'org_1', name: 'Current Org' },
12 +];
13 +
14 +/** The `limit` of every `org.list` request the mock client served. */
15 +const recordLimits = () => {
16 + const limits: Array<unknown> = [];
17 + const onRequest = (request: MockAccountRequest) => {
18 + if (request.operation === 'org.list') {
19 + limits.push((request.params as { readonly limit?: number } | undefined)?.limit);
20 + }
21 + };
22 + return { limits, onRequest };
23 +};
24 +
25 +describe('CLI: composio orgs list', () => {
26 + layer(TestLive())('[Given] no API key', it => {
27 + it.effect('[Then] fails with NotLoggedInError', () =>
28 + Effect.gen(function* () {
29 + const error = yield* cli(['orgs', 'list']).pipe(Effect.flip);
30 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
31 + })
32 + );
33 + });
34 +
35 + const defaultLimit = recordLimits();
36 + layer(
37 + TestLive({
38 + fixture: LOGGED_IN_FIXTURE,
39 + accountData: { organizations: ORGANIZATIONS, onRequest: defaultLimit.onRequest },
40 + })
41 + )('[Given] two organizations and a current org', it => {
42 + it.effect('[Then] prints them as JSON on stdout and marks the current one on stderr', () =>
43 + Effect.gen(function* () {
44 + yield* cli(['orgs', 'list']);
45 +
46 + const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
47 + const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
48 + expect(stdout).toEqual([
49 + JSON.stringify([
50 + { id: 'org_0', name: 'Other Org', is_selected_global_org: false },
51 + { id: 'org_1', name: 'Current Org', is_selected_global_org: true },
52 + ]),
53 + ]);
54 + expect(stderr).toEqual([
55 + '-- composio dev orgs list --',
56 + 'Loaded 2 orgs',
57 + ' Other Org (org_0)\n✓ Current Org (org_1)',
58 + '-- Hint: run `composio dev orgs switch` to switch the default global org/project. --',
59 + ]);
60 + expect(defaultLimit.limits).toEqual([50]);
61 + })
62 + );
63 + });
64 +
65 + const clamped = recordLimits();
66 + layer(
67 + TestLive({
68 + fixture: LOGGED_IN_FIXTURE,
69 + accountData: { organizations: ORGANIZATIONS, onRequest: clamped.onRequest },
70 + })
71 + )('[Given] --limit outside 1..1000', it => {
72 + it.effect('[Then] clamps the requested limit into range', () =>
73 + Effect.gen(function* () {
74 + yield* cli(['orgs', 'list', '--limit', '5000']);
75 + yield* cli(['orgs', 'list', '--limit', '0']);
76 +
77 + expect(clamped.limits).toEqual([1000, 1]);
78 + })
79 + );
80 + });
81 +
82 + layer(TestLive({ fixture: LOGGED_IN_FIXTURE, accountData: { organizations: [] } }))(
83 + '[Given] no organizations',
84 + it => {
85 + it.effect('[Then] warns and prints no data', () =>
86 + Effect.gen(function* () {
87 + yield* cli(['orgs', 'list']);
88 +
89 + const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
90 + const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
91 + expect(stdout).toEqual([]);
92 + expect(stderr).toContain('No organizations found.');
93 + expect(stderr).not.toContain(
94 + '-- Hint: run `composio dev orgs switch` to switch the default global org/project. --'
95 + );
96 + })
97 + );
98 + }
99 + );
100 +});
ts/packages/cli/test/src/commands/orgs/list/orgs.list.handler.test.ts new
+160
@@ -0,0 +1,160 @@
1 +import { Auth, make, type ComposioClientShape } from '@composio/client/effect';
2 +import { describe, expect, it } from '@effect/vitest';
3 +import { Console, Effect, Layer, Option } from 'effect';
4 +import { HttpClient } from 'effect/http';
5 +import { runOrgsList } from 'src/commands/orgs/list/orgs.list.handler';
6 +import { NO_ORGANIZATIONS_MESSAGE } from 'src/commands/orgs/list/orgs.list.format';
7 +import type { OrganizationSummary } from 'src/services/composio-account';
8 +import { ComposioClientSingleton } from 'src/services/composio-clients';
9 +import { TerminalUI } from 'src/services/terminal-ui';
10 +import { ComposioUserContext } from 'src/services/user-context';
11 +import { MockConsole } from 'test/__utils__';
12 +import { mockAccountResources, type MockRequestScope } from 'test/__utils__/layers/accounts';
13 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
14 +
15 +const ORGANIZATIONS: ReadonlyArray<OrganizationSummary> = [
16 + { id: 'org_first', name: 'First Org' },
17 + { id: 'org_second', name: 'Second Org' },
18 +];
19 +
20 +// A resource the account mocks do not shadow reaches this transport and dies with its URL.
21 +const baseClient = make(
22 + { auth: Auth.project('test'), baseURL: 'https://mock.invalid' },
23 + HttpClient.make(request =>
24 + Effect.die(new Error(`unexpected network call from the orgs list handler test: ${request.url}`))
25 + )
26 +);
27 +
28 +interface OrgsListFixture {
29 + readonly apiKey?: Option.Option<string>;
30 + readonly orgId?: Option.Option<string>;
31 + readonly organizations?: ReadonlyArray<OrganizationSummary>;
32 +}
33 +
34 +/**
35 + * What `runOrgsList` reads: a user context, the account family of the mock client, and a
36 + * headless terminal whose stdout data lands in `outputs` and whose `org.list` limits land in
37 + * `limits`.
38 + */
39 +const orgsListTest = (fixture: OrgsListFixture = {}) => {
40 + const outputs: Array<string> = [];
41 + const limits: Array<unknown> = [];
42 + const apiKey = fixture.apiKey ?? Option.some('uak_orgs_list');
43 + const accountData = {
44 + organizations: fixture.organizations ?? ORGANIZATIONS,
45 + onRequest: (request: { readonly params?: unknown }) => {
46 + limits.push((request.params as { readonly limit?: number } | undefined)?.limit);
47 + },
48 + };
49 + const clientFor = (scope: MockRequestScope): ComposioClientShape =>
50 + // The shadows answer only the fields the handler reads, as in `test-layer.ts`.
51 + ({
52 + ...baseClient,
53 + ...mockAccountResources(accountData, scope),
54 + }) as unknown as ComposioClientShape;
55 +
56 + const layer = Layer.mergeAll(
57 + Layer.effect(Console.Console, MockConsole.make),
58 + Layer.succeed(
59 + TerminalUI,
60 + TerminalUI.of({
61 + ...terminalUITestImpl,
62 + output: data =>
63 + Effect.sync(() => {
64 + outputs.push(data);
65 + }),
66 + })
67 + ),
68 + Layer.succeed(
69 + ComposioUserContext,
70 + ComposioUserContext.of({
71 + data: {
72 + apiKey,
73 + baseURL: 'https://mock.invalid',
74 + webURL: 'https://platform.mock.invalid/',
75 + orgId: fixture.orgId ?? Option.none(),
76 + projectId: Option.none(),
77 + testUserId: Option.none(),
78 + },
79 + isLoggedIn: () => Option.isSome(apiKey),
80 + logout: Effect.void,
81 + login: () => Effect.void,
82 + update: () => Effect.void,
83 + })
84 + ),
85 + Layer.succeed(
86 + ComposioClientSingleton,
87 + ComposioClientSingleton.of({
88 + get: () => Effect.succeed(clientFor({})),
89 + getFor: (scope: MockRequestScope) => Effect.succeed(clientFor(scope)),
90 + getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
91 + })
92 + )
93 + );
94 + return { layer, outputs, limits };
95 +};
96 +
97 +describe('runOrgsList', () => {
98 + it.effect('[Given] a current org [Then] flags only that org as selected', () => {
99 + const { layer, outputs } = orgsListTest({ orgId: Option.some('org_second') });
100 + return Effect.gen(function* () {
101 + yield* runOrgsList({ limit: 50 });
102 +
103 + expect(outputs.map(output => JSON.parse(output))).toEqual([
104 + [
105 + { id: 'org_first', name: 'First Org', is_selected_global_org: false },
106 + { id: 'org_second', name: 'Second Org', is_selected_global_org: true },
107 + ],
108 + ]);
109 + }).pipe(Effect.provide(layer));
110 + });
111 +
112 + it.effect('[Given] no current org [Then] flags no org as selected', () => {
113 + const { layer, outputs } = orgsListTest();
114 + return Effect.gen(function* () {
115 + yield* runOrgsList({ limit: 50 });
116 +
117 + expect(JSON.parse(outputs[0] ?? '[]')).toEqual([
118 + { id: 'org_first', name: 'First Org', is_selected_global_org: false },
119 + { id: 'org_second', name: 'Second Org', is_selected_global_org: false },
120 + ]);
121 + }).pipe(Effect.provide(layer));
122 + });
123 +
124 + it.effect.each([
125 + { limit: 50, expected: 50 },
126 + { limit: 0, expected: 1 },
127 + { limit: -3, expected: 1 },
128 + { limit: 1001, expected: 1000 },
129 + ])('[Given] limit $limit [Then] requests $expected organizations', ({ limit, expected }) => {
130 + const { layer, limits } = orgsListTest();
131 + return Effect.gen(function* () {
132 + yield* runOrgsList({ limit });
133 +
134 + expect(limits).toEqual([expected]);
135 + }).pipe(Effect.provide(layer));
136 + });
137 +
138 + it.effect('[Given] no organizations [Then] warns and outputs nothing', () => {
139 + const { layer, outputs } = orgsListTest({ organizations: [] });
140 + return Effect.gen(function* () {
141 + yield* runOrgsList({ limit: 50 });
142 +
143 + expect(outputs).toEqual([]);
144 + expect(yield* MockConsole.getLines({ stream: 'stderr' })).toEqual([NO_ORGANIZATIONS_MESSAGE]);
145 + }).pipe(Effect.provide(layer));
146 + });
147 +
148 + it.effect(
149 + '[Given] no stored API key [Then] fails with NotLoggedInError before any request',
150 + () => {
151 + const { layer, limits } = orgsListTest({ apiKey: Option.none() });
152 + return Effect.gen(function* () {
153 + const error = yield* Effect.flip(runOrgsList({ limit: 50 }));
154 +
155 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
156 + expect(limits).toEqual([]);
157 + }).pipe(Effect.provide(layer));
158 + }
159 + );
160 +});