1
+import path from 'node:path';
2
import { Command, Options } from '@effect/cli';
3
+import { FileSystem } from '@effect/platform';
4
import { DateTime, Effect, Option, Schedule } from 'effect';
5
import open from 'open';
6
import {
8
getSessionInfo,
9
getSessionInfoByUserApiKey,
10
listOrganizations,
11
+ type OrganizationSummary,
12
type SessionInfoResponse,
13
} from 'src/services/composio-clients';
14
import { ComposioUserContext } from 'src/services/user-context';
15
import { TerminalUI } from 'src/services/terminal-ui';
16
import { commandHintStep } from 'src/services/command-hints';
17
import { runOrgSelection } from 'src/effects/select-org-project';
18
+import { setupCacheDir } from 'src/effects/setup-cache-dir';
19
import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
20
import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';
21
import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
22
import { APP_VERSION } from 'src/constants';
23
+import { isInteractiveTerminal } from 'src/utils/stdio';
24
import {
25
ensureAgentSignupAllowed,
26
getOrSignupReadyAgent,
33
Options.withDescription('Login without browser interaction')
34
);
35
36
+const pollOpt = Options.boolean('poll').pipe(
37
+ Options.withDefault(false),
38
+ Options.withDescription('Poll the most recent pending browser login and complete it')
39
+);
40
+
41
const noWait = Options.boolean('no-wait').pipe(
42
Options.withDefault(false),
43
Options.withDescription(
46
);
47
48
const keyOpt = Options.text('key').pipe(
39
- Options.withDescription('Complete login using session key from composio login --no-wait'),
49
+ Options.withDescription('Poll and complete login using the session key from composio login'),
50
Options.optional
51
);
52
56
);
57
58
const orgOpt = Options.text('org').pipe(
49
- Options.withDescription('Default organization ID or name to store for CLI commands'),
59
+ Options.withDescription('Current organization ID or name to store for CLI commands'),
60
Options.optional
61
);
62
63
const yesOpt = Options.boolean('yes').pipe(
64
Options.withAlias('y'),
65
Options.withDefault(false),
56
- Options.withDescription('Skip org picker; use session default org')
66
+ Options.withDescription('Skip org picker; use current org')
67
);
68
69
const noSkillInstall = Options.boolean('no-skill-install').pipe(
76
Options.withDescription('Sign up or log in using a Composio agent identity')
77
);
78
79
+const PENDING_LOGIN_FILE_NAME = 'pending-login-session.json';
80
+const PENDING_LOGIN_TTL_MS = 10 * 60 * 1000;
81
+const LOGIN_POLL_INTERVAL_SECONDS = 5;
82
+const LOGIN_POLL_TIMEOUT_SECONDS = 10 * 60;
83
+const LOGIN_POLL_RETRIES = Math.ceil(LOGIN_POLL_TIMEOUT_SECONDS / LOGIN_POLL_INTERVAL_SECONDS);
84
+
85
+type PendingLoginSession = {
86
+ readonly key: string;
87
+ readonly loginUrl: string;
88
+ readonly expiresAt: string;
89
+ readonly cachedAt: string;
90
+};
91
+
92
+const pendingLoginPath = Effect.gen(function* () {
93
+ const cacheDir = yield* setupCacheDir;
94
+ return path.join(cacheDir, PENDING_LOGIN_FILE_NAME);
95
+});
96
+
97
+const isRecord = (value: unknown): value is Record<string, unknown> =>
98
+ typeof value === 'object' && value !== null;
99
+
100
+const parsePendingLoginSession = (raw: string): PendingLoginSession => {
101
+ const parsed: unknown = JSON.parse(raw);
102
+ if (
103
+ !isRecord(parsed) ||
104
+ typeof parsed.key !== 'string' ||
105
+ typeof parsed.loginUrl !== 'string' ||
106
+ typeof parsed.expiresAt !== 'string' ||
107
+ typeof parsed.cachedAt !== 'string'
108
+ ) {
109
+ throw new Error('Pending login cache is invalid');
110
+ }
111
+ return {
112
+ key: parsed.key,
113
+ loginUrl: parsed.loginUrl,
114
+ expiresAt: parsed.expiresAt,
115
+ cachedAt: parsed.cachedAt,
116
+ };
117
+};
118
+
119
+const writePendingLoginSession = (session: Omit<PendingLoginSession, 'cachedAt'>) =>
120
+ Effect.gen(function* () {
121
+ const fs = yield* FileSystem.FileSystem;
122
+ const filePath = yield* pendingLoginPath;
123
+ const payload: PendingLoginSession = {
124
+ ...session,
125
+ cachedAt: new Date().toISOString(),
126
+ };
127
+ yield* fs.writeFileString(filePath, `${JSON.stringify(payload, null, 2)}\n`);
128
+ });
129
+
130
+const clearPendingLoginSession = Effect.gen(function* () {
131
+ const fs = yield* FileSystem.FileSystem;
132
+ const filePath = yield* pendingLoginPath;
133
+ yield* fs.remove(filePath).pipe(Effect.catchAll(() => Effect.void));
134
+});
135
+
136
+const readPendingLoginSession = Effect.gen(function* () {
137
+ const fs = yield* FileSystem.FileSystem;
138
+ const filePath = yield* pendingLoginPath;
139
+ const exists = yield* fs.exists(filePath);
140
+ if (!exists) {
141
+ return yield* Effect.fail(
142
+ new Error('No pending login found. Run `composio login < /dev/null` first.')
143
+ );
144
+ }
145
+
146
+ const session = yield* fs
147
+ .readFileString(filePath, 'utf8')
148
+ .pipe(Effect.map(parsePendingLoginSession));
149
+ const cachedAt = Date.parse(session.cachedAt);
150
+ if (!Number.isFinite(cachedAt) || Date.now() - cachedAt > PENDING_LOGIN_TTL_MS) {
151
+ yield* clearPendingLoginSession;
152
+ return yield* Effect.fail(
153
+ new Error('Pending login expired. Run `composio login < /dev/null` again.')
154
+ );
155
+ }
156
+
157
+ return session;
158
+});
159
+
160
+const formatNonInteractiveLoginInstructions = (params: {
161
+ readonly loginUrl: string;
162
+ readonly pollCommand: string;
163
+}) => `Open this URL in your browser to log in:
164
+
165
+ ${params.loginUrl}
166
+
167
+Then run this command to complete login:
168
+
169
+ ${params.pollCommand}
170
+
171
+hint: For agents: Show the URL above to the user to click, then run the command above. The command uses the cached login key, polls for up to 10 minutes, and exits once credentials are saved. Do not ask the user whether to poll — they already requested login.`;
172
+
173
+const formatPollLoginComplete = (params: {
174
+ readonly email?: string;
175
+ readonly defaultOrgId: string;
176
+ readonly defaultOrgName?: string;
177
+ readonly organizations: ReadonlyArray<OrganizationSummary>;
178
+}) => {
179
+ const orgLines =
180
+ params.organizations.length > 0
181
+ ? params.organizations
182
+ .map(org => ` ${org.id === params.defaultOrgId ? '*' : '-'} ${org.name} (${org.id})`)
183
+ .join('\n')
184
+ : ' No organizations were returned for this account.';
185
+
186
+ return `Login complete${params.email ? ` for ${params.email}` : ''}.
187
+
188
+Current org:
189
+
190
+ ${params.defaultOrgName ?? params.defaultOrgId} (${params.defaultOrgId})
191
+
192
+Available organizations:
193
+
194
+${orgLines}
195
+
196
+The CLI selected the first organization as your current org. To choose a different current org, run:
197
+
198
+ composio orgs switch --org-id <org_id>`;
199
+};
200
+
201
+const serializePollLoginResult = (params: {
202
+ readonly email?: string;
203
+ readonly defaultOrgId: string;
204
+ readonly defaultOrgName?: string;
205
+ readonly organizations: ReadonlyArray<OrganizationSummary>;
206
+}) =>
207
+ JSON.stringify(
208
+ {
209
+ email: params.email ?? null,
210
+ current_org: {
211
+ id: params.defaultOrgId,
212
+ name: params.defaultOrgName ?? params.defaultOrgId,
213
+ },
214
+ organizations: params.organizations.map(org => ({
215
+ id: org.id,
216
+ name: org.name,
217
+ selected: org.id === params.defaultOrgId,
218
+ })),
219
+ switch_command: 'composio orgs switch --org-id <org_id>',
220
+ },
221
+ null,
222
+ 2
223
+ );
224
+
225
const formatLoginSuccessMessage = (params: { email?: string; orgName?: string }): string => {
226
const { email, orgName } = params;
227
if (email && orgName) {
249
yield* ui.log.success(formatLoginSuccessMessage({ email, orgName }));
250
if (!skipHints) {
251
yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
96
- yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
252
+ yield* ui.log.info(commandHintStep('Switch your current org', 'root.orgs.switch'));
253
}
254
255
yield* ui.output(
423
* When noWait is false: polls until session is linked (same as browser flow).
424
* When noWait is true: checks once and fails if not linked.
425
*/
270
-const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPicker: boolean }) =>
426
+const loginWithKey = (params: {
427
+ key: string;
428
+ noWait: boolean;
429
+ skipOrgProjectPicker: boolean;
430
+ pollRetries?: number;
431
+ defaultToFirstOrg?: boolean;
432
+ skipOutput?: boolean;
433
+}) =>
434
Effect.gen(function* () {
435
const ui = yield* TerminalUI;
436
const ctx = yield* ComposioUserContext;
470
);
471
}),
472
Schedule.exponential('0.3 seconds').pipe(
310
- Schedule.intersect(Schedule.recurs(15)),
311
- Schedule.intersect(Schedule.spaced('5 seconds'))
473
+ Schedule.intersect(Schedule.recurs(params.pollRetries ?? 15)),
474
+ Schedule.intersect(Schedule.spaced(`${LOGIN_POLL_INTERVAL_SECONDS} seconds`))
475
)
476
).pipe(
477
Effect.tap(() => spinner.stop('Login successful')),
486
userApiKey: uakApiKey,
487
});
488
489
+ const organizations = params.defaultToFirstOrg
490
+ ? yield* listOrganizations({
491
+ baseURL: ctx.data.baseURL,
492
+ apiKey: uakApiKey,
493
+ }).pipe(
494
+ Effect.map(response => response.data),
495
+ Effect.catchAll(error =>
496
+ Effect.gen(function* () {
497
+ yield* Effect.logDebug('Failed to list organizations after login:', error);
498
+ return [] as ReadonlyArray<OrganizationSummary>;
499
+ })
500
+ )
501
+ )
502
+ : [];
503
+ const defaultOrg = params.defaultToFirstOrg ? organizations[0] : undefined;
504
const xProjectId = uakSessionInfo.project.nano_id;
327
- const xOrgId = uakSessionInfo.project.org.id;
505
+ const xOrgId = defaultOrg?.id ?? uakSessionInfo.project.org.id;
506
+ const xOrgName = defaultOrg?.name ?? uakSessionInfo.project.org.name;
507
508
const willRunPicker = !params.skipOrgProjectPicker;
509
yield* storeCredentials({
513
initialProjectId: xProjectId,
514
fallbackEmail: linkedSession.account.email,
515
skipHints: willRunPicker,
337
- skipOutput: willRunPicker,
516
+ skipOutput: true,
517
});
518
519
if (willRunPicker) {
524
Effect.catchAll(error =>
525
Effect.gen(function* () {
526
yield* Effect.logDebug('Org picker failed:', error);
348
- yield* ui.log.warn('Could not load org list. Using session default org.');
527
+ yield* ui.log.warn('Could not load org list. Using current org.');
528
return undefined;
529
})
530
)
548
orgId: finalOrgId,
549
orgName: finalOrgName,
550
});
551
+ return {
552
+ email: linkedSession.account.email ?? undefined,
553
+ orgId: finalOrgId,
554
+ orgName: finalOrgName,
555
+ organizations,
556
+ };
557
+ }
558
+
559
+ if (!params.skipOutput) {
560
+ yield* emitLoginComplete({
561
+ email: linkedSession.account.email ?? undefined,
562
+ orgId: xOrgId,
563
+ orgName: xOrgName,
564
+ });
565
}
566
+
567
+ return {
568
+ email: linkedSession.account.email ?? undefined,
569
+ orgId: xOrgId,
570
+ orgName: xOrgName,
571
+ organizations,
572
+ };
573
});
574
575
/**
603
yield* Effect.logDebug(`Created session: ${session.id}`);
604
605
const url = `${ctx.data.webURL}?cliKey=${session.id}`;
606
+ const pollCommand = 'composio login --poll';
607
+ const expiresAt = DateTime.formatIso(session.expiresAt);
608
+ yield* writePendingLoginSession({
609
+ key: session.id,
610
+ loginUrl: url,
611
+ expiresAt,
612
+ });
613
+
614
+ const canPrompt = isInteractiveTerminal();
615
+ const effectiveNoWait = params.noWait || !canPrompt;
616
+ const effectiveNoBrowser = params.noBrowser || effectiveNoWait;
617
+
618
+ if (effectiveNoWait) {
619
+ const loginInstructions = formatNonInteractiveLoginInstructions({
620
+ loginUrl: url,
621
+ pollCommand,
622
+ });
623
+
624
+ if (canPrompt) {
625
+ yield* ui.log.info('Please login using the following URL:');
626
+ yield* ui.note(url, 'Login URL');
627
+ yield* ui.note(loginInstructions, 'Login instructions');
628
+ }
629
+
630
+ yield* ui.output(loginInstructions);
631
+ return;
632
+ }
633
407
- const effectiveNoBrowser = params.noBrowser || params.noWait;
634
if (effectiveNoBrowser) {
635
yield* ui.log.info('Please login using the following URL:');
636
} else {
639
640
yield* ui.note(url, 'Login URL');
641
416
- if (params.noWait) {
417
- const loginInfo = {
418
- status: 'pending',
419
- message: 'Complete login by opening the URL',
420
- login_url: url,
421
- cli_key: session.id,
422
- expires_at: DateTime.formatIso(session.expiresAt),
423
- };
424
- yield* ui.note(JSON.stringify(loginInfo, null, 2), 'Login info');
425
- yield* ui.output(JSON.stringify(loginInfo, null, 2));
426
- return;
427
- }
428
-
642
yield* ui.output(url);
643
644
if (!effectiveNoBrowser) {
712
Effect.catchAll(error =>
713
Effect.gen(function* () {
714
yield* Effect.logDebug('Org picker failed:', error);
502
- yield* ui.log.warn('Could not load org list. Using session default org.');
715
+ yield* ui.log.warn('Could not load org list. Using current org.');
716
return undefined;
717
})
718
)
747
* Use --no-wait to print login URL and session info (JSON) then exit without opening browser or waiting.
748
* Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;
749
* with --no-wait, checks once and fails if not linked.
537
- * Use --user-api-key to log in directly without a browser flow, and --org to override the default org.
750
+ * Use --user-api-key to log in directly without a browser flow, and --org to override the current org.
751
* Use --agent to sign up or log in using a Composio agent identity.
539
- * Use -y to skip org picker and use session default org.
752
+ * Use -y to skip org picker and use current org.
753
*
754
* @example
755
* ```bash
768
'login',
769
{
770
noBrowser,
771
+ poll: pollOpt,
772
noWait,
773
key: keyOpt,
774
userApiKey: userApiKeyOpt,
777
noSkillInstall,
778
agent: agentOpt,
779
},
566
- ({ noBrowser, noWait, key, userApiKey, org, yes, noSkillInstall, agent }) =>
780
+ ({ noBrowser, poll, noWait, key, userApiKey, org, yes, noSkillInstall, agent }) =>
781
Effect.gen(function* () {
782
const ui = yield* TerminalUI;
783
const ctx = yield* ComposioUserContext;
784
+ const canPrompt = isInteractiveTerminal();
785
571
- yield* ui.intro('composio login');
786
+ if (canPrompt) {
787
+ yield* ui.intro('composio login');
788
+ }
789
790
if (Option.isSome(key) && Option.isSome(userApiKey)) {
791
return yield* Effect.fail(new Error('Use either `--key` or `--user-api-key`, not both.'));
792
}
793
794
+ if (
795
+ poll &&
796
+ (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey) || agent)
797
+ ) {
798
+ return yield* Effect.fail(
799
+ new Error(
800
+ '`--poll` cannot be combined with browser, session, direct-login, or agent flags.'
801
+ )
802
+ );
803
+ }
804
+
805
if (agent && (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey))) {
806
return yield* Effect.fail(
807
new Error('`--agent` cannot be combined with browser, session, or direct-login flags.')
820
);
821
}
822
823
+ if (poll) {
824
+ const pendingLogin = yield* readPendingLoginSession;
825
+ const loginResult = yield* loginWithKey({
826
+ key: pendingLogin.key,
827
+ noWait: false,
828
+ skipOrgProjectPicker: true,
829
+ pollRetries: LOGIN_POLL_RETRIES,
830
+ defaultToFirstOrg: true,
831
+ skipOutput: true,
832
+ });
833
+ yield* clearPendingLoginSession;
834
+ const pollSummaryParams = {
835
+ email: loginResult.email,
836
+ defaultOrgId: loginResult.orgId,
837
+ defaultOrgName: loginResult.orgName,
838
+ organizations: loginResult.organizations,
839
+ };
840
+ const pollSummary = formatPollLoginComplete(pollSummaryParams);
841
+ if (canPrompt) {
842
+ yield* ui.note(pollSummary, 'Login complete');
843
+ }
844
+ yield* ui.output(serializePollLoginResult(pollSummaryParams), { force: true });
845
+ if (!noSkillInstall && canPrompt) {
846
+ yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
847
+ }
848
+ return;
849
+ }
850
+
851
if (agent) {
852
return yield* handleAgentAuthError(
853
Effect.gen(function* () {
859
`Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`
860
);
861
yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));
606
- if (!noSkillInstall) {
862
+ if (!noSkillInstall && canPrompt) {
863
yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
864
}
865
})
872
noWait,
873
skipOrgProjectPicker: true,
874
});
619
- if (!noSkillInstall) {
875
+ if (!noSkillInstall && canPrompt) {
876
yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
877
}
878
return;
883
userApiKey: userApiKey.value,
884
org: Option.getOrUndefined(org),
885
});
630
- if (!noSkillInstall) {
886
+ if (!noSkillInstall && canPrompt) {
887
yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
888
}
889
return;
907
skipOrgProjectPicker: yes,
908
});
909
654
- if (!noSkillInstall && !noWait) {
910
+ if (!noSkillInstall && !noWait && canPrompt) {
911
yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
912
}
913
})