@devries-cameron20 / composio-1 / commits / 9b4a64e49
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.

refactor(cli): split `login` into per-flow handlers (#4929)

This PR: - moves the pending-login cache (`pending-login-session.json`) out of `login.cmd.ts` into a `PendingLoginSession` service (`src/services/pending-login-session.ts`) with a `Default` layer, wired into `cli-main.ts` and `TestLive`. `PendingLoginError` keeps its tag and messages; the TTL check now reads the Effect `Clock`, so tests drive it with `TestClock` - splits `login.cmd.ts` (1024 lines) into `login/login.{cmd,handler,format,errors}.ts`. `runLogin` validates the flag combination with one `Match.value` table, in the same order as before, then dispatches through `Match.valueTags` to five exported handlers: `handlePollLogin`, `handleAgentLogin`, `handleSessionKeyLogin`, `handleDirectLogin` and `handleBrowserLogin`. Each takes only the params it uses, so none re-checks an `Option` the dispatcher already resolved - moves the browser login (`browserLogin`, `storeCredentials`, `emitLoginComplete`, the org picker step and the shared poll spinner) to `src/effects/browser-login.ts`, since `dev init` runs it too. `init.cmd.ts` stops importing from `login`'s file and declares its own `--no-browser` flag, with the same description - moves `completeAgentLogin` to `src/effects/complete-agent-login.ts` and uses it from `agent login` as well, so `login --agent`, the headless agent reuse and `agent login` print one stdout payload - replaces the if-chains with `Option`/`Array` combinators and `Effect.when`. It also drops two unreachable branches: `loginWithKey`'s org picker, which no caller enabled, and `emitLoginComplete`'s `skipHints`, which was only set when nothing was printed - adds `login.handler.test.ts` (21 tests), `pending-login-session.test.ts` (5) and `agent/agent.login.cmd.test.ts` (4: the two `agent login` cases from `agent.cmd.test.ts`, plus a key the API rejects and an identity without credentials yet). It removes `agent.login` from `COMMAND_TEST_EXEMPTIONS` (16 to 15) ## Context This is unit U6 of the command-layout series. The plan said `agent login` reads the pending-login file. It does not: the file is written by `browserLogin` (`login` and `dev init`) and read only by `login --poll`. The service is still the right home, because two commands write it. What `agent login` does share with `login` is the agent completion step, so that is the part this PR makes common. The handler tests run without argv or `TestLive`. They use the `layers/accounts.ts` mock client resources, an in-memory `PendingLoginSession` double (`test/__utils__/layers/pending-login-session.ts`), and service doubles for the session repository and the user context. `test-layer.ts` only gains the `PendingLoginSession.Default` layer and its import. It builds on #4927 only in that it rebases on the extracted layers. No user-visible output changes, so there is no CHANGELOG entry. Evidence: - **Characterization:** `login/login.cmd.test.ts` (moved from `commands/login.cmd.test.ts`, unchanged) and `init.cmd.test.ts` pass on every commit. - **Validation order:** a 9-row table in the handler test pins each usage error, its `option`, and which check wins when two apply (for example `--key --user-api-key --poll` reports the pair, and `--poll --agent` reports `--poll`). - **Stdout payloads:** the `--poll` summary JSON, the `--key` and `--user-api-key` login JSON, and the `agent login` summary are asserted as exact strings. - **Mutation check:** turning off `announce` on the `--key` flow fails the handler test. - **Binary smoke:** `bun src/bin.ts` on this branch and on `origin/next` (32917664b), with an isolated `HOME`, telemetry off, stdin closed, and the backend and agents API pointed at `http://127.0.0.1:9`. - It runs 17 invocations: `login --help`, `agent login --help`, `dev init --help`, five usage errors, `--poll` with nothing cached, headless `login` and `login --no-wait`, `--key`, `--user-api-key`, `agent login` and `login --agent` against the unreachable backend, and `login` / `agent login` with a fake `COMPOSIO_USER_API_KEY`. - Help pages, stdout, exit codes and every message line match. The only differences are source locations inside defect stack traces (`login.cmd.ts:156` becomes `pending-login-session.ts:94`, and `cli-main.ts:288` becomes `:295`). The logged-in transcript needs a real account and was not run. Verified locally on the branch tip: | Check | Result | | --- | --- | | `pnpm typecheck` (root) | passes | | `pnpm --filter @composio/cli test` | 159 files, 1897 passed, 1 skipped | | `validate:command-tests` | 15 exemptions (was 16) | | `validate:boundaries` | unchanged, 5 registered disables | | `lint:effect` | 0 diagnostics | | `oxlint`, prettier on touched files | clean | ## Deferred - The other four `agent` commands stay in the legacy shape with their exemptions, for U9. - `init.cmd.ts` is still legacy-shaped. It now reaches the browser login through `src/effects/`, not through `login`. - The error tags `commands/PendingLoginError` and `commands/LoginSessionError` keep their `commands/` prefix even though the classes now live in `src/services/` and `src/effects/`. The tag shows up in the error banner, so renaming it would change output. - The bundled `composio-cli` skill refresh stays a follow-up PR. No `login` usage changes here.

Alberto Schiabel committed Oct 16, 2026 at 14:12 UTC 9b4a64e491bb35e3cb741a9c4307ccbc6de3b3f9
20 files changed +2045 -1085
ts/packages/cli/scripts/command-tests.ts
-1
@@ -20,7 +20,6 @@ const TEST_SUFFIX = '.cmd.test.ts';
20 export const COMMAND_TEST_EXEMPTIONS: readonly CommandTestExemption[] = [
21 { command: 'agent/commands/agent.claim.cmd.ts', reason: 'no test yet' },
22 { command: 'agent/commands/agent.inbox.cmd.ts', reason: 'no test yet' },
23 - { command: 'agent/commands/agent.login.cmd.ts', reason: 'no test yet' },
23 { command: 'agent/commands/agent.signup.cmd.ts', reason: 'no test yet' },
24 { command: 'agent/commands/agent.whoami.cmd.ts', reason: 'no test yet' },
25 { command: 'artifacts.cmd.ts', reason: 'no test yet' },
ts/packages/cli/src/cli-main.ts
+7
@@ -52,6 +52,7 @@ import { LogLevelFromConfigLive } from 'src/effects/with-log-level';
52 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
53 import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
54 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
55 +import { PendingLoginSession } from 'src/services/pending-login-session';
56 import { SetupCommandError } from 'src/services/setup-command-error';
57 import { ShellSetupAbortError } from 'src/commands/install.cmd';
58 import { isUsageFailure, type UsageFailure } from 'src/commands/errors';
@@ -127,6 +128,11 @@ export const SetupSkillInstallerLive = Layer.provide(
128 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
129 ) satisfies RequiredLayer;
130
131 +export const PendingLoginSessionLive = Layer.provide(
132 + PendingLoginSession.Default,
133 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
134 +) satisfies RequiredLayer;
135 +
136 const layers = Layer.mergeAll(
137 CliConfigLive.pipe(Layer.provide(LogLevelFromConfigLive)),
138 NodeOs.Default,
@@ -145,6 +151,7 @@ const layers = Layer.mergeAll(
151 SetupSkillInstallerLive,
152 TriggersRealtimeLive,
153 ProjectContextLive,
154 + PendingLoginSessionLive,
155 BunServices.layer,
156 BunFileSystem.layer,
157 BunPath.layer,
ts/packages/cli/src/commands/agent/commands/agent.login.cmd.ts
+2 -11
@@ -1,14 +1,12 @@
1 import { Effect } from 'effect';
2 import { Argument, Command } from 'effect/cli';
3 +import { completeAgentLogin } from 'src/effects/complete-agent-login';
4 import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
5 import {
6 ensureAgentSignupAllowed,
7 fetchAgentWhoami,
7 - loginWithAgentIdentity,
8 - safeAgentSummary,
8 writeStoredAgentIdentity,
9 } from 'src/services/agents';
11 -import { TerminalUI } from 'src/services/terminal-ui';
10
11 const composioAgentKey = Argument.String('composio_agent_key').pipe(
12 Argument.withDescription('Composio agent key for an existing agent identity')
@@ -19,17 +17,10 @@ export const agentCmd$Login = Command.make('login', { composioAgentKey }).pipe(
17 Command.withHandler(({ composioAgentKey }) =>
18 handleAgentAuthError(
19 Effect.gen(function* () {
22 - const ui = yield* TerminalUI;
23 -
20 yield* ensureAgentSignupAllowed;
25 -
21 const identity = yield* fetchAgentWhoami(composioAgentKey);
22 const saved = yield* writeStoredAgentIdentity(identity);
28 - yield* loginWithAgentIdentity(saved);
29 -
30 - const summary = safeAgentSummary(saved);
31 - yield* ui.log.success(`Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`);
32 - yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));
23 + yield* completeAgentLogin(saved);
24 })
25 )
26 )
ts/packages/cli/src/commands/index.ts
+1 -1
@@ -5,7 +5,7 @@ import { getVersion } from 'src/effects/version';
5 import { versionCmd } from './version.cmd';
6 import { upgradeCmd } from './upgrade.cmd';
7 import { whoamiCmd } from './whoami.cmd';
8 -import { loginCmd } from './login.cmd';
8 +import { loginCmd } from './login/login.cmd';
9 import { signupCmd } from './signup.cmd';
10 import { setupCmd } from './setup.cmd';
11 import { listenCmd } from './listen.cmd';
ts/packages/cli/src/commands/init.cmd.ts
+6 -1
@@ -18,7 +18,7 @@ import {
18 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
19 import * as constants from 'src/constants';
20 import { TerminalUI } from 'src/services/terminal-ui';
21 -import { browserLogin, noBrowser as noBrowserOpt } from 'src/commands/login.cmd';
21 +import { browserLogin } from 'src/effects/browser-login';
22 import { setupCacheDir } from 'src/effects/setup-cache-dir';
23 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
24 import {
@@ -41,6 +41,11 @@ import {
41 * - `--yes` / `-y` — auto-select the first project from the list
42 */
43
44 +const noBrowserOpt = Flag.Boolean('no-browser').pipe(
45 + Flag.withDefault(false),
46 + Flag.withDescription('Login without browser interaction')
47 +);
48 +
49 const yesOpt = Flag.Boolean('yes').pipe(
50 Flag.withAlias('y'),
51 Flag.withDefault(false),
ts/packages/cli/src/commands/login.cmd.ts deleted
-1024
@@ -1,1024 +0,0 @@
1 -import { commandInputError } from 'src/commands/errors';
2 -import { Command, Flag } from 'effect/cli';
3 -import * as FileSystem from 'effect/FileSystem';
4 -import * as Path from 'effect/Path';
5 -import { Data, DateTime, Effect, Option, Schedule, Schema } from 'effect';
6 -import open from 'open';
7 -import { ComposioSessionRepository } from 'src/services/composio-clients';
8 -import {
9 - getSessionInfo,
10 - getSessionInfoByUserApiKey,
11 - listOrganizations,
12 - sessionUserIdOf,
13 - type OrganizationSummary,
14 - type SessionInfoResponse,
15 -} from 'src/services/composio-account';
16 -import { ComposioUserContext } from 'src/services/user-context';
17 -import { TerminalUI } from 'src/services/terminal-ui';
18 -import { commandHintStep } from 'src/services/command-hints';
19 -import { runOrgSelection } from 'src/effects/select-org-project';
20 -import { linkAnalyticsIdentityForOrg } from 'src/effects/link-analytics-identity';
21 -import { setupCacheDir } from 'src/effects/setup-cache-dir';
22 -import { atomicWritePrivateFileString, ensurePrivateFileMode } from 'src/utils/atomic-write';
23 -import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
24 -import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';
25 -import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
26 -import { APP_VERSION } from 'src/constants';
27 -import {
28 - ensureAgentSignupAllowed,
29 - getOrSignupReadyAgent,
30 - getStoredReadyAgent,
31 - isAgentIdentityForApiKey,
32 - loginWithAgentIdentity,
33 - safeAgentSummary,
34 - type AgentIdentity,
35 -} from 'src/services/agents';
36 -
37 -export const noBrowser = Flag.Boolean('no-browser').pipe(
38 - Flag.withDefault(false),
39 - Flag.withDescription('Login without browser interaction')
40 -);
41 -
42 -const pollOpt = Flag.Boolean('poll').pipe(
43 - Flag.withDefault(false),
44 - Flag.withDescription('Poll the most recent pending browser login and complete it')
45 -);
46 -
47 -const noWait = Flag.Boolean('no-wait').pipe(
48 - Flag.withDefault(false),
49 - Flag.withDescription(
50 - 'Print login URL and session info, then exit without opening browser or waiting'
51 - )
52 -);
53 -
54 -const keyOpt = Flag.String('key').pipe(
55 - Flag.withDescription('Poll and complete login using the session key from composio login'),
56 - Flag.optional
57 -);
58 -
59 -const userApiKeyOpt = Flag.String('user-api-key').pipe(
60 - Flag.withDescription('Log in directly with a Composio user API key'),
61 - Flag.optional
62 -);
63 -
64 -const orgOpt = Flag.String('org').pipe(
65 - Flag.withDescription('Current organization ID or name to store for CLI commands'),
66 - Flag.optional
67 -);
68 -
69 -const yesOpt = Flag.Boolean('yes').pipe(
70 - Flag.withAlias('y'),
71 - Flag.withDefault(false),
72 - Flag.withDescription('Skip org picker; use current org')
73 -);
74 -
75 -const noSkillInstall = Flag.Boolean('no-skill-install').pipe(
76 - Flag.withDefault(false),
77 - Flag.withDescription('Skip installing the composio-cli skill for Claude Code')
78 -);
79 -
80 -const agentOpt = Flag.Boolean('agent').pipe(
81 - Flag.withDefault(false),
82 - Flag.withDescription('Sign up or log in using a Composio agent identity')
83 -);
84 -
85 -const PENDING_LOGIN_FILE_NAME = 'pending-login-session.json';
86 -const PENDING_LOGIN_TTL_MS = 10 * 60 * 1000;
87 -const LOGIN_POLL_INTERVAL_SECONDS = 5;
88 -const LOGIN_POLL_TIMEOUT_SECONDS = 10 * 60;
89 -const LOGIN_POLL_RETRIES = Math.ceil(LOGIN_POLL_TIMEOUT_SECONDS / LOGIN_POLL_INTERVAL_SECONDS);
90 -
91 -const PendingLoginSession = Schema.Struct({
92 - key: Schema.String,
93 - loginUrl: Schema.String,
94 - expiresAt: Schema.String,
95 - cachedAt: Schema.String,
96 -});
97 -type PendingLoginSession = Schema.Schema.Type<typeof PendingLoginSession>;
98 -
99 -class PendingLoginError extends Data.TaggedError('commands/PendingLoginError')<{
100 - readonly message: string;
101 - readonly reason: 'invalid' | 'io' | 'missing' | 'expired';
102 - readonly cause?: unknown;
103 -}> {}
104 -
105 -class LoginSessionError extends Data.TaggedError('commands/LoginSessionError')<{
106 - readonly message: string;
107 - readonly operation: 'load' | 'poll';
108 - readonly status?: string;
109 - readonly cause?: unknown;
110 -}> {}
111 -
112 -class LoginBrowserOpenError extends Data.TaggedError('commands/LoginBrowserOpenError')<{
113 - readonly message: string;
114 - readonly cause: unknown;
115 -}> {}
116 -
117 -class InvalidOrganizationError extends Data.TaggedError('commands/InvalidOrganizationError')<{
118 - readonly message: string;
119 - readonly requestedOrg: string;
120 -}> {}
121 -
122 -const invalidOptionValue = commandInputError('login');
123 -
124 -const pendingLoginPath = Effect.gen(function* () {
125 - const path = yield* Path.Path;
126 - const cacheDir = yield* setupCacheDir;
127 - return path.join(cacheDir, PENDING_LOGIN_FILE_NAME);
128 -});
129 -
130 -const writePendingLoginSession = (session: Omit<PendingLoginSession, 'cachedAt'>) =>
131 - Effect.gen(function* () {
132 - const fs = yield* FileSystem.FileSystem;
133 - const filePath = yield* pendingLoginPath;
134 - const payload: PendingLoginSession = {
135 - ...session,
136 - cachedAt: new Date().toISOString(),
137 - };
138 - yield* atomicWritePrivateFileString({
139 - fs,
140 - target: filePath,
141 - contents: `${JSON.stringify(payload, null, 2)}\n`,
142 - });
143 - });
144 -
145 -const clearPendingLoginSession = Effect.gen(function* () {
146 - const fs = yield* FileSystem.FileSystem;
147 - const filePath = yield* pendingLoginPath;
148 - yield* fs.remove(filePath).pipe(Effect.ignore);
149 -});
150 -
151 -const readPendingLoginSession = Effect.gen(function* () {
152 - const fs = yield* FileSystem.FileSystem;
153 - const filePath = yield* pendingLoginPath;
154 - const exists = yield* fs.exists(filePath);
155 - if (!exists) {
156 - return yield* new PendingLoginError({
157 - message: 'No pending login found. Run `composio login < /dev/null` first.',
158 - reason: 'missing',
159 - });
160 - }
161 -
162 - const rawSession = yield* ensurePrivateFileMode({ fs, target: filePath }).pipe(
163 - Effect.andThen(fs.readFileString(filePath, 'utf8')),
164 - Effect.mapError(
165 - cause =>
166 - new PendingLoginError({
167 - message: 'Failed to read pending login cache',
168 - reason: 'io',
169 - cause,
170 - })
171 - )
172 - );
173 - const session = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(PendingLoginSession))(
174 - rawSession
175 - ).pipe(
176 - Effect.mapError(
177 - cause =>
178 - new PendingLoginError({
179 - message: 'Pending login cache is invalid',
180 - reason: 'invalid',
181 - cause,
182 - })
183 - )
184 - );
185 - const cachedAt = Date.parse(session.cachedAt);
186 - if (!Number.isFinite(cachedAt) || Date.now() - cachedAt > PENDING_LOGIN_TTL_MS) {
187 - yield* clearPendingLoginSession;
188 - return yield* new PendingLoginError({
189 - message: 'Pending login expired. Run `composio login < /dev/null` again.',
190 - reason: 'expired',
191 - });
192 - }
193 -
194 - return session;
195 -});
196 -
197 -const formatNonInteractiveLoginInstructions = (params: {
198 - readonly loginUrl: string;
199 - readonly pollCommand: string;
200 -}) => `Open this URL in your browser to log in:
201 -
202 - ${params.loginUrl}
203 -
204 -Then run this command to complete login:
205 -
206 - ${params.pollCommand}
207 -
208 -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.
209 -
210 -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.`;
211 -
212 -const formatPollLoginComplete = (params: {
213 - readonly email?: string;
214 - readonly defaultOrgId: string;
215 - readonly defaultOrgName?: string;
216 - readonly organizations: ReadonlyArray<OrganizationSummary>;
217 -}) => {
218 - const orgLines =
219 - params.organizations.length > 0
220 - ? params.organizations
221 - .map(org => ` ${org.id === params.defaultOrgId ? '*' : '-'} ${org.name} (${org.id})`)
222 - .join('\n')
223 - : ' No organizations were returned for this account.';
224 -
225 - return `Login complete${params.email ? ` for ${params.email}` : ''}.
226 -
227 -Current org:
228 -
229 - ${params.defaultOrgName ?? params.defaultOrgId} (${params.defaultOrgId})
230 -
231 -Available organizations:
232 -
233 -${orgLines}
234 -
235 -The CLI selected the first organization as your current org. To choose a different current org, run:
236 -
237 - composio orgs switch --org-id <org_id>`;
238 -};
239 -
240 -const serializePollLoginResult = (params: {
241 - readonly email?: string;
242 - readonly defaultOrgId: string;
243 - readonly defaultOrgName?: string;
244 - readonly organizations: ReadonlyArray<OrganizationSummary>;
245 -}) =>
246 - JSON.stringify(
247 - {
248 - email: params.email ?? null,
249 - current_org: {
250 - id: params.defaultOrgId,
251 - name: params.defaultOrgName ?? params.defaultOrgId,
252 - },
253 - organizations: params.organizations.map(org => ({
254 - id: org.id,
255 - name: org.name,
256 - selected: org.id === params.defaultOrgId,
257 - })),
258 - switch_command: 'composio orgs switch --org-id <org_id>',
259 - },
260 - null,
261 - 2
262 - );
263 -
264 -const formatLoginSuccessMessage = (params: { email?: string; orgName?: string }): string => {
265 - const { email, orgName } = params;
266 - if (email && orgName) {
267 - return `Logged in as ${email} in "${orgName}"`;
268 - }
269 - if (email) {
270 - return `Logged in as ${email}`;
271 - }
272 - if (orgName) {
273 - return `Logged in successfully in "${orgName}"`;
274 - }
275 - return 'Logged in successfully';
276 -};
277 -
278 -const emitLoginComplete = (params: {
279 - email?: string;
280 - orgId: string;
281 - orgName?: string;
282 - skipHints?: boolean;
283 -}) =>
284 - Effect.gen(function* () {
285 - const ui = yield* TerminalUI;
286 - const { email, orgId, orgName, skipHints = false } = params;
287 -
288 - yield* ui.log.success(formatLoginSuccessMessage({ email, orgName }));
289 - if (!skipHints) {
290 - yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
291 - yield* ui.log.info(commandHintStep('Switch your current org', 'root.orgs.switch'));
292 - }
293 -
294 - yield* ui.output(
295 - JSON.stringify({
296 - email,
297 - org_id: orgId,
298 - org_name: orgName ?? '',
299 - })
300 - );
301 -
302 - if (!skipHints) {
303 - yield* ui.outro("You're all set!");
304 - }
305 - });
306 -
307 -const completeAgentLogin = (identity: AgentIdentity) =>
308 - Effect.gen(function* () {
309 - const ui = yield* TerminalUI;
310 - yield* loginWithAgentIdentity(identity);
311 - const summary = safeAgentSummary(identity);
312 - yield* ui.log.success(`Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`);
313 - yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));
314 - });
315 -
316 -const resolveDirectLoginOrganization = (params: {
317 - apiKey: string;
318 - requestedOrg?: string;
319 - fallbackOrgId: string;
320 - fallbackOrgName?: string;
321 -}) =>
322 - Effect.gen(function* () {
323 - const ui = yield* TerminalUI;
324 - const { apiKey, requestedOrg, fallbackOrgId, fallbackOrgName } = params;
325 -
326 - if (!requestedOrg) {
327 - return {
328 - id: fallbackOrgId,
329 - name: fallbackOrgName ?? fallbackOrgId,
330 - };
331 - }
332 -
333 - const organizations = yield* listOrganizations({ apiKey });
334 - const match = organizations.data.find(
335 - org => org.id === requestedOrg || org.name === requestedOrg
336 - );
337 -
338 - if (!match) {
339 - yield* ui.log.error(`Organization "${requestedOrg}" was not found for this API key.`);
340 - return yield* new InvalidOrganizationError({
341 - message: 'Invalid organization. Run `composio orgs list` to inspect available orgs.',
342 - requestedOrg,
343 - });
344 - }
345 -
346 - return match;
347 - });
348 -
349 -const directLogin = (params: { userApiKey: string; org?: string }) =>
350 - Effect.gen(function* () {
351 - const ctx = yield* ComposioUserContext;
352 - const sessionInfo = yield* getSessionInfoByUserApiKey({
353 - userApiKey: params.userApiKey,
354 - });
355 -
356 - const selectedOrg = yield* resolveDirectLoginOrganization({
357 - apiKey: params.userApiKey,
358 - requestedOrg: params.org,
359 - fallbackOrgId: sessionInfo.project.org.id,
360 - fallbackOrgName: sessionInfo.project.org.name,
361 - });
362 -
363 - const sessionUserId = sessionUserIdOf(sessionInfo);
364 - const testUserId = sessionUserId
365 - ? `pg-test-${sessionUserId}`
366 - : Option.getOrUndefined(ctx.data.testUserId);
367 -
368 - yield* ctx.login(params.userApiKey, selectedOrg.id, testUserId);
369 - yield* linkAnalyticsIdentityForOrg({
370 - apiKey: params.userApiKey,
371 - orgId: selectedOrg.id,
372 - knownIdentity: {
373 - orgId: sessionInfo.project.org.id,
374 - orgMemberId: sessionInfo.org_member.id,
375 - },
376 - });
377 - yield* primeConsumerConnectedToolkitsCacheInBackground({
378 - orgId: selectedOrg.id,
379 - });
380 - yield* emitLoginComplete({
381 - email: sessionInfo.org_member.email || undefined,
382 - orgId: selectedOrg.id,
383 - orgName: selectedOrg.name,
384 - });
385 - });
386 -
387 -/**
388 - * Verifies credentials via session/info and stores them.
389 - *
390 - * Resolves ComposioUserContext from the Effect context rather
391 - * than accepting them as parameters -- this keeps the signature focused on
392 - * data and avoids hand-rolled structural types.
393 - */
394 -const storeCredentials = (params: {
395 - uakApiKey: string;
396 - initialOrgId: string;
397 - initialProjectId: string;
398 - fallbackEmail: string;
399 - /** When true, skip the init/switch hints and outro (shown later after org picker). */
400 - skipHints?: boolean;
401 - /** When true, skip JSON output (emitted later after org picker with final selection). */
402 - skipOutput?: boolean;
403 - /** When true, wait to link analytics until the org picker has made its final selection. */
404 - deferAnalyticsIdentity?: boolean;
405 -}) =>
406 - Effect.gen(function* () {
407 - const ctx = yield* ComposioUserContext;
408 -
409 - const {
410 - uakApiKey,
411 - initialOrgId,
412 - initialProjectId,
413 - fallbackEmail,
414 - skipHints = false,
415 - skipOutput = false,
416 - deferAnalyticsIdentity = false,
417 - } = params;
418 -
419 - // Call session/info to enrich the login with org/project metadata.
420 - // All errors are non-fatal (browser login) since the linked session is already authenticated.
421 - const sessionInfo: SessionInfoResponse | undefined = yield* getSessionInfo({
422 - apiKey: uakApiKey,
423 - orgId: initialOrgId,
424 - projectId: initialProjectId,
425 - }).pipe(
426 - // Catch-all rather than per-tag: the linked session is already
427 - // authenticated, so no way this enrichment can fail may stop the
428 - // credential from being stored.
429 - Effect.catch(e =>
430 - Effect.gen(function* () {
431 - yield* Effect.logDebug('Session info fetch failed:', e);
432 - return undefined;
433 - })
434 - )
435 - );
436 -
437 - // Use session/info as the canonical source of org/project IDs when available.
438 - // The initial IDs come from the linked session response (which may use session-level
439 - // identifiers rather than the actual org/project IDs).
440 - const orgId = sessionInfo?.project.org.id ?? initialOrgId;
441 - const sessionUserId = sessionInfo ? sessionUserIdOf(sessionInfo) : undefined;
442 - const testUserId = sessionUserId
443 - ? `pg-test-${sessionUserId}`
444 - : Option.getOrUndefined(ctx.data.testUserId);
445 -
446 - if (sessionInfo) {
447 - if (initialOrgId !== orgId) {
448 - yield* Effect.logDebug(`orgId corrected: ${initialOrgId} -> ${orgId} (from session/info)`);
449 - }
450 - }
451 -
452 - yield* ctx.login(uakApiKey, orgId, testUserId);
453 - // Linked only after the credential persists, so stitching cannot outlive a failed login.
454 - if (!deferAnalyticsIdentity) {
455 - yield* linkAnalyticsIdentityForOrg({
456 - apiKey: uakApiKey,
457 - orgId,
458 - knownIdentity: sessionInfo
459 - ? {
460 - orgId: sessionInfo.project.org.id,
461 - orgMemberId: sessionInfo.org_member.id,
462 - }
463 - : undefined,
464 - });
465 - }
466 - yield* primeConsumerConnectedToolkitsCacheInBackground({
467 - orgId,
468 - });
469 -
470 - if (!skipOutput) {
471 - yield* emitLoginComplete({
472 - email: sessionInfo?.org_member.email || fallbackEmail || undefined,
473 - orgId,
474 - orgName: sessionInfo?.project.org.name || undefined,
475 - skipHints,
476 - });
477 - }
478 - });
479 -
480 -/**
481 - * Completes login using an existing session key (from composio login --no-wait).
482 - * Fetches the session, optionally polls until linked, then stores credentials.
483 - *
484 - * When noWait is false: polls until session is linked (same as browser flow).
485 - * When noWait is true: checks once and fails if not linked.
486 - */
487 -const loginWithKey = (params: {
488 - key: string;
489 - noWait: boolean;
490 - skipOrgProjectPicker: boolean;
491 - pollRetries?: number;
492 - defaultToFirstOrg?: boolean;
493 - skipOutput?: boolean;
494 -}) =>
495 - Effect.gen(function* () {
496 - const ui = yield* TerminalUI;
497 - const ctx = yield* ComposioUserContext;
498 - const client = yield* ComposioSessionRepository;
499 -
500 - const getSessionEffect = client.getSession({ id: params.key }).pipe(
501 - Effect.mapError(
502 - cause =>
503 - new LoginSessionError({
504 - message:
505 - 'Session not found or expired. Run `composio login --no-wait` to get a new session.',
506 - operation: 'load',
507 - cause,
508 - })
509 - )
510 - );
511 -
512 - let linkedSession;
513 - if (params.noWait) {
514 - const session = yield* getSessionEffect;
515 - if (session.status !== 'linked') {
516 - yield* ui.log.error('Login not complete. Open the URL and finish authentication.');
517 - yield* ui.log.info('Then run `composio login --key <key>` again.');
518 - return yield* new LoginSessionError({
519 - message: 'Session not yet linked',
520 - operation: 'poll',
521 - status: session.status,
522 - });
523 - }
524 - linkedSession = session;
525 - } else {
526 - linkedSession = yield* ui.useMakeSpinner('Waiting for login...', spinner =>
527 - Effect.retry(
528 - Effect.gen(function* () {
529 - const currentSession = yield* getSessionEffect;
530 - if (currentSession.status === 'linked') {
531 - return currentSession;
532 - }
533 - return yield* new LoginSessionError({
534 - message: `Session status is still '${currentSession.status}', waiting for 'linked'`,
535 - operation: 'poll',
536 - status: currentSession.status,
537 - });
538 - }),
539 - {
540 - // v4 dropped `Schedule.intersect`/`Schedule.recurs`; `Schedule.max` recurs while every
541 - // schedule in the list still wants to and waits for the slowest one between attempts
542 - // (the v4 equivalent of intersecting delay-producing schedules), and the retry count
543 - // cap moves onto `Effect.retry`'s own `times` option.
544 - schedule: Schedule.max([
545 - Schedule.exponential('0.3 seconds'),
546 - Schedule.spaced(`${LOGIN_POLL_INTERVAL_SECONDS} seconds`),
547 - ]),
548 - times: params.pollRetries ?? 15,
549 - }
550 - ).pipe(
551 - Effect.tap(() => spinner.stop('Login successful')),
552 - Effect.tapError(() => spinner.error('Login timed out. Please try again.'))
553 - )
554 - );
555 - }
556 - const uakApiKey = linkedSession.api_key;
557 -
558 - const uakSessionInfo = yield* getSessionInfoByUserApiKey({
559 - userApiKey: uakApiKey,
560 - });
561 -
562 - const organizations = params.defaultToFirstOrg
563 - ? yield* listOrganizations({
564 - apiKey: uakApiKey,
565 - }).pipe(
566 - Effect.map(response => response.data),
567 - Effect.catch(error =>
568 - Effect.gen(function* () {
569 - yield* Effect.logDebug('Failed to list organizations after login:', error);
570 - return [];
571 - })
572 - )
573 - )
574 - : [];
575 - const defaultOrg = params.defaultToFirstOrg ? organizations[0] : undefined;
576 - const xProjectId = uakSessionInfo.project.nano_id;
577 - const xOrgId = defaultOrg?.id ?? uakSessionInfo.project.org.id;
578 - const xOrgName = defaultOrg?.name ?? uakSessionInfo.project.org.name;
579 -
580 - const willRunPicker = !params.skipOrgProjectPicker;
581 - yield* storeCredentials({
582 - uakApiKey,
583 - initialOrgId: xOrgId,
584 - initialProjectId: xProjectId,
585 - fallbackEmail: linkedSession.account.email,
586 - skipHints: willRunPicker,
587 - skipOutput: true,
588 - deferAnalyticsIdentity: willRunPicker,
589 - });
590 -
591 - if (willRunPicker) {
592 - const result = yield* runOrgSelection({
593 - apiKey: uakApiKey,
594 - }).pipe(
595 - Effect.catch(error =>
596 - Effect.gen(function* () {
597 - yield* Effect.logDebug('Org picker failed:', error);
598 - yield* ui.log.warn('Could not load org list. Using current org.');
599 - return undefined;
600 - })
601 - )
602 - );
603 - if (result) {
604 - const sessionUserId = sessionUserIdOf(uakSessionInfo);
605 - const testUserId = sessionUserId ? `pg-test-${sessionUserId}` : undefined;
606 - yield* ctx.login(
607 - uakApiKey,
608 - result.id,
609 - testUserId ?? Option.getOrUndefined(ctx.data.testUserId)
610 - );
611 - yield* primeConsumerConnectedToolkitsCacheInBackground({
612 - orgId: result.id,
613 - });
614 - }
615 - const finalOrgId = result?.id ?? xOrgId;
616 - const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';
617 - yield* linkAnalyticsIdentityForOrg({
618 - apiKey: uakApiKey,
619 - orgId: finalOrgId,
620 - knownIdentity: {
621 - orgId: uakSessionInfo.project.org.id,
622 - orgMemberId: uakSessionInfo.org_member.id,
623 - },
624 - });
625 - yield* emitLoginComplete({
626 - email: linkedSession.account.email ?? undefined,
627 - orgId: finalOrgId,
628 - orgName: finalOrgName,
629 - });
630 - return {
631 - email: linkedSession.account.email ?? undefined,
632 - orgId: finalOrgId,
633 - orgName: finalOrgName,
634 - organizations,
635 - };
636 - }
637 -
638 - if (!params.skipOutput) {
639 - yield* emitLoginComplete({
640 - email: linkedSession.account.email ?? undefined,
641 - orgId: xOrgId,
642 - orgName: xOrgName,
643 - });
644 - }
645 -
646 - return {
647 - email: linkedSession.account.email ?? undefined,
648 - orgId: xOrgId,
649 - orgName: xOrgName,
650 - organizations,
651 - };
652 - });
653 -
654 -/**
655 - * Runs the browser-based login flow: creates a CLI session, opens the browser,
656 - * polls until linked, enriches via session/info, and stores credentials.
657 - *
658 - * Shared by `composio login` (scope: 'user') and `composio init` (scope: 'project').
659 - *
660 - * Resolves TerminalUI, ComposioUserContext, and ComposioSessionRepository
661 - * from the Effect context.
662 - */
663 -export const browserLogin = (params: {
664 - /** Session scope: 'user' for login, 'project' for init. */
665 - scope: 'user' | 'project';
666 - /** When true, don't open browser — just show the URL. */
667 - noBrowser: boolean;
668 - /** When true, print URL/session info and exit without waiting (implies noBrowser). */
669 - noWait?: boolean;
670 - /** When true (login only), skip org/project picker and use session defaults. When false, prompt for org/project. */
671 - skipOrgProjectPicker?: boolean;
672 -}) =>
673 - Effect.gen(function* () {
674 - const ui = yield* TerminalUI;
675 - const ctx = yield* ComposioUserContext;
676 - const client = yield* ComposioSessionRepository;
677 -
678 - yield* Effect.logDebug(`Authenticating (scope: ${params.scope})...`);
679 -
680 - const session = yield* client.createSession({ scope: params.scope });
681 -
682 - yield* Effect.logDebug(`Created session: ${session.id}`);
683 -
684 - const url = `${ctx.data.webURL}?cliKey=${session.id}`;
685 - const pollCommand = 'composio login --poll';
686 - const expiresAt = DateTime.formatIso(session.expiresAt);
687 - yield* writePendingLoginSession({
688 - key: session.id,
689 - loginUrl: url,
690 - expiresAt,
691 - });
692 -
693 - const { canPrompt, canDecorate } = yield* ui.capabilities;
694 - const effectiveNoWait = params.noWait || !canPrompt;
695 - const effectiveNoBrowser = params.noBrowser || effectiveNoWait;
696 -
697 - if (effectiveNoWait) {
698 - const loginInstructions = formatNonInteractiveLoginInstructions({
699 - loginUrl: url,
700 - pollCommand,
701 - });
702 -
703 - if (canDecorate) {
704 - yield* ui.log.info('Please login using the following URL:');
705 - yield* ui.note(url, 'Login URL');
706 - yield* ui.note(loginInstructions, 'Login instructions');
707 - }
708 -
709 - yield* ui.output(loginInstructions);
710 - return;
711 - }
712 -
713 - if (effectiveNoBrowser) {
714 - yield* ui.log.info('Please login using the following URL:');
715 - } else {
716 - yield* ui.log.step('Redirecting you to the login page');
717 - }
718 -
719 - yield* ui.note(url, 'Login URL');
720 -
721 - yield* ui.output(url);
722 -
723 - if (!effectiveNoBrowser) {
724 - yield* Effect.tryPromise({
725 - try: () => open(url, { wait: false }),
726 - catch: cause =>
727 - new LoginBrowserOpenError({ message: 'Failed to open the browser.', cause }),
728 - }).pipe(
729 - Effect.catchTag('commands/LoginBrowserOpenError', error =>
730 - Effect.gen(function* () {
731 - yield* Effect.logDebug('Failed to open browser:', error);
732 - yield* ui.log.warn('Could not open the browser automatically.');
733 - yield* ui.log.info(
734 - `Tip: try using the \`--no-browser\` flag and open the URL manually.`
735 - );
736 - })
737 - )
738 - );
739 - }
740 -
741 - const linkedSession = yield* ui.useMakeSpinner('Waiting for login...', spinner =>
742 - Effect.retry(
743 - Effect.gen(function* () {
744 - const currentSession = yield* client.getSession({ ...session });
745 - if (currentSession.status === 'linked') {
746 - return currentSession;
747 - }
748 - return yield* new LoginSessionError({
749 - message: `Session status is still '${currentSession.status}', waiting for 'linked'`,
750 - operation: 'poll',
751 - status: currentSession.status,
752 - });
753 - }),
754 - {
755 - schedule: Schedule.max([
756 - Schedule.exponential('0.3 seconds'),
757 - Schedule.spaced('5 seconds'),
758 - ]),
759 - times: 15,
760 - }
761 - ).pipe(
762 - Effect.tap(() => spinner.stop('Login successful')),
763 - Effect.tapError(() => spinner.error('Login timed out. Please try again.'))
764 - )
765 - );
766 -
767 - yield* Effect.logDebug(`Linked session ID: ${linkedSession.id}`);
768 -
769 - // e.g., "uak_b813ydmoEYdB_xBxGHeW"
770 - const uakApiKey = linkedSession.api_key;
771 -
772 - const uakSessionInfo = yield* getSessionInfoByUserApiKey({
773 - userApiKey: uakApiKey,
774 - });
775 -
776 - // e.g., "pr_xlSR6oN5jIlk"
777 - const xProjectId = uakSessionInfo.project.nano_id;
778 - // e.g., "k2OiqRLMdHyM"
779 - const xOrgId = uakSessionInfo.project.org.id;
780 -
781 - yield* Effect.logDebug('UAK session info:', { xProjectId, xOrgId });
782 -
783 - const willRunPicker = params.scope === 'user' && !params.skipOrgProjectPicker;
784 - yield* storeCredentials({
785 - uakApiKey,
786 - initialOrgId: xOrgId,
787 - initialProjectId: xProjectId,
788 - fallbackEmail: linkedSession.account.email,
789 - skipHints: willRunPicker,
790 - skipOutput: willRunPicker,
791 - deferAnalyticsIdentity: willRunPicker,
792 - });
793 -
794 - if (willRunPicker) {
795 - const result = yield* runOrgSelection({
796 - apiKey: uakApiKey,
797 - }).pipe(
798 - Effect.catch(error =>
799 - Effect.gen(function* () {
800 - yield* Effect.logDebug('Org picker failed:', error);
801 - yield* ui.log.warn('Could not load org list. Using current org.');
802 - return undefined;
803 - })
804 - )
805 - );
806 - if (result) {
807 - const sessionUserId = sessionUserIdOf(uakSessionInfo);
808 - const testUserId = sessionUserId ? `pg-test-${sessionUserId}` : undefined;
809 - yield* ctx.login(
810 - uakApiKey,
811 - result.id,
812 - testUserId ?? Option.getOrUndefined(ctx.data.testUserId)
813 - );
814 - yield* primeConsumerConnectedToolkitsCacheInBackground({
815 - orgId: result.id,
816 - });
817 - }
818 - const finalOrgId = result?.id ?? xOrgId;
819 - const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';
820 - yield* linkAnalyticsIdentityForOrg({
821 - apiKey: uakApiKey,
822 - orgId: finalOrgId,
823 - knownIdentity: {
824 - orgId: uakSessionInfo.project.org.id,
825 - orgMemberId: uakSessionInfo.org_member.id,
826 - },
827 - });
828 - yield* emitLoginComplete({
829 - email: linkedSession.account.email ?? undefined,
830 - orgId: finalOrgId,
831 - orgName: finalOrgName,
832 - });
833 - }
834 - });
835 -
836 -/**
837 - * CLI command to login using Composio's CLI session APIs.
838 - *
839 - * Browser-based: Opens browser for OAuth flow (default).
840 - * Use --no-browser to skip auto-opening the browser and print the URL instead.
841 - * Use --no-wait to print login URL and session info (JSON) then exit without opening browser or waiting.
842 - * Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;
843 - * with --no-wait, checks once and fails if not linked.
844 - * Use --user-api-key to log in directly without a browser flow, and --org to override the current org.
845 - * Use --agent to sign up or log in using a Composio agent identity.
846 - * Use -y to skip org picker and use current org.
847 - *
848 - * Non-interactive default flow: prints URL + poll instructions, or logs in
849 - * unattended when a READY agent identity is already stored.
850 - *
851 - * @example
852 - * ```bash
853 - * composio login
854 - * composio login --no-browser
855 - * composio login --no-wait
856 - * composio login --key <key>
857 - * composio login --key <key> --no-wait
858 - * composio login --user-api-key <uak>
859 - * composio login --user-api-key <uak> --org <org>
860 - * composio login --agent
861 - * composio login -y
862 - * ```
863 - */
864 -export const loginCmd = Command.make(
865 - 'login',
866 - {
867 - noBrowser,
868 - poll: pollOpt,
869 - noWait,
870 - key: keyOpt,
871 - userApiKey: userApiKeyOpt,
872 - org: orgOpt,
873 - yes: yesOpt,
874 - noSkillInstall,
875 - agent: agentOpt,
876 - },
877 - ({ noBrowser, poll, noWait, key, userApiKey, org, yes, noSkillInstall, agent }) =>
878 - Effect.gen(function* () {
879 - const ui = yield* TerminalUI;
880 - const ctx = yield* ComposioUserContext;
881 - const { canPrompt, canDecorate } = yield* ui.capabilities;
882 -
883 - if (canDecorate) {
884 - yield* ui.intro('composio login');
885 - }
886 -
887 - if (Option.isSome(key) && Option.isSome(userApiKey)) {
888 - return yield* invalidOptionValue('Use either `--key` or `--user-api-key`, not both.');
889 - }
890 -
891 - const hasBrowserOrSessionFlag = noBrowser || noWait;
892 - const hasDirectLoginFlag = Option.isSome(key) || Option.isSome(userApiKey);
893 -
894 - if (poll && (hasBrowserOrSessionFlag || hasDirectLoginFlag || agent)) {
895 - return yield* invalidOptionValue(
896 - '`--poll` cannot be combined with browser, session, direct-login, or agent flags.',
897 - '--poll'
898 - );
899 - }
900 -
901 - if (agent && (hasBrowserOrSessionFlag || hasDirectLoginFlag)) {
902 - return yield* invalidOptionValue(
903 - '`--agent` cannot be combined with browser, session, or direct-login flags.',
904 - '--agent'
905 - );
906 - }
907 -
908 - if (Option.isSome(org) && Option.isNone(userApiKey)) {
909 - return yield* invalidOptionValue('`--org` requires `--user-api-key`.', '--org');
910 - }
911 -
912 - if (Option.isSome(userApiKey) && (hasBrowserOrSessionFlag || Option.isSome(key))) {
913 - return yield* invalidOptionValue(
914 - '`--user-api-key` is a direct login path and cannot be combined with browser or session flags.',
915 - '--user-api-key'
916 - );
917 - }
918 -
919 - if (poll) {
920 - const pendingLogin = yield* readPendingLoginSession;
921 - const loginResult = yield* loginWithKey({
922 - key: pendingLogin.key,
923 - noWait: false,
924 - skipOrgProjectPicker: true,
925 - pollRetries: LOGIN_POLL_RETRIES,
926 - defaultToFirstOrg: true,
927 - skipOutput: true,
928 - });
929 - yield* clearPendingLoginSession;
930 - const pollSummaryParams = {
931 - email: loginResult.email,
932 - defaultOrgId: loginResult.orgId,
933 - defaultOrgName: loginResult.orgName,
934 - organizations: loginResult.organizations,
935 - };
936 - const pollSummary = formatPollLoginComplete(pollSummaryParams);
937 - if (canDecorate) {
938 - yield* ui.note(pollSummary, 'Login complete');
939 - }
940 - yield* ui.output(serializePollLoginResult(pollSummaryParams), { force: true });
941 - if (!noSkillInstall && canPrompt) {
942 - yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
943 - }
944 - return;
945 - }
946 -
947 - if (agent) {
948 - return yield* handleAgentAuthError(
949 - Effect.gen(function* () {
950 - yield* ensureAgentSignupAllowed;
951 - const identity = yield* getOrSignupReadyAgent();
952 - yield* completeAgentLogin(identity);
953 - if (!noSkillInstall && canPrompt) {
954 - yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
955 - }
956 - })
957 - );
958 - }
959 -
960 - if (Option.isSome(key)) {
961 - yield* loginWithKey({
962 - key: key.value,
963 - noWait,
964 - skipOrgProjectPicker: true,
965 - });
966 - if (!noSkillInstall && canPrompt) {
967 - yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
968 - }
969 - return;
970 - }
971 -
972 - if (Option.isSome(userApiKey)) {
973 - yield* directLogin({
974 - userApiKey: userApiKey.value,
975 - org: Option.getOrUndefined(org),
976 - });
977 - if (!noSkillInstall && canPrompt) {
978 - yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
979 - }
980 - return;
981 - }
982 -
983 - if (ctx.isLoggedIn()) {
984 - if (Option.isSome(ctx.data.orgId)) {
985 - yield* ui.log.warn(`You're already logged in!`);
986 - yield* ui.outro(
987 - 'If you want to log in with a different account, please run `composio logout` first.'
988 - );
989 - return;
990 - }
991 - yield* ui.log.step('Re-authenticating for multi-project support...');
992 - }
993 -
994 - // Reuse-only by design: headless login may complete with an existing
995 - // agent identity but must never auto-create one for a human in a pipe.
996 - // `--no-browser` and `--no-wait` opt out: both promise a specific output
997 - // contract (printed URL, session JSON) that silent agent reuse would replace.
998 - const requestedExplicitLoginFlow = noBrowser || noWait;
999 - if (!canPrompt && !requestedExplicitLoginFlow) {
1000 - const storedAgent = yield* getStoredReadyAgent;
1001 - if (Option.isSome(storedAgent)) {
1002 - const identity = storedAgent.value;
1003 - const activeApiKey = ctx.data.apiKey;
1004 - if (
1005 - Option.isNone(activeApiKey) ||
1006 - isAgentIdentityForApiKey(identity, activeApiKey.value)
1007 - ) {
1008 - return yield* handleAgentAuthError(completeAgentLogin(identity));
1009 - }
1010 - }
1011 - }
1012 -
1013 - yield* browserLogin({
1014 - scope: 'user',
1015 - noBrowser,
1016 - noWait,
1017 - skipOrgProjectPicker: yes,
1018 - });
1019 -
1020 - if (!noSkillInstall && !noWait && canPrompt) {
1021 - yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
1022 - }
1023 - })
1024 -).pipe(Command.withDescription('Log in to the Composio SDK.'));
ts/packages/cli/src/commands/login/login.cmd.ts new
+94
@@ -0,0 +1,94 @@
1 +import { Command, Flag } from 'effect/cli';
2 +import { runLogin } from './login.handler';
3 +
4 +const noBrowser = Flag.Boolean('no-browser').pipe(
5 + Flag.withDefault(false),
6 + Flag.withDescription('Login without browser interaction')
7 +);
8 +
9 +const pollOpt = Flag.Boolean('poll').pipe(
10 + Flag.withDefault(false),
11 + Flag.withDescription('Poll the most recent pending browser login and complete it')
12 +);
13 +
14 +const noWait = Flag.Boolean('no-wait').pipe(
15 + Flag.withDefault(false),
16 + Flag.withDescription(
17 + 'Print login URL and session info, then exit without opening browser or waiting'
18 + )
19 +);
20 +
21 +const keyOpt = Flag.String('key').pipe(
22 + Flag.withDescription('Poll and complete login using the session key from composio login'),
23 + Flag.optional
24 +);
25 +
26 +const userApiKeyOpt = Flag.String('user-api-key').pipe(
27 + Flag.withDescription('Log in directly with a Composio user API key'),
28 + Flag.optional
29 +);
30 +
31 +const orgOpt = Flag.String('org').pipe(
32 + Flag.withDescription('Current organization ID or name to store for CLI commands'),
33 + Flag.optional
34 +);
35 +
36 +const yesOpt = Flag.Boolean('yes').pipe(
37 + Flag.withAlias('y'),
38 + Flag.withDefault(false),
39 + Flag.withDescription('Skip org picker; use current org')
40 +);
41 +
42 +const noSkillInstall = Flag.Boolean('no-skill-install').pipe(
43 + Flag.withDefault(false),
44 + Flag.withDescription('Skip installing the composio-cli skill for Claude Code')
45 +);
46 +
47 +const agentOpt = Flag.Boolean('agent').pipe(
48 + Flag.withDefault(false),
49 + Flag.withDescription('Sign up or log in using a Composio agent identity')
50 +);
51 +
52 +/**
53 + * CLI command to login using Composio's CLI session APIs.
54 + *
55 + * Browser-based: Opens browser for OAuth flow (default).
56 + * Use --no-browser to skip auto-opening the browser and print the URL instead.
57 + * Use --no-wait to print login URL and session info (JSON) then exit without opening browser or waiting.
58 + * Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;
59 + * with --no-wait, checks once and fails if not linked.
60 + * Use --user-api-key to log in directly without a browser flow, and --org to override the current org.
61 + * Use --agent to sign up or log in using a Composio agent identity.
62 + * Use -y to skip org picker and use current org.
63 + *
64 + * Non-interactive default flow: prints URL + poll instructions, or logs in
65 + * unattended when a READY agent identity is already stored.
66 + *
67 + * @example
68 + * ```bash
69 + * composio login
70 + * composio login --no-browser
71 + * composio login --no-wait
72 + * composio login --key <key>
73 + * composio login --key <key> --no-wait
74 + * composio login --user-api-key <uak>
75 + * composio login --user-api-key <uak> --org <org>
76 + * composio login --agent
77 + * composio login -y
78 + * ```
79 + */
80 +export const loginCmd = Command.make(
81 + 'login',
82 + {
83 + noBrowser,
84 + poll: pollOpt,
85 + noWait,
86 + key: keyOpt,
87 + userApiKey: userApiKeyOpt,
88 + org: orgOpt,
89 + yes: yesOpt,
90 + noSkillInstall,
91 + agent: agentOpt,
92 + },
93 + runLogin
94 +).pipe(Command.withDescription('Log in to the Composio SDK.'));
ts/packages/cli/src/commands/login/login.errors.ts new
+9
@@ -0,0 +1,9 @@
1 +import { Data } from 'effect';
2 +
3 +/** `--org` names no organization the user API key can see. */
4 +export class InvalidOrganizationError extends Data.TaggedError(
5 + 'commands/InvalidOrganizationError'
6 +)<{
7 + readonly message: string;
8 + readonly requestedOrg: string;
9 +}> {}
ts/packages/cli/src/commands/login/login.format.ts new
+88
@@ -0,0 +1,88 @@
1 +import { Array as Arr } from 'effect';
2 +import type { OrganizationSummary } from 'src/services/composio-account';
3 +
4 +// --- usage messages ---------------------------------------------------------------------------
5 +
6 +export const KEY_AND_USER_API_KEY_MESSAGE = 'Use either `--key` or `--user-api-key`, not both.';
7 +export const POLL_WITH_OTHER_FLAGS_MESSAGE =
8 + '`--poll` cannot be combined with browser, session, direct-login, or agent flags.';
9 +export const AGENT_WITH_OTHER_FLAGS_MESSAGE =
10 + '`--agent` cannot be combined with browser, session, or direct-login flags.';
11 +export const ORG_WITHOUT_USER_API_KEY_MESSAGE = '`--org` requires `--user-api-key`.';
12 +export const USER_API_KEY_WITH_SESSION_FLAGS_MESSAGE =
13 + '`--user-api-key` is a direct login path and cannot be combined with browser or session flags.';
14 +
15 +// --- stderr -----------------------------------------------------------------------------------
16 +
17 +export const ALREADY_LOGGED_IN_MESSAGE = `You're already logged in!`;
18 +export const ALREADY_LOGGED_IN_OUTRO =
19 + 'If you want to log in with a different account, please run `composio logout` first.';
20 +export const REAUTHENTICATING_MESSAGE = 'Re-authenticating for multi-project support...';
21 +
22 +export const SESSION_NOT_FOUND_MESSAGE =
23 + 'Session not found or expired. Run `composio login --no-wait` to get a new session.';
24 +export const SESSION_NOT_LINKED_MESSAGE =
25 + 'Login not complete. Open the URL and finish authentication.';
26 +export const SESSION_NOT_LINKED_HINT = 'Then run `composio login --key <key>` again.';
27 +
28 +export const organizationNotFoundMessage = (requestedOrg: string) =>
29 + `Organization "${requestedOrg}" was not found for this API key.`;
30 +export const INVALID_ORGANIZATION_MESSAGE =
31 + 'Invalid organization. Run `composio orgs list` to inspect available orgs.';
32 +
33 +/** What `composio login --poll` completed: the account, its current org, and the others. */
34 +export type PollLoginSummary = {
35 + readonly email?: string;
36 + readonly defaultOrgId: string;
37 + readonly defaultOrgName?: string;
38 + readonly organizations: ReadonlyArray<OrganizationSummary>;
39 +};
40 +
41 +const SWITCH_ORG_COMMAND = 'composio orgs switch --org-id <org_id>';
42 +
43 +/** The note `composio login --poll` prints once the login completes. */
44 +export const formatPollLoginComplete = (summary: PollLoginSummary) => {
45 + const orgLines = Arr.match(summary.organizations, {
46 + onEmpty: () => ' No organizations were returned for this account.',
47 + onNonEmpty: organizations =>
48 + organizations
49 + .map(org => ` ${org.id === summary.defaultOrgId ? '*' : '-'} ${org.name} (${org.id})`)
50 + .join('\n'),
51 + });
52 +
53 + return `Login complete${summary.email ? ` for ${summary.email}` : ''}.
54 +
55 +Current org:
56 +
57 + ${summary.defaultOrgName ?? summary.defaultOrgId} (${summary.defaultOrgId})
58 +
59 +Available organizations:
60 +
61 +${orgLines}
62 +
63 +The CLI selected the first organization as your current org. To choose a different current org, run:
64 +
65 + ${SWITCH_ORG_COMMAND}`;
66 +};
67 +
68 +// --- stdout -----------------------------------------------------------------------------------
69 +
70 +/** The stdout payload of `composio login --poll`. */
71 +export const formatPollLoginJson = (summary: PollLoginSummary) =>
72 + JSON.stringify(
73 + {
74 + email: summary.email ?? null,
75 + current_org: {
76 + id: summary.defaultOrgId,
77 + name: summary.defaultOrgName ?? summary.defaultOrgId,
78 + },
79 + organizations: summary.organizations.map(org => ({
80 + id: org.id,
81 + name: org.name,
82 + selected: org.id === summary.defaultOrgId,
83 + })),
84 + switch_command: SWITCH_ORG_COMMAND,
85 + },
86 + null,
87 + 2
88 + );
ts/packages/cli/src/commands/login/login.handler.ts new
+410
@@ -0,0 +1,410 @@
1 +import { Array as Arr, Data, Effect, Match, Option, pipe } from 'effect';
2 +import { commandInputError } from 'src/commands/errors';
3 +import { APP_VERSION } from 'src/constants';
4 +import {
5 + browserLogin,
6 + emitLoginComplete,
7 + LOGIN_POLL_INTERVAL_SECONDS,
8 + LoginSessionError,
9 + playgroundTestUserId,
10 + storeCredentials,
11 + waitForLinkedSession,
12 +} from 'src/effects/browser-login';
13 +import type { RetrievedSession } from 'src/models/session';
14 +import { completeAgentLogin } from 'src/effects/complete-agent-login';
15 +import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
16 +import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';
17 +import { linkAnalyticsIdentityForOrg } from 'src/effects/link-analytics-identity';
18 +import {
19 + ensureAgentSignupAllowed,
20 + getOrSignupReadyAgent,
21 + getStoredReadyAgent,
22 + isAgentIdentityForApiKey,
23 + type AgentIdentity,
24 +} from 'src/services/agents';
25 +import {
26 + getSessionInfoByUserApiKey,
27 + listOrganizations,
28 + type OrganizationSummary,
29 +} from 'src/services/composio-account';
30 +import { ComposioSessionRepository } from 'src/services/composio-clients';
31 +import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
32 +import { PendingLoginSession } from 'src/services/pending-login-session';
33 +import { TerminalUI } from 'src/services/terminal-ui';
34 +import { ComposioUserContext } from 'src/services/user-context';
35 +import { InvalidOrganizationError } from './login.errors';
36 +import {
37 + AGENT_WITH_OTHER_FLAGS_MESSAGE,
38 + ALREADY_LOGGED_IN_MESSAGE,
39 + ALREADY_LOGGED_IN_OUTRO,
40 + INVALID_ORGANIZATION_MESSAGE,
41 + KEY_AND_USER_API_KEY_MESSAGE,
42 + ORG_WITHOUT_USER_API_KEY_MESSAGE,
43 + POLL_WITH_OTHER_FLAGS_MESSAGE,
44 + REAUTHENTICATING_MESSAGE,
45 + SESSION_NOT_FOUND_MESSAGE,
46 + SESSION_NOT_LINKED_HINT,
47 + SESSION_NOT_LINKED_MESSAGE,
48 + USER_API_KEY_WITH_SESSION_FLAGS_MESSAGE,
49 + formatPollLoginComplete,
50 + formatPollLoginJson,
51 + organizationNotFoundMessage,
52 + type PollLoginSummary,
53 +} from './login.format';
54 +
55 +/** The flags of `composio login`. */
56 +export type LoginParams = {
57 + readonly noBrowser: boolean;
58 + readonly poll: boolean;
59 + readonly noWait: boolean;
60 + readonly key: Option.Option<string>;
61 + readonly userApiKey: Option.Option<string>;
62 + readonly org: Option.Option<string>;
63 + readonly yes: boolean;
64 + readonly noSkillInstall: boolean;
65 + readonly agent: boolean;
66 +};
67 +
68 +/** The five ways `login` can complete; the flags pick one. */
69 +type LoginFlow = Data.TaggedEnum<{
70 + Poll: Record<never, never>;
71 + Agent: Record<never, never>;
72 + SessionKey: { readonly key: string };
73 + Direct: { readonly userApiKey: string };
74 + Browser: Record<never, never>;
75 +}>;
76 +const LoginFlow = Data.taggedEnum<LoginFlow>();
77 +
78 +const LOGIN_POLL_TIMEOUT_SECONDS = 10 * 60;
79 +/** `--poll` keeps checking for the pending login's whole TTL. */
80 +const LOGIN_POLL_RETRIES = Math.ceil(LOGIN_POLL_TIMEOUT_SECONDS / LOGIN_POLL_INTERVAL_SECONDS);
81 +
82 +const invalidOptionValue = commandInputError('login');
83 +
84 +// --- shared steps -----------------------------------------------------------------------------
85 +
86 +/** Installs the composio-cli skill after a login, unless skipped or nobody can answer a prompt. */
87 +const offerSkillInstall = (skip: boolean) =>
88 + Effect.gen(function* () {
89 + const ui = yield* TerminalUI;
90 + const { canPrompt } = yield* ui.capabilities;
91 + yield* Effect.when(
92 + installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) }),
93 + Effect.succeed(canPrompt && !skip)
94 + );
95 + });
96 +
97 +/** The session, or a failure after telling the user to finish the browser step first. */
98 +const requireLinkedNow = (session: RetrievedSession) =>
99 + Effect.gen(function* () {
100 + const ui = yield* TerminalUI;
101 + if (session.status === 'linked') {
102 + return session;
103 + }
104 + yield* ui.log.error(SESSION_NOT_LINKED_MESSAGE);
105 + yield* ui.log.info(SESSION_NOT_LINKED_HINT);
106 + return yield* new LoginSessionError({
107 + message: 'Session not yet linked',
108 + operation: 'poll',
109 + status: session.status,
110 + });
111 + });
112 +
113 +/**
114 + * Completes the CLI session behind `key`: checks it once (`noWait`) or waits until it is
115 + * linked, then stores its user API key. With `defaultToFirstOrg`, the first of the account's
116 + * organizations becomes the current org. Reports the login only when `announce`.
117 + */
118 +const loginWithKey = (params: {
119 + readonly key: string;
120 + readonly noWait: boolean;
121 + readonly announce: boolean;
122 + readonly pollRetries?: number;
123 + readonly defaultToFirstOrg?: boolean;
124 +}) =>
125 + Effect.gen(function* () {
126 + const client = yield* ComposioSessionRepository;
127 + const getSession = client
128 + .getSession({ id: params.key })
129 + .pipe(
130 + Effect.mapError(
131 + cause =>
132 + new LoginSessionError({ message: SESSION_NOT_FOUND_MESSAGE, operation: 'load', cause })
133 + )
134 + );
135 + const linkedSession = yield* params.noWait
136 + ? Effect.flatMap(getSession, requireLinkedNow)
137 + : waitForLinkedSession(getSession, params.pollRetries);
138 +
139 + const uakApiKey = linkedSession.api_key;
140 + const sessionInfo = yield* getSessionInfoByUserApiKey({ userApiKey: uakApiKey });
141 + const organizations: ReadonlyArray<OrganizationSummary> = params.defaultToFirstOrg
142 + ? yield* listOrganizations({ apiKey: uakApiKey }).pipe(
143 + Effect.map(response => response.data),
144 + Effect.catch(error =>
145 + Effect.logDebug('Failed to list organizations after login:', error).pipe(Effect.as([]))
146 + )
147 + )
148 + : [];
149 + const defaultOrg = Arr.head(organizations);
150 + const orgId = Option.match(defaultOrg, {
151 + onNone: () => sessionInfo.project.org.id,
152 + onSome: org => org.id,
153 + });
154 + const orgName = Option.match(defaultOrg, {
155 + onNone: () => sessionInfo.project.org.name,
156 + onSome: org => org.name,
157 + });
158 +
159 + yield* storeCredentials({
160 + uakApiKey,
161 + initialOrgId: orgId,
162 + initialProjectId: sessionInfo.project.nano_id,
163 + fallbackEmail: linkedSession.account.email,
164 + announce: false,
165 + linkAnalytics: true,
166 + });
167 +
168 + const email = linkedSession.account.email ?? undefined;
169 + if (params.announce) {
170 + yield* emitLoginComplete({ email, orgId, orgName });
171 + }
172 + return { email, orgId, orgName, organizations };
173 + });
174 +
175 +/** The organization `--org` names, by ID or name, among those the key can see. */
176 +const findOrganization = (apiKey: string, requestedOrg: string) =>
177 + Effect.gen(function* () {
178 + const ui = yield* TerminalUI;
179 + const organizations = yield* listOrganizations({ apiKey });
180 + const match = Arr.findFirst(
181 + organizations.data,
182 + org => org.id === requestedOrg || org.name === requestedOrg
183 + );
184 + return yield* Option.match(match, {
185 + onSome: Effect.succeed,
186 + onNone: () =>
187 + ui.log.error(organizationNotFoundMessage(requestedOrg)).pipe(
188 + Effect.andThen(
189 + Effect.fail(
190 + new InvalidOrganizationError({
191 + message: INVALID_ORGANIZATION_MESSAGE,
192 + requestedOrg,
193 + })
194 + )
195 + )
196 + ),
197 + });
198 + });
199 +
200 +/**
201 + * A stored READY agent identity a headless login may reuse: only when nobody can answer a
202 + * prompt, no explicit browser flow was asked for, and the identity is the active login if
203 + * there is one.
204 + */
205 +const reusableStoredAgent = (requestedExplicitLoginFlow: boolean) =>
206 + Effect.gen(function* () {
207 + const ui = yield* TerminalUI;
208 + const ctx = yield* ComposioUserContext;
209 + const { canPrompt } = yield* ui.capabilities;
210 + if (canPrompt || requestedExplicitLoginFlow) {
211 + return Option.none<AgentIdentity>();
212 + }
213 + const stored = yield* getStoredReadyAgent;
214 + const activeApiKey = ctx.data.apiKey;
215 + return Option.filter(
216 + stored,
217 + identity =>
218 + Option.isNone(activeApiKey) ||
219 + Option.exists(activeApiKey, apiKey => isAgentIdentityForApiKey(identity, apiKey))
220 + );
221 + });
222 +
223 +// --- flows ------------------------------------------------------------------------------------
224 +
225 +/** `login --poll`: completes the browser login a headless `login` cached. */
226 +export const handlePollLogin = (params: Pick<LoginParams, 'noSkillInstall'>) =>
227 + Effect.gen(function* () {
228 + const ui = yield* TerminalUI;
229 + const pendingLoginSession = yield* PendingLoginSession;
230 + const pendingLogin = yield* pendingLoginSession.read;
231 + const result = yield* loginWithKey({
232 + key: pendingLogin.key,
233 + noWait: false,
234 + announce: false,
235 + pollRetries: LOGIN_POLL_RETRIES,
236 + defaultToFirstOrg: true,
237 + });
238 + yield* pendingLoginSession.clear;
239 +
240 + const summary: PollLoginSummary = {
241 + email: result.email,
242 + defaultOrgId: result.orgId,
243 + defaultOrgName: result.orgName,
244 + organizations: result.organizations,
245 + };
246 + const { canDecorate } = yield* ui.capabilities;
247 + if (canDecorate) {
248 + yield* ui.note(formatPollLoginComplete(summary), 'Login complete');
249 + }
250 + yield* ui.output(formatPollLoginJson(summary), { force: true });
251 + yield* offerSkillInstall(params.noSkillInstall);
252 + });
253 +
254 +/** `login --agent`: logs in with the stored agent identity, signing one up when there is none. */
255 +const handleAgentLogin = (params: Pick<LoginParams, 'noSkillInstall'>) =>
256 + handleAgentAuthError(
257 + Effect.gen(function* () {
258 + yield* ensureAgentSignupAllowed;
259 + const identity = yield* getOrSignupReadyAgent();
260 + yield* completeAgentLogin(identity);
261 + yield* offerSkillInstall(params.noSkillInstall);
262 + })
263 + );
264 +
265 +/** `login --key`: completes the CLI session a `login --no-wait` printed. */
266 +export const handleSessionKeyLogin = (
267 + params: Pick<LoginParams, 'noWait' | 'noSkillInstall'> & { readonly key: string }
268 +) =>
269 + loginWithKey({ key: params.key, noWait: params.noWait, announce: true }).pipe(
270 + Effect.andThen(offerSkillInstall(params.noSkillInstall))
271 + );
272 +
273 +/** `login --user-api-key [--org]`: stores a user API key without a browser. */
274 +export const handleDirectLogin = (
275 + params: Pick<LoginParams, 'org' | 'noSkillInstall'> & { readonly userApiKey: string }
276 +) =>
277 + Effect.gen(function* () {
278 + const ctx = yield* ComposioUserContext;
279 + const { userApiKey } = params;
280 + const sessionInfo = yield* getSessionInfoByUserApiKey({ userApiKey });
281 + const homeOrg = sessionInfo.project.org;
282 +
283 + const selectedOrg = yield* Option.match(
284 + Option.filter(params.org, requestedOrg => requestedOrg.length > 0),
285 + {
286 + onNone: () => Effect.succeed({ id: homeOrg.id, name: homeOrg.name ?? homeOrg.id }),
287 + onSome: requestedOrg => findOrganization(userApiKey, requestedOrg),
288 + }
289 + );
290 +
291 + yield* ctx.login(
292 + userApiKey,
293 + selectedOrg.id,
294 + playgroundTestUserId(Option.some(sessionInfo), ctx.data.testUserId)
295 + );
296 + yield* linkAnalyticsIdentityForOrg({
297 + apiKey: userApiKey,
298 + orgId: selectedOrg.id,
299 + knownIdentity: { orgId: homeOrg.id, orgMemberId: sessionInfo.org_member.id },
300 + });
301 + yield* primeConsumerConnectedToolkitsCacheInBackground({ orgId: selectedOrg.id });
302 + yield* emitLoginComplete({
303 + email: sessionInfo.org_member.email || undefined,
304 + orgId: selectedOrg.id,
305 + orgName: selectedOrg.name,
306 + });
307 + yield* offerSkillInstall(params.noSkillInstall);
308 + });
309 +
310 +/**
311 + * `login` with no direct-login flag: the browser login, unless the user is already logged in
312 + * with an org. A headless run reuses a stored READY agent identity instead, but never signs
313 + * one up for a human in a pipe; `--no-browser` and `--no-wait` opt out of that reuse, since
314 + * both promise output (the printed URL, the session JSON) that it would replace.
315 + */
316 +export const handleBrowserLogin = (
317 + params: Pick<LoginParams, 'noBrowser' | 'noWait' | 'yes' | 'noSkillInstall'>
318 +) =>
319 + Effect.gen(function* () {
320 + const ui = yield* TerminalUI;
321 + const ctx = yield* ComposioUserContext;
322 +
323 + if (ctx.isLoggedIn()) {
324 + if (Option.isSome(ctx.data.orgId)) {
325 + yield* ui.log.warn(ALREADY_LOGGED_IN_MESSAGE);
326 + yield* ui.outro(ALREADY_LOGGED_IN_OUTRO);
327 + return;
328 + }
329 + yield* ui.log.step(REAUTHENTICATING_MESSAGE);
330 + }
331 +
332 + const storedAgent = yield* reusableStoredAgent(params.noBrowser || params.noWait);
333 + yield* Option.match(storedAgent, {
334 + onSome: identity => handleAgentAuthError(completeAgentLogin(identity)),
335 + onNone: () =>
336 + browserLogin({
337 + scope: 'user',
338 + noBrowser: params.noBrowser,
339 + noWait: params.noWait,
340 + skipOrgProjectPicker: params.yes,
341 + }).pipe(Effect.andThen(offerSkillInstall(params.noSkillInstall || params.noWait))),
342 + });
343 + });
344 +
345 +// --- dispatch ---------------------------------------------------------------------------------
346 +
347 +/**
348 + * Validates the flag combination and picks the flow. The checks run in a fixed order, so a
349 + * command line with several mistakes reports the first one.
350 + */
351 +const selectLoginFlow = (params: LoginParams) => {
352 + const flags = {
353 + key: Option.isSome(params.key),
354 + userApiKey: Option.isSome(params.userApiKey),
355 + org: Option.isSome(params.org),
356 + browserOrSession: params.noBrowser || params.noWait,
357 + poll: params.poll,
358 + agent: params.agent,
359 + };
360 + type Flags = typeof flags;
361 + const reject = (message: string, option?: string) =>
362 + Effect.fail(invalidOptionValue(message, option));
363 + return Match.value(flags).pipe(
364 + Match.when({ key: true, userApiKey: true }, () => reject(KEY_AND_USER_API_KEY_MESSAGE)),
365 + Match.when(
366 + (f: Flags) => f.poll && (f.browserOrSession || f.key || f.userApiKey || f.agent),
367 + () => reject(POLL_WITH_OTHER_FLAGS_MESSAGE, '--poll')
368 + ),
369 + Match.when(
370 + (f: Flags) => f.agent && (f.browserOrSession || f.key || f.userApiKey),
371 + () => reject(AGENT_WITH_OTHER_FLAGS_MESSAGE, '--agent')
372 + ),
373 + Match.when({ org: true, userApiKey: false }, () =>
374 + reject(ORG_WITHOUT_USER_API_KEY_MESSAGE, '--org')
375 + ),
376 + Match.when({ userApiKey: true, browserOrSession: true }, () =>
377 + reject(USER_API_KEY_WITH_SESSION_FLAGS_MESSAGE, '--user-api-key')
378 + ),
379 + Match.when({ poll: true }, () => Effect.succeed(LoginFlow.Poll())),
380 + Match.when({ agent: true }, () => Effect.succeed(LoginFlow.Agent())),
381 + Match.orElse(() =>
382 + Effect.succeed(
383 + pipe(
384 + Option.map(params.key, key => LoginFlow.SessionKey({ key })),
385 + Option.orElse(() =>
386 + Option.map(params.userApiKey, userApiKey => LoginFlow.Direct({ userApiKey }))
387 + ),
388 + Option.getOrElse(() => LoginFlow.Browser())
389 + )
390 + )
391 + )
392 + );
393 +};
394 +
395 +/** `composio login`: validates the flag combination, then runs the flow it selects. */
396 +export const runLogin = (params: LoginParams) =>
397 + Effect.gen(function* () {
398 + const ui = yield* TerminalUI;
399 + const { canDecorate } = yield* ui.capabilities;
400 + yield* Effect.when(ui.intro('composio login'), Effect.succeed(canDecorate));
401 +
402 + const flow = yield* selectLoginFlow(params);
403 + yield* Match.valueTags(flow, {
404 + Poll: () => handlePollLogin(params),
405 + Agent: () => handleAgentLogin(params),
406 + SessionKey: ({ key }) => handleSessionKeyLogin({ ...params, key }),
407 + Direct: ({ userApiKey }) => handleDirectLogin({ ...params, userApiKey }),
408 + Browser: () => handleBrowserLogin(params),
409 + });
410 + });
ts/packages/cli/src/effects/browser-login.ts new
+394
@@ -0,0 +1,394 @@
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, Effect, Option, Schedule, pipe } from 'effect';
7 +import open from 'open';
8 +import type { RetrievedSession } from 'src/models/session';
9 +import { ComposioSessionRepository } from 'src/services/composio-clients';
10 +import {
11 + getSessionInfo,
12 + getSessionInfoByUserApiKey,
13 + sessionUserIdOf,
14 + type SessionInfoResponse,
15 +} from 'src/services/composio-account';
16 +import { commandHintStep } from 'src/services/command-hints';
17 +import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
18 +import { PendingLoginSession } from 'src/services/pending-login-session';
19 +import { TerminalUI } from 'src/services/terminal-ui';
20 +import { ComposioUserContext } from 'src/services/user-context';
21 +import { linkAnalyticsIdentityForOrg } from './link-analytics-identity';
22 +import { runOrgSelection } from './select-org-project';
23 +
24 +export class LoginSessionError extends Data.TaggedError('commands/LoginSessionError')<{
25 + readonly message: string;
26 + readonly operation: 'load' | 'poll';
27 + readonly status?: string;
28 + readonly cause?: unknown;
29 +}> {}
30 +
31 +class LoginBrowserOpenError extends Data.TaggedError('commands/LoginBrowserOpenError')<{
32 + readonly message: string;
33 + readonly cause: unknown;
34 +}> {}
35 +
36 +export type LinkedSession = Extract<RetrievedSession, { readonly status: 'linked' }>;
37 +
38 +/** Seconds between two checks of a session that is not linked yet. */
39 +export const LOGIN_POLL_INTERVAL_SECONDS = 5;
40 +
41 +/** How many times a session is checked again before the wait gives up, by default. */
42 +const DEFAULT_LOGIN_POLL_RETRIES = 15;
43 +
44 +const POLL_COMMAND = 'composio login --poll';
45 +
46 +// --- presentation -----------------------------------------------------------------------------
47 +
48 +const formatNonInteractiveLoginInstructions = (params: {
49 + readonly loginUrl: string;
50 + readonly pollCommand: string;
51 +}) => `Open this URL in your browser to log in:
52 +
53 + ${params.loginUrl}
54 +
55 +Then run this command to complete login:
56 +
57 + ${params.pollCommand}
58 +
59 +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.
60 +
61 +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.`;
62 +
63 +const formatLoginSuccessMessage = (params: {
64 + readonly email?: string;
65 + readonly orgName?: string;
66 +}): string =>
67 + `Logged in ${params.email ? `as ${params.email}` : 'successfully'}${params.orgName ? ` in "${params.orgName}"` : ''}`;
68 +
69 +/** The stdout payload of a completed login. */
70 +const formatLoginCompleteJson = (params: {
71 + readonly email?: string;
72 + readonly orgId: string;
73 + readonly orgName?: string;
74 +}) =>
75 + JSON.stringify({
76 + email: params.email,
77 + org_id: params.orgId,
78 + org_name: params.orgName ?? '',
79 + });
80 +
81 +/** Reports a completed login: the success line and next-step hints on stderr, the JSON on stdout. */
82 +export const emitLoginComplete = (params: {
83 + readonly email?: string;
84 + readonly orgId: string;
85 + readonly orgName?: string;
86 +}) =>
87 + Effect.gen(function* () {
88 + const ui = yield* TerminalUI;
89 + yield* ui.log.success(formatLoginSuccessMessage(params));
90 + yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
91 + yield* ui.log.info(commandHintStep('Switch your current org', 'root.orgs.switch'));
92 + yield* ui.output(formatLoginCompleteJson(params));
93 + yield* ui.outro("You're all set!");
94 + });
95 +
96 +// --- shared steps -----------------------------------------------------------------------------
97 +
98 +/**
99 + * The playground test user of the session's member, or `fallback` when there is no session
100 + * info or it carries no user id.
101 + */
102 +export const playgroundTestUserId = (
103 + sessionInfo: Option.Option<SessionInfoResponse>,
104 + fallback: Option.Option<string>
105 +) =>
106 + pipe(
107 + sessionInfo,
108 + Option.map(sessionUserIdOf),
109 + Option.filter(userId => userId.length > 0),
110 + Option.map(userId => `pg-test-${userId}`),
111 + Option.orElse(() => fallback),
112 + Option.getOrUndefined
113 + );
114 +
115 +/** The session, or a `poll` failure naming its status while it is not linked yet. */
116 +const requireLinkedSession = (session: RetrievedSession) =>
117 + session.status === 'linked'
118 + ? Effect.succeed(session)
119 + : Effect.fail(
120 + new LoginSessionError({
121 + message: `Session status is still '${session.status}', waiting for 'linked'`,
122 + operation: 'poll',
123 + status: session.status,
124 + })
125 + );
126 +
127 +/**
128 + * Checks the session behind a spinner until it is linked, `times` more times at most, waiting
129 + * at least `LOGIN_POLL_INTERVAL_SECONDS` between checks.
130 + */
131 +export const waitForLinkedSession = <E, R>(
132 + getSession: Effect.Effect<RetrievedSession, E, R>,
133 + times: number = DEFAULT_LOGIN_POLL_RETRIES
134 +) =>
135 + Effect.gen(function* () {
136 + const ui = yield* TerminalUI;
137 + return yield* ui.useMakeSpinner('Waiting for login...', spinner =>
138 + Effect.retry(Effect.flatMap(getSession, requireLinkedSession), {
139 + // v4 dropped `Schedule.intersect`/`Schedule.recurs`; `Schedule.max` recurs while every
140 + // schedule in the list still wants to and waits for the slowest one between attempts
141 + // (the v4 equivalent of intersecting delay-producing schedules), and the retry count
142 + // cap moves onto `Effect.retry`'s own `times` option.
143 + schedule: Schedule.max([
144 + Schedule.exponential('0.3 seconds'),
145 + Schedule.spaced(`${LOGIN_POLL_INTERVAL_SECONDS} seconds`),
146 + ]),
147 + times,
148 + }).pipe(
149 + Effect.tap(() => spinner.stop('Login successful')),
150 + Effect.tapError(() => spinner.error('Login timed out. Please try again.'))
151 + )
152 + );
153 + });
154 +
155 +/**
156 + * Verifies the linked session's key through session/info and stores it as the CLI's login.
157 + * The session info is enrichment only: the linked session is already authenticated, so a
158 + * failed lookup falls back to the IDs the caller passes.
159 + */
160 +export const storeCredentials = (params: {
161 + readonly uakApiKey: string;
162 + readonly initialOrgId: string;
163 + readonly initialProjectId: string;
164 + readonly fallbackEmail: string;
165 + /** Report the login (stderr and stdout) once stored. */
166 + readonly announce: boolean;
167 + /** Link the analytics identity now, rather than after a later org selection. */
168 + readonly linkAnalytics: boolean;
169 +}) =>
170 + Effect.gen(function* () {
171 + const ctx = yield* ComposioUserContext;
172 + const sessionInfo = yield* getSessionInfo({
173 + apiKey: params.uakApiKey,
174 + orgId: params.initialOrgId,
175 + projectId: params.initialProjectId,
176 + }).pipe(
177 + Effect.map(Option.some),
178 + // Catch-all rather than per-tag: no way this enrichment can fail may stop the
179 + // credential from being stored.
180 + Effect.catch(error =>
181 + Effect.logDebug('Session info fetch failed:', error).pipe(
182 + Effect.as(Option.none<SessionInfoResponse>())
183 + )
184 + )
185 + );
186 +
187 + // session/info is the canonical source of the org ID; the linked session may carry a
188 + // session-level identifier instead.
189 + const orgId = Option.match(sessionInfo, {
190 + onNone: () => params.initialOrgId,
191 + onSome: info => info.project.org.id,
192 + });
193 + if (orgId !== params.initialOrgId) {
194 + yield* Effect.logDebug(
195 + `orgId corrected: ${params.initialOrgId} -> ${orgId} (from session/info)`
196 + );
197 + }
198 +
199 + yield* ctx.login(
200 + params.uakApiKey,
201 + orgId,
202 + playgroundTestUserId(sessionInfo, ctx.data.testUserId)
203 + );
204 + // Linked only after the credential persists, so stitching cannot outlive a failed login.
205 + if (params.linkAnalytics) {
206 + yield* linkAnalyticsIdentityForOrg({
207 + apiKey: params.uakApiKey,
208 + orgId,
209 + knownIdentity: Option.getOrUndefined(
210 + Option.map(sessionInfo, info => ({
211 + orgId: info.project.org.id,
212 + orgMemberId: info.org_member.id,
213 + }))
214 + ),
215 + });
216 + }
217 + yield* primeConsumerConnectedToolkitsCacheInBackground({ orgId });
218 +
219 + if (params.announce) {
220 + yield* emitLoginComplete({
221 + email:
222 + Option.getOrUndefined(Option.map(sessionInfo, info => info.org_member.email)) ||
223 + params.fallbackEmail ||
224 + undefined,
225 + orgId,
226 + orgName:
227 + Option.getOrUndefined(Option.map(sessionInfo, info => info.project.org.name)) ||
228 + undefined,
229 + });
230 + }
231 + });
232 +
233 +/**
234 + * Lets the user pick the current org after a browser login, stores the pick, links the
235 + * analytics identity for it, and reports the login. A failed org list keeps the session's org.
236 + */
237 +const completeOrgSelection = (params: {
238 + readonly uakApiKey: string;
239 + readonly sessionInfo: SessionInfoResponse;
240 + readonly linkedSession: LinkedSession;
241 +}) =>
242 + Effect.gen(function* () {
243 + const ui = yield* TerminalUI;
244 + const ctx = yield* ComposioUserContext;
245 + const { uakApiKey, sessionInfo, linkedSession } = params;
246 +
247 + const selected = yield* runOrgSelection({ apiKey: uakApiKey }).pipe(
248 + Effect.map(Option.fromUndefinedOr),
249 + Effect.catch(error =>
250 + Effect.gen(function* () {
251 + yield* Effect.logDebug('Org picker failed:', error);
252 + yield* ui.log.warn('Could not load org list. Using current org.');
253 + return Option.none();
254 + })
255 + )
256 + );
257 + yield* Option.match(selected, {
258 + onNone: () => Effect.void,
259 + onSome: org =>
260 + ctx
261 + .login(
262 + uakApiKey,
263 + org.id,
264 + playgroundTestUserId(Option.some(sessionInfo), ctx.data.testUserId)
265 + )
266 + .pipe(Effect.andThen(primeConsumerConnectedToolkitsCacheInBackground({ orgId: org.id }))),
267 + });
268 +
269 + const orgId = Option.match(selected, {
270 + onNone: () => sessionInfo.project.org.id,
271 + onSome: org => org.id,
272 + });
273 + yield* linkAnalyticsIdentityForOrg({
274 + apiKey: uakApiKey,
275 + orgId,
276 + knownIdentity: {
277 + orgId: sessionInfo.project.org.id,
278 + orgMemberId: sessionInfo.org_member.id,
279 + },
280 + });
281 + yield* emitLoginComplete({
282 + email: linkedSession.account.email ?? undefined,
283 + orgId,
284 + orgName: Option.match(selected, {
285 + onNone: () => sessionInfo.project.org.name ?? '',
286 + onSome: org => org.name,
287 + }),
288 + });
289 + });
290 +
291 +/** Opens the login URL in the default browser; a failure only prints a hint. */
292 +const openLoginUrl = (url: string) =>
293 + Effect.gen(function* () {
294 + const ui = yield* TerminalUI;
295 + yield* Effect.tryPromise({
296 + try: () => open(url, { wait: false }),
297 + catch: cause => new LoginBrowserOpenError({ message: 'Failed to open the browser.', cause }),
298 + }).pipe(
299 + Effect.catchTag('commands/LoginBrowserOpenError', error =>
300 + Effect.gen(function* () {
301 + yield* Effect.logDebug('Failed to open browser:', error);
302 + yield* ui.log.warn('Could not open the browser automatically.');
303 + yield* ui.log.info(`Tip: try using the \`--no-browser\` flag and open the URL manually.`);
304 + })
305 + )
306 + );
307 + });
308 +
309 +/**
310 + * Runs the browser login: creates a CLI session and caches it for `composio login --poll`,
311 + * then either prints the poll instructions and returns (`noWait`, or nobody can answer a
312 + * prompt), or shows the URL (opening it unless `noBrowser`), waits until the session is
313 + * linked, and stores the credentials. A `user` login then lets the user pick the current org
314 + * unless `skipOrgProjectPicker`.
315 + */
316 +export const browserLogin = (params: {
317 + /** Session scope: 'user' for login, 'project' for init. */
318 + readonly scope: 'user' | 'project';
319 + /** When true, don't open browser — just show the URL. */
320 + readonly noBrowser: boolean;
321 + /** When true, print URL/session info and exit without waiting (implies noBrowser). */
322 + readonly noWait?: boolean;
323 + /** When true (login only), skip the org picker and use the session's org. */
324 + readonly skipOrgProjectPicker?: boolean;
325 +}) =>
326 + Effect.gen(function* () {
327 + const ui = yield* TerminalUI;
328 + const ctx = yield* ComposioUserContext;
329 + const client = yield* ComposioSessionRepository;
330 + const pendingLogin = yield* PendingLoginSession;
331 +
332 + yield* Effect.logDebug(`Authenticating (scope: ${params.scope})...`);
333 + const session = yield* client.createSession({ scope: params.scope });
334 + yield* Effect.logDebug(`Created session: ${session.id}`);
335 +
336 + const url = `${ctx.data.webURL}?cliKey=${session.id}`;
337 + yield* pendingLogin.write({
338 + key: session.id,
339 + loginUrl: url,
340 + expiresAt: DateTime.formatIso(session.expiresAt),
341 + });
342 +
343 + const { canPrompt, canDecorate } = yield* ui.capabilities;
344 + const effectiveNoWait = params.noWait || !canPrompt;
345 + const effectiveNoBrowser = params.noBrowser || effectiveNoWait;
346 +
347 + if (effectiveNoWait) {
348 + const loginInstructions = formatNonInteractiveLoginInstructions({
349 + loginUrl: url,
350 + pollCommand: POLL_COMMAND,
351 + });
352 + if (canDecorate) {
353 + yield* ui.log.info('Please login using the following URL:');
354 + yield* ui.note(url, 'Login URL');
355 + yield* ui.note(loginInstructions, 'Login instructions');
356 + }
357 + yield* ui.output(loginInstructions);
358 + return;
359 + }
360 +
361 + yield* effectiveNoBrowser
362 + ? ui.log.info('Please login using the following URL:')
363 + : ui.log.step('Redirecting you to the login page');
364 + yield* ui.note(url, 'Login URL');
365 + yield* ui.output(url);
366 + if (!effectiveNoBrowser) {
367 + yield* openLoginUrl(url);
368 + }
369 +
370 + const linkedSession = yield* waitForLinkedSession(client.getSession({ id: session.id }));
371 + yield* Effect.logDebug(`Linked session ID: ${linkedSession.id}`);
372 +
373 + // e.g., "uak_b813ydmoEYdB_xBxGHeW"
374 + const uakApiKey = linkedSession.api_key;
375 + const sessionInfo = yield* getSessionInfoByUserApiKey({ userApiKey: uakApiKey });
376 + yield* Effect.logDebug('UAK session info:', {
377 + xProjectId: sessionInfo.project.nano_id,
378 + xOrgId: sessionInfo.project.org.id,
379 + });
380 +
381 + const willRunPicker = params.scope === 'user' && !params.skipOrgProjectPicker;
382 + yield* storeCredentials({
383 + uakApiKey,
384 + initialOrgId: sessionInfo.project.org.id,
385 + initialProjectId: sessionInfo.project.nano_id,
386 + fallbackEmail: linkedSession.account.email,
387 + announce: !willRunPicker,
388 + linkAnalytics: !willRunPicker,
389 + });
390 +
391 + if (willRunPicker) {
392 + yield* completeOrgSelection({ uakApiKey, sessionInfo, linkedSession });
393 + }
394 + });
ts/packages/cli/src/effects/complete-agent-login.ts new
+17
@@ -0,0 +1,17 @@
1 +import { Effect } from 'effect';
2 +import { loginWithAgentIdentity, safeAgentSummary, type AgentIdentity } from 'src/services/agents';
3 +import { TerminalUI } from 'src/services/terminal-ui';
4 +
5 +/**
6 + * Stores an agent identity's credential as the CLI's login and reports it: the success line on
7 + * stderr, the identity summary with `logged_in: true` on stdout. Shared by `composio agent
8 + * login` and the agent paths of `composio login`, so both print the same payload.
9 + */
10 +export const completeAgentLogin = (identity: AgentIdentity) =>
11 + Effect.gen(function* () {
12 + const ui = yield* TerminalUI;
13 + yield* loginWithAgentIdentity(identity);
14 + const summary = safeAgentSummary(identity);
15 + yield* ui.log.success(`Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`);
16 + yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));
17 + });
ts/packages/cli/src/services/pending-login-session.ts new
+144
@@ -0,0 +1,144 @@
1 +/**
2 + * The browser login that `composio login` started without waiting: its session key and URL,
3 + * cached in `<cache dir>/pending-login-session.json` so that `composio login --poll` can
4 + * complete it from another process. `composio dev init` starts the same browser login, so the
5 + * file outlives any one command.
6 + */
7 +import * as FileSystem from 'effect/FileSystem';
8 +import * as Path from 'effect/Path';
9 +import type { Config, PlatformError } from 'effect';
10 +import { Clock, Context, Data, DateTime, Effect, Layer, Schema } from 'effect';
11 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
12 +import { atomicWritePrivateFileString, ensurePrivateFileMode } from 'src/utils/atomic-write';
13 +import { NodeOs } from './node-os';
14 +
15 +export const PENDING_LOGIN_FILE_NAME = 'pending-login-session.json';
16 +
17 +/** How long a cached login stays usable, counted from when it was cached. */
18 +const PENDING_LOGIN_TTL_MS = 10 * 60 * 1000;
19 +
20 +export const PendingLogin = Schema.Struct({
21 + key: Schema.String,
22 + loginUrl: Schema.String,
23 + expiresAt: Schema.String,
24 + cachedAt: Schema.String,
25 +});
26 +export type PendingLogin = Schema.Schema.Type<typeof PendingLogin>;
27 +
28 +export class PendingLoginError extends Data.TaggedError('commands/PendingLoginError')<{
29 + readonly message: string;
30 + readonly reason: 'invalid' | 'io' | 'missing' | 'expired';
31 + readonly cause?: unknown;
32 +}> {}
33 +
34 +export type PendingLoginSessionShape = {
35 + /** Caches a started login, stamped with the current time, in a file only the user can read. */
36 + readonly write: (
37 + session: Omit<PendingLogin, 'cachedAt'>
38 + ) => Effect.Effect<void, Config.ConfigError | PlatformError.PlatformError>;
39 + /**
40 + * The cached login. Fails with `missing` when there is none, `io` or `invalid` when the file
41 + * cannot be read or decoded, and `expired` (after deleting it) when it is past its TTL.
42 + */
43 + readonly read: Effect.Effect<
44 + PendingLogin,
45 + PendingLoginError | Config.ConfigError | PlatformError.PlatformError
46 + >;
47 + /** Deletes the cached login; a missing file is not an error. */
48 + readonly clear: Effect.Effect<void>;
49 +};
50 +
51 +const decodePendingLogin = Schema.decodeUnknownEffect(Schema.fromJsonString(PendingLogin));
52 +
53 +const isExpired = (cachedAt: string, now: number) => {
54 + const cachedAtMs = Date.parse(cachedAt);
55 + return !Number.isFinite(cachedAtMs) || now - cachedAtMs > PENDING_LOGIN_TTL_MS;
56 +};
57 +
58 +const makePendingLoginSession = Effect.gen(function* () {
59 + const fs = yield* FileSystem.FileSystem;
60 + const path = yield* Path.Path;
61 + const os = yield* NodeOs;
62 +
63 + // Resolved on every call: the cache directory comes from configuration read at call time.
64 + const filePath = setupCacheDir.pipe(
65 + Effect.map(cacheDir => path.join(cacheDir, PENDING_LOGIN_FILE_NAME)),
66 + Effect.provideService(FileSystem.FileSystem, fs),
67 + Effect.provideService(Path.Path, path),
68 + Effect.provideService(NodeOs, os)
69 + );
70 +
71 + const clear = filePath.pipe(
72 + Effect.flatMap(target => fs.remove(target)),
73 + Effect.ignore
74 + );
75 +
76 + const write: PendingLoginSessionShape['write'] = session =>
77 + Effect.gen(function* () {
78 + const target = yield* filePath;
79 + const cachedAt = DateTime.formatIso(yield* DateTime.now);
80 + const payload: PendingLogin = { ...session, cachedAt };
81 + yield* atomicWritePrivateFileString({
82 + fs,
83 + target,
84 + contents: `${JSON.stringify(payload, null, 2)}\n`,
85 + });
86 + });
87 +
88 + const read = Effect.gen(function* () {
89 + const target = yield* filePath;
90 + yield* fs.exists(target).pipe(
91 + Effect.filterOrFail(
92 + exists => exists,
93 + () =>
94 + new PendingLoginError({
95 + message: 'No pending login found. Run `composio login < /dev/null` first.',
96 + reason: 'missing',
97 + })
98 + )
99 + );
100 + const raw = yield* ensurePrivateFileMode({ fs, target }).pipe(
101 + Effect.andThen(fs.readFileString(target, 'utf8')),
102 + Effect.mapError(
103 + cause =>
104 + new PendingLoginError({
105 + message: 'Failed to read pending login cache',
106 + reason: 'io',
107 + cause,
108 + })
109 + )
110 + );
111 + const session = yield* decodePendingLogin(raw).pipe(
112 + Effect.mapError(
113 + cause =>
114 + new PendingLoginError({
115 + message: 'Pending login cache is invalid',
116 + reason: 'invalid',
117 + cause,
118 + })
119 + )
120 + );
121 + const now = yield* Clock.currentTimeMillis;
122 + if (isExpired(session.cachedAt, now)) {
123 + yield* clear;
124 + return yield* new PendingLoginError({
125 + message: 'Pending login expired. Run `composio login < /dev/null` again.',
126 + reason: 'expired',
127 + });
128 + }
129 + return session;
130 + });
131 +
132 + return { write, read, clear } satisfies PendingLoginSessionShape;
133 +});
134 +
135 +export class PendingLoginSession extends Context.Service<
136 + PendingLoginSession,
137 + PendingLoginSessionShape
138 +>()('services/PendingLoginSession') {
139 + static readonly Default: Layer.Layer<
140 + PendingLoginSession,
141 + never,
142 + FileSystem.FileSystem | Path.Path | NodeOs
143 + > = Layer.effect(PendingLoginSession, makePendingLoginSession);
144 +}
ts/packages/cli/test/__utils__/layers/pending-login-session.ts new
+40
@@ -0,0 +1,40 @@
1 +import { Effect, Layer, Option } from 'effect';
2 +import {
3 + PendingLoginError,
4 + PendingLoginSession,
5 + type PendingLogin,
6 +} from 'src/services/pending-login-session';
7 +
8 +/**
9 + * An in-memory `PendingLoginSession`: `write` stamps `cachedAt`, `read` answers what was
10 + * written (or `initial`) and fails as `missing` once cleared, and `current` shows the cached
11 + * login, for assertions.
12 + */
13 +export const PendingLoginSessionTest = (initial: Option.Option<PendingLogin> = Option.none()) => {
14 + let cached = initial;
15 + const service = PendingLoginSession.of({
16 + write: session =>
17 + Effect.sync(() => {
18 + cached = Option.some({ ...session, cachedAt: '2026-01-01T00:00:00.000Z' });
19 + }),
20 + read: Effect.suspend(() =>
21 + Option.match(cached, {
22 + onSome: Effect.succeed,
23 + onNone: () =>
24 + Effect.fail(
25 + new PendingLoginError({
26 + message: 'No pending login found. Run `composio login < /dev/null` first.',
27 + reason: 'missing',
28 + })
29 + ),
30 + })
31 + ),
32 + clear: Effect.sync(() => {
33 + cached = Option.none();
34 + }),
35 + });
36 + return {
37 + layer: Layer.succeed(PendingLoginSession, service),
38 + current: () => cached,
39 + };
40 +};
ts/packages/cli/test/__utils__/services/test-layer.ts
+5
@@ -35,6 +35,7 @@ import * as MockTerminal from './mock-terminal';
35 import { TerminalUITest } from './terminal-ui-test';
36 import { NodeProcess } from 'src/services/node-process';
37 import { cliDebugFlagsLayer } from 'src/services/runtime-flags';
38 +import { PendingLoginSession } from 'src/services/pending-login-session';
39 import {
40 ComposioClientSingleton,
41 ComposioSessionRepository,
@@ -889,6 +890,10 @@ export const TestLayer = (input?: TestLiveInput) =>
890 // `src/commands/index.ts` provides these for real invocations; direct-effect tests that
891 // never route through the root command still need the "no CLI flag override" default.
892 cliDebugFlagsLayer(),
893 + Layer.provide(
894 + PendingLoginSession.Default,
895 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest)
896 + ),
897 Layer.provide(
898 ProjectContext.Default,
899 Layer.mergeAll(BunFileSystem.layer, NodeOsTest, NodeProcessTest)
ts/packages/cli/test/src/commands/agent/agent.cmd.test.ts
-47
@@ -165,42 +165,6 @@ describe('CLI: composio agent', () => {
165 );
166 });
167
168 - layer(TestLive())(it => {
169 - it.effect('agent login restores an existing agent from composio_agent_key', () =>
170 - Effect.gen(function* () {
171 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
172 - jsonResponse({
173 - ...agentSignupResponse,
174 - composio_agent_key: 'cak_existing',
175 - agent_key: 'cak_existing',
176 - })
177 - );
178 -
179 - yield* cli(['agent', 'login', 'cak_existing']);
180 -
181 - expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
182 - expect.stringContaining('/api/whoami'),
183 - expect.objectContaining({
184 - method: 'GET',
185 - headers: expect.objectContaining({ Authorization: 'Bearer cak_existing' }),
186 - })
187 - );
188 - const ctx = yield* ComposioUserContext;
189 - expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
190 - expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
191 -
192 - const fs = yield* FileSystem.FileSystem;
193 - const cacheDir = yield* setupCacheDir;
194 - const agentConfigRaw = yield* fs.readFileString(path.join(cacheDir, 'agent.json'), 'utf8');
195 - expect(JSON.parse(agentConfigRaw)).toMatchObject({
196 - composio_agent_key: 'cak_existing',
197 - agent_key: 'cak_existing',
198 - composio: { user_api_key: 'uak_agent' },
199 - });
200 - })
201 - );
202 - });
203 -
168 layer(TestLive({ fixture: 'user-config-example' }))(it => {
169 it.effect('agent commands show a soft auth warning when signed in as a human user', () =>
170 Effect.gen(function* () {
@@ -223,16 +187,5 @@ describe('CLI: composio agent', () => {
187 expect(process.exitCode).toBe(1);
188 })
189 );
226 -
227 - it.effect('agent login shows a soft auth warning when signed in as a human user', () =>
228 - Effect.gen(function* () {
229 - yield* cli(['agent', 'login', 'cak_existing']);
230 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
231 -
232 - expect(output).toContain('currently signed in to Composio as a regular user');
233 - expect(output).toContain('composio logout');
234 - expect(process.exitCode).toBe(1);
235 - })
236 - );
190 });
191 });
ts/packages/cli/test/src/commands/agent/agent.login.cmd.test.ts new
+142
@@ -0,0 +1,142 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import { Effect, Option } from 'effect';
4 +import path from 'node:path';
5 +import { afterEach, vi } from 'vitest';
6 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 +import { ComposioUserContext } from 'src/services/user-context';
8 +import { cli, MockConsole, TestLive } from 'test/__utils__';
9 +
10 +const existingAgent = {
11 + status: 'READY',
12 + slug: 'test-agent',
13 + email: 'test-agent@agent.composio.ai',
14 + composio_agent_key: 'cak_existing',
15 + agent_key: 'cak_existing',
16 + composio: {
17 + member_id: 'mem_agent',
18 + org_id: 'org_agent',
19 + project_id: 'proj_agent',
20 + user_api_key: 'uak_agent',
21 + },
22 +};
23 +
24 +const jsonResponse = (body: unknown, status = 200) =>
25 + new Response(JSON.stringify(body), {
26 + status,
27 + headers: { 'Content-Type': 'application/json' },
28 + });
29 +
30 +const agentConfigPath = Effect.map(setupCacheDir, cacheDir => path.join(cacheDir, 'agent.json'));
31 +
32 +describe('CLI: composio agent login', () => {
33 + afterEach(() => {
34 + vi.restoreAllMocks();
35 + process.exitCode = undefined;
36 + });
37 +
38 + layer(TestLive())(it => {
39 + it.effect(
40 + '[Given] a key the agents API knows [Then] stores the identity, logs in, and prints its summary',
41 + () =>
42 + Effect.gen(function* () {
43 + const fetchSpy = vi
44 + .spyOn(globalThis, 'fetch')
45 + .mockImplementation(async () => jsonResponse(existingAgent));
46 +
47 + yield* cli(['agent', 'login', 'cak_existing']);
48 +
49 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
50 + expect.stringContaining('/api/whoami'),
51 + expect.objectContaining({
52 + method: 'GET',
53 + headers: expect.objectContaining({ Authorization: 'Bearer cak_existing' }),
54 + })
55 + );
56 + const ctx = yield* ComposioUserContext;
57 + expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
58 + expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
59 +
60 + const fs = yield* FileSystem.FileSystem;
61 + const agentConfigRaw = yield* fs.readFileString(yield* agentConfigPath, 'utf8');
62 + expect(JSON.parse(agentConfigRaw)).toMatchObject({
63 + composio_agent_key: 'cak_existing',
64 + agent_key: 'cak_existing',
65 + composio: { user_api_key: 'uak_agent' },
66 + });
67 +
68 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
69 + expect(lines).toContain('Logged in as Composio agent test-agent@agent.composio.ai');
70 + expect(lines.at(-1)).toBe(
71 + JSON.stringify({
72 + account_type: 'agent',
73 + status: 'READY',
74 + slug: 'test-agent',
75 + email: 'test-agent@agent.composio.ai',
76 + org_id: 'org_agent',
77 + project_id: 'proj_agent',
78 + member_id: 'mem_agent',
79 + claimed_by: null,
80 + claimed_at: null,
81 + logged_in: true,
82 + })
83 + );
84 + })
85 + );
86 + });
87 +
88 + layer(TestLive())(it => {
89 + it.effect('[Given] a key the agents API rejects [Then] fails and stores nothing', () =>
90 + Effect.gen(function* () {
91 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
92 + jsonResponse({ message: 'Invalid agent key' }, 401)
93 + );
94 +
95 + const error = yield* cli(['agent', 'login', 'cak_revoked']).pipe(Effect.flip);
96 +
97 + expect(error).toMatchObject({ message: 'Invalid agent key', status: 401 });
98 + const ctx = yield* ComposioUserContext;
99 + expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();
100 + const fs = yield* FileSystem.FileSystem;
101 + expect(yield* fs.exists(yield* agentConfigPath)).toBe(false);
102 + })
103 + );
104 + });
105 +
106 + layer(TestLive())(it => {
107 + it.effect(
108 + '[Given] an identity without credentials yet [Then] warns, exits 1, and does not log in',
109 + () =>
110 + Effect.gen(function* () {
111 + vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
112 + jsonResponse({ ...existingAgent, status: 'PENDING', composio: undefined })
113 + );
114 +
115 + yield* cli(['agent', 'login', 'cak_existing']);
116 +
117 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
118 + expect(output).toContain('Agent identity is not ready yet.');
119 + expect(output).not.toContain('"logged_in":true');
120 + expect(process.exitCode).toBe(1);
121 + const ctx = yield* ComposioUserContext;
122 + expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();
123 + })
124 + );
125 + });
126 +
127 + layer(TestLive({ fixture: 'user-config-example' }))(it => {
128 + it.effect('[Given] the CLI is signed in as a human user [Then] shows a soft auth warning', () =>
129 + Effect.gen(function* () {
130 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
131 +
132 + yield* cli(['agent', 'login', 'cak_existing']);
133 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
134 +
135 + expect(output).toContain('currently signed in to Composio as a regular user');
136 + expect(output).toContain('composio logout');
137 + expect(process.exitCode).toBe(1);
138 + expect(fetchSpy).not.toHaveBeenCalled();
139 + })
140 + );
141 + });
142 +});
ts/packages/cli/test/src/commands/login/login.cmd.test.ts renamed
ts/packages/cli/test/src/commands/login/login.handler.test.ts new
+561
@@ -0,0 +1,561 @@
1 +import { Auth, make, type ComposioClientShape, type NotFoundError } from '@composio/client/effect';
2 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3 +import * as BunPath from '@effect/platform-bun/BunPath';
4 +import { describe, expect, it } from '@effect/vitest';
5 +import { ConfigProvider, Console, DateTime, Effect, Layer, Option } from 'effect';
6 +import { HttpClient } from 'effect/http';
7 +import * as tempy from 'tempy';
8 +import {
9 + handleBrowserLogin,
10 + handleDirectLogin,
11 + handlePollLogin,
12 + handleSessionKeyLogin,
13 + runLogin,
14 + type LoginParams,
15 +} from 'src/commands/login/login.handler';
16 +import {
17 + AGENT_WITH_OTHER_FLAGS_MESSAGE,
18 + ALREADY_LOGGED_IN_MESSAGE,
19 + INVALID_ORGANIZATION_MESSAGE,
20 + KEY_AND_USER_API_KEY_MESSAGE,
21 + ORG_WITHOUT_USER_API_KEY_MESSAGE,
22 + POLL_WITH_OTHER_FLAGS_MESSAGE,
23 + SESSION_NOT_FOUND_MESSAGE,
24 + SESSION_NOT_LINKED_MESSAGE,
25 + USER_API_KEY_WITH_SESSION_FLAGS_MESSAGE,
26 +} from 'src/commands/login/login.format';
27 +import type { RetrievedSession } from 'src/models/session';
28 +import type { OrganizationSummary } from 'src/services/composio-account';
29 +import { ComposioClientSingleton, ComposioSessionRepository } from 'src/services/composio-clients';
30 +import { NodeOs } from 'src/services/node-os';
31 +import { NodeProcess } from 'src/services/node-process';
32 +import { ProjectContext } from 'src/services/project-context';
33 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
34 +import { ComposioUserContext } from 'src/services/user-context';
35 +import { MockConsole, ToolkitsTest } from 'test/__utils__';
36 +import { notFoundError } from 'test/__utils__/layers/not-found';
37 +import { mockAccountResources, type MockRequestScope } from 'test/__utils__/layers/accounts';
38 +import { PendingLoginSessionTest } from 'test/__utils__/layers/pending-login-session';
39 +import { hostOnlyEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
40 +import { makeSessionInfo } from 'test/__utils__/models/account';
41 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
42 +import { afterEach, vi } from 'vitest';
43 +
44 +vi.mock('open', () => ({
45 + default: vi.fn(async () => undefined),
46 +}));
47 +
48 +const analytics = vi.hoisted(() => ({ linked: [] as Array<string> }));
49 +
50 +// Records each analytics identity link instead of enqueueing an event.
51 +vi.mock('src/analytics/dispatch', async importOriginal => {
52 + const actual = await importOriginal<typeof import('src/analytics/dispatch')>();
53 + const { Effect } = await import('effect');
54 + return {
55 + ...actual,
56 + analyticsIdentityLinkingEnabled: Effect.succeed(true),
57 + linkApolloIdentityForAnalytics: ((apolloUserId: string) =>
58 + Effect.sync(() => {
59 + analytics.linked.push(apolloUserId);
60 + })) as unknown as typeof actual.linkApolloIdentityForAnalytics,
61 + };
62 +});
63 +
64 +afterEach(() => {
65 + analytics.linked.length = 0;
66 +});
67 +
68 +const ORGANIZATIONS: ReadonlyArray<OrganizationSummary> = [
69 + { id: 'org_first', name: 'First Org' },
70 + { id: 'org_second', name: 'Second Org' },
71 +];
72 +
73 +const HOME_SESSION_INFO = makeSessionInfo({
74 + orgId: 'org_home',
75 + orgName: 'Home Org',
76 + orgMemberId: 'member_home',
77 + userId: 'user_123',
78 + email: 'cli@example.com',
79 +});
80 +
81 +/** The key's home org without an org scope, otherwise the requested org with its own member. */
82 +const sessionInfoFor = (scope: MockRequestScope) =>
83 + scope.orgId === undefined
84 + ? HOME_SESSION_INFO
85 + : makeSessionInfo({
86 + orgId: scope.orgId,
87 + orgName: `${scope.orgId} name`,
88 + orgMemberId: `member_${scope.orgId}`,
89 + userId: 'user_123',
90 + email: 'cli@example.com',
91 + });
92 +
93 +const params = (overrides: Partial<LoginParams> = {}): LoginParams => ({
94 + noBrowser: false,
95 + poll: false,
96 + noWait: false,
97 + key: Option.none(),
98 + userApiKey: Option.none(),
99 + org: Option.none(),
100 + yes: false,
101 + noSkillInstall: true,
102 + agent: false,
103 + ...overrides,
104 +});
105 +
106 +const pendingSession = (id: string): RetrievedSession => ({
107 + id,
108 + code: '001122',
109 + expiresAt: DateTime.makeUnsafe('2026-01-01T00:10:00.000Z'),
110 + status: 'pending',
111 + api_key: null,
112 +});
113 +
114 +const linkedSession = (id: string): RetrievedSession => ({
115 + id,
116 + code: '001122',
117 + expiresAt: DateTime.makeUnsafe('2026-01-01T00:10:00.000Z'),
118 + status: 'linked',
119 + api_key: 'uak_linked',
120 + account: { id: 'account_id', name: 'Poll User', email: 'poll@example.com' },
121 +});
122 +
123 +interface LoginFixture {
124 + /** The stored login the user context starts with. */
125 + readonly apiKey?: Option.Option<string>;
126 + readonly orgId?: Option.Option<string>;
127 + readonly pending?: Parameters<typeof PendingLoginSessionTest>[0];
128 + /** What `getSession` answers; a failure stands for an unknown or expired session. */
129 + readonly session?: Effect.Effect<RetrievedSession, NotFoundError>;
130 +}
131 +
132 +// A resource the account mocks do not shadow reaches this transport and dies with its URL.
133 +const baseClient = make(
134 + {
135 + auth: Auth.project('test'),
136 + baseURL: 'https://mock.invalid',
137 + },
138 + HttpClient.make(request =>
139 + Effect.die(new Error(`unexpected network call from the login handler test: ${request.url}`))
140 + )
141 +);
142 +
143 +/**
144 + * What a login handler needs and nothing more: the account family of the mock client, a CLI
145 + * session double, an in-memory pending login, a user context that records `login` calls, and a
146 + * headless terminal whose stdout data lands in `outputs`.
147 + */
148 +const loginHandlerTest = (fixture: LoginFixture = {}) => {
149 + const logins: Array<{
150 + readonly apiKey: string;
151 + readonly orgId?: string;
152 + readonly testUserId?: string;
153 + }> = [];
154 + const outputs: Array<string> = [];
155 + const createdSessions: Array<string> = [];
156 + const pending = PendingLoginSessionTest(fixture.pending);
157 + const apiKey = fixture.apiKey ?? Option.none();
158 +
159 + const clientFor = (scope: MockRequestScope): ComposioClientShape =>
160 + // The shadows answer only the fields the handlers read; `test-layer.ts` shadows its mock
161 + // client the same way.
162 + ({
163 + ...baseClient,
164 + ...mockAccountResources({ sessionInfo: sessionInfoFor, organizations: ORGANIZATIONS }, scope),
165 + }) as unknown as ComposioClientShape;
166 +
167 + const dir = tempy.temporaryDirectory({ prefix: 'login-handler' });
168 + const layer = Layer.mergeAll(
169 + Layer.effect(Console.Console, MockConsole.make),
170 + Layer.succeed(
171 + TerminalUI,
172 + TerminalUI.of({
173 + ...terminalUITestImpl,
174 + capabilities: Effect.succeed(
175 + getTerminalCapabilities({
176 + stdin: { isTTY: false },
177 + stdout: { isTTY: false },
178 + stderr: { isTTY: false },
179 + })
180 + ),
181 + output: data =>
182 + Effect.sync(() => {
183 + outputs.push(data);
184 + }),
185 + })
186 + ),
187 + Layer.succeed(
188 + ComposioUserContext,
189 + ComposioUserContext.of({
190 + data: {
191 + apiKey,
192 + baseURL: 'https://mock.invalid',
193 + webURL: 'https://platform.mock.invalid/',
194 + orgId: fixture.orgId ?? Option.none(),
195 + projectId: Option.none(),
196 + testUserId: Option.none(),
197 + },
198 + isLoggedIn: () => Option.isSome(apiKey),
199 + logout: Effect.void,
200 + login: (loginApiKey, orgId, testUserId) =>
201 + Effect.sync(() => {
202 + logins.push({ apiKey: loginApiKey, orgId, testUserId });
203 + }),
204 + update: () => Effect.void,
205 + })
206 + ),
207 + Layer.succeed(
208 + ComposioSessionRepository,
209 + ComposioSessionRepository.of({
210 + createSession: ({ scope } = {}) =>
211 + Effect.sync(() => {
212 + createdSessions.push(scope ?? 'user');
213 + return {
214 + id: 'session-new',
215 + code: '001122',
216 + expiresAt: DateTime.makeUnsafe('2026-01-01T00:10:00.000Z'),
217 + status: 'pending' as const,
218 + };
219 + }),
220 + getSession: () => fixture.session ?? Effect.succeed(linkedSession('session-key')),
221 + getRealtimeCredentials: () => Effect.die(new Error('unexpected realtime credentials')),
222 + authRealtimeChannel: () => Effect.die(new Error('unexpected realtime auth')),
223 + })
224 + ),
225 + Layer.succeed(
226 + ComposioClientSingleton,
227 + ComposioClientSingleton.of({
228 + get: () => Effect.succeed(clientFor({})),
229 + getFor: (scope: MockRequestScope) => Effect.succeed(clientFor(scope)),
230 + getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
231 + })
232 + ),
233 + pending.layer,
234 + // The consumer-toolkits cache refresh a login starts in the background reads these.
235 + ToolkitsTest(),
236 + Layer.succeed(ProjectContext, ProjectContext.of({ resolve: Effect.succeed(Option.none()) })),
237 + Layer.succeed(
238 + HttpClient.HttpClient,
239 + HttpClient.make(request =>
240 + Effect.die(new Error(`unexpected HTTP call from the login handler test: ${request.url}`))
241 + )
242 + ),
243 + BunFileSystem.layer,
244 + BunPath.layer,
245 + Layer.succeed(
246 + NodeOs,
247 + NodeOs.of({ homedir: dir, tmpdir: dir, arch: 'arm64', platform: 'darwin' })
248 + ),
249 + Layer.succeed(
250 + NodeProcess,
251 + NodeProcess.of({
252 + cwd: dir,
253 + execPath: `${dir}/composio`,
254 + platform: 'darwin',
255 + arch: 'arm64',
256 + setExitCode: () => Effect.void,
257 + })
258 + ),
259 + ConfigProvider.layer(hostOnlyEnvConfigProvider)
260 + );
261 + return { layer, logins, outputs, createdSessions, pending };
262 +};
263 +
264 +const stderr = MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
265 +
266 +describe('runLogin', () => {
267 + // The checks run in a fixed order; each row also proves the earlier checks let it through.
268 + it.effect.each([
269 + {
270 + name: '--key with --user-api-key',
271 + flags: { key: Option.some('k'), userApiKey: Option.some('uak') },
272 + message: KEY_AND_USER_API_KEY_MESSAGE,
273 + option: undefined,
274 + },
275 + {
276 + name: '--key, --user-api-key and --poll (the pair is reported first)',
277 + flags: { key: Option.some('k'), userApiKey: Option.some('uak'), poll: true },
278 + message: KEY_AND_USER_API_KEY_MESSAGE,
279 + option: undefined,
280 + },
281 + {
282 + name: '--poll with --no-browser',
283 + flags: { poll: true, noBrowser: true },
284 + message: POLL_WITH_OTHER_FLAGS_MESSAGE,
285 + option: '--poll',
286 + },
287 + {
288 + name: '--poll with --user-api-key',
289 + flags: { poll: true, userApiKey: Option.some('uak') },
290 + message: POLL_WITH_OTHER_FLAGS_MESSAGE,
291 + option: '--poll',
292 + },
293 + {
294 + name: '--poll with --agent (before the --agent check)',
295 + flags: { poll: true, agent: true },
296 + message: POLL_WITH_OTHER_FLAGS_MESSAGE,
297 + option: '--poll',
298 + },
299 + {
300 + name: '--agent with --no-wait',
301 + flags: { agent: true, noWait: true },
302 + message: AGENT_WITH_OTHER_FLAGS_MESSAGE,
303 + option: '--agent',
304 + },
305 + {
306 + name: '--agent with --key',
307 + flags: { agent: true, key: Option.some('k') },
308 + message: AGENT_WITH_OTHER_FLAGS_MESSAGE,
309 + option: '--agent',
310 + },
311 + {
312 + name: '--org without --user-api-key',
313 + flags: { org: Option.some('org_first'), key: Option.some('k') },
314 + message: ORG_WITHOUT_USER_API_KEY_MESSAGE,
315 + option: '--org',
316 + },
317 + {
318 + name: '--user-api-key with --no-wait',
319 + flags: { userApiKey: Option.some('uak'), noWait: true },
320 + message: USER_API_KEY_WITH_SESSION_FLAGS_MESSAGE,
321 + option: '--user-api-key',
322 + },
323 + ])('[Given] $name [Then] fails with a usage error', ({ flags, message, option }) => {
324 + const { layer, logins, createdSessions } = loginHandlerTest();
325 + return Effect.gen(function* () {
326 + const error = yield* Effect.flip(runLogin(params(flags)));
327 +
328 + expect(error).toMatchObject({
329 + _tag: 'commands/CommandInputError',
330 + command: 'login',
331 + message,
332 + option,
333 + });
334 + expect(logins).toEqual([]);
335 + expect(createdSessions).toEqual([]);
336 + }).pipe(Effect.provide(layer));
337 + });
338 +
339 + it.effect('[Given] --poll and nothing cached [Then] runs the poll flow', () => {
340 + const { layer } = loginHandlerTest();
341 + return Effect.gen(function* () {
342 + const error = yield* Effect.flip(runLogin(params({ poll: true })));
343 +
344 + expect(error).toMatchObject({ _tag: 'commands/PendingLoginError', reason: 'missing' });
345 + }).pipe(Effect.provide(layer));
346 + });
347 +
348 + it.effect('[Given] --user-api-key [Then] runs the direct flow, not the browser one', () => {
349 + const { layer, logins, createdSessions } = loginHandlerTest();
350 + return Effect.gen(function* () {
351 + yield* runLogin(params({ userApiKey: Option.some('uak_direct') }));
352 +
353 + expect(logins.map(login => login.apiKey)).toEqual(['uak_direct']);
354 + expect(createdSessions).toEqual([]);
355 + }).pipe(Effect.provide(layer));
356 + });
357 +
358 + it.effect('[Given] no flags [Then] runs the browser flow', () => {
359 + const { layer, createdSessions } = loginHandlerTest();
360 + return Effect.gen(function* () {
361 + yield* runLogin(params());
362 +
363 + expect(createdSessions).toEqual(['user']);
364 + }).pipe(Effect.provide(layer));
365 + });
366 +});
367 +
368 +describe('handlePollLogin', () => {
369 + it.effect(
370 + '[Given] a cached login that is linked [Then] stores the first org, clears the cache, and prints the summary JSON',
371 + () => {
372 + const { layer, logins, outputs, pending } = loginHandlerTest({
373 + pending: Option.some({
374 + key: 'session-key',
375 + loginUrl: 'https://platform.mock.invalid/?cliKey=session-key',
376 + expiresAt: '2026-01-01T00:10:00.000Z',
377 + cachedAt: '2026-01-01T00:00:00.000Z',
378 + }),
379 + });
380 + return Effect.gen(function* () {
381 + yield* handlePollLogin({ noSkillInstall: true });
382 +
383 + expect(logins).toEqual([
384 + { apiKey: 'uak_linked', orgId: 'org_first', testUserId: 'pg-test-user_123' },
385 + ]);
386 + expect(analytics.linked).toEqual(['member_org_first']);
387 + expect(Option.isNone(pending.current())).toBe(true);
388 + expect(outputs).toEqual([
389 + JSON.stringify(
390 + {
391 + email: 'poll@example.com',
392 + current_org: { id: 'org_first', name: 'First Org' },
393 + organizations: [
394 + { id: 'org_first', name: 'First Org', selected: true },
395 + { id: 'org_second', name: 'Second Org', selected: false },
396 + ],
397 + switch_command: 'composio orgs switch --org-id <org_id>',
398 + },
399 + null,
400 + 2
401 + ),
402 + ]);
403 + }).pipe(Effect.provide(layer));
404 + }
405 + );
406 +});
407 +
408 +describe('handleSessionKeyLogin', () => {
409 + it.effect('[Given] an unknown session key [Then] fails to load the session', () => {
410 + const { layer, logins } = loginHandlerTest({
411 + session: Effect.fail(notFoundError('session not found')),
412 + });
413 + return Effect.gen(function* () {
414 + const error = yield* Effect.flip(
415 + handleSessionKeyLogin({ key: 'session-key', noWait: true, noSkillInstall: true })
416 + );
417 +
418 + expect(error).toMatchObject({
419 + _tag: 'commands/LoginSessionError',
420 + operation: 'load',
421 + message: SESSION_NOT_FOUND_MESSAGE,
422 + });
423 + expect(logins).toEqual([]);
424 + }).pipe(Effect.provide(layer));
425 + });
426 +
427 + it.effect(
428 + '[Given] --no-wait and a session still pending [Then] reports it and stores nothing',
429 + () => {
430 + const { layer, logins, outputs } = loginHandlerTest({
431 + session: Effect.succeed(pendingSession('session-key')),
432 + });
433 + return Effect.gen(function* () {
434 + const error = yield* Effect.flip(
435 + handleSessionKeyLogin({ key: 'session-key', noWait: true, noSkillInstall: true })
436 + );
437 +
438 + expect(error).toMatchObject({
439 + _tag: 'commands/LoginSessionError',
440 + operation: 'poll',
441 + status: 'pending',
442 + });
443 + expect(yield* stderr).toContain(SESSION_NOT_LINKED_MESSAGE);
444 + expect(logins).toEqual([]);
445 + expect(outputs).toEqual([]);
446 + }).pipe(Effect.provide(layer));
447 + }
448 + );
449 +
450 + it.effect(
451 + '[Given] --no-wait and a linked session [Then] stores the key and prints the login JSON',
452 + () => {
453 + const { layer, logins, outputs } = loginHandlerTest();
454 + return Effect.gen(function* () {
455 + yield* handleSessionKeyLogin({ key: 'session-key', noWait: true, noSkillInstall: true });
456 +
457 + expect(logins.map(login => login.apiKey)).toEqual(['uak_linked']);
458 + expect(outputs).toEqual([
459 + JSON.stringify({ email: 'poll@example.com', org_id: 'org_home', org_name: 'Home Org' }),
460 + ]);
461 + expect(analytics.linked).toEqual(['member_org_home']);
462 + }).pipe(Effect.provide(layer));
463 + }
464 + );
465 +});
466 +
467 +describe('handleDirectLogin', () => {
468 + it.effect('[Given] --org naming an org by name [Then] stores that org', () => {
469 + const { layer, logins, outputs } = loginHandlerTest();
470 + return Effect.gen(function* () {
471 + yield* handleDirectLogin({
472 + userApiKey: 'uak_direct',
473 + org: Option.some('Second Org'),
474 + noSkillInstall: true,
475 + });
476 +
477 + expect(logins).toEqual([
478 + { apiKey: 'uak_direct', orgId: 'org_second', testUserId: 'pg-test-user_123' },
479 + ]);
480 + expect(outputs).toEqual([
481 + JSON.stringify({ email: 'cli@example.com', org_id: 'org_second', org_name: 'Second Org' }),
482 + ]);
483 + }).pipe(Effect.provide(layer));
484 + });
485 +
486 + it.effect('[Given] an empty --org [Then] keeps the home org of the key', () => {
487 + const { layer, logins } = loginHandlerTest();
488 + return Effect.gen(function* () {
489 + yield* handleDirectLogin({
490 + userApiKey: 'uak_direct',
491 + org: Option.some(''),
492 + noSkillInstall: true,
493 + });
494 +
495 + expect(logins.map(login => login.orgId)).toEqual(['org_home']);
496 + expect(analytics.linked).toEqual(['member_home']);
497 + }).pipe(Effect.provide(layer));
498 + });
499 +
500 + it.effect('[Given] --org naming no visible org [Then] fails without storing the key', () => {
501 + const { layer, logins, outputs } = loginHandlerTest();
502 + return Effect.gen(function* () {
503 + const error = yield* Effect.flip(
504 + handleDirectLogin({
505 + userApiKey: 'uak_direct',
506 + org: Option.some('Missing Org'),
507 + noSkillInstall: true,
508 + })
509 + );
510 +
511 + expect(error).toMatchObject({
512 + _tag: 'commands/InvalidOrganizationError',
513 + message: INVALID_ORGANIZATION_MESSAGE,
514 + requestedOrg: 'Missing Org',
515 + });
516 + expect(yield* stderr).toContain('Organization "Missing Org" was not found for this API key.');
517 + expect(logins).toEqual([]);
518 + expect(outputs).toEqual([]);
519 + }).pipe(Effect.provide(layer));
520 + });
521 +});
522 +
523 +describe('handleBrowserLogin', () => {
524 + it.effect('[Given] a stored login with an org [Then] warns and starts no session', () => {
525 + const { layer, createdSessions, outputs } = loginHandlerTest({
526 + apiKey: Option.some('uak_existing'),
527 + orgId: Option.some('org_existing'),
528 + });
529 + return Effect.gen(function* () {
530 + yield* handleBrowserLogin(params());
531 +
532 + expect(yield* stderr).toContain(ALREADY_LOGGED_IN_MESSAGE);
533 + expect(createdSessions).toEqual([]);
534 + expect(outputs).toEqual([]);
535 + }).pipe(Effect.provide(layer));
536 + });
537 +
538 + it.effect(
539 + '[Given] a headless run and no stored agent [Then] caches the session and prints the poll instructions',
540 + () => {
541 + const { layer, createdSessions, outputs, pending, logins } = loginHandlerTest();
542 + return Effect.gen(function* () {
543 + yield* handleBrowserLogin(params());
544 +
545 + expect(createdSessions).toEqual(['user']);
546 + expect(pending.current()).toEqual(
547 + Option.some({
548 + key: 'session-new',
549 + loginUrl: 'https://platform.mock.invalid/?cliKey=session-new',
550 + expiresAt: '2026-01-01T00:10:00.000Z',
551 + cachedAt: '2026-01-01T00:00:00.000Z',
552 + })
553 + );
554 + expect(outputs).toHaveLength(1);
555 + expect(outputs[0]).toContain('https://platform.mock.invalid/?cliKey=session-new');
556 + expect(outputs[0]).toContain('composio login --poll');
557 + expect(logins).toEqual([]);
558 + }).pipe(Effect.provide(layer));
559 + }
560 + );
561 +});
ts/packages/cli/test/src/services/pending-login-session.test.ts new
+125
@@ -0,0 +1,125 @@
1 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 +import * as BunPath from '@effect/platform-bun/BunPath';
3 +import { describe, expect, it } from '@effect/vitest';
4 +import { ConfigProvider, Effect, Layer } from 'effect';
5 +import * as FileSystem from 'effect/FileSystem';
6 +import { TestClock } from 'effect/testing';
7 +import path from 'node:path';
8 +import * as tempy from 'tempy';
9 +import * as constants from 'src/constants';
10 +import { defaultNodeOs, NodeOs } from 'src/services/node-os';
11 +import { PENDING_LOGIN_FILE_NAME, PendingLoginSession } from 'src/services/pending-login-session';
12 +import { hostOnlyEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
13 +
14 +const STARTED = {
15 + key: 'session-key',
16 + loginUrl: 'https://dashboard.composio.dev/?cliKey=session-key',
17 + expiresAt: '1970-01-01T00:10:00.000Z',
18 +};
19 +
20 +/** The real service over a fresh home directory, so the file lands in `<home>/.composio`. */
21 +const pendingLoginTest = () => {
22 + const home = tempy.temporaryDirectory({ prefix: 'pending-login' });
23 + const file = path.join(home, constants.USER_COMPOSIO_DIR, PENDING_LOGIN_FILE_NAME);
24 + const layer = Layer.mergeAll(
25 + Layer.provide(
26 + PendingLoginSession.Default,
27 + Layer.mergeAll(
28 + BunFileSystem.layer,
29 + BunPath.layer,
30 + Layer.succeed(NodeOs, NodeOs.of(defaultNodeOs({ homedir: home })))
31 + )
32 + ),
33 + BunFileSystem.layer,
34 + ConfigProvider.layer(hostOnlyEnvConfigProvider)
35 + );
36 + return { file, layer };
37 +};
38 +
39 +describe('PendingLoginSession', () => {
40 + it.effect(
41 + '[Given] a written login [Then] reads it back from a file only the user can read',
42 + () => {
43 + const { file, layer } = pendingLoginTest();
44 + return Effect.gen(function* () {
45 + const pending = yield* PendingLoginSession;
46 + const fs = yield* FileSystem.FileSystem;
47 +
48 + yield* pending.write(STARTED);
49 +
50 + expect(yield* pending.read).toEqual({ ...STARTED, cachedAt: '1970-01-01T00:00:00.000Z' });
51 + expect((yield* fs.stat(file)).mode & 0o777).toBe(0o600);
52 + }).pipe(Effect.provide(layer));
53 + }
54 + );
55 +
56 + it.effect('[Given] no cached login [Then] fails as missing', () => {
57 + const { layer } = pendingLoginTest();
58 + return Effect.gen(function* () {
59 + const pending = yield* PendingLoginSession;
60 +
61 + const error = yield* Effect.flip(pending.read);
62 +
63 + expect(error).toMatchObject({
64 + _tag: 'commands/PendingLoginError',
65 + reason: 'missing',
66 + message: 'No pending login found. Run `composio login < /dev/null` first.',
67 + });
68 + }).pipe(Effect.provide(layer));
69 + });
70 +
71 + it.effect('[Given] a file that is not a cached login [Then] fails as invalid', () => {
72 + const { file, layer } = pendingLoginTest();
73 + return Effect.gen(function* () {
74 + const pending = yield* PendingLoginSession;
75 + const fs = yield* FileSystem.FileSystem;
76 + yield* fs.makeDirectory(path.dirname(file), { recursive: true });
77 + yield* fs.writeFileString(file, '{"key":"only-a-key"}');
78 +
79 + const error = yield* Effect.flip(pending.read);
80 +
81 + expect(error).toMatchObject({ reason: 'invalid', message: 'Pending login cache is invalid' });
82 + }).pipe(Effect.provide(layer));
83 + });
84 +
85 + it.effect(
86 + '[Given] a login cached over ten minutes ago [Then] deletes it and fails as expired',
87 + () => {
88 + const { file, layer } = pendingLoginTest();
89 + return Effect.gen(function* () {
90 + const pending = yield* PendingLoginSession;
91 + const fs = yield* FileSystem.FileSystem;
92 + yield* pending.write(STARTED);
93 +
94 + yield* TestClock.adjust('10 minutes');
95 + expect(yield* pending.read).toMatchObject({ key: STARTED.key });
96 +
97 + yield* TestClock.adjust('1 millis');
98 + const error = yield* Effect.flip(pending.read);
99 +
100 + expect(error).toMatchObject({
101 + reason: 'expired',
102 + message: 'Pending login expired. Run `composio login < /dev/null` again.',
103 + });
104 + expect(yield* fs.exists(file)).toBe(false);
105 + }).pipe(Effect.provide(layer));
106 + }
107 + );
108 +
109 + it.effect(
110 + '[Given] a cached login [When] cleared twice [Then] the file is gone and both succeed',
111 + () => {
112 + const { file, layer } = pendingLoginTest();
113 + return Effect.gen(function* () {
114 + const pending = yield* PendingLoginSession;
115 + const fs = yield* FileSystem.FileSystem;
116 + yield* pending.write(STARTED);
117 +
118 + yield* pending.clear;
119 + yield* pending.clear;
120 +
121 + expect(yield* fs.exists(file)).toBe(false);
122 + }).pipe(Effect.provide(layer));
123 + }
124 + );
125 +});