Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import { Array as Arr, Data, Effect, Match, Option, Predicate, pipe } from 'effect'; |
| 2 | import { commandInputError } from 'src/commands/errors'; |
| 3 | import { APP_VERSION } from 'src/constants'; |
| 4 | import { AUTHORIZATION_TIMEOUT_SECONDS } from 'src/effects/authorization-poll'; |
| 5 | import { |
| 6 | browserLogin, |
| 7 | emitLoginComplete, |
| 8 | loginUrlFor, |
| 9 | LoginSessionError, |
| 10 | playgroundTestUserId, |
| 11 | POLL_COMMAND, |
| 12 | storeCredentials, |
| 13 | waitForLinkedSession, |
| 14 | type PendingLoginAnswer, |
| 15 | } from 'src/effects/browser-login'; |
| 16 | import type { RetrievedSession } from 'src/models/session'; |
| 17 | import { completeAgentLogin } from 'src/effects/complete-agent-login'; |
| 18 | import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error'; |
| 19 | import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill'; |
| 20 | import { linkAnalyticsIdentityForOrg } from 'src/effects/link-analytics-identity'; |
| 21 | import { |
| 22 | ensureAgentSignupAllowed, |
| 23 | getOrSignupReadyAgent, |
| 24 | getStoredReadyAgent, |
| 25 | isAgentIdentityForApiKey, |
| 26 | type AgentIdentity, |
| 27 | } from 'src/services/agents'; |
| 28 | import { |
| 29 | getSessionInfoByUserApiKey, |
| 30 | listOrganizations, |
| 31 | type OrganizationSummary, |
| 32 | } from 'src/services/composio-account'; |
| 33 | import { ComposioSessionRepository } from 'src/services/composio-clients'; |
| 34 | import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache'; |
| 35 | import { PendingLoginSession } from 'src/services/pending-login-session'; |
| 36 | import { TerminalUI } from 'src/services/terminal-ui'; |
| 37 | import { ComposioUserContext } from 'src/services/user-context'; |
| 38 | import { InvalidOrganizationError, LoginSessionRequestError } from './login.errors'; |
| 39 | import { |
| 40 | AGENT_WITH_OTHER_FLAGS_MESSAGE, |
| 41 | ALREADY_LOGGED_IN_MESSAGE, |
| 42 | ALREADY_LOGGED_IN_OUTRO, |
| 43 | INVALID_ORGANIZATION_MESSAGE, |
| 44 | invalidTimeoutMessage, |
| 45 | KEY_AND_USER_API_KEY_MESSAGE, |
| 46 | ORG_WITHOUT_USER_API_KEY_MESSAGE, |
| 47 | POLL_WITH_OTHER_FLAGS_MESSAGE, |
| 48 | REAUTHENTICATING_MESSAGE, |
| 49 | SESSION_NOT_FOUND_MESSAGE, |
| 50 | SESSION_NOT_LINKED_HINT, |
| 51 | SESSION_NOT_LINKED_MESSAGE, |
| 52 | TIMEOUT_WITHOUT_POLL_MESSAGE, |
| 53 | USER_API_KEY_WITH_SESSION_FLAGS_MESSAGE, |
| 54 | formatPollLoginComplete, |
| 55 | formatPollLoginJson, |
| 56 | organizationNotFoundMessage, |
| 57 | type PollLoginSummary, |
| 58 | } from './login.format'; |
| 59 | |
| 60 | /** The flags of `composio login`. */ |
| 61 | export type LoginParams = { |
| 62 | readonly noBrowser: boolean; |
| 63 | readonly poll: boolean; |
| 64 | readonly timeout: Option.Option<string>; |
| 65 | readonly noWait: boolean; |
| 66 | readonly key: Option.Option<string>; |
| 67 | readonly userApiKey: Option.Option<string>; |
| 68 | readonly org: Option.Option<string>; |
| 69 | readonly yes: boolean; |
| 70 | readonly noSkillInstall: boolean; |
| 71 | readonly agent: boolean; |
| 72 | }; |
| 73 | |
| 74 | /** The five ways `login` can complete; the flags pick one. */ |
| 75 | type LoginFlow = Data.TaggedEnum<{ |
| 76 | Poll: Record<never, never>; |
| 77 | Agent: Record<never, never>; |
| 78 | SessionKey: { readonly key: string }; |
| 79 | Direct: { readonly userApiKey: string }; |
| 80 | Browser: Record<never, never>; |
| 81 | }>; |
| 82 | const LoginFlow = Data.taggedEnum<LoginFlow>(); |
| 83 | |
| 84 | const invalidOptionValue = commandInputError('login'); |
| 85 | |
| 86 | // --- shared steps ----------------------------------------------------------------------------- |
| 87 | |
| 88 | /** |
| 89 | * Seconds `composio login --poll` may wait: a whole number from 1 to a pending login's lifetime, |
| 90 | * which is also the default. A longer wait would outlive the login it waits for. |
| 91 | */ |
| 92 | const parsePollTimeout = (timeout: Option.Option<string>) => |
| 93 | Effect.gen(function* () { |
| 94 | if (Option.isNone(timeout)) { |
| 95 | return AUTHORIZATION_TIMEOUT_SECONDS; |
| 96 | } |
| 97 | const trimmed = timeout.value.trim(); |
| 98 | const seconds = /^\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN; |
| 99 | if (seconds >= 1 && seconds <= AUTHORIZATION_TIMEOUT_SECONDS) { |
| 100 | return seconds; |
| 101 | } |
| 102 | return yield* Effect.fail( |
| 103 | invalidOptionValue(invalidTimeoutMessage(AUTHORIZATION_TIMEOUT_SECONDS), '--timeout') |
| 104 | ); |
| 105 | }); |
| 106 | |
| 107 | /** Installs the composio-cli skill after a login, unless skipped or nobody can answer a prompt. */ |
| 108 | const offerSkillInstall = (skip: boolean) => |
| 109 | Effect.gen(function* () { |
| 110 | const ui = yield* TerminalUI; |
| 111 | const { canPrompt } = yield* ui.capabilities; |
| 112 | yield* Effect.when( |
| 113 | installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) }), |
| 114 | Effect.succeed(canPrompt && !skip) |
| 115 | ); |
| 116 | }); |
| 117 | |
| 118 | /** The session, or a failure after telling the user to finish the browser step first. */ |
| 119 | const requireLinkedNow = (session: RetrievedSession) => |
| 120 | Effect.gen(function* () { |
| 121 | const ui = yield* TerminalUI; |
| 122 | if (session.status === 'linked') { |
| 123 | return session; |
| 124 | } |
| 125 | yield* ui.log.error(SESSION_NOT_LINKED_MESSAGE); |
| 126 | yield* ui.log.info(SESSION_NOT_LINKED_HINT); |
| 127 | return yield* new LoginSessionError({ |
| 128 | message: 'Session not yet linked', |
| 129 | operation: 'poll', |
| 130 | status: session.status, |
| 131 | }); |
| 132 | }); |
| 133 | |
| 134 | /** |
| 135 | * Completes the CLI session behind `key`: checks it once (`noWait`) or waits until it is |
| 136 | * linked, then stores its user API key. With `defaultToFirstOrg`, the first of the account's |
| 137 | * organizations becomes the current org. Reports the login only when `announce`. |
| 138 | */ |
| 139 | const loginWithKey = (params: { |
| 140 | readonly key: string; |
| 141 | readonly noWait: boolean; |
| 142 | readonly announce: boolean; |
| 143 | readonly defaultToFirstOrg?: boolean; |
| 144 | /** Where the person finishes this login, and how a wait that runs out resumes it. */ |
| 145 | readonly pending: PendingLoginAnswer; |
| 146 | /** How long to wait for the session to link; a pending login's lifetime when omitted. */ |
| 147 | readonly timeoutSeconds?: number; |
| 148 | }) => |
| 149 | Effect.gen(function* () { |
| 150 | const client = yield* ComposioSessionRepository; |
| 151 | const getSession = client.getSession({ id: params.key }).pipe( |
| 152 | // Only a 404 means the session is gone; any other failure keeps its cause. |
| 153 | Effect.mapError(cause => |
| 154 | Predicate.isTagged(cause, '@composio/client/NotFoundError') |
| 155 | ? new LoginSessionError({ message: SESSION_NOT_FOUND_MESSAGE, operation: 'load', cause }) |
| 156 | : new LoginSessionRequestError({ message: 'Failed to load the login session.', cause }) |
| 157 | ) |
| 158 | ); |
| 159 | const linkedSession = yield* params.noWait |
| 160 | ? Effect.flatMap(getSession, requireLinkedNow) |
| 161 | : waitForLinkedSession(getSession, { |
| 162 | ...params.pending, |
| 163 | timeoutSeconds: params.timeoutSeconds, |
| 164 | }); |
| 165 | |
| 166 | const uakApiKey = linkedSession.api_key; |
| 167 | const sessionInfo = yield* getSessionInfoByUserApiKey({ userApiKey: uakApiKey }); |
| 168 | const organizations: ReadonlyArray<OrganizationSummary> = params.defaultToFirstOrg |
| 169 | ? yield* listOrganizations({ apiKey: uakApiKey }).pipe( |
| 170 | Effect.map(response => response.data), |
| 171 | Effect.catch(error => |
| 172 | Effect.logDebug('Failed to list organizations after login:', error).pipe(Effect.as([])) |
| 173 | ) |
| 174 | ) |
| 175 | : []; |
| 176 | const defaultOrg = Arr.head(organizations); |
| 177 | const orgId = Option.match(defaultOrg, { |
| 178 | onNone: () => sessionInfo.project.org.id, |
| 179 | onSome: org => org.id, |
| 180 | }); |
| 181 | const orgName = Option.match(defaultOrg, { |
| 182 | onNone: () => sessionInfo.project.org.name, |
| 183 | onSome: org => org.name, |
| 184 | }); |
| 185 | |
| 186 | yield* storeCredentials({ |
| 187 | uakApiKey, |
| 188 | initialOrgId: orgId, |
| 189 | initialProjectId: sessionInfo.project.nano_id, |
| 190 | fallbackEmail: linkedSession.account.email, |
| 191 | announce: false, |
| 192 | linkAnalytics: true, |
| 193 | }); |
| 194 | |
| 195 | const email = linkedSession.account.email ?? undefined; |
| 196 | if (params.announce) { |
| 197 | yield* emitLoginComplete({ email, orgId, orgName }); |
| 198 | } |
| 199 | return { email, orgId, orgName, organizations }; |
| 200 | }); |
| 201 | |
| 202 | /** The organization `--org` names, by ID or name, among those the key can see. */ |
| 203 | const findOrganization = (apiKey: string, requestedOrg: string) => |
| 204 | Effect.gen(function* () { |
| 205 | const ui = yield* TerminalUI; |
| 206 | const organizations = yield* listOrganizations({ apiKey }); |
| 207 | const match = Arr.findFirst( |
| 208 | organizations.data, |
| 209 | org => org.id === requestedOrg || org.name === requestedOrg |
| 210 | ); |
| 211 | return yield* Option.match(match, { |
| 212 | onSome: Effect.succeed, |
| 213 | onNone: () => |
| 214 | ui.log.error(organizationNotFoundMessage(requestedOrg)).pipe( |
| 215 | Effect.andThen( |
| 216 | Effect.fail( |
| 217 | new InvalidOrganizationError({ |
| 218 | message: INVALID_ORGANIZATION_MESSAGE, |
| 219 | requestedOrg, |
| 220 | }) |
| 221 | ) |
| 222 | ) |
| 223 | ), |
| 224 | }); |
| 225 | }); |
| 226 | |
| 227 | /** |
| 228 | * A stored READY agent identity a headless login may reuse: only when nobody can answer a |
| 229 | * prompt, no explicit browser flow was asked for, and the identity is the active login if |
| 230 | * there is one. |
| 231 | */ |
| 232 | const reusableStoredAgent = (requestedExplicitLoginFlow: boolean) => |
| 233 | Effect.gen(function* () { |
| 234 | const ui = yield* TerminalUI; |
| 235 | const ctx = yield* ComposioUserContext; |
| 236 | const { canPrompt } = yield* ui.capabilities; |
| 237 | if (canPrompt || requestedExplicitLoginFlow) { |
| 238 | return Option.none<AgentIdentity>(); |
| 239 | } |
| 240 | const stored = yield* getStoredReadyAgent; |
| 241 | const activeApiKey = ctx.data.apiKey; |
| 242 | return Option.filter( |
| 243 | stored, |
| 244 | identity => |
| 245 | Option.isNone(activeApiKey) || |
| 246 | Option.exists(activeApiKey, apiKey => isAgentIdentityForApiKey(identity, apiKey)) |
| 247 | ); |
| 248 | }); |
| 249 | |
| 250 | // --- flows ------------------------------------------------------------------------------------ |
| 251 | |
| 252 | /** |
| 253 | * `login --poll`: completes the browser login a headless `login` cached, waiting at most |
| 254 | * `--timeout` seconds. A wait that runs out leaves the cached login in place and fails with the |
| 255 | * status it saw, the URL, and the same command to run again. |
| 256 | */ |
| 257 | export const handlePollLogin = (params: Pick<LoginParams, 'noSkillInstall' | 'timeout'>) => |
| 258 | Effect.gen(function* () { |
| 259 | const ui = yield* TerminalUI; |
| 260 | const timeoutSeconds = yield* parsePollTimeout(params.timeout); |
| 261 | const pendingLoginSession = yield* PendingLoginSession; |
| 262 | const pendingLogin = yield* pendingLoginSession.read; |
| 263 | const result = yield* loginWithKey({ |
| 264 | key: pendingLogin.key, |
| 265 | noWait: false, |
| 266 | announce: false, |
| 267 | defaultToFirstOrg: true, |
| 268 | pending: { |
| 269 | loginUrl: pendingLogin.loginUrl, |
| 270 | resumeCommand: `${POLL_COMMAND} --timeout ${timeoutSeconds}`, |
| 271 | }, |
| 272 | timeoutSeconds, |
| 273 | }); |
| 274 | yield* pendingLoginSession.clear; |
| 275 | |
| 276 | const summary: PollLoginSummary = { |
| 277 | email: result.email, |
| 278 | defaultOrgId: result.orgId, |
| 279 | defaultOrgName: result.orgName, |
| 280 | organizations: result.organizations, |
| 281 | }; |
| 282 | const { canDecorate } = yield* ui.capabilities; |
| 283 | if (canDecorate) { |
| 284 | yield* ui.note(formatPollLoginComplete(summary), 'Login complete'); |
| 285 | } |
| 286 | yield* ui.output(formatPollLoginJson(summary), { force: true }); |
| 287 | yield* offerSkillInstall(params.noSkillInstall); |
| 288 | }); |
| 289 | |
| 290 | /** `login --agent`: logs in with the stored agent identity, signing one up when there is none. */ |
| 291 | const handleAgentLogin = (params: Pick<LoginParams, 'noSkillInstall'>) => |
| 292 | handleAgentAuthError( |
| 293 | Effect.gen(function* () { |
| 294 | yield* ensureAgentSignupAllowed; |
| 295 | const identity = yield* getOrSignupReadyAgent(); |
| 296 | yield* completeAgentLogin(identity); |
| 297 | yield* offerSkillInstall(params.noSkillInstall); |
| 298 | }) |
| 299 | ); |
| 300 | |
| 301 | /** `login --key`: completes the CLI session a `login --no-wait` printed. */ |
| 302 | export const handleSessionKeyLogin = ( |
| 303 | params: Pick<LoginParams, 'noWait' | 'noSkillInstall'> & { readonly key: string } |
| 304 | ) => |
| 305 | Effect.gen(function* () { |
| 306 | const ctx = yield* ComposioUserContext; |
| 307 | yield* loginWithKey({ |
| 308 | key: params.key, |
| 309 | noWait: params.noWait, |
| 310 | announce: true, |
| 311 | pending: { |
| 312 | loginUrl: loginUrlFor(ctx.data.webURL, params.key), |
| 313 | resumeCommand: `composio login --key ${params.key}`, |
| 314 | }, |
| 315 | }); |
| 316 | yield* offerSkillInstall(params.noSkillInstall); |
| 317 | }); |
| 318 | |
| 319 | /** `login --user-api-key [--org]`: stores a user API key without a browser. */ |
| 320 | export const handleDirectLogin = ( |
| 321 | params: Pick<LoginParams, 'org' | 'noSkillInstall'> & { readonly userApiKey: string } |
| 322 | ) => |
| 323 | Effect.gen(function* () { |
| 324 | const ctx = yield* ComposioUserContext; |
| 325 | const { userApiKey } = params; |
| 326 | const sessionInfo = yield* getSessionInfoByUserApiKey({ userApiKey }); |
| 327 | const homeOrg = sessionInfo.project.org; |
| 328 | |
| 329 | const selectedOrg = yield* Option.match( |
| 330 | Option.filter(params.org, requestedOrg => requestedOrg.length > 0), |
| 331 | { |
| 332 | onNone: () => Effect.succeed({ id: homeOrg.id, name: homeOrg.name ?? homeOrg.id }), |
| 333 | onSome: requestedOrg => findOrganization(userApiKey, requestedOrg), |
| 334 | } |
| 335 | ); |
| 336 | |
| 337 | yield* ctx.login( |
| 338 | userApiKey, |
| 339 | selectedOrg.id, |
| 340 | playgroundTestUserId(Option.some(sessionInfo), ctx.data.testUserId) |
| 341 | ); |
| 342 | yield* linkAnalyticsIdentityForOrg({ |
| 343 | apiKey: userApiKey, |
| 344 | orgId: selectedOrg.id, |
| 345 | knownIdentity: { orgId: homeOrg.id, orgMemberId: sessionInfo.org_member.id }, |
| 346 | }); |
| 347 | yield* primeConsumerConnectedToolkitsCacheInBackground({ orgId: selectedOrg.id }); |
| 348 | yield* emitLoginComplete({ |
| 349 | email: sessionInfo.org_member.email || undefined, |
| 350 | orgId: selectedOrg.id, |
| 351 | orgName: selectedOrg.name, |
| 352 | }); |
| 353 | yield* offerSkillInstall(params.noSkillInstall); |
| 354 | }); |
| 355 | |
| 356 | /** |
| 357 | * `login` with no direct-login flag: the browser login, unless the user is already logged in |
| 358 | * with an org. A headless run reuses a stored READY agent identity instead, but never signs |
| 359 | * one up for a human in a pipe; `--no-browser` and `--no-wait` opt out of that reuse, since |
| 360 | * both promise output (the printed URL, the session JSON) that it would replace. |
| 361 | */ |
| 362 | export const handleBrowserLogin = ( |
| 363 | params: Pick<LoginParams, 'noBrowser' | 'noWait' | 'yes' | 'noSkillInstall'> |
| 364 | ) => |
| 365 | Effect.gen(function* () { |
| 366 | const ui = yield* TerminalUI; |
| 367 | const ctx = yield* ComposioUserContext; |
| 368 | |
| 369 | if (ctx.isLoggedIn()) { |
| 370 | if (Option.isSome(ctx.data.orgId)) { |
| 371 | yield* ui.log.warn(ALREADY_LOGGED_IN_MESSAGE); |
| 372 | yield* ui.outro(ALREADY_LOGGED_IN_OUTRO); |
| 373 | return; |
| 374 | } |
| 375 | yield* ui.log.step(REAUTHENTICATING_MESSAGE); |
| 376 | } |
| 377 | |
| 378 | const storedAgent = yield* reusableStoredAgent(params.noBrowser || params.noWait); |
| 379 | yield* Option.match(storedAgent, { |
| 380 | onSome: identity => handleAgentAuthError(completeAgentLogin(identity)), |
| 381 | onNone: () => |
| 382 | browserLogin({ |
| 383 | scope: 'user', |
| 384 | noBrowser: params.noBrowser, |
| 385 | noWait: params.noWait, |
| 386 | skipOrgProjectPicker: params.yes, |
| 387 | }).pipe(Effect.andThen(offerSkillInstall(params.noSkillInstall || params.noWait))), |
| 388 | }); |
| 389 | }); |
| 390 | |
| 391 | // --- dispatch --------------------------------------------------------------------------------- |
| 392 | |
| 393 | /** |
| 394 | * Validates the flag combination and picks the flow. The checks run in a fixed order, so a |
| 395 | * command line with several mistakes reports the first one. |
| 396 | */ |
| 397 | const selectLoginFlow = (params: LoginParams) => { |
| 398 | const flags = { |
| 399 | key: Option.isSome(params.key), |
| 400 | userApiKey: Option.isSome(params.userApiKey), |
| 401 | org: Option.isSome(params.org), |
| 402 | browserOrSession: params.noBrowser || params.noWait, |
| 403 | poll: params.poll, |
| 404 | timeout: Option.isSome(params.timeout), |
| 405 | agent: params.agent, |
| 406 | }; |
| 407 | type Flags = typeof flags; |
| 408 | const reject = (message: string, option?: string) => |
| 409 | Effect.fail(invalidOptionValue(message, option)); |
| 410 | return Match.value(flags).pipe( |
| 411 | Match.when({ key: true, userApiKey: true }, () => reject(KEY_AND_USER_API_KEY_MESSAGE)), |
| 412 | Match.when( |
| 413 | (f: Flags) => f.poll && (f.browserOrSession || f.key || f.userApiKey || f.agent), |
| 414 | () => reject(POLL_WITH_OTHER_FLAGS_MESSAGE, '--poll') |
| 415 | ), |
| 416 | Match.when( |
| 417 | (f: Flags) => f.timeout && !f.poll, |
| 418 | () => reject(TIMEOUT_WITHOUT_POLL_MESSAGE, '--timeout') |
| 419 | ), |
| 420 | Match.when( |
| 421 | (f: Flags) => f.agent && (f.browserOrSession || f.key || f.userApiKey), |
| 422 | () => reject(AGENT_WITH_OTHER_FLAGS_MESSAGE, '--agent') |
| 423 | ), |
| 424 | Match.when({ org: true, userApiKey: false }, () => |
| 425 | reject(ORG_WITHOUT_USER_API_KEY_MESSAGE, '--org') |
| 426 | ), |
| 427 | Match.when({ userApiKey: true, browserOrSession: true }, () => |
| 428 | reject(USER_API_KEY_WITH_SESSION_FLAGS_MESSAGE, '--user-api-key') |
| 429 | ), |
| 430 | Match.when({ poll: true }, () => Effect.succeed(LoginFlow.Poll())), |
| 431 | Match.when({ agent: true }, () => Effect.succeed(LoginFlow.Agent())), |
| 432 | Match.orElse(() => |
| 433 | Effect.succeed( |
| 434 | pipe( |
| 435 | Option.map(params.key, key => LoginFlow.SessionKey({ key })), |
| 436 | Option.orElse(() => |
| 437 | Option.map(params.userApiKey, userApiKey => LoginFlow.Direct({ userApiKey })) |
| 438 | ), |
| 439 | Option.getOrElse(() => LoginFlow.Browser()) |
| 440 | ) |
| 441 | ) |
| 442 | ) |
| 443 | ); |
| 444 | }; |
| 445 | |
| 446 | /** `composio login`: validates the flag combination, then runs the flow it selects. */ |
| 447 | export const runLogin = (params: LoginParams) => |
| 448 | Effect.gen(function* () { |
| 449 | const ui = yield* TerminalUI; |
| 450 | const { canDecorate } = yield* ui.capabilities; |
| 451 | yield* Effect.when(ui.intro('composio login'), Effect.succeed(canDecorate)); |
| 452 | |
| 453 | const flow = yield* selectLoginFlow(params); |
| 454 | yield* Match.valueTags(flow, { |
| 455 | Poll: () => handlePollLogin(params), |
| 456 | Agent: () => handleAgentLogin(params), |
| 457 | SessionKey: ({ key }) => handleSessionKeyLogin({ ...params, key }), |
| 458 | Direct: ({ userApiKey }) => handleDirectLogin({ ...params, userApiKey }), |
| 459 | Browser: () => handleBrowserLogin(params), |
| 460 | }); |
| 461 | }); |