Skip to content

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

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

Musthaq Ahamadeed4ce5a48aa
diff --git a/ts/packages/cli/src/commands/init.cmd.ts b/ts/packages/cli/src/commands/init.cmd.ts
index be109a642..266e5b690 100644
--- a/ts/packages/cli/src/commands/init.cmd.ts
+++ b/ts/packages/cli/src/commands/init.cmd.ts
@@ -22,7 +22,7 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
*
* ## Behavior
*
- * 1. **Project selection** — fetches projects from the API or accepts `--org-id`/`--project-id`.
+ * 1. **Project selection** — fetches projects from the API and prompts for selection.
* 2. **Writes config** — saves `<cwd>/.composio/project.json`.
*
* ## Flags
@@ -30,16 +30,6 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
* - `--yes` / `-y` — auto-select the first project from the list
*/
-const orgIdOpt = Options.text('org-id').pipe(
- Options.optional,
- Options.withDescription('Organization ID (skip interactive picker)')
-);
-
-const projectIdOpt = Options.text('project-id').pipe(
- Options.optional,
- Options.withDescription('Project ID (skip interactive picker)')
-);
-
const yesOpt = Options.boolean('yes').pipe(
Options.withAlias('y'),
Options.withDefault(false),
@@ -221,26 +211,21 @@ const selectDefaultProject = (params: {
* CLI command to initialize a Composio project in the current directory.
*
* Creates `<cwd>/.composio/project.json` with org_id and project_id.
- *
- * Supports two modes:
- * 1. Interactive: Fetches projects from the API and prompts for selection
- * 2. Non-interactive: Accepts --org-id and --project-id flags for agents/CI
+ * Fetches projects from the API and prompts for selection.
*
* @example
* ```bash
* composio init
- * composio init --org-id <org> --project-id <project>
+ * composio init --yes
* ```
*/
export const initCmd = CliCommand.make(
'init',
{
- orgId: orgIdOpt,
- projectId: projectIdOpt,
noBrowser: noBrowserOpt,
yes: yesOpt,
},
- ({ orgId, projectId, noBrowser, yes }) =>
+ ({ noBrowser, yes }) =>
Effect.gen(function* () {
const ui = yield* TerminalUI;
const proc = yield* NodeProcess;
@@ -249,42 +234,6 @@ export const initCmd = CliCommand.make(
const composioDir = path.join(proc.cwd, constants.PROJECT_COMPOSIO_DIR);
- // Agent-native path: --org-id and --project-id flags skip project picker
- if (Option.isSome(orgId) && Option.isSome(projectId)) {
- const selected: ProjectKeys = {
- orgId: orgId.value,
- projectId: projectId.value,
- projectName: Option.none(),
- orgName: Option.none(),
- email: Option.none(),
- testUserId: Option.none(),
- };
-
- yield* writeProjectConfig(composioDir, selected);
- yield* ensureProjectApiKeyInEnv({ cwd: proc.cwd, selected }).pipe(
- Effect.catchTag('services/HttpServerError', e =>
- Effect.gen(function* () {
- yield* Effect.logDebug('Failed to resolve project API key from session/info:', e);
- yield* logEnvCreationHttpError(ui)(e);
- })
- ),
- Effect.catchTag('services/HttpDecodingError', e =>
- Effect.gen(function* () {
- yield* Effect.logDebug('Failed to decode API key response:', e);
- yield* logEnvCreationDecodingError(ui)(e);
- })
- )
- );
-
- yield* ui.log.success(`Project initialized in ${composioDir}/`);
- yield* ui.log.info(
- 'To switch your default global org/project later, run `composio orgs switch`.'
- );
- yield* ui.output(makeOutputJson(selected, composioDir));
- yield* ui.outro('');
- return;
- }
-
yield* initInteractiveFlow({ composioDir, noBrowser, yes });
})
).pipe(CliCommand.withDescription('Initialize a Composio project in the current directory.'));
@@ -327,7 +276,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
yield* Effect.logDebug('Failed to list org projects:', e);
yield* ui.log.warn('Could not fetch projects from the server.');
yield* ui.log.info(
- 'Use `composio init --org-id <org> --project-id <project>` to set up manually.'
+ 'Create a project at https://platform.composio.dev, then run `composio init` again.'
);
yield* ui.outro('');
return yield* Effect.fail(e);
@@ -338,7 +287,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
yield* Effect.logDebug('Failed to decode org projects response:', e);
yield* ui.log.warn('Unexpected response from the server.');
yield* ui.log.info(
- 'Use `composio init --org-id <org> --project-id <project>` to set up manually.'
+ 'Create a project at https://platform.composio.dev, then run `composio init` again.'
);
yield* ui.outro('');
return yield* Effect.fail(e);
diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.ts
index e19167149..9bcd4763f 100644
--- a/ts/packages/cli/src/commands/login.cmd.ts
+++ b/ts/packages/cli/src/commands/login.cmd.ts
@@ -9,25 +9,17 @@ import {
} from 'src/services/composio-clients';
import { ComposioUserContext } from 'src/services/user-context';
import { TerminalUI } from 'src/services/terminal-ui';
+import { runOrgProjectSelection } from 'src/effects/select-org-project';
export const noBrowser = Options.boolean('no-browser').pipe(
Options.withDefault(false),
Options.withDescription('Login without browser interaction')
);
-const apiKeyOpt = Options.text('api-key').pipe(
- Options.optional,
- Options.withDescription('API key for non-interactive login (agents/CI)')
-);
-
-const orgIdOpt = Options.text('org-id').pipe(
- Options.optional,
- Options.withDescription('Organization ID for non-interactive login')
-);
-
-const projectIdOpt = Options.text('project-id').pipe(
- Options.optional,
- Options.withDescription('Project ID for non-interactive login')
+const yesOpt = Options.boolean('yes').pipe(
+ Options.withAlias('y'),
+ Options.withDefault(false),
+ Options.withDescription('Skip org/project picker; use session defaults')
);
/**
@@ -43,12 +35,10 @@ const storeCredentials = (params: {
initialOrgId: string;
initialProjectId: string;
fallbackEmail: string;
- /**
- * When true, 400/401/403 from session/info will fail the login.
- * Used for non-interactive login where the user provides explicit IDs.
- * When false, all session/info errors are non-fatal (browser login).
- */
- strictVerification: boolean;
+ /** When true, skip the init/switch hints and outro (shown later after org/project picker). */
+ skipHints?: boolean;
+ /** When true, skip JSON output (emitted later after org/project picker with final selection). */
+ skipOutput?: boolean;
}) =>
Effect.gen(function* () {
const ui = yield* TerminalUI;
@@ -60,13 +50,12 @@ const storeCredentials = (params: {
initialOrgId,
initialProjectId,
fallbackEmail,
- strictVerification,
+ skipHints = false,
+ skipOutput = false,
} = params;
// Call session/info to enrich the login with org/project metadata.
- // In strict mode (non-interactive login), 400/401/403 are hard failures.
- // In non-strict mode (browser login), all errors are non-fatal since
- // the linked session is already authenticated.
+ // All errors are non-fatal (browser login) since the linked session is already authenticated.
const sessionInfo: SessionInfoResponse | undefined = yield* getSessionInfo({
baseURL,
apiKey: uakApiKey,
@@ -75,9 +64,6 @@ const storeCredentials = (params: {
}).pipe(
Effect.catchTag('services/HttpServerError', e =>
Effect.gen(function* () {
- if (strictVerification && e.status && e.status >= 400 && e.status < 500) {
- return yield* Effect.fail(e);
- }
yield* Effect.logDebug(`Session info fetch failed (HTTP ${e.status ?? '?'}):`, e);
return undefined;
})
@@ -116,23 +102,31 @@ const storeCredentials = (params: {
const email = sessionInfo?.org_member.email || fallbackEmail || undefined;
yield* ui.log.success(email ? `Logged in as ${email}` : 'Logged in successfully');
- yield* ui.log.info('Run `composio init` in your project directory to set up project context.');
- yield* ui.log.info(
- 'To switch your default global org/project later, run `composio orgs switch`.'
- );
+ if (!skipHints) {
+ yield* ui.log.info(
+ 'Run `composio init` in your project directory to set up project context.'
+ );
+ yield* ui.log.info(
+ 'To switch your default global org/project later, run `composio orgs switch`.'
+ );
+ }
// Emit structured JSON for piped/scripted consumption (agent-native)
- yield* ui.output(
- JSON.stringify({
- email,
- org_id: orgId,
- project_id: projectId,
- org_name: sessionInfo?.project.org.name ?? '',
- project_name: sessionInfo?.project.name ?? '',
- })
- );
+ if (!skipOutput) {
+ yield* ui.output(
+ JSON.stringify({
+ email,
+ org_id: orgId,
+ project_id: projectId,
+ org_name: sessionInfo?.project.org.name ?? '',
+ project_name: sessionInfo?.project.name ?? '',
+ })
+ );
+ }
- yield* ui.outro("You're all set!");
+ if (!skipHints) {
+ yield* ui.outro("You're all set!");
+ }
});
/**
@@ -149,6 +143,8 @@ export const browserLogin = (params: {
scope: 'user' | 'project';
/** When true, don't open browser — just show the URL. */
noBrowser: boolean;
+ /** When true (login only), skip org/project picker and use session defaults. When false, prompt for org/project. */
+ skipOrgProjectPicker?: boolean;
}) =>
Effect.gen(function* () {
const ui = yield* TerminalUI;
@@ -224,93 +220,100 @@ export const browserLogin = (params: {
yield* Effect.logDebug('UAK session info:', { xProjectId, xOrgId });
+ const willRunPicker = params.scope === 'user' && !params.skipOrgProjectPicker;
yield* storeCredentials({
baseURL: ctx.data.baseURL,
uakApiKey,
initialOrgId: xOrgId,
initialProjectId: xProjectId,
fallbackEmail: linkedSession.account.email,
- strictVerification: false,
+ skipHints: willRunPicker,
+ skipOutput: willRunPicker,
});
+
+ if (willRunPicker) {
+ const result = yield* runOrgProjectSelection({
+ apiKey: uakApiKey,
+ baseURL: ctx.data.baseURL,
+ }).pipe(
+ Effect.catchAll(error =>
+ Effect.gen(function* () {
+ yield* Effect.logDebug('Org/project picker failed:', error);
+ yield* ui.log.warn('Could not load org/project list. Using session defaults.');
+ return undefined;
+ })
+ )
+ );
+ if (result) {
+ const sessionUserId = uakSessionInfo.org_member.user_id ?? uakSessionInfo.org_member.id;
+ const testUserId = sessionUserId ? `pg-test-${sessionUserId}` : undefined;
+ yield* ctx.login(
+ uakApiKey,
+ result.org.id,
+ result.project.id,
+ testUserId ?? Option.getOrUndefined(ctx.data.testUserId)
+ );
+ yield* ui.log.success(
+ `Default org/project set to "${result.org.name}" / "${result.project.name}".`
+ );
+ }
+ // Emit JSON with final org/project (from picker or session) for piped/scripted consumption
+ const finalOrgId = result?.org.id ?? xOrgId;
+ const finalProjectId = result?.project.id ?? xProjectId;
+ const finalOrgName = result?.org.name ?? uakSessionInfo.project.org.name ?? '';
+ const finalProjectName = result?.project.name ?? uakSessionInfo.project.name ?? '';
+ yield* ui.output(
+ JSON.stringify({
+ email: linkedSession.account.email ?? undefined,
+ org_id: finalOrgId,
+ project_id: finalProjectId,
+ org_name: finalOrgName,
+ project_name: finalProjectName,
+ })
+ );
+ yield* ui.log.info(
+ 'Run `composio init` in your project directory to set up project context.'
+ );
+ yield* ui.log.info(
+ 'To switch your default global org/project later, run `composio orgs switch`.'
+ );
+ yield* ui.outro("You're all set!");
+ }
});
/**
* CLI command to login using Composio's CLI session APIs.
*
- * Supports two modes:
- * 1. Browser-based: Opens browser for OAuth flow (default)
- * 2. Non-interactive: Accepts --api-key, --org-id, --project-id flags for agents/CI
+ * Browser-based: Opens browser for OAuth flow (default).
+ * Use --no-browser to skip auto-opening the browser and print the URL instead.
+ * Use -y to skip org/project picker and use session defaults.
*
* @example
* ```bash
* composio login
* composio login --no-browser
- * composio login --api-key uak_xxx --org-id org-id --project-id proj-id
+ * composio login -y
* ```
*/
-export const loginCmd = Command.make(
- 'login',
- { noBrowser, apiKey: apiKeyOpt, orgId: orgIdOpt, projectId: projectIdOpt },
- ({ noBrowser, apiKey, orgId, projectId }) =>
- Effect.gen(function* () {
- const ui = yield* TerminalUI;
- const ctx = yield* ComposioUserContext;
-
- yield* ui.intro('composio login');
+export const loginCmd = Command.make('login', { noBrowser, yes: yesOpt }, ({ noBrowser, yes }) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const ctx = yield* ComposioUserContext;
- // Non-interactive path: --api-key, --org-id, --project-id flags skip browser flow.
- // All three must be provided together; partial flags are an error.
- const nonInteractiveFlags = [apiKey, orgId, projectId];
- const anyProvided = nonInteractiveFlags.some(Option.isSome);
- const allProvided = nonInteractiveFlags.every(Option.isSome);
+ yield* ui.intro('composio login');
- if (anyProvided && !allProvided) {
- const missing = [
- Option.isNone(apiKey) && '--api-key',
- Option.isNone(orgId) && '--org-id',
- Option.isNone(projectId) && '--project-id',
- ].filter(Boolean);
- yield* ui.log.error(`Missing required flag(s): ${missing.join(', ')}`);
- yield* ui.log.info(
- 'Non-interactive login requires all three: --api-key, --org-id, --project-id'
+ if (ctx.isLoggedIn()) {
+ // Allow re-login when orgId/projectId are not yet set (old CLI login without multi-project support)
+ if (Option.isSome(ctx.data.orgId) && Option.isSome(ctx.data.projectId)) {
+ yield* ui.log.warn(`You're already logged in!`);
+ yield* ui.outro(
+ 'If you want to log in with a different account, please run `composio logout` first.'
);
- yield* ui.outro('');
- return;
- }
-
- // Strict verification: 400/401/403 from session/info are hard failures since
- // the user explicitly provided the IDs.
- if (
- allProvided &&
- Option.isSome(apiKey) &&
- Option.isSome(orgId) &&
- Option.isSome(projectId)
- ) {
- yield* Effect.logDebug('Non-interactive login with provided credentials');
- yield* storeCredentials({
- baseURL: ctx.data.baseURL,
- uakApiKey: apiKey.value,
- initialOrgId: orgId.value,
- initialProjectId: projectId.value,
- fallbackEmail: '',
- strictVerification: true,
- });
return;
}
+ yield* ui.log.step('Re-authenticating for multi-project support...');
+ }
- if (ctx.isLoggedIn()) {
- // Allow re-login when orgId/projectId are not yet set (old CLI login without multi-project support)
- if (Option.isSome(ctx.data.orgId) && Option.isSome(ctx.data.projectId)) {
- yield* ui.log.warn(`You're already logged in!`);
- yield* ui.log.info(
- `If you want to log in with a different account, please run \`composio logout\` first.`
- );
- yield* ui.outro('');
- return;
- }
- yield* ui.log.step('Re-authenticating for multi-project support...');
- }
-
- yield* browserLogin({ scope: 'user', noBrowser });
- })
+ yield* browserLogin({ scope: 'user', noBrowser, skipOrgProjectPicker: yes });
+ })
).pipe(Command.withDescription('Log in to the Composio SDK.'));
diff --git a/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts b/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts
index 2afc0abf3..a74892a3e 100644
--- a/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts
+++ b/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts
@@ -1,15 +1,9 @@
import { Command, Options } from '@effect/cli';
import { Effect, Option } from 'effect';
import { requireAuth } from 'src/effects/require-auth';
+import { runOrgProjectSelection } from 'src/effects/select-org-project';
import { TerminalUI } from 'src/services/terminal-ui';
-import {
- listOrganizationProjects,
- listOrganizations,
- type OrganizationSummary,
- type OrganizationProjectSummary,
-} from 'src/services/composio-clients';
import { ComposioUserContext } from 'src/services/user-context';
-import { clampLimit } from 'src/ui/clamp-limit';
const orgId = Options.text('org-id').pipe(
Options.optional,
@@ -26,56 +20,6 @@ const limit = Options.integer('limit').pipe(
Options.withDescription('Max org/projects to fetch from API (default: 50)')
);
-const selectOrganization = (params: {
- organizations: ReadonlyArray<OrganizationSummary>;
- selectedOrgId?: string;
-}) =>
- Effect.gen(function* () {
- const { organizations, selectedOrgId } = params;
- const ui = yield* TerminalUI;
- if (organizations.length === 0) return undefined;
-
- if (selectedOrgId) {
- const explicitMatch = organizations.find(org => org.id === selectedOrgId);
- if (explicitMatch) return explicitMatch;
- }
-
- if (organizations.length === 1) return organizations[0];
-
- return yield* ui.select('Select a default organization (global scope):', [
- ...organizations.map(org => ({
- value: org,
- label: org.name,
- hint: org.id,
- })),
- ]);
- });
-
-const selectProject = (params: {
- projects: ReadonlyArray<OrganizationProjectSummary>;
- selectedProjectId?: string;
-}) =>
- Effect.gen(function* () {
- const { projects, selectedProjectId } = params;
- const ui = yield* TerminalUI;
- if (projects.length === 0) return undefined;
-
- if (selectedProjectId) {
- const explicitMatch = projects.find(project => project.id === selectedProjectId);
- if (explicitMatch) return explicitMatch;
- }
-
- if (projects.length === 1) return projects[0];
-
- return yield* ui.select('Select a default project (global scope):', [
- ...projects.map(project => ({
- value: project,
- label: project.name,
- hint: project.id,
- })),
- ]);
- });
-
export const orgsCmd$Switch = Command.make(
'switch',
{ orgId, projectId, limit },
@@ -94,74 +38,25 @@ export const orgsCmd$Switch = Command.make(
return;
}
- const clampedLimit = clampLimit(limit);
- const explicitOrgId = Option.getOrUndefined(orgId);
- const explicitProjectId = Option.getOrUndefined(projectId);
-
yield* ui.note(
'This updates your default global org/project context for CLI commands. Use `composio init` for per-project local overrides.',
'Global defaults'
);
- const selectedOrganization =
- explicitOrgId !== undefined
- ? ({ id: explicitOrgId, name: explicitOrgId } satisfies OrganizationSummary)
- : yield* Effect.gen(function* () {
- const organizations = yield* listOrganizations({
- baseURL: ctx.data.baseURL,
- apiKey,
- limit: clampedLimit,
- });
- yield* ui.log.info(`Loaded ${organizations.data.length} orgs`);
- return organizations;
- }).pipe(
- Effect.flatMap(organizations =>
- Effect.gen(function* () {
- if (organizations.data.length === 0) {
- return undefined;
- }
- return yield* selectOrganization({
- organizations: organizations.data,
- selectedOrgId: explicitOrgId,
- });
- })
- )
- );
-
- if (!selectedOrganization) {
- yield* ui.log.warn('No organizations found for this API key.');
- yield* ui.outro('No org selected.');
- return;
- }
- yield* ui.log.info(
- `Selected organization: "${selectedOrganization.name}" (${selectedOrganization.id})`
- );
-
- const projects = yield* listOrganizationProjects({
- baseURL: ctx.data.baseURL,
+ const result = yield* runOrgProjectSelection({
apiKey,
- orgId: selectedOrganization.id,
- limit: clampedLimit,
+ baseURL: ctx.data.baseURL,
+ explicitOrgId: Option.getOrUndefined(orgId),
+ explicitProjectId: Option.getOrUndefined(projectId),
+ limit,
});
- yield* ui.log.info(`Loaded ${projects.data.length} projects`);
- if (projects.data.length === 0) {
- yield* ui.log.warn(`No projects found for org "${selectedOrganization.name}".`);
- yield* ui.outro('No projects available.');
+ if (!result) {
+ yield* ui.outro('No org selected.');
return;
}
- const selectedProject = yield* selectProject({
- projects: projects.data,
- selectedProjectId: explicitProjectId,
- });
-
- if (!selectedProject) {
- yield* ui.log.warn('No project selected.');
- yield* ui.outro('No project selected.');
- return;
- }
- yield* ui.log.info(`Selected project: "${selectedProject.name}" (${selectedProject.id})`);
+ const { org: selectedOrganization, project: selectedProject } = result;
yield* ctx.login(
apiKey,
diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.ts
index 9f0562339..21fcfe9e2 100644
--- a/ts/packages/cli/src/commands/root-help.ts
+++ b/ts/packages/cli/src/commands/root-help.ts
@@ -27,12 +27,10 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [
{
name: 'login',
description: 'Log in to the Composio CLI session.',
- usage: 'login [--no-browser] [--api-key text] [--org-id text] [--project-id text]',
+ usage: 'login [--no-browser] [-y, --yes]',
options: [
{ name: '--no-browser', description: 'Login without browser interaction' },
- { name: '--api-key', description: 'API key for non-interactive login (agents/CI)' },
- { name: '--org-id', description: 'Organization ID for non-interactive login' },
- { name: '--project-id', description: 'Project ID for non-interactive login' },
+ { name: '-y, --yes', description: 'Skip org/project picker; use session defaults' },
],
},
{
@@ -43,10 +41,8 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [
{
name: 'init',
description: 'Initialize a Composio project in the current directory.',
- usage: 'init [--org-id text] [--project-id text] [--no-browser] [-y, --yes]',
+ usage: 'init [--no-browser] [-y, --yes]',
options: [
- { name: '--org-id', description: 'Organization ID (skip interactive picker)' },
- { name: '--project-id', description: 'Project ID (skip interactive picker)' },
{ name: '--no-browser', description: 'Skip opening browser for auth' },
{ name: '-y, --yes', description: 'Auto-select default org/project' },
],
diff --git a/ts/packages/cli/src/effects/select-org-project.ts b/ts/packages/cli/src/effects/select-org-project.ts
new file mode 100644
index 000000000..73fc3798b
--- /dev/null
+++ b/ts/packages/cli/src/effects/select-org-project.ts
@@ -0,0 +1,113 @@
+import { Effect } from 'effect';
+import { TerminalUI } from 'src/services/terminal-ui';
+import {
+ listOrganizationProjects,
+ listOrganizations,
+ type OrganizationProjectSummary,
+ type OrganizationSummary,
+} from 'src/services/composio-clients';
+import { clampLimit } from 'src/ui/clamp-limit';
+
+const DEFAULT_LIMIT = 50;
+
+/** Prompts user to select an org, or auto-selects if only one. */
+const selectOrganization = (organizations: ReadonlyArray<OrganizationSummary>) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ if (organizations.length === 0) return undefined;
+ if (organizations.length === 1) return organizations[0];
+ return yield* ui.select('Select a default organization (global scope):', [
+ ...organizations.map(org => ({ value: org, label: org.name, hint: org.id })),
+ ]);
+ });
+
+/**
+ * Prompts user to select a project, or auto-selects if only one.
+ * When explicitProjectId is provided (e.g. from `orgs switch --project-id`), finds and returns it without prompting.
+ */
+const selectProject = (
+ projects: ReadonlyArray<OrganizationProjectSummary>,
+ explicitProjectId?: string
+) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ if (projects.length === 0) return undefined;
+ if (explicitProjectId) {
+ const match = projects.find(p => p.id === explicitProjectId);
+ if (match) return match;
+ }
+ if (projects.length === 1) return projects[0];
+ return yield* ui.select('Select a default project (global scope):', [
+ ...projects.map(project => ({ value: project, label: project.name, hint: project.id })),
+ ]);
+ });
+
+/**
+ * Runs the org/project selection flow: lists orgs, prompts for org (or auto-selects if 1),
+ * lists projects, prompts for project (or auto-selects if 1).
+ *
+ * Reused by `composio orgs switch` and `composio login -y`.
+ *
+ * @param params.apiKey - User API key for API calls
+ * @param params.baseURL - API base URL
+ * @param params.explicitOrgId - If provided, skip org picker and use this org
+ * @param params.explicitProjectId - If provided (and org selected), skip project picker
+ * @param params.limit - Max orgs/projects to fetch (default 50)
+ */
+export const runOrgProjectSelection = (params: {
+ apiKey: string;
+ baseURL: string;
+ explicitOrgId?: string;
+ explicitProjectId?: string;
+ limit?: number;
+}) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const { apiKey, baseURL, explicitOrgId, explicitProjectId, limit = DEFAULT_LIMIT } = params;
+ const clampedLimit = clampLimit(limit);
+
+ const selectedOrganization =
+ explicitOrgId !== undefined
+ ? ({ id: explicitOrgId, name: explicitOrgId } satisfies OrganizationSummary)
+ : yield* Effect.gen(function* () {
+ const organizations = yield* listOrganizations({
+ baseURL,
+ apiKey,
+ limit: clampedLimit,
+ });
+ yield* ui.log.info(`Loaded ${organizations.data.length} orgs`);
+ if (organizations.data.length === 0) return undefined;
+ return yield* selectOrganization(organizations.data);
+ });
+
+ if (!selectedOrganization) {
+ yield* ui.log.warn('No organizations found for this API key.');
+ return undefined;
+ }
+ yield* ui.log.info(
+ `Selected organization: "${selectedOrganization.name}" (${selectedOrganization.id})`
+ );
+
+ const projects = yield* listOrganizationProjects({
+ baseURL,
+ apiKey,
+ orgId: selectedOrganization.id,
+ limit: clampedLimit,
+ });
+ yield* ui.log.info(`Loaded ${projects.data.length} projects`);
+
+ if (projects.data.length === 0) {
+ yield* ui.log.warn(`No projects found for org "${selectedOrganization.name}".`);
+ return undefined;
+ }
+
+ const selectedProject = yield* selectProject(projects.data, explicitProjectId);
+
+ if (!selectedProject) {
+ yield* ui.log.warn('No project selected.');
+ return undefined;
+ }
+ yield* ui.log.info(`Selected project: "${selectedProject.name}" (${selectedProject.id})`);
+
+ return { org: selectedOrganization, project: selectedProject } as const;
+ });
diff --git a/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap b/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap
index 5c4ff97d3..4235c57ed 100644
--- a/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap
+++ b/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap
@@ -22,12 +22,10 @@ BASIC COMMANDS
login
Log in to the Composio CLI session.
- Usage: composio login [--no-browser] [--api-key text] [--org-id text] [--project-id text]
+ Usage: composio login [--no-browser] [-y, --yes]
Options:
--no-browser Login without browser interaction
- --api-key API key for non-interactive login (agents/CI)
- --org-id Organization ID for non-interactive login
- --project-id Project ID for non-interactive login
+ -y, --yes Skip org/project picker; use session defaults
logout
Log out from the Composio CLI session.
@@ -35,10 +33,8 @@ BASIC COMMANDS
init
Initialize a Composio project in the current directory.
- Usage: composio init [--org-id text] [--project-id text] [--no-browser] [-y, --yes]
+ Usage: composio init [--no-browser] [-y, --yes]
Options:
- --org-id Organization ID (skip interactive picker)
- --project-id Project ID (skip interactive picker)
--no-browser Skip opening browser for auth
-y, --yes Auto-select default org/project
diff --git a/ts/packages/cli/test/src/commands/init.cmd.test.ts b/ts/packages/cli/test/src/commands/init.cmd.test.ts
index a315d4224..8db2ae649 100644
--- a/ts/packages/cli/test/src/commands/init.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/init.cmd.test.ts
@@ -1,50 +1,19 @@
-import path from 'node:path';
import { describe, expect, layer } from '@effect/vitest';
import { Effect } from 'effect';
-import { FileSystem } from '@effect/platform';
-import { NodeProcess } from 'src/services/node-process';
import { cli, TestLive, MockConsole } from 'test/__utils__';
describe('CLI: composio init', () => {
- describe('[Given] --org-id + --project-id flags', () => {
+ describe('init --help', () => {
layer(TestLive({ fixture: 'typescript-project' }))(it => {
- it.scoped('[Then] it initializes project config and prints machine output', () =>
+ it.scoped('[Then] shows --no-browser and --yes, no --org-id or --project-id', () =>
Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const proc = yield* NodeProcess;
-
- yield* cli(['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes']);
-
- const lines = yield* MockConsole.getLines({ stripAnsi: true });
- const output = lines.join('\n');
-
- expect(output).toContain('-- composio init --');
- expect(output).toContain('Project initialized in');
- expect(output).toContain('"org_id":"org1"');
- expect(output).toContain('"project_id":"proj1"');
-
- const projectConfigPath = path.join(proc.cwd, '.composio', 'project.json');
- const exists = yield* fs.exists(projectConfigPath);
- expect(exists).toBe(true);
-
- const projectConfigRaw = yield* fs.readFileString(projectConfigPath, 'utf8');
- const projectConfig = JSON.parse(projectConfigRaw) as Record<string, unknown>;
- expect(projectConfig.org_id).toBe('org1');
- expect(projectConfig.project_id).toBe('proj1');
- })
- );
- });
- });
-
- describe('[Given] explicit project ids but no global credentials', () => {
- layer(TestLive({ fixture: 'typescript-project' }))(it => {
- it.scoped('[Then] it warns and skips .env.local creation', () =>
- Effect.gen(function* () {
- yield* cli(['init', '--org-id', 'org1', '--project-id', 'proj1']);
-
+ yield* cli(['init', '--help']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
- expect(output).toContain('No global API key found; skipping .env.local creation.');
+ expect(output).toContain('--no-browser');
+ expect(output).toContain('--yes');
+ expect(output).not.toContain('--org-id');
+ expect(output).not.toContain('--project-id');
})
);
});
diff --git a/ts/packages/cli/test/src/commands/login.cmd.test.ts b/ts/packages/cli/test/src/commands/login.cmd.test.ts
index 17e61b9cf..bb2c7c4f3 100644
--- a/ts/packages/cli/test/src/commands/login.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/login.cmd.test.ts
@@ -1,64 +1,7 @@
import { describe, expect, layer } from '@effect/vitest';
import { vi, afterEach } from 'vitest';
import { Effect } from 'effect';
-import { ComposioUserContext } from 'src/services/user-context';
-import { cli, TestLive, MockConsole } from 'test/__utils__';
-
-// ── Helpers ──────────────────────────────────────────────────────────────────
-
-/**
- * Build a canned SessionInfoResponse JSON body for mocking `getSessionInfo`
- * and `getSessionInfoByUserApiKey`.
- */
-const makeSessionInfoBody = (overrides?: {
- orgId?: string;
- orgNanoId?: string;
- orgMemberId?: string;
- orgName?: string;
- projectId?: string;
- projectNanoId?: string;
- projectName?: string;
- email?: string;
- memberName?: string;
-}) => ({
- project: {
- name: overrides?.projectName ?? 'test-project',
- id: overrides?.projectId ?? 'proj_test_123',
- org_id: overrides?.orgId ?? 'org_test_456',
- nano_id: overrides?.projectNanoId ?? 'pr_nano_789',
- email: overrides?.email ?? '[email protected]',
- created_at: '2026-01-01T00:00:00.000Z',
- updated_at: '2026-01-01T00:00:00.000Z',
- org: {
- name: overrides?.orgName ?? 'Test Org',
- id: overrides?.orgNanoId ?? 'org_nano_456',
- plan: 'free',
- },
- },
- org_member: {
- id: overrides?.orgMemberId ?? 'org_member_uuid_456',
- email: overrides?.email ?? '[email protected]',
- name: overrides?.memberName ?? 'Test User',
- role: 'admin',
- },
- api_key: {
- name: 'default',
- project_id: overrides?.projectId ?? 'proj_test_123',
- id: 'ak_test',
- org_member_id: overrides?.orgId ?? 'org_test_456',
- },
-});
-
-/**
- * Creates a mock Response object.
- */
-function mockFetchResponse(body: unknown, status = 200): Response {
- const bodyStr = JSON.stringify(body);
- return new Response(bodyStr, {
- status,
- headers: { 'Content-Type': 'application/json' },
- });
-}
+import { cli, MockConsole, TestLive } from 'test/__utils__';
// ── Tests ────────────────────────────────────────────────────────────────────
@@ -67,188 +10,19 @@ describe('CLI: composio login', () => {
vi.restoreAllMocks();
});
- describe('[When] not logged in', () => {
- describe('non-interactive login: session/info succeeds', () => {
- layer(TestLive())(it => {
- it.scoped('[Then] stores credentials with enriched org/project IDs', () =>
- Effect.gen(function* () {
- const ctx = yield* ComposioUserContext;
- expect(ctx.isLoggedIn()).toBe(false);
-
- // Mock fetch for getSessionInfo call
- const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
- mockFetchResponse(
- makeSessionInfoBody({
- orgId: 'org_verified_uuid',
- orgNanoId: 'org_verified_nano',
- orgMemberId: 'org_member_verified_uuid',
- projectId: 'proj_verified_uuid',
- projectNanoId: 'proj_verified_nano',
- email: '[email protected]',
- projectName: 'Verified Project',
- orgName: 'Verified Org',
- })
- )
- );
-
- yield* cli([
- 'login',
- '--api-key',
- 'uak_test_key',
- '--org-id',
- 'org_initial',
- '--project-id',
- 'proj_initial',
- ]);
-
- // Verify fetch was called with session/info endpoint and correct headers
- expect(fetchSpy).toHaveBeenCalledOnce();
- const [url, init] = fetchSpy.mock.calls[0]!;
- expect(url).toContain('/api/v3/auth/session/info');
- expect((init as RequestInit).headers).toMatchObject({
- 'x-user-api-key': 'uak_test_key',
- 'x-org-id': 'org_initial',
- 'x-project-id': 'proj_initial',
- });
-
- // The mutable isLoggedIn closure reflects the login
- expect(ctx.isLoggedIn()).toBe(true);
-
- // Verify console output contains the enriched email and success message
- const lines = yield* MockConsole.getLines();
- const output = lines.join('\n');
- expect(output).toContain('[email protected]');
- expect(output).toContain('"org_id":"org_verified_nano"');
- expect(output).toContain('"project_id":"proj_verified_nano"');
- expect(output).toContain("You're all set!");
- })
- );
- });
- });
-
- describe('non-interactive login: session/info returns 500', () => {
- layer(TestLive())(it => {
- it.scoped('[Then] falls back to initial IDs on server error', () =>
- Effect.gen(function* () {
- const ctx = yield* ComposioUserContext;
- expect(ctx.isLoggedIn()).toBe(false);
-
- // Mock fetch to return a 500 error.
- // In strict mode, only 400-499 are hard failures.
- // 500 falls through the generic catch → undefined sessionInfo → use initial IDs.
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(
- mockFetchResponse(
- {
- status: 500,
- error: {
- error: {
- message: 'Internal server error',
- suggested_fix: 'Try again later',
- code: 500,
- },
- },
- },
- 500
- )
- );
-
- yield* cli([
- 'login',
- '--api-key',
- 'uak_fallback_key',
- '--org-id',
- 'org_fallback',
- '--project-id',
- 'proj_fallback',
- ]);
-
- // Credentials stored with initial (uncorrected) IDs since session/info failed
- expect(ctx.isLoggedIn()).toBe(true);
-
- const lines = yield* MockConsole.getLines();
- const output = lines.join('\n');
- expect(output).toContain('Logged in');
- })
- );
- });
- });
-
- describe('non-interactive login: session/info returns 401', () => {
- layer(TestLive())(it => {
- it.scoped('[Then] rejects invalid API key', () =>
- Effect.gen(function* () {
- const ctx = yield* ComposioUserContext;
- expect(ctx.isLoggedIn()).toBe(false);
-
- // Mock fetch to return 401
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(
- mockFetchResponse(
- {
- status: 401,
- error: {
- error: {
- message: 'Invalid API key',
- suggested_fix: 'Check your API key',
- code: 401,
- },
- },
- },
- 401
- )
- );
-
- // Non-interactive login: strict verification fails on 401
- const result = yield* cli([
- 'login',
- '--api-key',
- 'uak_bad_key',
- '--org-id',
- 'org_test',
- '--project-id',
- 'proj_test',
- ]).pipe(Effect.either);
-
- // The command should fail
- expect(result._tag).toBe('Left');
-
- // Should NOT be logged in after a failed verification
- expect(ctx.isLoggedIn()).toBe(false);
- })
- );
- });
- });
-
- describe('non-interactive login: session/info network failure', () => {
- layer(TestLive())(it => {
- it.scoped('[Then] falls back to initial IDs on network error', () =>
- Effect.gen(function* () {
- const ctx = yield* ComposioUserContext;
- expect(ctx.isLoggedIn()).toBe(false);
-
- // Mock fetch to throw a network error
- vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('fetch failed'));
-
- yield* cli([
- 'login',
- '--api-key',
- 'uak_network_key',
- '--org-id',
- 'org_net',
- '--project-id',
- 'proj_net',
- ]);
-
- // Network errors are non-fatal even in strict mode (only 400-499 are strict)
- // Actually: the fetch itself fails → HttpServerError with no status →
- // strict check (e.status >= 400 && < 500) doesn't match → falls through → undefined
- expect(ctx.isLoggedIn()).toBe(true);
-
- const lines = yield* MockConsole.getLines();
- const output = lines.join('\n');
- expect(output).toContain('Logged in');
- })
- );
- });
+ describe('login --help', () => {
+ layer(TestLive())(it => {
+ it.scoped('[Then] shows --no-browser and -y/--yes (skip picker), no --api-key', () =>
+ Effect.gen(function* () {
+ yield* cli(['login', '--help']);
+ const lines = yield* MockConsole.getLines();
+ const output = lines.join('\n');
+ expect(output).toContain('--no-browser');
+ expect(output).toContain('--yes');
+ expect(output).toContain('-y');
+ expect(output).not.toContain('--api-key');
+ })
+ );
});
});
});