@devries-cameron20 / composio Mirror · read-only
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 440 lines 16.3 KB
Raw
1 /**
2 * The browser login through a CLI session, shared by `composio login` (user scope) and
3 * `composio dev init` (project scope): create the session, show or open its URL, wait for it
4 * to be linked, then store the user API key it carries.
5 */
6 import { Data, DateTime, Duration, Effect, Option, Predicate, Ref, pipe } from 'effect';
7 import { formatLoginStillPending } from 'src/commands/login/login.format';
8 import {
9 AUTHORIZATION_TIMEOUT_MINUTES,
10 AUTHORIZATION_TIMEOUT_SECONDS,
11 authorizationPollScheduleFor,
12 } from 'src/effects/authorization-poll';
13 import { ExpectedFailure } from 'src/effects/expected-failure';
14 import open from 'open';
15 import type { RetrievedSession } from 'src/models/session';
16 import { ComposioSessionRepository } from 'src/services/composio-clients';
17 import {
18 getSessionInfo,
19 getSessionInfoByUserApiKey,
20 sessionUserIdOf,
21 type SessionInfoResponse,
22 } from 'src/services/composio-account';
23 import { commandHintStep } from 'src/services/command-hints';
24 import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
25 import { PendingLoginSession } from 'src/services/pending-login-session';
26 import { TerminalUI } from 'src/services/terminal-ui';
27 import { ComposioUserContext } from 'src/services/user-context';
28 import { linkAnalyticsIdentityForOrg } from './link-analytics-identity';
29 import { runOrgSelection } from './select-org-project';
30
31 export class LoginSessionError extends Data.TaggedError('commands/LoginSessionError')<{
32 readonly message: string;
33 readonly operation: 'load' | 'poll';
34 readonly status?: string;
35 readonly cause?: unknown;
36 }> {
37 get [ExpectedFailure]() {
38 return true;
39 }
40 }
41
42 class LoginBrowserOpenError extends Data.TaggedError('commands/LoginBrowserOpenError')<{
43 readonly message: string;
44 readonly cause: unknown;
45 }> {}
46
47 export type LinkedSession = Extract<RetrievedSession, { readonly status: 'linked' }>;
48
49 /** The command that completes a browser login another process cached. */
50 export const POLL_COMMAND = 'composio login --poll';
51
52 /**
53 * The bound the login instructions teach an agent, in seconds: short enough to fit inside a turn
54 * of the caller's own deadline, long enough not to give up while a person finds the page.
55 */
56 const AGENT_POLL_TIMEOUT_SECONDS = 120;
57
58 // --- presentation -----------------------------------------------------------------------------
59
60 const formatNonInteractiveLoginInstructions = (params: {
61 readonly loginUrl: string;
62 readonly pollCommand: string;
63 }) => `Open this URL in your browser to log in:
64
65 ${params.loginUrl}
66
67 Then run this command to complete login:
68
69 ${params.pollCommand}
70
71 hint: For agents: Show the URL above to the user to click, then run \`${params.pollCommand} --timeout ${AGENT_POLL_TIMEOUT_SECONDS}\`. It waits at most that long and exits once credentials are saved; the pending login lives ${AUTHORIZATION_TIMEOUT_MINUTES} minutes. If it exits with the login still pending, it prints the URL again — wait for the user to click, then run the same command again. Do not ask the user whether to poll — they already requested login.
72
73 hint: For unattended agents: If no human is available to open the URL, run \`composio login --agent\` instead — it signs the CLI in with a Composio agent account (creating one if needed) without a browser. Never use it when a human is present to log in with their own account.`;
74
75 const formatLoginSuccessMessage = (params: {
76 readonly email?: string;
77 readonly orgName?: string;
78 }): string =>
79 `Logged in ${params.email ? `as ${params.email}` : 'successfully'}${params.orgName ? ` in "${params.orgName}"` : ''}`;
80
81 /** The stdout payload of a completed login. */
82 const formatLoginCompleteJson = (params: {
83 readonly email?: string;
84 readonly orgId: string;
85 readonly orgName?: string;
86 }) =>
87 JSON.stringify({
88 email: params.email,
89 org_id: params.orgId,
90 org_name: params.orgName ?? '',
91 });
92
93 /** Reports a completed login: the success line and next-step hints on stderr, the JSON on stdout. */
94 export const emitLoginComplete = (params: {
95 readonly email?: string;
96 readonly orgId: string;
97 readonly orgName?: string;
98 }) =>
99 Effect.gen(function* () {
100 const ui = yield* TerminalUI;
101 yield* ui.log.success(formatLoginSuccessMessage(params));
102 yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
103 yield* ui.log.info(commandHintStep('Switch your current org', 'root.orgs.switch'));
104 yield* ui.output(formatLoginCompleteJson(params));
105 yield* ui.outro("You're all set!");
106 });
107
108 // --- shared steps -----------------------------------------------------------------------------
109
110 /**
111 * The playground test user of the session's member, or `fallback` when there is no session
112 * info or it carries no user id.
113 */
114 export const playgroundTestUserId = (
115 sessionInfo: Option.Option<SessionInfoResponse>,
116 fallback: Option.Option<string>
117 ) =>
118 pipe(
119 sessionInfo,
120 Option.map(sessionUserIdOf),
121 Option.filter(userId => userId.length > 0),
122 Option.map(userId => `pg-test-${userId}`),
123 Option.orElse(() => fallback),
124 Option.getOrUndefined
125 );
126
127 /** The URL a person opens to link the CLI session `sessionId`. */
128 export const loginUrlFor = (webURL: string, sessionId: string) => `${webURL}?cliKey=${sessionId}`;
129
130 /** Where a waiting login sends the person when it runs out, and how to pick it up again. */
131 export type PendingLoginAnswer = {
132 /** The URL that finishes this login. */
133 readonly loginUrl: string;
134 /** The command that resumes the wait on the same login. */
135 readonly resumeCommand: string;
136 };
137
138 /** The answer a wait gives about a session that is still not linked. */
139 const pendingLoginError = (status: string, pending: PendingLoginAnswer) =>
140 new LoginSessionError({
141 message: formatLoginStillPending({ status, ...pending }),
142 operation: 'poll',
143 status,
144 });
145
146 /** The session, or a `poll` failure carrying the status it is waiting on and where to finish it. */
147 const requireLinkedSession = (session: RetrievedSession, pending: PendingLoginAnswer) =>
148 session.status === 'linked'
149 ? Effect.succeed(session)
150 : Effect.fail(pendingLoginError(session.status, pending));
151
152 /**
153 * Checks the session behind a spinner until it is linked, on `authorizationPollScheduleFor`:
154 * `timeoutSeconds` at most, a pending login's own lifetime by default. A wait that runs out fails
155 * with the status it last saw and where to finish the login, and never stores anything.
156 *
157 * The schedule bounds the retries, not a check already in flight: a slow answer, and the client's
158 * own retries of it, would outlast the bound. So the wait also gets a deadline of its own, and
159 * reports the last status it saw rather than nothing.
160 */
161 export const waitForLinkedSession = <E, R>(
162 getSession: Effect.Effect<RetrievedSession, E, R>,
163 pending: PendingLoginAnswer & { readonly timeoutSeconds?: number }
164 ) =>
165 Effect.gen(function* () {
166 const ui = yield* TerminalUI;
167 const timeoutSeconds = pending.timeoutSeconds ?? AUTHORIZATION_TIMEOUT_SECONDS;
168 const lastStatus = yield* Ref.make('pending');
169 return yield* ui.useMakeSpinner('Waiting for login...', spinner =>
170 Effect.retry(
171 Effect.flatMap(getSession, session =>
172 Effect.andThen(
173 Ref.set(lastStatus, session.status),
174 requireLinkedSession(session, pending)
175 )
176 ),
177 authorizationPollScheduleFor(timeoutSeconds)
178 ).pipe(
179 Effect.timeoutOrElse({
180 duration: Duration.seconds(timeoutSeconds),
181 orElse: () =>
182 Effect.flatMap(Ref.get(lastStatus), status =>
183 Effect.fail(pendingLoginError(status, pending))
184 ),
185 }),
186 Effect.tap(() => spinner.stop('Login successful')),
187 Effect.tapError(error =>
188 spinner.error(
189 Predicate.isTagged(error, 'commands/LoginSessionError')
190 ? 'Login still pending'
191 : 'Login failed'
192 )
193 )
194 )
195 );
196 });
197
198 /**
199 * Verifies the linked session's key through session/info and stores it as the CLI's login.
200 * The session info is enrichment only: the linked session is already authenticated, so a
201 * failed lookup falls back to the IDs the caller passes.
202 */
203 export const storeCredentials = (params: {
204 readonly uakApiKey: string;
205 readonly initialOrgId: string;
206 readonly initialProjectId: string;
207 readonly fallbackEmail: string;
208 /** Report the login (stderr and stdout) once stored. */
209 readonly announce: boolean;
210 /** Link the analytics identity now, rather than after a later org selection. */
211 readonly linkAnalytics: boolean;
212 }) =>
213 Effect.gen(function* () {
214 const ctx = yield* ComposioUserContext;
215 const sessionInfo = yield* getSessionInfo({
216 apiKey: params.uakApiKey,
217 orgId: params.initialOrgId,
218 projectId: params.initialProjectId,
219 }).pipe(
220 Effect.map(Option.some),
221 // Catch-all rather than per-tag: no way this enrichment can fail may stop the
222 // credential from being stored.
223 Effect.catch(error =>
224 Effect.logDebug('Session info fetch failed:', error).pipe(
225 Effect.as(Option.none<SessionInfoResponse>())
226 )
227 )
228 );
229
230 // session/info is the canonical source of the org ID; the linked session may carry a
231 // session-level identifier instead.
232 const orgId = Option.match(sessionInfo, {
233 onNone: () => params.initialOrgId,
234 onSome: info => info.project.org.id,
235 });
236 if (orgId !== params.initialOrgId) {
237 yield* Effect.logDebug(
238 `orgId corrected: ${params.initialOrgId} -> ${orgId} (from session/info)`
239 );
240 }
241
242 yield* ctx.login(
243 params.uakApiKey,
244 orgId,
245 playgroundTestUserId(sessionInfo, ctx.data.testUserId)
246 );
247 // Linked only after the credential persists, so stitching cannot outlive a failed login.
248 if (params.linkAnalytics) {
249 yield* linkAnalyticsIdentityForOrg({
250 apiKey: params.uakApiKey,
251 orgId,
252 knownIdentity: Option.getOrUndefined(
253 Option.map(sessionInfo, info => ({
254 orgId: info.project.org.id,
255 orgMemberId: info.org_member.id,
256 }))
257 ),
258 });
259 }
260 yield* primeConsumerConnectedToolkitsCacheInBackground({ orgId });
261
262 if (params.announce) {
263 yield* emitLoginComplete({
264 email:
265 Option.getOrUndefined(Option.map(sessionInfo, info => info.org_member.email)) ||
266 params.fallbackEmail ||
267 undefined,
268 orgId,
269 orgName:
270 Option.getOrUndefined(Option.map(sessionInfo, info => info.project.org.name)) ||
271 undefined,
272 });
273 }
274 });
275
276 /**
277 * Lets the user pick the current org after a browser login, stores the pick, links the
278 * analytics identity for it, and reports the login. A failed org list keeps the session's org.
279 */
280 const completeOrgSelection = (params: {
281 readonly uakApiKey: string;
282 readonly sessionInfo: SessionInfoResponse;
283 readonly linkedSession: LinkedSession;
284 }) =>
285 Effect.gen(function* () {
286 const ui = yield* TerminalUI;
287 const ctx = yield* ComposioUserContext;
288 const { uakApiKey, sessionInfo, linkedSession } = params;
289
290 const selected = yield* runOrgSelection({ apiKey: uakApiKey }).pipe(
291 Effect.map(Option.fromUndefinedOr),
292 Effect.catch(error =>
293 Effect.gen(function* () {
294 yield* Effect.logDebug('Org picker failed:', error);
295 yield* ui.log.warn('Could not load org list. Using current org.');
296 return Option.none();
297 })
298 )
299 );
300 yield* Option.match(selected, {
301 onNone: () => Effect.void,
302 onSome: org =>
303 ctx
304 .login(
305 uakApiKey,
306 org.id,
307 playgroundTestUserId(Option.some(sessionInfo), ctx.data.testUserId)
308 )
309 .pipe(Effect.andThen(primeConsumerConnectedToolkitsCacheInBackground({ orgId: org.id }))),
310 });
311
312 const orgId = Option.match(selected, {
313 onNone: () => sessionInfo.project.org.id,
314 onSome: org => org.id,
315 });
316 yield* linkAnalyticsIdentityForOrg({
317 apiKey: uakApiKey,
318 orgId,
319 knownIdentity: {
320 orgId: sessionInfo.project.org.id,
321 orgMemberId: sessionInfo.org_member.id,
322 },
323 });
324 yield* emitLoginComplete({
325 email: linkedSession.account.email ?? undefined,
326 orgId,
327 orgName: Option.match(selected, {
328 onNone: () => sessionInfo.project.org.name ?? '',
329 onSome: org => org.name,
330 }),
331 });
332 });
333
334 /** Opens the login URL in the default browser; a failure only prints a hint. */
335 const openLoginUrl = (url: string) =>
336 Effect.gen(function* () {
337 const ui = yield* TerminalUI;
338 yield* Effect.tryPromise({
339 try: () => open(url, { wait: false }),
340 catch: cause => new LoginBrowserOpenError({ message: 'Failed to open the browser.', cause }),
341 }).pipe(
342 Effect.catchTag('commands/LoginBrowserOpenError', error =>
343 Effect.gen(function* () {
344 yield* Effect.logDebug('Failed to open browser:', error);
345 yield* ui.log.warn('Could not open the browser automatically.');
346 yield* ui.log.info(`Tip: try using the \`--no-browser\` flag and open the URL manually.`);
347 })
348 )
349 );
350 });
351
352 /**
353 * Runs the browser login: creates a CLI session and caches it for `composio login --poll`,
354 * then either prints the poll instructions and returns (`noWait`, or nobody can answer a
355 * prompt), or shows the URL (opening it unless `noBrowser`), waits until the session is
356 * linked, and stores the credentials. A `user` login then lets the user pick the current org
357 * unless `skipOrgProjectPicker`.
358 */
359 export const browserLogin = (params: {
360 /** Session scope: 'user' for login, 'project' for init. */
361 readonly scope: 'user' | 'project';
362 /** When true, don't open browser — just show the URL. */
363 readonly noBrowser: boolean;
364 /** When true, print URL/session info and exit without waiting (implies noBrowser). */
365 readonly noWait?: boolean;
366 /** When true (login only), skip the org picker and use the session's org. */
367 readonly skipOrgProjectPicker?: boolean;
368 }) =>
369 Effect.gen(function* () {
370 const ui = yield* TerminalUI;
371 const ctx = yield* ComposioUserContext;
372 const client = yield* ComposioSessionRepository;
373 const pendingLogin = yield* PendingLoginSession;
374
375 yield* Effect.logDebug(`Authenticating (scope: ${params.scope})...`);
376 const session = yield* client.createSession({ scope: params.scope });
377 yield* Effect.logDebug(`Created session: ${session.id}`);
378
379 const url = loginUrlFor(ctx.data.webURL, session.id);
380 yield* pendingLogin.write({
381 key: session.id,
382 loginUrl: url,
383 expiresAt: DateTime.formatIso(session.expiresAt),
384 });
385
386 const { canPrompt, canDecorate } = yield* ui.capabilities;
387 const effectiveNoWait = params.noWait || !canPrompt;
388 const effectiveNoBrowser = params.noBrowser || effectiveNoWait;
389
390 if (effectiveNoWait) {
391 const loginInstructions = formatNonInteractiveLoginInstructions({
392 loginUrl: url,
393 pollCommand: POLL_COMMAND,
394 });
395 if (canDecorate) {
396 yield* ui.log.info('Please login using the following URL:');
397 yield* ui.note(url, 'Login URL');
398 yield* ui.note(loginInstructions, 'Login instructions');
399 }
400 yield* ui.output(loginInstructions);
401 return;
402 }
403
404 yield* effectiveNoBrowser
405 ? ui.log.info('Please login using the following URL:')
406 : ui.log.step('Redirecting you to the login page');
407 yield* ui.note(url, 'Login URL');
408 yield* ui.output(url);
409 if (!effectiveNoBrowser) {
410 yield* openLoginUrl(url);
411 }
412
413 const linkedSession = yield* waitForLinkedSession(client.getSession({ id: session.id }), {
414 loginUrl: url,
415 resumeCommand: POLL_COMMAND,
416 });
417 yield* Effect.logDebug(`Linked session ID: ${linkedSession.id}`);
418
419 // e.g., "uak_b813ydmoEYdB_xBxGHeW"
420 const uakApiKey = linkedSession.api_key;
421 const sessionInfo = yield* getSessionInfoByUserApiKey({ userApiKey: uakApiKey });
422 yield* Effect.logDebug('UAK session info:', {
423 xProjectId: sessionInfo.project.nano_id,
424 xOrgId: sessionInfo.project.org.id,
425 });
426
427 const willRunPicker = params.scope === 'user' && !params.skipOrgProjectPicker;
428 yield* storeCredentials({
429 uakApiKey,
430 initialOrgId: sessionInfo.project.org.id,
431 initialProjectId: sessionInfo.project.nano_id,
432 fallbackEmail: linkedSession.account.email,
433 announce: !willRunPicker,
434 linkAnalytics: !willRunPicker,
435 });
436
437 if (willRunPicker) {
438 yield* completeOrgSelection({ uakApiKey, sessionInfo, linkedSession });
439 }
440 });