@devries-cameron20 / composio Mirror · read-only / commits / 1692bbee7
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

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

Synced Nov 21, 21:00 UTC

fix(cli): make output more LLM friendly (#3450)

## Summary - Route Effect pretty logger output to stderr and share a TTY-based interactive detector for human-only CLI UI. - Gate upgrade notices and default browser login waiting on interactive stdio; non-interactive `composio login` now emits session JSON and exits. - Stream `composio run` helper/subagent logs to stderr (or only to the run log with `--logs-off`) without polluting stdout. - Add a CLI patch changeset. ## Tests - `pnpm -C ts/packages/cli exec vitest run test/src/services/update-check.test.ts test/src/commands/login.cmd.test.ts test/src/commands/run.cmd.test.ts` - `pnpm --filter @composio/cli typecheck` - `pnpm typecheck` - `pnpm exec eslint ts/packages/cli/src/utils/stdio.ts ts/packages/cli/src/services/terminal-ui.ts ts/packages/cli/src/services/update-check.ts ts/packages/cli/src/cli-main.ts ts/packages/cli/src/commands/login.cmd.ts ts/packages/cli/src/commands/run.cmd.ts ts/packages/cli/src/services/run-helpers-runtime.ts --no-warn-ignored` - `pnpm exec prettier --check ts/packages/cli/src/utils/stdio.ts ts/packages/cli/src/services/terminal-ui.ts ts/packages/cli/src/services/update-check.ts ts/packages/cli/src/cli-main.ts ts/packages/cli/src/commands/login.cmd.ts ts/packages/cli/src/commands/run.cmd.ts ts/packages/cli/src/services/run-helpers-runtime.ts ts/packages/cli/test/src/services/update-check.test.ts ts/packages/cli/test/src/commands/login.cmd.test.ts` ## Notes - Initial targeted `pnpm --filter @composio/cli test -- ...` ran the full CLI suite and failed before building `@composio/cli-keyring`; after building/installing workspace deps, the targeted Vitest command above passed.

Rahul Tarak committed May 19, 2026 at 01:45 UTC 1692bbee7a46d6ecda10a7975b4de9bcd18ed396
30 files changed +665 -117
.changeset/quiet-llm-friendly-cli.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +"@composio/cli": patch
3 +---
4 +
5 +Make CLI output more LLM-friendly by gating human-only notices/prompts on interactive TTYs and keeping logs on stderr.
.gitleaks.toml new
+8
@@ -0,0 +1,8 @@
1 +[extend]
2 +useDefault = true
3 +
4 +[allowlist]
5 +description = "Ignore test fixtures and assertions in TypeScript test files"
6 +paths = [
7 + '''\.test\.ts$''',
8 +]
.gitleaksignore
+3
@@ -9,6 +9,9 @@ cadbd463fddb5b31c901d2c222b73354b6d87327:docs/content/docs/tools-direct/toolkit-
9
10 # Test fixture dummy token for verifying Authorization header forwarding (not a real secret)
11 694231f9ffcdb23ca5baf67509101355764d81dc:ts/packages/cli/test/src/services/update-check.test.ts:generic-api-key:296
12 +
13 +# Test assertion for login session JSON field name (not a secret)
14 +9458c6e1b91cb4a2857289cefd723b132b3a9496:ts/packages/cli/test/src/commands/login.cmd.test.ts:generic-api-key:76
15 e921d2d767a779fcaf40fb4f1fde789424d4b7c9:docs/content/docs/importing-existing-connections.mdx:curl-auth-header:207
16 786f40ade6a3a7287c4c79694830edf3c02001d5:docs/content/docs/importing-existing-connections.mdx:curl-auth-header:247
17 786f40ade6a3a7287c4c79694830edf3c02001d5:docs/content/docs/importing-existing-connections.mdx:curl-auth-header:287
ts/packages/cli/src/cli-main.ts
+1 -1
@@ -115,7 +115,7 @@ const layers = Layer.mergeAll(
115 FetchHttpClient.layer,
116 StdinLive,
117 TerminalUILive,
118 - Logger.pretty
118 + Logger.replace(Logger.defaultLogger, Logger.prettyLogger({ stderr: true }))
119 ) satisfies RequiredLayer;
120
121 export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: number) => void) => {
ts/packages/cli/src/commands/agent/commands/agent.whoami.cmd.ts
+1 -1
@@ -26,7 +26,7 @@ export const agentCmd$Whoami = Command.make('whoami', {}).pipe(
26 `Status: ${summary.status}`,
27 `Email: ${summary.email ?? 'unknown'}`,
28 `Slug: ${summary.slug ?? 'unknown'}`,
29 - `Default Org ID: ${summary.org_id ?? 'pending'}`,
29 + `Current Org ID: ${summary.org_id ?? 'pending'}`,
30 `Project ID: ${summary.project_id ?? 'pending'}`,
31 `Claimed By: ${summary.claimed_by ?? 'not claimed'}`,
32 ].join('\n'),
ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts
+25 -2
@@ -9,13 +9,20 @@ import {
9 resolveCommandProject,
10 } from 'src/services/command-project';
11 import { TerminalUI } from 'src/services/terminal-ui';
12 +import {
13 + getConnectedAccountPermissionGroup,
14 + getConsumerPermissionSnapshot,
15 +} from 'src/services/tool-permissions';
16
17 const toolkit = Options.text('toolkit').pipe(
18 Options.withDescription('Filter by toolkit slug (e.g. "gmail")'),
19 Options.optional
20 );
21
18 -const formatConnectionsJson = (items: ReadonlyArray<ConnectedAccountItem>): string => {
22 +const formatConnectionsJson = (
23 + items: ReadonlyArray<ConnectedAccountItem>,
24 + permissionGroups: ReadonlyMap<string, string | undefined> = new Map()
25 +): string => {
26 const toolkitCounts = items.reduce<Map<string, number>>((acc, item) => {
27 acc.set(item.toolkit.slug, (acc.get(item.toolkit.slug) ?? 0) + 1);
28 return acc;
@@ -30,6 +37,7 @@ const formatConnectionsJson = (items: ReadonlyArray<ConnectedAccountItem>): stri
37 status: item.status,
38 ...(includeAlias ? { alias: item.alias ?? null } : {}),
39 ...(item.word_id != null ? { word_id: item.word_id } : {}),
40 + permission_group: permissionGroups.get(item.id) ?? null,
41 };
42
43 if (!acc[toolkit]) {
@@ -72,8 +80,23 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit
80 })
81 );
82 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
83 + const permissionSnapshot = yield* getConsumerPermissionSnapshot({
84 + orgId: resolvedProject.orgId,
85 + projectId: resolvedProject.projectId,
86 + consumerUserId,
87 + connectedAccountIds: result.items.map(item => item.id),
88 + });
89 + const permissionGroups = new Map(
90 + result.items.map(item => [
91 + item.id,
92 + getConnectedAccountPermissionGroup({
93 + snapshot: permissionSnapshot,
94 + connectedAccountId: item.id,
95 + }),
96 + ])
97 + );
98
76 - yield* ui.output(formatConnectionsJson(result.items), { force: true });
99 + yield* ui.output(formatConnectionsJson(result.items, permissionGroups), { force: true });
100 })
101 ).pipe(
102 Command.withDescription(
ts/packages/cli/src/commands/init.cmd.ts
+1 -1
@@ -33,7 +33,7 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
33 const yesOpt = Options.boolean('yes').pipe(
34 Options.withAlias('y'),
35 Options.withDefault(false),
36 - Options.withDescription('Auto-select the default org project, else first developer project')
36 + Options.withDescription('Auto-select the current org project, else first developer project')
37 );
38
39 // ---------------------------------------------------------------------------
ts/packages/cli/src/commands/login.cmd.ts
+289 -33
@@ -1,4 +1,6 @@
1 +import path from 'node:path';
2 import { Command, Options } from '@effect/cli';
3 +import { FileSystem } from '@effect/platform';
4 import { DateTime, Effect, Option, Schedule } from 'effect';
5 import open from 'open';
6 import {
@@ -6,16 +8,19 @@ import {
8 getSessionInfo,
9 getSessionInfoByUserApiKey,
10 listOrganizations,
11 + type OrganizationSummary,
12 type SessionInfoResponse,
13 } from 'src/services/composio-clients';
14 import { ComposioUserContext } from 'src/services/user-context';
15 import { TerminalUI } from 'src/services/terminal-ui';
16 import { commandHintStep } from 'src/services/command-hints';
17 import { runOrgSelection } from 'src/effects/select-org-project';
18 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
19 import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
20 import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';
21 import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
22 import { APP_VERSION } from 'src/constants';
23 +import { isInteractiveTerminal } from 'src/utils/stdio';
24 import {
25 ensureAgentSignupAllowed,
26 getOrSignupReadyAgent,
@@ -28,6 +33,11 @@ export const noBrowser = Options.boolean('no-browser').pipe(
33 Options.withDescription('Login without browser interaction')
34 );
35
36 +const pollOpt = Options.boolean('poll').pipe(
37 + Options.withDefault(false),
38 + Options.withDescription('Poll the most recent pending browser login and complete it')
39 +);
40 +
41 const noWait = Options.boolean('no-wait').pipe(
42 Options.withDefault(false),
43 Options.withDescription(
@@ -36,7 +46,7 @@ const noWait = Options.boolean('no-wait').pipe(
46 );
47
48 const keyOpt = Options.text('key').pipe(
39 - Options.withDescription('Complete login using session key from composio login --no-wait'),
49 + Options.withDescription('Poll and complete login using the session key from composio login'),
50 Options.optional
51 );
52
@@ -46,14 +56,14 @@ const userApiKeyOpt = Options.text('user-api-key').pipe(
56 );
57
58 const orgOpt = Options.text('org').pipe(
49 - Options.withDescription('Default organization ID or name to store for CLI commands'),
59 + Options.withDescription('Current organization ID or name to store for CLI commands'),
60 Options.optional
61 );
62
63 const yesOpt = Options.boolean('yes').pipe(
64 Options.withAlias('y'),
65 Options.withDefault(false),
56 - Options.withDescription('Skip org picker; use session default org')
66 + Options.withDescription('Skip org picker; use current org')
67 );
68
69 const noSkillInstall = Options.boolean('no-skill-install').pipe(
@@ -66,6 +76,152 @@ const agentOpt = Options.boolean('agent').pipe(
76 Options.withDescription('Sign up or log in using a Composio agent identity')
77 );
78
79 +const PENDING_LOGIN_FILE_NAME = 'pending-login-session.json';
80 +const PENDING_LOGIN_TTL_MS = 10 * 60 * 1000;
81 +const LOGIN_POLL_INTERVAL_SECONDS = 5;
82 +const LOGIN_POLL_TIMEOUT_SECONDS = 10 * 60;
83 +const LOGIN_POLL_RETRIES = Math.ceil(LOGIN_POLL_TIMEOUT_SECONDS / LOGIN_POLL_INTERVAL_SECONDS);
84 +
85 +type PendingLoginSession = {
86 + readonly key: string;
87 + readonly loginUrl: string;
88 + readonly expiresAt: string;
89 + readonly cachedAt: string;
90 +};
91 +
92 +const pendingLoginPath = Effect.gen(function* () {
93 + const cacheDir = yield* setupCacheDir;
94 + return path.join(cacheDir, PENDING_LOGIN_FILE_NAME);
95 +});
96 +
97 +const isRecord = (value: unknown): value is Record<string, unknown> =>
98 + typeof value === 'object' && value !== null;
99 +
100 +const parsePendingLoginSession = (raw: string): PendingLoginSession => {
101 + const parsed: unknown = JSON.parse(raw);
102 + if (
103 + !isRecord(parsed) ||
104 + typeof parsed.key !== 'string' ||
105 + typeof parsed.loginUrl !== 'string' ||
106 + typeof parsed.expiresAt !== 'string' ||
107 + typeof parsed.cachedAt !== 'string'
108 + ) {
109 + throw new Error('Pending login cache is invalid');
110 + }
111 + return {
112 + key: parsed.key,
113 + loginUrl: parsed.loginUrl,
114 + expiresAt: parsed.expiresAt,
115 + cachedAt: parsed.cachedAt,
116 + };
117 +};
118 +
119 +const writePendingLoginSession = (session: Omit<PendingLoginSession, 'cachedAt'>) =>
120 + Effect.gen(function* () {
121 + const fs = yield* FileSystem.FileSystem;
122 + const filePath = yield* pendingLoginPath;
123 + const payload: PendingLoginSession = {
124 + ...session,
125 + cachedAt: new Date().toISOString(),
126 + };
127 + yield* fs.writeFileString(filePath, `${JSON.stringify(payload, null, 2)}\n`);
128 + });
129 +
130 +const clearPendingLoginSession = Effect.gen(function* () {
131 + const fs = yield* FileSystem.FileSystem;
132 + const filePath = yield* pendingLoginPath;
133 + yield* fs.remove(filePath).pipe(Effect.catchAll(() => Effect.void));
134 +});
135 +
136 +const readPendingLoginSession = Effect.gen(function* () {
137 + const fs = yield* FileSystem.FileSystem;
138 + const filePath = yield* pendingLoginPath;
139 + const exists = yield* fs.exists(filePath);
140 + if (!exists) {
141 + return yield* Effect.fail(
142 + new Error('No pending login found. Run `composio login < /dev/null` first.')
143 + );
144 + }
145 +
146 + const session = yield* fs
147 + .readFileString(filePath, 'utf8')
148 + .pipe(Effect.map(parsePendingLoginSession));
149 + const cachedAt = Date.parse(session.cachedAt);
150 + if (!Number.isFinite(cachedAt) || Date.now() - cachedAt > PENDING_LOGIN_TTL_MS) {
151 + yield* clearPendingLoginSession;
152 + return yield* Effect.fail(
153 + new Error('Pending login expired. Run `composio login < /dev/null` again.')
154 + );
155 + }
156 +
157 + return session;
158 +});
159 +
160 +const formatNonInteractiveLoginInstructions = (params: {
161 + readonly loginUrl: string;
162 + readonly pollCommand: string;
163 +}) => `Open this URL in your browser to log in:
164 +
165 + ${params.loginUrl}
166 +
167 +Then run this command to complete login:
168 +
169 + ${params.pollCommand}
170 +
171 +hint: For agents: Show the URL above to the user to click, then run the command above. The command uses the cached login key, polls for up to 10 minutes, and exits once credentials are saved. Do not ask the user whether to poll — they already requested login.`;
172 +
173 +const formatPollLoginComplete = (params: {
174 + readonly email?: string;
175 + readonly defaultOrgId: string;
176 + readonly defaultOrgName?: string;
177 + readonly organizations: ReadonlyArray<OrganizationSummary>;
178 +}) => {
179 + const orgLines =
180 + params.organizations.length > 0
181 + ? params.organizations
182 + .map(org => ` ${org.id === params.defaultOrgId ? '*' : '-'} ${org.name} (${org.id})`)
183 + .join('\n')
184 + : ' No organizations were returned for this account.';
185 +
186 + return `Login complete${params.email ? ` for ${params.email}` : ''}.
187 +
188 +Current org:
189 +
190 + ${params.defaultOrgName ?? params.defaultOrgId} (${params.defaultOrgId})
191 +
192 +Available organizations:
193 +
194 +${orgLines}
195 +
196 +The CLI selected the first organization as your current org. To choose a different current org, run:
197 +
198 + composio orgs switch --org-id <org_id>`;
199 +};
200 +
201 +const serializePollLoginResult = (params: {
202 + readonly email?: string;
203 + readonly defaultOrgId: string;
204 + readonly defaultOrgName?: string;
205 + readonly organizations: ReadonlyArray<OrganizationSummary>;
206 +}) =>
207 + JSON.stringify(
208 + {
209 + email: params.email ?? null,
210 + current_org: {
211 + id: params.defaultOrgId,
212 + name: params.defaultOrgName ?? params.defaultOrgId,
213 + },
214 + organizations: params.organizations.map(org => ({
215 + id: org.id,
216 + name: org.name,
217 + selected: org.id === params.defaultOrgId,
218 + })),
219 + switch_command: 'composio orgs switch --org-id <org_id>',
220 + },
221 + null,
222 + 2
223 + );
224 +
225 const formatLoginSuccessMessage = (params: { email?: string; orgName?: string }): string => {
226 const { email, orgName } = params;
227 if (email && orgName) {
@@ -93,7 +249,7 @@ const emitLoginComplete = (params: {
249 yield* ui.log.success(formatLoginSuccessMessage({ email, orgName }));
250 if (!skipHints) {
251 yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
96 - yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
252 + yield* ui.log.info(commandHintStep('Switch your current org', 'root.orgs.switch'));
253 }
254
255 yield* ui.output(
@@ -267,7 +423,14 @@ const storeCredentials = (params: {
423 * When noWait is false: polls until session is linked (same as browser flow).
424 * When noWait is true: checks once and fails if not linked.
425 */
270 -const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPicker: boolean }) =>
426 +const loginWithKey = (params: {
427 + key: string;
428 + noWait: boolean;
429 + skipOrgProjectPicker: boolean;
430 + pollRetries?: number;
431 + defaultToFirstOrg?: boolean;
432 + skipOutput?: boolean;
433 +}) =>
434 Effect.gen(function* () {
435 const ui = yield* TerminalUI;
436 const ctx = yield* ComposioUserContext;
@@ -307,8 +470,8 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
470 );
471 }),
472 Schedule.exponential('0.3 seconds').pipe(
310 - Schedule.intersect(Schedule.recurs(15)),
311 - Schedule.intersect(Schedule.spaced('5 seconds'))
473 + Schedule.intersect(Schedule.recurs(params.pollRetries ?? 15)),
474 + Schedule.intersect(Schedule.spaced(`${LOGIN_POLL_INTERVAL_SECONDS} seconds`))
475 )
476 ).pipe(
477 Effect.tap(() => spinner.stop('Login successful')),
@@ -323,8 +486,24 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
486 userApiKey: uakApiKey,
487 });
488
489 + const organizations = params.defaultToFirstOrg
490 + ? yield* listOrganizations({
491 + baseURL: ctx.data.baseURL,
492 + apiKey: uakApiKey,
493 + }).pipe(
494 + Effect.map(response => response.data),
495 + Effect.catchAll(error =>
496 + Effect.gen(function* () {
497 + yield* Effect.logDebug('Failed to list organizations after login:', error);
498 + return [] as ReadonlyArray<OrganizationSummary>;
499 + })
500 + )
501 + )
502 + : [];
503 + const defaultOrg = params.defaultToFirstOrg ? organizations[0] : undefined;
504 const xProjectId = uakSessionInfo.project.nano_id;
327 - const xOrgId = uakSessionInfo.project.org.id;
505 + const xOrgId = defaultOrg?.id ?? uakSessionInfo.project.org.id;
506 + const xOrgName = defaultOrg?.name ?? uakSessionInfo.project.org.name;
507
508 const willRunPicker = !params.skipOrgProjectPicker;
509 yield* storeCredentials({
@@ -334,7 +513,7 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
513 initialProjectId: xProjectId,
514 fallbackEmail: linkedSession.account.email,
515 skipHints: willRunPicker,
337 - skipOutput: willRunPicker,
516 + skipOutput: true,
517 });
518
519 if (willRunPicker) {
@@ -345,7 +524,7 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
524 Effect.catchAll(error =>
525 Effect.gen(function* () {
526 yield* Effect.logDebug('Org picker failed:', error);
348 - yield* ui.log.warn('Could not load org list. Using session default org.');
527 + yield* ui.log.warn('Could not load org list. Using current org.');
528 return undefined;
529 })
530 )
@@ -369,7 +548,28 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
548 orgId: finalOrgId,
549 orgName: finalOrgName,
550 });
551 + return {
552 + email: linkedSession.account.email ?? undefined,
553 + orgId: finalOrgId,
554 + orgName: finalOrgName,
555 + organizations,
556 + };
557 + }
558 +
559 + if (!params.skipOutput) {
560 + yield* emitLoginComplete({
561 + email: linkedSession.account.email ?? undefined,
562 + orgId: xOrgId,
563 + orgName: xOrgName,
564 + });
565 }
566 +
567 + return {
568 + email: linkedSession.account.email ?? undefined,
569 + orgId: xOrgId,
570 + orgName: xOrgName,
571 + organizations,
572 + };
573 });
574
575 /**
@@ -403,8 +603,34 @@ export const browserLogin = (params: {
603 yield* Effect.logDebug(`Created session: ${session.id}`);
604
605 const url = `${ctx.data.webURL}?cliKey=${session.id}`;
606 + const pollCommand = 'composio login --poll';
607 + const expiresAt = DateTime.formatIso(session.expiresAt);
608 + yield* writePendingLoginSession({
609 + key: session.id,
610 + loginUrl: url,
611 + expiresAt,
612 + });
613 +
614 + const canPrompt = isInteractiveTerminal();
615 + const effectiveNoWait = params.noWait || !canPrompt;
616 + const effectiveNoBrowser = params.noBrowser || effectiveNoWait;
617 +
618 + if (effectiveNoWait) {
619 + const loginInstructions = formatNonInteractiveLoginInstructions({
620 + loginUrl: url,
621 + pollCommand,
622 + });
623 +
624 + if (canPrompt) {
625 + yield* ui.log.info('Please login using the following URL:');
626 + yield* ui.note(url, 'Login URL');
627 + yield* ui.note(loginInstructions, 'Login instructions');
628 + }
629 +
630 + yield* ui.output(loginInstructions);
631 + return;
632 + }
633
407 - const effectiveNoBrowser = params.noBrowser || params.noWait;
634 if (effectiveNoBrowser) {
635 yield* ui.log.info('Please login using the following URL:');
636 } else {
@@ -413,19 +639,6 @@ export const browserLogin = (params: {
639
640 yield* ui.note(url, 'Login URL');
641
416 - if (params.noWait) {
417 - const loginInfo = {
418 - status: 'pending',
419 - message: 'Complete login by opening the URL',
420 - login_url: url,
421 - cli_key: session.id,
422 - expires_at: DateTime.formatIso(session.expiresAt),
423 - };
424 - yield* ui.note(JSON.stringify(loginInfo, null, 2), 'Login info');
425 - yield* ui.output(JSON.stringify(loginInfo, null, 2));
426 - return;
427 - }
428 -
642 yield* ui.output(url);
643
644 if (!effectiveNoBrowser) {
@@ -499,7 +712,7 @@ export const browserLogin = (params: {
712 Effect.catchAll(error =>
713 Effect.gen(function* () {
714 yield* Effect.logDebug('Org picker failed:', error);
502 - yield* ui.log.warn('Could not load org list. Using session default org.');
715 + yield* ui.log.warn('Could not load org list. Using current org.');
716 return undefined;
717 })
718 )
@@ -534,9 +747,9 @@ export const browserLogin = (params: {
747 * Use --no-wait to print login URL and session info (JSON) then exit without opening browser or waiting.
748 * Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;
749 * with --no-wait, checks once and fails if not linked.
537 - * Use --user-api-key to log in directly without a browser flow, and --org to override the default org.
750 + * Use --user-api-key to log in directly without a browser flow, and --org to override the current org.
751 * Use --agent to sign up or log in using a Composio agent identity.
539 - * Use -y to skip org picker and use session default org.
752 + * Use -y to skip org picker and use current org.
753 *
754 * @example
755 * ```bash
@@ -555,6 +768,7 @@ export const loginCmd = Command.make(
768 'login',
769 {
770 noBrowser,
771 + poll: pollOpt,
772 noWait,
773 key: keyOpt,
774 userApiKey: userApiKeyOpt,
@@ -563,17 +777,31 @@ export const loginCmd = Command.make(
777 noSkillInstall,
778 agent: agentOpt,
779 },
566 - ({ noBrowser, noWait, key, userApiKey, org, yes, noSkillInstall, agent }) =>
780 + ({ noBrowser, poll, noWait, key, userApiKey, org, yes, noSkillInstall, agent }) =>
781 Effect.gen(function* () {
782 const ui = yield* TerminalUI;
783 const ctx = yield* ComposioUserContext;
784 + const canPrompt = isInteractiveTerminal();
785
571 - yield* ui.intro('composio login');
786 + if (canPrompt) {
787 + yield* ui.intro('composio login');
788 + }
789
790 if (Option.isSome(key) && Option.isSome(userApiKey)) {
791 return yield* Effect.fail(new Error('Use either `--key` or `--user-api-key`, not both.'));
792 }
793
794 + if (
795 + poll &&
796 + (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey) || agent)
797 + ) {
798 + return yield* Effect.fail(
799 + new Error(
800 + '`--poll` cannot be combined with browser, session, direct-login, or agent flags.'
801 + )
802 + );
803 + }
804 +
805 if (agent && (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey))) {
806 return yield* Effect.fail(
807 new Error('`--agent` cannot be combined with browser, session, or direct-login flags.')
@@ -592,6 +820,34 @@ export const loginCmd = Command.make(
820 );
821 }
822
823 + if (poll) {
824 + const pendingLogin = yield* readPendingLoginSession;
825 + const loginResult = yield* loginWithKey({
826 + key: pendingLogin.key,
827 + noWait: false,
828 + skipOrgProjectPicker: true,
829 + pollRetries: LOGIN_POLL_RETRIES,
830 + defaultToFirstOrg: true,
831 + skipOutput: true,
832 + });
833 + yield* clearPendingLoginSession;
834 + const pollSummaryParams = {
835 + email: loginResult.email,
836 + defaultOrgId: loginResult.orgId,
837 + defaultOrgName: loginResult.orgName,
838 + organizations: loginResult.organizations,
839 + };
840 + const pollSummary = formatPollLoginComplete(pollSummaryParams);
841 + if (canPrompt) {
842 + yield* ui.note(pollSummary, 'Login complete');
843 + }
844 + yield* ui.output(serializePollLoginResult(pollSummaryParams), { force: true });
845 + if (!noSkillInstall && canPrompt) {
846 + yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
847 + }
848 + return;
849 + }
850 +
851 if (agent) {
852 return yield* handleAgentAuthError(
853 Effect.gen(function* () {
@@ -603,7 +859,7 @@ export const loginCmd = Command.make(
859 `Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`
860 );
861 yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));
606 - if (!noSkillInstall) {
862 + if (!noSkillInstall && canPrompt) {
863 yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
864 }
865 })
@@ -616,7 +872,7 @@ export const loginCmd = Command.make(
872 noWait,
873 skipOrgProjectPicker: true,
874 });
619 - if (!noSkillInstall) {
875 + if (!noSkillInstall && canPrompt) {
876 yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
877 }
878 return;
@@ -627,7 +883,7 @@ export const loginCmd = Command.make(
883 userApiKey: userApiKey.value,
884 org: Option.getOrUndefined(org),
885 });
630 - if (!noSkillInstall) {
886 + if (!noSkillInstall && canPrompt) {
887 yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
888 }
889 return;
@@ -651,7 +907,7 @@ export const loginCmd = Command.make(
907 skipOrgProjectPicker: yes,
908 });
909
654 - if (!noSkillInstall && !noWait) {
910 + if (!noSkillInstall && !noWait && canPrompt) {
911 yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
912 }
913 })
ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts
+6 -5
@@ -31,14 +31,15 @@ export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId,
31 }
32
33 yield* ui.note(
34 - 'This updates your default org for CLI commands. Use `composio dev init` for local developer project setup.',
35 - 'Global defaults'
34 + 'This updates your current org for CLI commands. Use `composio dev init` for local developer project setup.',
35 + 'Current org'
36 );
37
38 const result = yield* runOrgSelection({
39 apiKey,
40 baseURL: ctx.data.baseURL,
41 explicitOrgId: Option.getOrUndefined(orgId),
42 + currentOrgId: Option.getOrUndefined(ctx.data.orgId),
43 limit,
44 });
45
@@ -49,13 +50,13 @@ export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId,
50
51 yield* ctx.login(apiKey, result.id, Option.getOrUndefined(ctx.data.testUserId));
52
52 - yield* ui.log.success(`Updated default org to "${result.name}".`);
53 + yield* ui.log.success(`Updated current org to "${result.name}".`);
54 yield* ui.output(
55 JSON.stringify({
56 scope: 'global',
57 org_id: result.id,
58 })
59 );
59 - yield* ui.outro('Default org updated.');
60 + yield* ui.outro('Current org updated.');
61 })
61 -).pipe(Command.withDescription('Switch default organization context.'));
62 +).pipe(Command.withDescription('Switch current organization context.'));
ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts
+2 -2
@@ -31,7 +31,7 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,
31
32 const resolvedOrgId = Option.getOrUndefined(orgId) ?? Option.getOrUndefined(ctx.data.orgId);
33 if (!resolvedOrgId) {
34 - yield* ui.log.warn('No default org is configured.');
34 + yield* ui.log.warn('No current org is configured.');
35 yield* ui.outro('Hint: run `composio orgs switch` first, or pass `--org-id`.');
36 return;
37 }
@@ -66,7 +66,7 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,
66 yield* ui.outro(
67 [
68 'Hint: run `composio dev init` in a directory to bind it to a developer project.',
69 - 'Run `composio orgs switch` to change your default org.',
69 + 'Run `composio orgs switch` to change your current org.',
70 ].join('\n')
71 );
72
ts/packages/cli/src/commands/root-help.ts
+10 -6
@@ -165,7 +165,7 @@ const ACCOUNT_COMMANDS: ReadonlyArray<TaggedValue<CompactCommand>> = [
165 tagged({ name: 'login', description: 'Log in to Composio' }),
166 tagged({ name: 'logout', description: 'Log out from Composio' }),
167 tagged({ name: 'whoami', description: 'Show current account info' }),
168 - tagged({ name: 'orgs', description: 'Manage default organization context (list, switch)' }),
168 + tagged({ name: 'orgs', description: 'Manage current organization context (list, switch)' }),
169 tagged({ name: 'version', description: 'Display CLI version' }),
170 tagged({ name: 'upgrade', description: 'Upgrade CLI to the latest version' }),
171 tagged({ name: 'config', description: 'View and manage CLI configuration' }),
@@ -829,13 +829,13 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHel
829
830 login: {
831 usage:
832 - 'composio login [--no-browser] [--no-wait] [--key text] [--user-api-key text] [--org text] [-y, --yes] [--no-skill-install]',
832 + 'composio login [--no-browser] [--poll] [--no-wait] [--key text] [--user-api-key text] [--org text] [-y, --yes] [--no-skill-install]',
833 description:
834 'Log in to the Composio CLI session. By default, also installs the composio-cli skill for Claude Code.',
835 options: [
836 {
837 name: '--key <text>',
838 - description: 'Complete login using session key from composio login --no-wait',
838 + description: 'Poll and complete login using the session key from composio login',
839 },
840 {
841 name: '--user-api-key <text>',
@@ -843,13 +843,17 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHel
843 },
844 {
845 name: '--org <text>',
846 - description: 'Default organization ID or name to store for CLI commands',
846 + description: 'Current organization ID or name to store for CLI commands',
847 },
848 ],
849 flags: [
850 { name: '--no-browser', description: 'Login without browser interaction' },
851 + {
852 + name: '--poll',
853 + description: 'Poll the cached pending login key for up to 10 minutes',
854 + },
855 { name: '--no-wait', description: 'Print login URL and session info, then exit' },
852 - { name: '-y, --yes', description: 'Skip org picker; use session default org' },
856 + { name: '-y, --yes', description: 'Skip org picker; use current org' },
857 {
858 name: '--no-skill-install',
859 description: 'Skip installing the composio-cli skill for Claude Code',
@@ -1015,7 +1019,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHel
1019 description: 'Initialize this directory with a developer project.',
1020 flags: [
1021 { name: '--no-browser', description: 'Login without browser interaction' },
1018 - { name: '-y, --yes', description: 'Auto-select the default org project' },
1022 + { name: '-y, --yes', description: 'Auto-select the current org project' },
1023 ],
1024 },
1025 'dev playground-execute': {
ts/packages/cli/src/commands/run.cmd.ts
+1 -3
@@ -38,9 +38,7 @@ const debug = Options.boolean('debug').pipe(
38 Options.withDefault(false)
39 );
40 const logsOff = Options.boolean('logs-off').pipe(
41 - Options.withDescription(
42 - 'Compatibility flag. Helper logs are written to the run log file instead of stderr.'
43 - ),
41 + Options.withDescription('Hide helper streaming logs; keep them only in the run log file.'),
42 Options.withDefault(false)
43 );
44 const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
ts/packages/cli/src/commands/signup.cmd.ts
+1 -1
@@ -56,7 +56,7 @@ export const runAgentSignup = (params: {
56 `Status: ${summary.status}`,
57 `Email: ${summary.email ?? 'unknown'}`,
58 `Slug: ${summary.slug ?? 'unknown'}`,
59 - `Default Org ID: ${summary.org_id ?? 'pending'}`,
59 + `Current Org ID: ${summary.org_id ?? 'pending'}`,
60 `Project ID: ${summary.project_id ?? 'pending'}`,
61 `Agent key: stored in ~/.composio/agent.json`,
62 ].join('\n'),
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+18 -11
@@ -583,6 +583,8 @@ const emitExecuteFailureTelemetry = (params: {
583 }
584 });
585
586 +const writeExecuteStdout = (ui: TerminalUI, data: string) => ui.output(data, { force: true });
587 +
588 export const showToolsExecuteInputHelp = (toolSlug: string) =>
589 Effect.gen(function* () {
590 if (!(yield* requireAuth)) return;
@@ -621,7 +623,8 @@ export const showToolsExecuteInputHelp = (toolSlug: string) =>
623
624 yield* ui.note(formatToolInputParameters(tool), `Execute Help: ${tool.slug}`);
625 yield* ui.log.step(`Run:\n> composio execute "${tool.slug}" -d '{"key":"value"}'`);
624 - yield* ui.output(
626 + yield* writeExecuteStdout(
627 + ui,
628 JSON.stringify({ slug: tool.slug, input_parameters: tool.input_parameters }, null, 2)
629 );
630 });
@@ -932,7 +935,8 @@ const emitCachedSchema = (
935 yield* ui.log.message(
936 `Schema saved, inspect keys like: jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}' ${definition.schemaPath}`
937 );
935 - yield* ui.output(
938 + yield* writeExecuteStdout(
939 + ui,
940 JSON.stringify(
941 {
942 slug,
@@ -1239,7 +1243,8 @@ const runConnectedToolkitFailFast = (params: {
1243 const message = `Toolkit "${toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`;
1244 yield* params.ui.log.error(message);
1245 yield* params.ui.note(connectionTips(params.slug, params.surface), 'Tips');
1242 - yield* params.ui.output(
1246 + yield* writeExecuteStdout(
1247 + params.ui,
1248 JSON.stringify(
1249 {
1250 successful: false,
@@ -1352,7 +1357,7 @@ const runExecuteWithSpinner = (params: {
1357 ? 'No tool was executed. Local validation was skipped.'
1358 : 'No tool was executed. Arguments were validated locally only.'
1359 );
1355 - yield* params.ui.output(JSON.stringify(summary, ciRedactReplacer, 2));
1360 + yield* writeExecuteStdout(params.ui, JSON.stringify(summary, ciRedactReplacer, 2));
1361 yield* appendCliSessionHistory({
1362 orgId:
1363 params.resolvedProject.projectType === 'CONSUMER'
@@ -1398,7 +1403,8 @@ const runExecuteWithSpinner = (params: {
1403 projectMode: params.projectMode,
1404 stage: 'execution',
1405 });
1401 - yield* params.ui.output(
1406 + yield* writeExecuteStdout(
1407 + params.ui,
1408 JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
1409 );
1410 yield* appendCliSessionHistory({
@@ -1448,7 +1454,7 @@ const runExecuteWithSpinner = (params: {
1454 stage: 'execution',
1455 logId: result.logId,
1456 });
1451 - yield* params.ui.output(JSON.stringify(result, ciRedactReplacer, 2));
1457 + yield* writeExecuteStdout(params.ui, JSON.stringify(result, ciRedactReplacer, 2));
1458 return yield* Effect.fail(new ToolExecutionError(summary.error));
1459 }
1460
@@ -1464,7 +1470,7 @@ const runExecuteWithSpinner = (params: {
1470 yield* params.ui.log.message(
1471 `Response stored in ${output.summary.outputFilePath} (${output.summary.tokenCount} tokens)`
1472 );
1467 - yield* params.ui.output(JSON.stringify(output.summary, ciRedactReplacer, 2));
1473 + yield* writeExecuteStdout(params.ui, JSON.stringify(output.summary, ciRedactReplacer, 2));
1474 yield* appendCliSessionHistory({
1475 orgId:
1476 params.resolvedProject.projectType === 'CONSUMER'
@@ -1488,8 +1494,7 @@ const runExecuteWithSpinner = (params: {
1494 return;
1495 }
1496
1491 - yield* params.ui.log.message(`Response\n${output.json}`);
1492 - yield* params.ui.output(output.json);
1497 + yield* writeExecuteStdout(params.ui, output.json);
1498 yield* appendCliSessionHistory({
1499 orgId:
1500 params.resolvedProject.projectType === 'CONSUMER'
@@ -1867,7 +1872,8 @@ const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>
1872 yield* ui.log.message(
1873 `Parallel execute completed: ${results.filter(result => result.successful).length}/${results.length} successful`
1874 );
1870 - yield* ui.output(
1875 + yield* writeExecuteStdout(
1876 + ui,
1877 JSON.stringify(
1878 {
1879 successful,
@@ -2041,7 +2047,8 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
2047 yield* ui.log.message(
2048 `Parallel execute completed: ${results.filter(result => result.successful).length}/${results.length} successful`
2049 );
2044 - yield* ui.output(
2050 + yield* writeExecuteStdout(
2051 + ui,
2052 JSON.stringify(
2053 {
2054 successful,
ts/packages/cli/src/commands/whoami.cmd.ts
+13 -8
@@ -5,6 +5,7 @@ import { ComposioUserContext } from 'src/services/user-context';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { commandHintStep } from 'src/services/command-hints';
7 import { readStoredAgentIdentity } from 'src/services/agents';
8 +import { getOrgEnhancedControlsStatus } from 'src/services/tool-permissions';
9
10 /**
11 * CLI command to display your account information.
@@ -27,8 +28,6 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
28 onNone: () => ui.log.warn('You are not logged in yet. Please run `composio login`.'),
29 onSome: apiKey =>
30 Effect.gen(function* () {
30 - const defaultOrgId = Option.getOrUndefined(ctx.data.orgId);
31 - const testUserId = Option.getOrUndefined(ctx.data.testUserId);
31 const sessionInfo = yield* getSessionInfoByUserApiKey({
32 baseURL: ctx.data.baseURL,
33 userApiKey: apiKey,
@@ -39,6 +38,14 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
38 const orgName = Option.map(sessionInfo, info => info.project.org.name).pipe(
39 Option.getOrUndefined
40 );
41 + const enhancedControls = yield* Option.match(sessionInfo, {
42 + onNone: () => Effect.succeed(undefined),
43 + onSome: info =>
44 + getOrgEnhancedControlsStatus({
45 + orgId: info.project.org.id,
46 + projectId: info.project.nano_id,
47 + }),
48 + });
49 const storedAgent = yield* readStoredAgentIdentity;
50 const isStoredAgentKey = Option.match(storedAgent, {
51 onNone: () => false,
@@ -51,9 +58,8 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
58 [
59 `Type: ${accountType}`,
60 `Email: ${email ?? 'unknown'}`,
54 - `Default Org: ${orgName ?? 'unknown'}`,
55 - `Default Org ID: ${defaultOrgId ?? 'not set'}`,
56 - `Test User ID: ${testUserId ?? 'not set'}`,
61 + `Current Org: ${orgName ?? 'unknown'}`,
62 + `Enhanced Controls: ${enhancedControls?.remoteEnabled ? 'on' : 'off'}`,
63 ].join('\n'),
64 'Global User Context'
65 );
@@ -67,9 +73,8 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
73 JSON.stringify({
74 account_type: accountType,
75 email: email ?? null,
70 - default_org_name: orgName ?? null,
71 - default_org_id: defaultOrgId ?? null,
72 - test_user_id: testUserId ?? null,
76 + current_org_name: orgName ?? null,
77 + enhanced_controls_enabled: enhancedControls?.remoteEnabled ?? null,
78 })
79 );
80 }),
ts/packages/cli/src/effects/select-org-project.ts
+29 -5
@@ -6,13 +6,33 @@ import { clampLimit } from 'src/ui/clamp-limit';
6 const DEFAULT_LIMIT = 50;
7
8 /** Prompts user to select an org, or auto-selects if only one. */
9 -const selectOrganization = (organizations: ReadonlyArray<OrganizationSummary>) =>
9 +const selectOrganization = (params: {
10 + organizations: ReadonlyArray<OrganizationSummary>;
11 + currentOrgId?: string;
12 +}) =>
13 Effect.gen(function* () {
14 const ui = yield* TerminalUI;
15 + const { organizations, currentOrgId } = params;
16 if (organizations.length === 0) return undefined;
17 if (organizations.length === 1) return organizations[0];
14 - return yield* ui.select('Select a default organization (global scope):', [
15 - ...organizations.map(org => ({ value: org, label: org.name, hint: org.id })),
18 +
19 + const currentOrganization = currentOrgId
20 + ? organizations.find(org => org.id === currentOrgId)
21 + : undefined;
22 + const orderedOrganizations = currentOrganization
23 + ? [currentOrganization, ...organizations.filter(org => org.id !== currentOrganization.id)]
24 + : organizations;
25 +
26 + if (currentOrganization) {
27 + yield* ui.log.info(`Current org: "${currentOrganization.name}" (${currentOrganization.id})`);
28 + }
29 +
30 + return yield* ui.select('Select current organization:', [
31 + ...orderedOrganizations.map(org => ({
32 + value: org,
33 + label: org.name,
34 + hint: org.id === currentOrgId ? `${org.id} (current)` : org.id,
35 + })),
36 ]);
37 });
38
@@ -20,11 +40,12 @@ export const runOrgSelection = (params: {
40 apiKey: string;
41 baseURL: string;
42 explicitOrgId?: string;
43 + currentOrgId?: string;
44 limit?: number;
45 }) =>
46 Effect.gen(function* () {
47 const ui = yield* TerminalUI;
27 - const { apiKey, baseURL, explicitOrgId, limit = DEFAULT_LIMIT } = params;
48 + const { apiKey, baseURL, explicitOrgId, currentOrgId, limit = DEFAULT_LIMIT } = params;
49 const clampedLimit = clampLimit(limit);
50
51 const selectedOrganization =
@@ -38,7 +59,10 @@ export const runOrgSelection = (params: {
59 });
60 yield* ui.log.info(`Loaded ${organizations.data.length} orgs`);
61 if (organizations.data.length === 0) return undefined;
41 - return yield* selectOrganization(organizations.data);
62 + return yield* selectOrganization({
63 + organizations: organizations.data,
64 + currentOrgId,
65 + });
66 });
67
68 if (!selectedOrganization) {
ts/packages/cli/src/services/command-project.ts
+1 -1
@@ -130,7 +130,7 @@ export const resolveCommandProject = (params: { mode: ProjectMode; projectName?:
130 export const formatResolveCommandProjectError = (error: unknown): Error => {
131 if (error instanceof MissingDefaultOrgError) {
132 return new Error(
133 - 'No default org configured. Run `composio login` or `composio dev orgs switch`.'
133 + 'No current org configured. Run `composio login` or `composio dev orgs switch`.'
134 );
135 }
136 if (error instanceof MissingDeveloperProjectError) {
ts/packages/cli/src/services/run-helpers-runtime.ts
+12 -2
@@ -311,10 +311,20 @@ export const installRunHelpers = async ({
311 }
312 };
313
314 + const shouldStreamHelperLog = (step: string, formattedLine: string | null): boolean => {
315 + if (helperContext.logsOff === true) return false;
316 + if (helperContext.debug === true) return true;
317 + return formattedLine !== null && (step.startsWith('subAgent.') || step.startsWith('agent.'));
318 + };
319 +
320 const helperDebugLog = (step: string, details: Record<string, unknown> = {}) => {
315 - const line = formatHelperDebugEvent(step, details);
321 + const formattedLine = formatHelperDebugEvent(step, details);
322 const elapsedMs = Date.now() - perfDebugStart;
317 - appendRunLogLine(line ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);
323 + const line = formattedLine ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`;
324 + appendRunLogLine(line);
325 + if (shouldStreamHelperLog(step, formattedLine)) {
326 + process.stderr.write(`${line}\n`);
327 + }
328 };
329
330 const parseJson = (text: string): unknown => {
ts/packages/cli/src/services/terminal-ui.ts
+20 -15
@@ -1,6 +1,7 @@
1 import process from 'node:process';
2 import * as p from '@clack/prompts';
3 import { Context, Effect, Exit, Layer } from 'effect';
4 +import { canRenderTerminalDecoration, isInteractiveTerminal } from 'src/utils/stdio';
5
6 // ---------------------------------------------------------------------------
7 // SpinnerHandle — returned by `useMakeSpinner` for manual control
@@ -30,10 +31,7 @@ export interface TerminalUI {
31 *
32 * Use this for values that scripts should capture (API keys, version strings, etc.).
33 */
33 - readonly output: (
34 - data: string,
35 - options?: { readonly force?: boolean }
36 - ) => Effect.Effect<void>;
34 + readonly output: (data: string, options?: { readonly force?: boolean }) => Effect.Effect<void>;
35
36 /** Display a session start marker (e.g., `┌ title`). Writes to stderr. */
37 readonly intro: (title: string) => Effect.Effect<void>;
@@ -114,15 +112,22 @@ export const TerminalUI = Context.GenericTag<TerminalUI>('services/TerminalUI');
112 // ---------------------------------------------------------------------------
113
114 /**
117 - * Whether the CLI is running interactively (stdout is a TTY).
118 - * When piped (stdout is NOT a TTY), all decoration is suppressed and only
119 - * `output()` writes raw data to stdout for machine consumption.
115 + * Whether the CLI can prompt for human input. Human-only prompts are shown only
116 + * when stdin/stdout/stderr are all TTYs; agent and shell pipelines get
117 + * non-interactive behavior.
118 */
121 -const isInteractive = !!process.stdout.isTTY;
119 +const canPrompt = isInteractiveTerminal();
120
123 -/** Run a decoration side-effect only in interactive mode. */
121 +/**
122 + * Whether the CLI can render auxiliary UI. Logs, notes, and spinners only need
123 + * stderr, so they can still be shown when stdin is redirected from /dev/null or
124 + * stdout is reserved for machine-readable JSON/data.
125 + */
126 +const canDecorate = canRenderTerminalDecoration();
127 +
128 +/** Run a decoration side-effect only when stderr is a terminal. */
129 function decorate(fn: () => void): void {
125 - if (isInteractive) fn();
130 + if (canDecorate) fn();
131 }
132
133 function createClackSpinnerHandle(
@@ -158,7 +163,7 @@ const silentSpinnerHandle: SpinnerHandle = {
163 const makeLive: TerminalUI = {
164 output: (data, options) =>
165 Effect.sync(() => {
161 - if (options?.force || !isInteractive) {
166 + if (options?.force || !canPrompt) {
167 process.stdout.write(`${data}\n`);
168 }
169 }),
@@ -190,7 +195,7 @@ const makeLive: TerminalUI = {
195 message: string,
196 options: ReadonlyArray<{ value: unknown; label: string; hint?: string }>
197 ) =>
193 - isInteractive
198 + canPrompt
199 ? Effect.promise(async () => {
200 const result = await p.select({
201 message,
@@ -205,7 +210,7 @@ const makeLive: TerminalUI = {
210 : Effect.succeed(options[0].value)) as TerminalUI['select'],
211
212 confirm: (message, options) =>
208 - isInteractive
213 + canPrompt
214 ? Effect.promise(async () => {
215 const result = await p.confirm({
216 message,
@@ -218,7 +223,7 @@ const makeLive: TerminalUI = {
223 : Effect.succeed(options?.defaultValue ?? true),
224
225 withSpinner: (message, effect, options) =>
221 - isInteractive
226 + canDecorate
227 ? Effect.acquireUseRelease(
228 Effect.sync(() => {
229 const s = p.spinner({ output: process.stderr });
@@ -242,7 +247,7 @@ const makeLive: TerminalUI = {
247 : effect,
248
249 useMakeSpinner: (message, use) =>
245 - isInteractive
250 + canDecorate
251 ? Effect.acquireUseRelease(
252 Effect.sync(() => {
253 const s = p.spinner({ output: process.stderr });
ts/packages/cli/src/services/tool-permissions.ts
+46
@@ -319,6 +319,52 @@ const permissionField = (toolSlug: string, connectedAccountId?: string) =>
319 const accountPermissionField = (connectedAccountId?: string) =>
320 `*:${connectedAccountId ?? NO_CONNECTED_ACCOUNT}`;
321
322 +export const getOrgEnhancedControlsStatus = (params: {
323 + readonly orgId: string;
324 + readonly projectId: string;
325 +}) =>
326 + Effect.gen(function* () {
327 + const userContext = yield* ComposioUserContext;
328 + const apiKey = Option.getOrUndefined(userContext.data.apiKey);
329 + if (!apiKey) return undefined;
330 +
331 + const config = yield* Effect.tryPromise(() =>
332 + fetchJson<ConsumerConfigResponse>({
333 + baseURL: userContext.data.baseURL,
334 + apiKey,
335 + orgId: params.orgId,
336 + projectId: params.projectId,
337 + path: '/api/v3.1/org/consumer/config',
338 + })
339 + );
340 + const remoteEnabled = readEnhancedControlsFlag(config);
341 + const platformSupported = isEnhancedControlsPlatformSupported();
342 + return {
343 + enabled: remoteEnabled && platformSupported,
344 + remoteEnabled,
345 + platformSupported,
346 + };
347 + }).pipe(
348 + Effect.catchAll(error =>
349 + Effect.gen(function* () {
350 + yield* Effect.logDebug('Failed to read enhanced controls status', error);
351 + return undefined;
352 + })
353 + )
354 + );
355 +
356 +export const getConnectedAccountPermissionGroup = (params: {
357 + readonly snapshot?: ConsumerPermissionSnapshot;
358 + readonly connectedAccountId?: string;
359 +}): PermissionOverrideState | PermissionDefaultMode | undefined => {
360 + if (!params.snapshot?.enhancedControlsEnabled || !params.snapshot.permissions) return undefined;
361 + return (
362 + params.snapshot.permissions.overrides?.[accountPermissionField(params.connectedAccountId)] ??
363 + params.snapshot.permissions.default ??
364 + 'allow_all'
365 + );
366 +};
367 +
368 const resolvePermissionState = (
369 params: GateParams
370 ): PermissionOverrideState | PermissionDefaultMode => {
ts/packages/cli/src/services/update-check.ts
+5
@@ -5,6 +5,7 @@ import { dirname, join } from 'node:path';
5 import semver from 'semver';
6 import { bold, cyanBright, dim } from 'src/ui/colors';
7 import { APP_VERSION, GITHUB_REPO } from '../constants';
8 +import { isInteractiveTerminal } from 'src/utils/stdio';
9 import { resolveInstalledCliVersion } from './run-companion-modules';
10
11 /**
@@ -50,6 +51,7 @@ export interface UpdateCheckConfig {
51 readonly binaryAssetName: string | undefined;
52 readonly accessToken: string | undefined;
53 readonly fetchFn: (url: string, init?: RequestInit) => Promise<Response>;
54 + readonly isInteractive: () => boolean;
55 }
56
57 const _home = join(homedir(), '.composio');
@@ -73,6 +75,7 @@ const defaultConfig: UpdateCheckConfig = {
75 binaryAssetName: getCurrentBinaryAssetName(),
76 accessToken: process.env.COMPOSIO_GITHUB_ACCESS_TOKEN,
77 fetchFn: fetch,
78 + isInteractive: isInteractiveTerminal,
79 };
80
81 // ── Pure helpers ────────────────────────────────────────────────────────
@@ -123,6 +126,8 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
126 */
127 function showUpdateNotice(): void {
128 try {
129 + if (!config.isInteractive()) return;
130 +
131 const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
132 if (!state.latestVersion || !semver.valid(state.latestVersion)) return;
133 if (state.latestVersion === config.currentVersion) return;
ts/packages/cli/src/utils/stdio.ts new
+39
@@ -0,0 +1,39 @@
1 +import process from 'node:process';
2 +
3 +export type TtyLikeStream = {
4 + readonly isTTY?: boolean;
5 +};
6 +
7 +export type InteractiveStdio = {
8 + readonly stdin?: TtyLikeStream;
9 + readonly stdout?: TtyLikeStream;
10 + readonly stderr?: TtyLikeStream;
11 +};
12 +
13 +const getStdio = (stdio: InteractiveStdio = {}) => ({
14 + stdin: stdio.stdin ?? process.stdin,
15 + stdout: stdio.stdout ?? process.stdout,
16 + stderr: stdio.stderr ?? process.stderr,
17 +});
18 +
19 +/**
20 + * True only when the CLI is attached to a human terminal for input, data output,
21 + * and decoration output. Agent/shell pipelines typically fail at least one of
22 + * these checks, so human-only prompts/notices should stay silent there.
23 + */
24 +export const isInteractiveTerminal = (stdio: InteractiveStdio = {}): boolean => {
25 + const { stdin, stdout, stderr } = getStdio(stdio);
26 +
27 + return Boolean(stdin.isTTY && stdout.isTTY && stderr.isTTY);
28 +};
29 +
30 +/**
31 + * True when stderr can render terminal decoration such as logs, notes, and
32 + * spinners. Unlike prompts/notices, decoration only needs stderr; stdout can
33 + * remain clean for JSON/data and stdin can be redirected from /dev/null.
34 + */
35 +export const canRenderTerminalDecoration = (stdio: InteractiveStdio = {}): boolean => {
36 + const { stderr } = getStdio(stdio);
37 +
38 + return Boolean(stderr.isTTY);
39 +};
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts
+1 -1
@@ -179,7 +179,7 @@ describe('CLI: composio dev connected-accounts list', () => {
179 it.scoped('warns user to login', () =>
180 Effect.gen(function* () {
181 const error = yield* Effect.flip(cli(['dev', 'connected-accounts', 'list']));
182 - expect(String(error)).toContain('No default org configured');
182 + expect(String(error)).toContain('No current org configured');
183 })
184 );
185 }
ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+9 -9
@@ -12,7 +12,7 @@ const parseJsonFromLines = (lines: ReadonlyArray<string>) => {
12 const line = lines[i];
13 if (!line) continue;
14 try {
15 - return JSON.parse(line) as Record<string, Array<Record<string, string>>>;
15 + return JSON.parse(line) as Record<string, Array<Record<string, unknown>>>;
16 } catch {
17 // continue
18 }
@@ -134,10 +134,10 @@ describe('CLI: composio connections list', () => {
134 const parsed = parseJsonFromLines(lines);
135
136 expect(parsed).toEqual({
137 - gmail: [{ status: 'ACTIVE' }],
137 + gmail: [{ status: 'ACTIVE', permission_group: null }],
138 github: [
139 - { status: 'ACTIVE', alias: 'work', word_id: 'castle' },
140 - { status: 'FAILED', alias: 'personal', word_id: 'forest' },
139 + { status: 'ACTIVE', alias: 'work', word_id: 'castle', permission_group: null },
140 + { status: 'FAILED', alias: 'personal', word_id: 'forest', permission_group: null },
141 ],
142 });
143 })
@@ -161,10 +161,10 @@ describe('CLI: composio connections list', () => {
161 const parsed = parseJsonFromLines(lines);
162
163 expect(parsed).toEqual({
164 - gmail: [{ status: 'ACTIVE' }],
164 + gmail: [{ status: 'ACTIVE', permission_group: null }],
165 github: [
166 - { status: 'ACTIVE', alias: 'work', word_id: 'castle' },
167 - { status: 'FAILED', alias: 'personal', word_id: 'forest' },
166 + { status: 'ACTIVE', alias: 'work', word_id: 'castle', permission_group: null },
167 + { status: 'FAILED', alias: 'personal', word_id: 'forest', permission_group: null },
168 ],
169 });
170 })
@@ -183,8 +183,8 @@ describe('CLI: composio connections list', () => {
183
184 expect(parsed).toEqual({
185 github: [
186 - { status: 'ACTIVE', alias: 'work', word_id: 'castle' },
187 - { status: 'FAILED', alias: 'personal', word_id: 'forest' },
186 + { status: 'ACTIVE', alias: 'work', word_id: 'castle', permission_group: null },
187 + { status: 'FAILED', alias: 'personal', word_id: 'forest', permission_group: null },
188 ],
189 });
190 })
ts/packages/cli/test/src/commands/login.cmd.test.ts
+63 -2
@@ -14,6 +14,25 @@ const mockFetchResponse = (body: unknown, status = 200) =>
14 headers: { 'Content-Type': 'application/json' },
15 });
16
17 +const setTtyState = (state: { stdin: boolean; stdout: boolean; stderr: boolean }) => {
18 + const descriptors = {
19 + stdin: Object.getOwnPropertyDescriptor(process.stdin, 'isTTY'),
20 + stdout: Object.getOwnPropertyDescriptor(process.stdout, 'isTTY'),
21 + stderr: Object.getOwnPropertyDescriptor(process.stderr, 'isTTY'),
22 + };
23 + Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: state.stdin });
24 + Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: state.stdout });
25 + Object.defineProperty(process.stderr, 'isTTY', { configurable: true, value: state.stderr });
26 + return () => {
27 + if (descriptors.stdin) Object.defineProperty(process.stdin, 'isTTY', descriptors.stdin);
28 + else delete (process.stdin as { isTTY?: boolean }).isTTY;
29 + if (descriptors.stdout) Object.defineProperty(process.stdout, 'isTTY', descriptors.stdout);
30 + else delete (process.stdout as { isTTY?: boolean }).isTTY;
31 + if (descriptors.stderr) Object.defineProperty(process.stderr, 'isTTY', descriptors.stderr);
32 + else delete (process.stderr as { isTTY?: boolean }).isTTY;
33 + };
34 +};
35 +
36 // ── Tests ────────────────────────────────────────────────────────────────────
37
38 describe('CLI: composio login', () => {
@@ -30,6 +49,7 @@ describe('CLI: composio login', () => {
49 const output = lines.join('\n');
50 expect(output).toContain('--no-browser');
51 expect(output).toContain('--no-wait');
52 + expect(output).toContain('--poll');
53 expect(output).toContain('--key');
54 expect(output).toContain('--user-api-key');
55 expect(output).toContain('--org');
@@ -41,6 +61,47 @@ describe('CLI: composio login', () => {
61 });
62 });
63
64 + layer(TestLive())(it => {
65 + it.scoped('[When] stdin is non-interactive [Then] login prints agent instructions', () =>
66 + Effect.gen(function* () {
67 + const restoreTty = setTtyState({ stdin: false, stdout: true, stderr: true });
68 + try {
69 + yield* cli(['login']);
70 + } finally {
71 + restoreTty();
72 + }
73 +
74 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
75 + expect(output).toContain('Open this URL in your browser to log in:');
76 + expect(output).toContain(
77 + 'https://dashboard.composio.dev/?cliKey=te00st11-d0c4-4efa-8117-c638886063e0'
78 + );
79 + expect(output).toContain('Then run this command to complete login:');
80 + expect(output).toContain('composio login --poll');
81 + expect(output).toContain('hint: For agents:');
82 + expect(output).toContain('cached login key');
83 + expect(output).toContain('polls for up to 10 minutes');
84 + expect(output).not.toContain('Expires at:');
85 + expect(output).toContain('Do not ask the user whether to poll');
86 +
87 + const fs = yield* FileSystem.FileSystem;
88 + const cacheDir = yield* setupCacheDir;
89 + const pendingLoginRaw = yield* fs.readFileString(
90 + path.join(cacheDir, 'pending-login-session.json'),
91 + 'utf8'
92 + );
93 + const pendingLogin = JSON.parse(pendingLoginRaw) as Record<string, unknown>;
94 + expect(pendingLogin.key).toBe('te00st11-d0c4-4efa-8117-c638886063e0');
95 +
96 + expect(output).not.toContain('-- composio login --');
97 + expect(output).not.toContain('Please login using the following URL');
98 + expect(output).not.toContain('Login URL');
99 + expect(output).not.toContain('Login instructions');
100 + expect(output).not.toContain('Installed composio-cli skill');
101 + })
102 + );
103 + });
104 +
105 layer(TestLive())(it => {
106 it.scoped('[When] logging in with --user-api-key --org [Then] stores the chosen org', () =>
107 Effect.gen(function* () {
@@ -63,7 +124,7 @@ describe('CLI: composio login', () => {
124 email: 'project@example.com',
125 created_at: '2026-01-01T00:00:00.000Z',
126 updated_at: '2026-01-01T00:00:00.000Z',
66 - org: { id: 'org_default', name: 'Default Org', plan: 'enterprise' },
127 + org: { id: 'org_default', name: 'Example Org', plan: 'enterprise' },
128 },
129 org_member: {
130 id: 'member_123',
@@ -80,7 +141,7 @@ describe('CLI: composio login', () => {
141 expect(new Headers(init?.headers).get('x-user-api-key')).toBe('uak_direct_key');
142 return mockFetchResponse({
143 organizations: [
83 - { id: 'org_default', name: 'Default Org' },
144 + { id: 'org_default', name: 'Example Org' },
145 { id: 'org_selected', name: 'Selected Org' },
146 ],
147 });
ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts
+1 -1
@@ -43,7 +43,7 @@ describe('CLI: composio dev projects list', () => {
43 expect(output).toContain(
44 'Hint: run `composio dev init` in a directory to bind it to a developer project.'
45 );
46 - expect(output).toContain('Run `composio orgs switch` to change your default org.');
46 + expect(output).toContain('Run `composio orgs switch` to change your current org.');
47 })
48 );
49 });
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+2
@@ -147,8 +147,10 @@ describe('CLI: composio execute', () => {
147 '{"recipient":"a"}',
148 ]);
149 const lines = yield* MockConsole.getLines({ stripAnsi: true });
150 + const outputText = lines.join('\n');
151 const output = parseLastJson(lines);
152
153 + expect(outputText).not.toContain('Response\n{');
154 // Response flows through real ToolsExecutorLive → mock session.execute
155 expect(output.successful).toBe(true);
156 expect(output.data.tool_slug).toBe('GMAIL_SEND_EMAIL');
ts/packages/cli/test/src/commands/whoami.cmd.test.ts
+8 -7
@@ -24,9 +24,8 @@ describe('CLI: composio whoami', () => {
24 expect(output).not.toContain(`api_key_from_test_config_provider`);
25 expect(output).not.toContain(`global_user_api_key`);
26 expect(output).toContain(`"email":null`);
27 - expect(output).toContain(`"default_org_name":null`);
28 - expect(output).toContain(`"default_org_id":null`);
29 - expect(output).toContain(`"test_user_id":null`);
27 + expect(output).toContain(`"current_org_name":null`);
28 + expect(output).not.toContain(`"test_user_id"`);
29 })
30 );
31 });
@@ -42,9 +41,8 @@ describe('CLI: composio whoami', () => {
41 expect(output).not.toContain(`api_key_from_test_fixture`);
42 expect(output).not.toContain(`global_user_api_key`);
43 expect(output).toContain(`"email":null`);
45 - expect(output).toContain(`"default_org_name":null`);
46 - expect(output).toContain(`"default_org_id":null`);
47 - expect(output).toContain(`"test_user_id":null`);
44 + expect(output).toContain(`"current_org_name":null`);
45 + expect(output).not.toContain(`"test_user_id"`);
46 })
47 );
48 });
@@ -90,7 +88,10 @@ describe('CLI: composio whoami', () => {
88 const lines = yield* MockConsole.getLines();
89 const output = lines.join('\n');
90 expect(output).toContain(`"email":"person@example.com"`);
93 - expect(output).toContain(`"default_org_name":"Acme Org"`);
91 + expect(output).toContain(`"current_org_name":"Acme Org"`);
92 + expect(output).toContain('Current Org: Acme Org');
93 + expect(output).not.toContain('Default Org');
94 + expect(output).not.toContain('Test User ID');
95 })
96 );
97 });
ts/packages/cli/test/src/services/update-check.test.ts
+11
@@ -31,6 +31,7 @@ function makeConfig(overrides?: Partial<UpdateCheckConfig>): UpdateCheckConfig {
31 binaryAssetName: 'composio-darwin-aarch64.zip',
32 accessToken: undefined,
33 fetchFn: () => Promise.reject(new Error('fetch not configured')),
34 + isInteractive: () => true,
35 ...overrides,
36 };
37 }
@@ -184,6 +185,16 @@ describe('showUpdateNotice', () => {
185 expect(output).toContain('composio upgrade');
186 });
187
188 + it('does not print upgrade hint in non-interactive environments', () => {
189 + const config = makeConfig({ currentVersion: '0.2.0', isInteractive: () => false });
190 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
191 + const { showUpdateNotice } = createUpdateChecker(config);
192 +
193 + showUpdateNotice();
194 +
195 + expect(stderrSpy).not.toHaveBeenCalled();
196 + });
197 +
198 it('silently ignores corrupt state file', () => {
199 const config = makeConfig();
200 mkdirSync(dirname(config.stateFile), { recursive: true });
ts/packages/cli/test/src/utils/stdio.test.ts new
+34
@@ -0,0 +1,34 @@
1 +import { describe, expect, it } from 'vitest';
2 +import { canRenderTerminalDecoration, isInteractiveTerminal } from 'src/utils/stdio';
3 +
4 +describe('stdio helpers', () => {
5 + it('requires all streams to be TTYs for interactive prompts', () => {
6 + expect(
7 + isInteractiveTerminal({
8 + stdin: { isTTY: false },
9 + stdout: { isTTY: true },
10 + stderr: { isTTY: true },
11 + })
12 + ).toBe(false);
13 + });
14 +
15 + it('allows terminal decoration when only stderr is a TTY', () => {
16 + expect(
17 + canRenderTerminalDecoration({
18 + stdin: { isTTY: false },
19 + stdout: { isTTY: true },
20 + stderr: { isTTY: true },
21 + })
22 + ).toBe(true);
23 + });
24 +
25 + it('suppresses terminal decoration when stderr is not a TTY', () => {
26 + expect(
27 + canRenderTerminalDecoration({
28 + stdin: { isTTY: true },
29 + stdout: { isTTY: true },
30 + stderr: { isTTY: false },
31 + })
32 + ).toBe(false);
33 + });
34 +});