@devries-cameron20 / composio-1 / commits / eed4ce5a4
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.

feat(cli): refactor login - remove --api-key, add interactive org/project picker (#2897)

## Summary - **Remove** `--api-key`, `--org-id`, `--project-id` flags from `composio login` and `composio init` - **Add** `-y` flag to login: skip org/project picker, use session defaults - **Default** (no `-y`): interactive org/project picker after login - **Extract** `runOrgProjectSelection` effect, reused in `composio orgs switch` - **Show** init/switch hints after picker when `-y` not passed - **Move** 'already logged in' hint to outro ## Usage ```bash composio login # Login, then interactive org/project picker composio login -y # Login, use session defaults (no picker) composio login --no-browser # Skip opening browser ``` Made with [Cursor](https://cursor.com)

Musthaq Ahamad committed Mar 13, 2026 at 11:44 UTC eed4ce5a48aa48ec1a51b06d7c4340edf4cba785
8 files changed +262 -567
ts/packages/cli/src/commands/init.cmd.ts
+6 -57
@@ -22,7 +22,7 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
22 *
23 * ## Behavior
24 *
25 - * 1. **Project selection** — fetches projects from the API or accepts `--org-id`/`--project-id`.
25 + * 1. **Project selection** — fetches projects from the API and prompts for selection.
26 * 2. **Writes config** — saves `<cwd>/.composio/project.json`.
27 *
28 * ## Flags
@@ -30,16 +30,6 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
30 * - `--yes` / `-y` — auto-select the first project from the list
31 */
32
33 -const orgIdOpt = Options.text('org-id').pipe(
34 - Options.optional,
35 - Options.withDescription('Organization ID (skip interactive picker)')
36 -);
37 -
38 -const projectIdOpt = Options.text('project-id').pipe(
39 - Options.optional,
40 - Options.withDescription('Project ID (skip interactive picker)')
41 -);
42 -
33 const yesOpt = Options.boolean('yes').pipe(
34 Options.withAlias('y'),
35 Options.withDefault(false),
@@ -221,26 +211,21 @@ const selectDefaultProject = (params: {
211 * CLI command to initialize a Composio project in the current directory.
212 *
213 * Creates `<cwd>/.composio/project.json` with org_id and project_id.
224 - *
225 - * Supports two modes:
226 - * 1. Interactive: Fetches projects from the API and prompts for selection
227 - * 2. Non-interactive: Accepts --org-id and --project-id flags for agents/CI
214 + * Fetches projects from the API and prompts for selection.
215 *
216 * @example
217 * ```bash
218 * composio init
232 - * composio init --org-id <org> --project-id <project>
219 + * composio init --yes
220 * ```
221 */
222 export const initCmd = CliCommand.make(
223 'init',
224 {
238 - orgId: orgIdOpt,
239 - projectId: projectIdOpt,
225 noBrowser: noBrowserOpt,
226 yes: yesOpt,
227 },
243 - ({ orgId, projectId, noBrowser, yes }) =>
228 + ({ noBrowser, yes }) =>
229 Effect.gen(function* () {
230 const ui = yield* TerminalUI;
231 const proc = yield* NodeProcess;
@@ -249,42 +234,6 @@ export const initCmd = CliCommand.make(
234
235 const composioDir = path.join(proc.cwd, constants.PROJECT_COMPOSIO_DIR);
236
252 - // Agent-native path: --org-id and --project-id flags skip project picker
253 - if (Option.isSome(orgId) && Option.isSome(projectId)) {
254 - const selected: ProjectKeys = {
255 - orgId: orgId.value,
256 - projectId: projectId.value,
257 - projectName: Option.none(),
258 - orgName: Option.none(),
259 - email: Option.none(),
260 - testUserId: Option.none(),
261 - };
262 -
263 - yield* writeProjectConfig(composioDir, selected);
264 - yield* ensureProjectApiKeyInEnv({ cwd: proc.cwd, selected }).pipe(
265 - Effect.catchTag('services/HttpServerError', e =>
266 - Effect.gen(function* () {
267 - yield* Effect.logDebug('Failed to resolve project API key from session/info:', e);
268 - yield* logEnvCreationHttpError(ui)(e);
269 - })
270 - ),
271 - Effect.catchTag('services/HttpDecodingError', e =>
272 - Effect.gen(function* () {
273 - yield* Effect.logDebug('Failed to decode API key response:', e);
274 - yield* logEnvCreationDecodingError(ui)(e);
275 - })
276 - )
277 - );
278 -
279 - yield* ui.log.success(`Project initialized in ${composioDir}/`);
280 - yield* ui.log.info(
281 - 'To switch your default global org/project later, run `composio orgs switch`.'
282 - );
283 - yield* ui.output(makeOutputJson(selected, composioDir));
284 - yield* ui.outro('');
285 - return;
286 - }
287 -
237 yield* initInteractiveFlow({ composioDir, noBrowser, yes });
238 })
239 ).pipe(CliCommand.withDescription('Initialize a Composio project in the current directory.'));
@@ -327,7 +276,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
276 yield* Effect.logDebug('Failed to list org projects:', e);
277 yield* ui.log.warn('Could not fetch projects from the server.');
278 yield* ui.log.info(
330 - 'Use `composio init --org-id <org> --project-id <project>` to set up manually.'
279 + 'Create a project at https://platform.composio.dev, then run `composio init` again.'
280 );
281 yield* ui.outro('');
282 return yield* Effect.fail(e);
@@ -338,7 +287,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
287 yield* Effect.logDebug('Failed to decode org projects response:', e);
288 yield* ui.log.warn('Unexpected response from the server.');
289 yield* ui.log.info(
341 - 'Use `composio init --org-id <org> --project-id <project>` to set up manually.'
290 + 'Create a project at https://platform.composio.dev, then run `composio init` again.'
291 );
292 yield* ui.outro('');
293 return yield* Effect.fail(e);
ts/packages/cli/src/commands/login.cmd.ts
+107 -104
@@ -9,25 +9,17 @@ import {
9 } from 'src/services/composio-clients';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { TerminalUI } from 'src/services/terminal-ui';
12 +import { runOrgProjectSelection } from 'src/effects/select-org-project';
13
14 export const noBrowser = Options.boolean('no-browser').pipe(
15 Options.withDefault(false),
16 Options.withDescription('Login without browser interaction')
17 );
18
18 -const apiKeyOpt = Options.text('api-key').pipe(
19 - Options.optional,
20 - Options.withDescription('API key for non-interactive login (agents/CI)')
21 -);
22 -
23 -const orgIdOpt = Options.text('org-id').pipe(
24 - Options.optional,
25 - Options.withDescription('Organization ID for non-interactive login')
26 -);
27 -
28 -const projectIdOpt = Options.text('project-id').pipe(
29 - Options.optional,
30 - Options.withDescription('Project ID for non-interactive login')
19 +const yesOpt = Options.boolean('yes').pipe(
20 + Options.withAlias('y'),
21 + Options.withDefault(false),
22 + Options.withDescription('Skip org/project picker; use session defaults')
23 );
24
25 /**
@@ -43,12 +35,10 @@ const storeCredentials = (params: {
35 initialOrgId: string;
36 initialProjectId: string;
37 fallbackEmail: string;
46 - /**
47 - * When true, 400/401/403 from session/info will fail the login.
48 - * Used for non-interactive login where the user provides explicit IDs.
49 - * When false, all session/info errors are non-fatal (browser login).
50 - */
51 - strictVerification: boolean;
38 + /** When true, skip the init/switch hints and outro (shown later after org/project picker). */
39 + skipHints?: boolean;
40 + /** When true, skip JSON output (emitted later after org/project picker with final selection). */
41 + skipOutput?: boolean;
42 }) =>
43 Effect.gen(function* () {
44 const ui = yield* TerminalUI;
@@ -60,13 +50,12 @@ const storeCredentials = (params: {
50 initialOrgId,
51 initialProjectId,
52 fallbackEmail,
63 - strictVerification,
53 + skipHints = false,
54 + skipOutput = false,
55 } = params;
56
57 // Call session/info to enrich the login with org/project metadata.
67 - // In strict mode (non-interactive login), 400/401/403 are hard failures.
68 - // In non-strict mode (browser login), all errors are non-fatal since
69 - // the linked session is already authenticated.
58 + // All errors are non-fatal (browser login) since the linked session is already authenticated.
59 const sessionInfo: SessionInfoResponse | undefined = yield* getSessionInfo({
60 baseURL,
61 apiKey: uakApiKey,
@@ -75,9 +64,6 @@ const storeCredentials = (params: {
64 }).pipe(
65 Effect.catchTag('services/HttpServerError', e =>
66 Effect.gen(function* () {
78 - if (strictVerification && e.status && e.status >= 400 && e.status < 500) {
79 - return yield* Effect.fail(e);
80 - }
67 yield* Effect.logDebug(`Session info fetch failed (HTTP ${e.status ?? '?'}):`, e);
68 return undefined;
69 })
@@ -116,23 +102,31 @@ const storeCredentials = (params: {
102
103 const email = sessionInfo?.org_member.email || fallbackEmail || undefined;
104 yield* ui.log.success(email ? `Logged in as ${email}` : 'Logged in successfully');
119 - yield* ui.log.info('Run `composio init` in your project directory to set up project context.');
120 - yield* ui.log.info(
121 - 'To switch your default global org/project later, run `composio orgs switch`.'
122 - );
105 + if (!skipHints) {
106 + yield* ui.log.info(
107 + 'Run `composio init` in your project directory to set up project context.'
108 + );
109 + yield* ui.log.info(
110 + 'To switch your default global org/project later, run `composio orgs switch`.'
111 + );
112 + }
113
114 // Emit structured JSON for piped/scripted consumption (agent-native)
125 - yield* ui.output(
126 - JSON.stringify({
127 - email,
128 - org_id: orgId,
129 - project_id: projectId,
130 - org_name: sessionInfo?.project.org.name ?? '',
131 - project_name: sessionInfo?.project.name ?? '',
132 - })
133 - );
115 + if (!skipOutput) {
116 + yield* ui.output(
117 + JSON.stringify({
118 + email,
119 + org_id: orgId,
120 + project_id: projectId,
121 + org_name: sessionInfo?.project.org.name ?? '',
122 + project_name: sessionInfo?.project.name ?? '',
123 + })
124 + );
125 + }
126
135 - yield* ui.outro("You're all set!");
127 + if (!skipHints) {
128 + yield* ui.outro("You're all set!");
129 + }
130 });
131
132 /**
@@ -149,6 +143,8 @@ export const browserLogin = (params: {
143 scope: 'user' | 'project';
144 /** When true, don't open browser — just show the URL. */
145 noBrowser: boolean;
146 + /** When true (login only), skip org/project picker and use session defaults. When false, prompt for org/project. */
147 + skipOrgProjectPicker?: boolean;
148 }) =>
149 Effect.gen(function* () {
150 const ui = yield* TerminalUI;
@@ -224,93 +220,100 @@ export const browserLogin = (params: {
220
221 yield* Effect.logDebug('UAK session info:', { xProjectId, xOrgId });
222
223 + const willRunPicker = params.scope === 'user' && !params.skipOrgProjectPicker;
224 yield* storeCredentials({
225 baseURL: ctx.data.baseURL,
226 uakApiKey,
227 initialOrgId: xOrgId,
228 initialProjectId: xProjectId,
229 fallbackEmail: linkedSession.account.email,
233 - strictVerification: false,
230 + skipHints: willRunPicker,
231 + skipOutput: willRunPicker,
232 });
233 +
234 + if (willRunPicker) {
235 + const result = yield* runOrgProjectSelection({
236 + apiKey: uakApiKey,
237 + baseURL: ctx.data.baseURL,
238 + }).pipe(
239 + Effect.catchAll(error =>
240 + Effect.gen(function* () {
241 + yield* Effect.logDebug('Org/project picker failed:', error);
242 + yield* ui.log.warn('Could not load org/project list. Using session defaults.');
243 + return undefined;
244 + })
245 + )
246 + );
247 + if (result) {
248 + const sessionUserId = uakSessionInfo.org_member.user_id ?? uakSessionInfo.org_member.id;
249 + const testUserId = sessionUserId ? `pg-test-${sessionUserId}` : undefined;
250 + yield* ctx.login(
251 + uakApiKey,
252 + result.org.id,
253 + result.project.id,
254 + testUserId ?? Option.getOrUndefined(ctx.data.testUserId)
255 + );
256 + yield* ui.log.success(
257 + `Default org/project set to "${result.org.name}" / "${result.project.name}".`
258 + );
259 + }
260 + // Emit JSON with final org/project (from picker or session) for piped/scripted consumption
261 + const finalOrgId = result?.org.id ?? xOrgId;
262 + const finalProjectId = result?.project.id ?? xProjectId;
263 + const finalOrgName = result?.org.name ?? uakSessionInfo.project.org.name ?? '';
264 + const finalProjectName = result?.project.name ?? uakSessionInfo.project.name ?? '';
265 + yield* ui.output(
266 + JSON.stringify({
267 + email: linkedSession.account.email ?? undefined,
268 + org_id: finalOrgId,
269 + project_id: finalProjectId,
270 + org_name: finalOrgName,
271 + project_name: finalProjectName,
272 + })
273 + );
274 + yield* ui.log.info(
275 + 'Run `composio init` in your project directory to set up project context.'
276 + );
277 + yield* ui.log.info(
278 + 'To switch your default global org/project later, run `composio orgs switch`.'
279 + );
280 + yield* ui.outro("You're all set!");
281 + }
282 });
283
284 /**
285 * CLI command to login using Composio's CLI session APIs.
286 *
240 - * Supports two modes:
241 - * 1. Browser-based: Opens browser for OAuth flow (default)
242 - * 2. Non-interactive: Accepts --api-key, --org-id, --project-id flags for agents/CI
287 + * Browser-based: Opens browser for OAuth flow (default).
288 + * Use --no-browser to skip auto-opening the browser and print the URL instead.
289 + * Use -y to skip org/project picker and use session defaults.
290 *
291 * @example
292 * ```bash
293 * composio login
294 * composio login --no-browser
248 - * composio login --api-key uak_xxx --org-id org-id --project-id proj-id
295 + * composio login -y
296 * ```
297 */
251 -export const loginCmd = Command.make(
252 - 'login',
253 - { noBrowser, apiKey: apiKeyOpt, orgId: orgIdOpt, projectId: projectIdOpt },
254 - ({ noBrowser, apiKey, orgId, projectId }) =>
255 - Effect.gen(function* () {
256 - const ui = yield* TerminalUI;
257 - const ctx = yield* ComposioUserContext;
258 -
259 - yield* ui.intro('composio login');
298 +export const loginCmd = Command.make('login', { noBrowser, yes: yesOpt }, ({ noBrowser, yes }) =>
299 + Effect.gen(function* () {
300 + const ui = yield* TerminalUI;
301 + const ctx = yield* ComposioUserContext;
302
261 - // Non-interactive path: --api-key, --org-id, --project-id flags skip browser flow.
262 - // All three must be provided together; partial flags are an error.
263 - const nonInteractiveFlags = [apiKey, orgId, projectId];
264 - const anyProvided = nonInteractiveFlags.some(Option.isSome);
265 - const allProvided = nonInteractiveFlags.every(Option.isSome);
303 + yield* ui.intro('composio login');
304
267 - if (anyProvided && !allProvided) {
268 - const missing = [
269 - Option.isNone(apiKey) && '--api-key',
270 - Option.isNone(orgId) && '--org-id',
271 - Option.isNone(projectId) && '--project-id',
272 - ].filter(Boolean);
273 - yield* ui.log.error(`Missing required flag(s): ${missing.join(', ')}`);
274 - yield* ui.log.info(
275 - 'Non-interactive login requires all three: --api-key, --org-id, --project-id'
305 + if (ctx.isLoggedIn()) {
306 + // Allow re-login when orgId/projectId are not yet set (old CLI login without multi-project support)
307 + if (Option.isSome(ctx.data.orgId) && Option.isSome(ctx.data.projectId)) {
308 + yield* ui.log.warn(`You're already logged in!`);
309 + yield* ui.outro(
310 + 'If you want to log in with a different account, please run `composio logout` first.'
311 );
277 - yield* ui.outro('');
278 - return;
279 - }
280 -
281 - // Strict verification: 400/401/403 from session/info are hard failures since
282 - // the user explicitly provided the IDs.
283 - if (
284 - allProvided &&
285 - Option.isSome(apiKey) &&
286 - Option.isSome(orgId) &&
287 - Option.isSome(projectId)
288 - ) {
289 - yield* Effect.logDebug('Non-interactive login with provided credentials');
290 - yield* storeCredentials({
291 - baseURL: ctx.data.baseURL,
292 - uakApiKey: apiKey.value,
293 - initialOrgId: orgId.value,
294 - initialProjectId: projectId.value,
295 - fallbackEmail: '',
296 - strictVerification: true,
297 - });
312 return;
313 }
314 + yield* ui.log.step('Re-authenticating for multi-project support...');
315 + }
316
301 - if (ctx.isLoggedIn()) {
302 - // Allow re-login when orgId/projectId are not yet set (old CLI login without multi-project support)
303 - if (Option.isSome(ctx.data.orgId) && Option.isSome(ctx.data.projectId)) {
304 - yield* ui.log.warn(`You're already logged in!`);
305 - yield* ui.log.info(
306 - `If you want to log in with a different account, please run \`composio logout\` first.`
307 - );
308 - yield* ui.outro('');
309 - return;
310 - }
311 - yield* ui.log.step('Re-authenticating for multi-project support...');
312 - }
313 -
314 - yield* browserLogin({ scope: 'user', noBrowser });
315 - })
317 + yield* browserLogin({ scope: 'user', noBrowser, skipOrgProjectPicker: yes });
318 + })
319 ).pipe(Command.withDescription('Log in to the Composio SDK.'));
ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts
+9 -114
@@ -1,15 +1,9 @@
1 import { Command, Options } from '@effect/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 +import { runOrgProjectSelection } from 'src/effects/select-org-project';
5 import { TerminalUI } from 'src/services/terminal-ui';
5 -import {
6 - listOrganizationProjects,
7 - listOrganizations,
8 - type OrganizationSummary,
9 - type OrganizationProjectSummary,
10 -} from 'src/services/composio-clients';
6 import { ComposioUserContext } from 'src/services/user-context';
12 -import { clampLimit } from 'src/ui/clamp-limit';
7
8 const orgId = Options.text('org-id').pipe(
9 Options.optional,
@@ -26,56 +20,6 @@ const limit = Options.integer('limit').pipe(
20 Options.withDescription('Max org/projects to fetch from API (default: 50)')
21 );
22
29 -const selectOrganization = (params: {
30 - organizations: ReadonlyArray<OrganizationSummary>;
31 - selectedOrgId?: string;
32 -}) =>
33 - Effect.gen(function* () {
34 - const { organizations, selectedOrgId } = params;
35 - const ui = yield* TerminalUI;
36 - if (organizations.length === 0) return undefined;
37 -
38 - if (selectedOrgId) {
39 - const explicitMatch = organizations.find(org => org.id === selectedOrgId);
40 - if (explicitMatch) return explicitMatch;
41 - }
42 -
43 - if (organizations.length === 1) return organizations[0];
44 -
45 - return yield* ui.select('Select a default organization (global scope):', [
46 - ...organizations.map(org => ({
47 - value: org,
48 - label: org.name,
49 - hint: org.id,
50 - })),
51 - ]);
52 - });
53 -
54 -const selectProject = (params: {
55 - projects: ReadonlyArray<OrganizationProjectSummary>;
56 - selectedProjectId?: string;
57 -}) =>
58 - Effect.gen(function* () {
59 - const { projects, selectedProjectId } = params;
60 - const ui = yield* TerminalUI;
61 - if (projects.length === 0) return undefined;
62 -
63 - if (selectedProjectId) {
64 - const explicitMatch = projects.find(project => project.id === selectedProjectId);
65 - if (explicitMatch) return explicitMatch;
66 - }
67 -
68 - if (projects.length === 1) return projects[0];
69 -
70 - return yield* ui.select('Select a default project (global scope):', [
71 - ...projects.map(project => ({
72 - value: project,
73 - label: project.name,
74 - hint: project.id,
75 - })),
76 - ]);
77 - });
78 -
23 export const orgsCmd$Switch = Command.make(
24 'switch',
25 { orgId, projectId, limit },
@@ -94,74 +38,25 @@ export const orgsCmd$Switch = Command.make(
38 return;
39 }
40
97 - const clampedLimit = clampLimit(limit);
98 - const explicitOrgId = Option.getOrUndefined(orgId);
99 - const explicitProjectId = Option.getOrUndefined(projectId);
100 -
41 yield* ui.note(
42 'This updates your default global org/project context for CLI commands. Use `composio init` for per-project local overrides.',
43 'Global defaults'
44 );
45
106 - const selectedOrganization =
107 - explicitOrgId !== undefined
108 - ? ({ id: explicitOrgId, name: explicitOrgId } satisfies OrganizationSummary)
109 - : yield* Effect.gen(function* () {
110 - const organizations = yield* listOrganizations({
111 - baseURL: ctx.data.baseURL,
112 - apiKey,
113 - limit: clampedLimit,
114 - });
115 - yield* ui.log.info(`Loaded ${organizations.data.length} orgs`);
116 - return organizations;
117 - }).pipe(
118 - Effect.flatMap(organizations =>
119 - Effect.gen(function* () {
120 - if (organizations.data.length === 0) {
121 - return undefined;
122 - }
123 - return yield* selectOrganization({
124 - organizations: organizations.data,
125 - selectedOrgId: explicitOrgId,
126 - });
127 - })
128 - )
129 - );
130 -
131 - if (!selectedOrganization) {
132 - yield* ui.log.warn('No organizations found for this API key.');
133 - yield* ui.outro('No org selected.');
134 - return;
135 - }
136 - yield* ui.log.info(
137 - `Selected organization: "${selectedOrganization.name}" (${selectedOrganization.id})`
138 - );
139 -
140 - const projects = yield* listOrganizationProjects({
141 - baseURL: ctx.data.baseURL,
46 + const result = yield* runOrgProjectSelection({
47 apiKey,
143 - orgId: selectedOrganization.id,
144 - limit: clampedLimit,
48 + baseURL: ctx.data.baseURL,
49 + explicitOrgId: Option.getOrUndefined(orgId),
50 + explicitProjectId: Option.getOrUndefined(projectId),
51 + limit,
52 });
146 - yield* ui.log.info(`Loaded ${projects.data.length} projects`);
53
148 - if (projects.data.length === 0) {
149 - yield* ui.log.warn(`No projects found for org "${selectedOrganization.name}".`);
150 - yield* ui.outro('No projects available.');
54 + if (!result) {
55 + yield* ui.outro('No org selected.');
56 return;
57 }
58
154 - const selectedProject = yield* selectProject({
155 - projects: projects.data,
156 - selectedProjectId: explicitProjectId,
157 - });
158 -
159 - if (!selectedProject) {
160 - yield* ui.log.warn('No project selected.');
161 - yield* ui.outro('No project selected.');
162 - return;
163 - }
164 - yield* ui.log.info(`Selected project: "${selectedProject.name}" (${selectedProject.id})`);
59 + const { org: selectedOrganization, project: selectedProject } = result;
60
61 yield* ctx.login(
62 apiKey,
ts/packages/cli/src/commands/root-help.ts
+3 -7
@@ -27,12 +27,10 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [
27 {
28 name: 'login',
29 description: 'Log in to the Composio CLI session.',
30 - usage: 'login [--no-browser] [--api-key text] [--org-id text] [--project-id text]',
30 + usage: 'login [--no-browser] [-y, --yes]',
31 options: [
32 { name: '--no-browser', description: 'Login without browser interaction' },
33 - { name: '--api-key', description: 'API key for non-interactive login (agents/CI)' },
34 - { name: '--org-id', description: 'Organization ID for non-interactive login' },
35 - { name: '--project-id', description: 'Project ID for non-interactive login' },
33 + { name: '-y, --yes', description: 'Skip org/project picker; use session defaults' },
34 ],
35 },
36 {
@@ -43,10 +41,8 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [
41 {
42 name: 'init',
43 description: 'Initialize a Composio project in the current directory.',
46 - usage: 'init [--org-id text] [--project-id text] [--no-browser] [-y, --yes]',
44 + usage: 'init [--no-browser] [-y, --yes]',
45 options: [
48 - { name: '--org-id', description: 'Organization ID (skip interactive picker)' },
49 - { name: '--project-id', description: 'Project ID (skip interactive picker)' },
46 { name: '--no-browser', description: 'Skip opening browser for auth' },
47 { name: '-y, --yes', description: 'Auto-select default org/project' },
48 ],
ts/packages/cli/src/effects/select-org-project.ts new
+113
@@ -0,0 +1,113 @@
1 +import { Effect } from 'effect';
2 +import { TerminalUI } from 'src/services/terminal-ui';
3 +import {
4 + listOrganizationProjects,
5 + listOrganizations,
6 + type OrganizationProjectSummary,
7 + type OrganizationSummary,
8 +} from 'src/services/composio-clients';
9 +import { clampLimit } from 'src/ui/clamp-limit';
10 +
11 +const DEFAULT_LIMIT = 50;
12 +
13 +/** Prompts user to select an org, or auto-selects if only one. */
14 +const selectOrganization = (organizations: ReadonlyArray<OrganizationSummary>) =>
15 + Effect.gen(function* () {
16 + const ui = yield* TerminalUI;
17 + if (organizations.length === 0) return undefined;
18 + if (organizations.length === 1) return organizations[0];
19 + return yield* ui.select('Select a default organization (global scope):', [
20 + ...organizations.map(org => ({ value: org, label: org.name, hint: org.id })),
21 + ]);
22 + });
23 +
24 +/**
25 + * Prompts user to select a project, or auto-selects if only one.
26 + * When explicitProjectId is provided (e.g. from `orgs switch --project-id`), finds and returns it without prompting.
27 + */
28 +const selectProject = (
29 + projects: ReadonlyArray<OrganizationProjectSummary>,
30 + explicitProjectId?: string
31 +) =>
32 + Effect.gen(function* () {
33 + const ui = yield* TerminalUI;
34 + if (projects.length === 0) return undefined;
35 + if (explicitProjectId) {
36 + const match = projects.find(p => p.id === explicitProjectId);
37 + if (match) return match;
38 + }
39 + if (projects.length === 1) return projects[0];
40 + return yield* ui.select('Select a default project (global scope):', [
41 + ...projects.map(project => ({ value: project, label: project.name, hint: project.id })),
42 + ]);
43 + });
44 +
45 +/**
46 + * Runs the org/project selection flow: lists orgs, prompts for org (or auto-selects if 1),
47 + * lists projects, prompts for project (or auto-selects if 1).
48 + *
49 + * Reused by `composio orgs switch` and `composio login -y`.
50 + *
51 + * @param params.apiKey - User API key for API calls
52 + * @param params.baseURL - API base URL
53 + * @param params.explicitOrgId - If provided, skip org picker and use this org
54 + * @param params.explicitProjectId - If provided (and org selected), skip project picker
55 + * @param params.limit - Max orgs/projects to fetch (default 50)
56 + */
57 +export const runOrgProjectSelection = (params: {
58 + apiKey: string;
59 + baseURL: string;
60 + explicitOrgId?: string;
61 + explicitProjectId?: string;
62 + limit?: number;
63 +}) =>
64 + Effect.gen(function* () {
65 + const ui = yield* TerminalUI;
66 + const { apiKey, baseURL, explicitOrgId, explicitProjectId, limit = DEFAULT_LIMIT } = params;
67 + const clampedLimit = clampLimit(limit);
68 +
69 + const selectedOrganization =
70 + explicitOrgId !== undefined
71 + ? ({ id: explicitOrgId, name: explicitOrgId } satisfies OrganizationSummary)
72 + : yield* Effect.gen(function* () {
73 + const organizations = yield* listOrganizations({
74 + baseURL,
75 + apiKey,
76 + limit: clampedLimit,
77 + });
78 + yield* ui.log.info(`Loaded ${organizations.data.length} orgs`);
79 + if (organizations.data.length === 0) return undefined;
80 + return yield* selectOrganization(organizations.data);
81 + });
82 +
83 + if (!selectedOrganization) {
84 + yield* ui.log.warn('No organizations found for this API key.');
85 + return undefined;
86 + }
87 + yield* ui.log.info(
88 + `Selected organization: "${selectedOrganization.name}" (${selectedOrganization.id})`
89 + );
90 +
91 + const projects = yield* listOrganizationProjects({
92 + baseURL,
93 + apiKey,
94 + orgId: selectedOrganization.id,
95 + limit: clampedLimit,
96 + });
97 + yield* ui.log.info(`Loaded ${projects.data.length} projects`);
98 +
99 + if (projects.data.length === 0) {
100 + yield* ui.log.warn(`No projects found for org "${selectedOrganization.name}".`);
101 + return undefined;
102 + }
103 +
104 + const selectedProject = yield* selectProject(projects.data, explicitProjectId);
105 +
106 + if (!selectedProject) {
107 + yield* ui.log.warn('No project selected.');
108 + return undefined;
109 + }
110 + yield* ui.log.info(`Selected project: "${selectedProject.name}" (${selectedProject.id})`);
111 +
112 + return { org: selectedOrganization, project: selectedProject } as const;
113 + });
ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap
+3 -7
@@ -22,12 +22,10 @@ BASIC COMMANDS
22
23 login
24 Log in to the Composio CLI session.
25 - Usage: composio login [--no-browser] [--api-key text] [--org-id text] [--project-id text]
25 + Usage: composio login [--no-browser] [-y, --yes]
26 Options:
27 --no-browser Login without browser interaction
28 - --api-key API key for non-interactive login (agents/CI)
29 - --org-id Organization ID for non-interactive login
30 - --project-id Project ID for non-interactive login
28 + -y, --yes Skip org/project picker; use session defaults
29
30 logout
31 Log out from the Composio CLI session.
@@ -35,10 +33,8 @@ BASIC COMMANDS
33
34 init
35 Initialize a Composio project in the current directory.
38 - Usage: composio init [--org-id text] [--project-id text] [--no-browser] [-y, --yes]
36 + Usage: composio init [--no-browser] [-y, --yes]
37 Options:
40 - --org-id Organization ID (skip interactive picker)
41 - --project-id Project ID (skip interactive picker)
38 --no-browser Skip opening browser for auth
39 -y, --yes Auto-select default org/project
40
ts/packages/cli/test/src/commands/init.cmd.test.ts
+7 -38
@@ -1,50 +1,19 @@
1 -import path from 'node:path';
1 import { describe, expect, layer } from '@effect/vitest';
2 import { Effect } from 'effect';
4 -import { FileSystem } from '@effect/platform';
5 -import { NodeProcess } from 'src/services/node-process';
3 import { cli, TestLive, MockConsole } from 'test/__utils__';
4
5 describe('CLI: composio init', () => {
9 - describe('[Given] --org-id + --project-id flags', () => {
6 + describe('init --help', () => {
7 layer(TestLive({ fixture: 'typescript-project' }))(it => {
11 - it.scoped('[Then] it initializes project config and prints machine output', () =>
8 + it.scoped('[Then] shows --no-browser and --yes, no --org-id or --project-id', () =>
9 Effect.gen(function* () {
13 - const fs = yield* FileSystem.FileSystem;
14 - const proc = yield* NodeProcess;
15 -
16 - yield* cli(['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes']);
17 -
18 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
19 - const output = lines.join('\n');
20 -
21 - expect(output).toContain('-- composio init --');
22 - expect(output).toContain('Project initialized in');
23 - expect(output).toContain('"org_id":"org1"');
24 - expect(output).toContain('"project_id":"proj1"');
25 -
26 - const projectConfigPath = path.join(proc.cwd, '.composio', 'project.json');
27 - const exists = yield* fs.exists(projectConfigPath);
28 - expect(exists).toBe(true);
29 -
30 - const projectConfigRaw = yield* fs.readFileString(projectConfigPath, 'utf8');
31 - const projectConfig = JSON.parse(projectConfigRaw) as Record<string, unknown>;
32 - expect(projectConfig.org_id).toBe('org1');
33 - expect(projectConfig.project_id).toBe('proj1');
34 - })
35 - );
36 - });
37 - });
38 -
39 - describe('[Given] explicit project ids but no global credentials', () => {
40 - layer(TestLive({ fixture: 'typescript-project' }))(it => {
41 - it.scoped('[Then] it warns and skips .env.local creation', () =>
42 - Effect.gen(function* () {
43 - yield* cli(['init', '--org-id', 'org1', '--project-id', 'proj1']);
44 -
10 + yield* cli(['init', '--help']);
11 const lines = yield* MockConsole.getLines({ stripAnsi: true });
12 const output = lines.join('\n');
47 - expect(output).toContain('No global API key found; skipping .env.local creation.');
13 + expect(output).toContain('--no-browser');
14 + expect(output).toContain('--yes');
15 + expect(output).not.toContain('--org-id');
16 + expect(output).not.toContain('--project-id');
17 })
18 );
19 });
ts/packages/cli/test/src/commands/login.cmd.test.ts
+14 -240
@@ -1,64 +1,7 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { vi, afterEach } from 'vitest';
3 import { Effect } from 'effect';
4 -import { ComposioUserContext } from 'src/services/user-context';
5 -import { cli, TestLive, MockConsole } from 'test/__utils__';
6 -
7 -// ── Helpers ──────────────────────────────────────────────────────────────────
8 -
9 -/**
10 - * Build a canned SessionInfoResponse JSON body for mocking `getSessionInfo`
11 - * and `getSessionInfoByUserApiKey`.
12 - */
13 -const makeSessionInfoBody = (overrides?: {
14 - orgId?: string;
15 - orgNanoId?: string;
16 - orgMemberId?: string;
17 - orgName?: string;
18 - projectId?: string;
19 - projectNanoId?: string;
20 - projectName?: string;
21 - email?: string;
22 - memberName?: string;
23 -}) => ({
24 - project: {
25 - name: overrides?.projectName ?? 'test-project',
26 - id: overrides?.projectId ?? 'proj_test_123',
27 - org_id: overrides?.orgId ?? 'org_test_456',
28 - nano_id: overrides?.projectNanoId ?? 'pr_nano_789',
29 - email: overrides?.email ?? 'test@composio.dev',
30 - created_at: '2026-01-01T00:00:00.000Z',
31 - updated_at: '2026-01-01T00:00:00.000Z',
32 - org: {
33 - name: overrides?.orgName ?? 'Test Org',
34 - id: overrides?.orgNanoId ?? 'org_nano_456',
35 - plan: 'free',
36 - },
37 - },
38 - org_member: {
39 - id: overrides?.orgMemberId ?? 'org_member_uuid_456',
40 - email: overrides?.email ?? 'test@composio.dev',
41 - name: overrides?.memberName ?? 'Test User',
42 - role: 'admin',
43 - },
44 - api_key: {
45 - name: 'default',
46 - project_id: overrides?.projectId ?? 'proj_test_123',
47 - id: 'ak_test',
48 - org_member_id: overrides?.orgId ?? 'org_test_456',
49 - },
50 -});
51 -
52 -/**
53 - * Creates a mock Response object.
54 - */
55 -function mockFetchResponse(body: unknown, status = 200): Response {
56 - const bodyStr = JSON.stringify(body);
57 - return new Response(bodyStr, {
58 - status,
59 - headers: { 'Content-Type': 'application/json' },
60 - });
61 -}
4 +import { cli, MockConsole, TestLive } from 'test/__utils__';
5
6 // ── Tests ────────────────────────────────────────────────────────────────────
7
@@ -67,188 +10,19 @@ describe('CLI: composio login', () => {
10 vi.restoreAllMocks();
11 });
12
70 - describe('[When] not logged in', () => {
71 - describe('non-interactive login: session/info succeeds', () => {
72 - layer(TestLive())(it => {
73 - it.scoped('[Then] stores credentials with enriched org/project IDs', () =>
74 - Effect.gen(function* () {
75 - const ctx = yield* ComposioUserContext;
76 - expect(ctx.isLoggedIn()).toBe(false);
77 -
78 - // Mock fetch for getSessionInfo call
79 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
80 - mockFetchResponse(
81 - makeSessionInfoBody({
82 - orgId: 'org_verified_uuid',
83 - orgNanoId: 'org_verified_nano',
84 - orgMemberId: 'org_member_verified_uuid',
85 - projectId: 'proj_verified_uuid',
86 - projectNanoId: 'proj_verified_nano',
87 - email: 'verified@composio.dev',
88 - projectName: 'Verified Project',
89 - orgName: 'Verified Org',
90 - })
91 - )
92 - );
93 -
94 - yield* cli([
95 - 'login',
96 - '--api-key',
97 - 'uak_test_key',
98 - '--org-id',
99 - 'org_initial',
100 - '--project-id',
101 - 'proj_initial',
102 - ]);
103 -
104 - // Verify fetch was called with session/info endpoint and correct headers
105 - expect(fetchSpy).toHaveBeenCalledOnce();
106 - const [url, init] = fetchSpy.mock.calls[0]!;
107 - expect(url).toContain('/api/v3/auth/session/info');
108 - expect((init as RequestInit).headers).toMatchObject({
109 - 'x-user-api-key': 'uak_test_key',
110 - 'x-org-id': 'org_initial',
111 - 'x-project-id': 'proj_initial',
112 - });
113 -
114 - // The mutable isLoggedIn closure reflects the login
115 - expect(ctx.isLoggedIn()).toBe(true);
116 -
117 - // Verify console output contains the enriched email and success message
118 - const lines = yield* MockConsole.getLines();
119 - const output = lines.join('\n');
120 - expect(output).toContain('verified@composio.dev');
121 - expect(output).toContain('"org_id":"org_verified_nano"');
122 - expect(output).toContain('"project_id":"proj_verified_nano"');
123 - expect(output).toContain("You're all set!");
124 - })
125 - );
126 - });
127 - });
128 -
129 - describe('non-interactive login: session/info returns 500', () => {
130 - layer(TestLive())(it => {
131 - it.scoped('[Then] falls back to initial IDs on server error', () =>
132 - Effect.gen(function* () {
133 - const ctx = yield* ComposioUserContext;
134 - expect(ctx.isLoggedIn()).toBe(false);
135 -
136 - // Mock fetch to return a 500 error.
137 - // In strict mode, only 400-499 are hard failures.
138 - // 500 falls through the generic catch → undefined sessionInfo → use initial IDs.
139 - vi.spyOn(globalThis, 'fetch').mockResolvedValue(
140 - mockFetchResponse(
141 - {
142 - status: 500,
143 - error: {
144 - error: {
145 - message: 'Internal server error',
146 - suggested_fix: 'Try again later',
147 - code: 500,
148 - },
149 - },
150 - },
151 - 500
152 - )
153 - );
154 -
155 - yield* cli([
156 - 'login',
157 - '--api-key',
158 - 'uak_fallback_key',
159 - '--org-id',
160 - 'org_fallback',
161 - '--project-id',
162 - 'proj_fallback',
163 - ]);
164 -
165 - // Credentials stored with initial (uncorrected) IDs since session/info failed
166 - expect(ctx.isLoggedIn()).toBe(true);
167 -
168 - const lines = yield* MockConsole.getLines();
169 - const output = lines.join('\n');
170 - expect(output).toContain('Logged in');
171 - })
172 - );
173 - });
174 - });
175 -
176 - describe('non-interactive login: session/info returns 401', () => {
177 - layer(TestLive())(it => {
178 - it.scoped('[Then] rejects invalid API key', () =>
179 - Effect.gen(function* () {
180 - const ctx = yield* ComposioUserContext;
181 - expect(ctx.isLoggedIn()).toBe(false);
182 -
183 - // Mock fetch to return 401
184 - vi.spyOn(globalThis, 'fetch').mockResolvedValue(
185 - mockFetchResponse(
186 - {
187 - status: 401,
188 - error: {
189 - error: {
190 - message: 'Invalid API key',
191 - suggested_fix: 'Check your API key',
192 - code: 401,
193 - },
194 - },
195 - },
196 - 401
197 - )
198 - );
199 -
200 - // Non-interactive login: strict verification fails on 401
201 - const result = yield* cli([
202 - 'login',
203 - '--api-key',
204 - 'uak_bad_key',
205 - '--org-id',
206 - 'org_test',
207 - '--project-id',
208 - 'proj_test',
209 - ]).pipe(Effect.either);
210 -
211 - // The command should fail
212 - expect(result._tag).toBe('Left');
213 -
214 - // Should NOT be logged in after a failed verification
215 - expect(ctx.isLoggedIn()).toBe(false);
216 - })
217 - );
218 - });
219 - });
220 -
221 - describe('non-interactive login: session/info network failure', () => {
222 - layer(TestLive())(it => {
223 - it.scoped('[Then] falls back to initial IDs on network error', () =>
224 - Effect.gen(function* () {
225 - const ctx = yield* ComposioUserContext;
226 - expect(ctx.isLoggedIn()).toBe(false);
227 -
228 - // Mock fetch to throw a network error
229 - vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('fetch failed'));
230 -
231 - yield* cli([
232 - 'login',
233 - '--api-key',
234 - 'uak_network_key',
235 - '--org-id',
236 - 'org_net',
237 - '--project-id',
238 - 'proj_net',
239 - ]);
240 -
241 - // Network errors are non-fatal even in strict mode (only 400-499 are strict)
242 - // Actually: the fetch itself fails → HttpServerError with no status →
243 - // strict check (e.status >= 400 && < 500) doesn't match → falls through → undefined
244 - expect(ctx.isLoggedIn()).toBe(true);
245 -
246 - const lines = yield* MockConsole.getLines();
247 - const output = lines.join('\n');
248 - expect(output).toContain('Logged in');
249 - })
250 - );
251 - });
13 + describe('login --help', () => {
14 + layer(TestLive())(it => {
15 + it.scoped('[Then] shows --no-browser and -y/--yes (skip picker), no --api-key', () =>
16 + Effect.gen(function* () {
17 + yield* cli(['login', '--help']);
18 + const lines = yield* MockConsole.getLines();
19 + const output = lines.join('\n');
20 + expect(output).toContain('--no-browser');
21 + expect(output).toContain('--yes');
22 + expect(output).toContain('-y');
23 + expect(output).not.toContain('--api-key');
24 + })
25 + );
26 });
27 });
28 });