1
import { Command, Options } from '@effect/cli';
2
-import { Effect, Option, Schedule } from 'effect';
2
+import { DateTime, Effect, Option, Schedule } from 'effect';
3
import open from 'open';
4
import {
5
ComposioSessionRepository,
16
Options.withDescription('Login without browser interaction')
17
);
18
19
+const noWait = Options.boolean('no-wait').pipe(
20
+ Options.withDefault(false),
21
+ Options.withDescription(
22
+ 'Print login URL and session info, then exit without opening browser or waiting'
23
+ )
24
+);
25
+
26
+const keyOpt = Options.text('key').pipe(
27
+ Options.withDescription('Complete login using session key from composio login --no-wait'),
28
+ Options.optional
29
+);
30
+
31
const yesOpt = Options.boolean('yes').pipe(
32
Options.withAlias('y'),
33
Options.withDefault(false),
141
}
142
});
143
144
+/**
145
+ * Completes login using an existing session key (from composio login --no-wait).
146
+ * Fetches the session, optionally polls until linked, then stores credentials.
147
+ *
148
+ * When noWait is false: polls until session is linked (same as browser flow).
149
+ * When noWait is true: checks once and fails if not linked.
150
+ */
151
+const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPicker: boolean }) =>
152
+ Effect.gen(function* () {
153
+ const ui = yield* TerminalUI;
154
+ const ctx = yield* ComposioUserContext;
155
+ const client = yield* ComposioSessionRepository;
156
+
157
+ const getSessionEffect = client
158
+ .getSession({ id: params.key })
159
+ .pipe(
160
+ Effect.catchAll(() =>
161
+ Effect.fail(
162
+ new Error(
163
+ 'Session not found or expired. Run `composio login --no-wait` to get a new session.'
164
+ )
165
+ )
166
+ )
167
+ );
168
+
169
+ let linkedSession;
170
+ if (params.noWait) {
171
+ const session = yield* getSessionEffect;
172
+ if (session.status !== 'linked') {
173
+ yield* ui.log.error('Login not complete. Open the URL and finish authentication.');
174
+ yield* ui.log.info('Then run `composio login --key <key>` again.');
175
+ return yield* Effect.fail(new Error('Session not yet linked'));
176
+ }
177
+ linkedSession = session;
178
+ } else {
179
+ linkedSession = yield* ui.useMakeSpinner('Waiting for login...', spinner =>
180
+ Effect.retry(
181
+ Effect.gen(function* () {
182
+ const currentSession = yield* getSessionEffect;
183
+ if (currentSession.status === 'linked') {
184
+ return currentSession;
185
+ }
186
+ return yield* Effect.fail(
187
+ new Error(`Session status is still '${currentSession.status}', waiting for 'linked'`)
188
+ );
189
+ }),
190
+ Schedule.exponential('0.3 seconds').pipe(
191
+ Schedule.intersect(Schedule.recurs(15)),
192
+ Schedule.intersect(Schedule.spaced('5 seconds'))
193
+ )
194
+ ).pipe(
195
+ Effect.tap(() => spinner.stop('Login successful')),
196
+ Effect.tapError(() => spinner.error('Login timed out. Please try again.'))
197
+ )
198
+ );
199
+ }
200
+ const uakApiKey = linkedSession.api_key;
201
+
202
+ const uakSessionInfo = yield* getSessionInfoByUserApiKey({
203
+ baseURL: ctx.data.baseURL,
204
+ userApiKey: uakApiKey,
205
+ });
206
+
207
+ const xProjectId = uakSessionInfo.project.nano_id;
208
+ const xOrgId = uakSessionInfo.project.org.id;
209
+
210
+ const willRunPicker = !params.skipOrgProjectPicker;
211
+ yield* storeCredentials({
212
+ baseURL: ctx.data.baseURL,
213
+ uakApiKey,
214
+ initialOrgId: xOrgId,
215
+ initialProjectId: xProjectId,
216
+ fallbackEmail: linkedSession.account.email,
217
+ skipHints: willRunPicker,
218
+ skipOutput: willRunPicker,
219
+ });
220
+
221
+ if (willRunPicker) {
222
+ const result = yield* runOrgProjectSelection({
223
+ apiKey: uakApiKey,
224
+ baseURL: ctx.data.baseURL,
225
+ }).pipe(
226
+ Effect.catchAll(error =>
227
+ Effect.gen(function* () {
228
+ yield* Effect.logDebug('Org/project picker failed:', error);
229
+ yield* ui.log.warn('Could not load org/project list. Using session defaults.');
230
+ return undefined;
231
+ })
232
+ )
233
+ );
234
+ if (result) {
235
+ const sessionUserId = uakSessionInfo.org_member.user_id ?? uakSessionInfo.org_member.id;
236
+ const testUserId = sessionUserId ? `pg-test-${sessionUserId}` : undefined;
237
+ yield* ctx.login(
238
+ uakApiKey,
239
+ result.org.id,
240
+ result.project.id,
241
+ testUserId ?? Option.getOrUndefined(ctx.data.testUserId)
242
+ );
243
+ yield* ui.log.success(
244
+ `Default org/project set to "${result.org.name}" / "${result.project.name}".`
245
+ );
246
+ }
247
+ const finalOrgId = result?.org.id ?? xOrgId;
248
+ const finalProjectId = result?.project.id ?? xProjectId;
249
+ const finalOrgName = result?.org.name ?? uakSessionInfo.project.org.name ?? '';
250
+ const finalProjectName = result?.project.name ?? uakSessionInfo.project.name ?? '';
251
+ yield* ui.output(
252
+ JSON.stringify({
253
+ email: linkedSession.account.email ?? undefined,
254
+ org_id: finalOrgId,
255
+ project_id: finalProjectId,
256
+ org_name: finalOrgName,
257
+ project_name: finalProjectName,
258
+ })
259
+ );
260
+ yield* ui.log.info(
261
+ 'Run `composio init` in your project directory to set up project context.'
262
+ );
263
+ yield* ui.log.info(
264
+ 'To switch your default global org/project later, run `composio orgs switch`.'
265
+ );
266
+ yield* ui.outro("You're all set!");
267
+ }
268
+ });
269
+
270
/**
271
* Runs the browser-based login flow: creates a CLI session, opens the browser,
272
* polls until linked, enriches via session/info, and stores credentials.
281
scope: 'user' | 'project';
282
/** When true, don't open browser — just show the URL. */
283
noBrowser: boolean;
284
+ /** When true, print URL/session info and exit without waiting (implies noBrowser). */
285
+ noWait?: boolean;
286
/** When true (login only), skip org/project picker and use session defaults. When false, prompt for org/project. */
287
skipOrgProjectPicker?: boolean;
288
}) =>
299
300
const url = `${ctx.data.webURL}?cliKey=${session.id}`;
301
162
- if (params.noBrowser) {
302
+ const effectiveNoBrowser = params.noBrowser || params.noWait;
303
+ if (effectiveNoBrowser) {
304
yield* ui.log.info('Please login using the following URL:');
305
} else {
306
yield* ui.log.step('Redirecting you to the login page');
307
}
308
309
yield* ui.note(url, 'Login URL');
310
+
311
+ if (params.noWait) {
312
+ const loginInfo = {
313
+ status: 'pending',
314
+ message: 'Complete login by opening the URL',
315
+ login_url: url,
316
+ cli_key: session.id,
317
+ expires_at: DateTime.formatIso(session.expiresAt),
318
+ };
319
+ yield* ui.note(JSON.stringify(loginInfo, null, 2), 'Login info');
320
+ yield* ui.output(JSON.stringify(loginInfo, null, 2));
321
+ return;
322
+ }
323
+
324
yield* ui.output(url);
325
171
- if (!params.noBrowser) {
326
+ if (!effectiveNoBrowser) {
327
yield* Effect.tryPromise(() => open(url, { wait: false })).pipe(
328
Effect.catchAll(error =>
329
Effect.gen(function* () {
441
*
442
* Browser-based: Opens browser for OAuth flow (default).
443
* Use --no-browser to skip auto-opening the browser and print the URL instead.
444
+ * Use --no-wait to print login URL and session info (JSON) then exit without opening browser or waiting.
445
+ * Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;
446
+ * with --no-wait, checks once and fails if not linked.
447
* Use -y to skip org/project picker and use session defaults.
448
*
449
* @example
450
* ```bash
451
* composio login
452
* composio login --no-browser
453
+ * composio login --no-wait
454
+ * composio login --key <key>
455
+ * composio login --key <key> --no-wait
456
* composio login -y
457
* ```
458
*/
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;
459
+export const loginCmd = Command.make(
460
+ 'login',
461
+ { noBrowser, noWait, key: keyOpt, yes: yesOpt },
462
+ ({ noBrowser, noWait, key, yes }) =>
463
+ Effect.gen(function* () {
464
+ const ui = yield* TerminalUI;
465
+ const ctx = yield* ComposioUserContext;
466
303
- yield* ui.intro('composio login');
467
+ yield* ui.intro('composio login');
468
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
- );
469
+ if (Option.isSome(key)) {
470
+ yield* loginWithKey({
471
+ key: key.value,
472
+ noWait,
473
+ skipOrgProjectPicker: true,
474
+ });
475
return;
476
}
314
- yield* ui.log.step('Re-authenticating for multi-project support...');
315
- }
477
317
- yield* browserLogin({ scope: 'user', noBrowser, skipOrgProjectPicker: yes });
318
- })
478
+ if (ctx.isLoggedIn()) {
479
+ // Allow re-login when orgId/projectId are not yet set (old CLI login without multi-project support)
480
+ if (Option.isSome(ctx.data.orgId) && Option.isSome(ctx.data.projectId)) {
481
+ yield* ui.log.warn(`You're already logged in!`);
482
+ yield* ui.outro(
483
+ 'If you want to log in with a different account, please run `composio logout` first.'
484
+ );
485
+ return;
486
+ }
487
+ yield* ui.log.step('Re-authenticating for multi-project support...');
488
+ }
489
+
490
+ yield* browserLogin({
491
+ scope: 'user',
492
+ noBrowser,
493
+ noWait,
494
+ skipOrgProjectPicker: yes,
495
+ });
496
+ })
497
).pipe(Command.withDescription('Log in to the Composio SDK.'));