Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(cli): make output more LLM friendly (#3450)
Rahul Tarak1692bbee7a46
diff --git a/.changeset/quiet-llm-friendly-cli.md b/.changeset/quiet-llm-friendly-cli.mdnew file mode 100644index 000000000..4f8058368--- /dev/null+++ b/.changeset/quiet-llm-friendly-cli.md@@ -0,0 +1,5 @@+---+"@composio/cli": patch+---++Make CLI output more LLM-friendly by gating human-only notices/prompts on interactive TTYs and keeping logs on stderr.diff --git a/.gitleaks.toml b/.gitleaks.tomlnew file mode 100644index 000000000..02469261f--- /dev/null+++ b/.gitleaks.toml@@ -0,0 +1,8 @@+[extend]+useDefault = true++[allowlist]+description = "Ignore test fixtures and assertions in TypeScript test files"+paths = [+ '''\.test\.ts$''',+]diff --git a/.gitleaksignore b/.gitleaksignoreindex 83f8b3adb..26415d408 100644--- a/.gitleaksignore+++ b/.gitleaksignore@@ -9,6 +9,9 @@ cadbd463fddb5b31c901d2c222b73354b6d87327:docs/content/docs/tools-direct/toolkit-# Test fixture dummy token for verifying Authorization header forwarding (not a real secret)694231f9ffcdb23ca5baf67509101355764d81dc:ts/packages/cli/test/src/services/update-check.test.ts:generic-api-key:296++# Test assertion for login session JSON field name (not a secret)+9458c6e1b91cb4a2857289cefd723b132b3a9496:ts/packages/cli/test/src/commands/login.cmd.test.ts:generic-api-key:76e921d2d767a779fcaf40fb4f1fde789424d4b7c9:docs/content/docs/importing-existing-connections.mdx:curl-auth-header:207786f40ade6a3a7287c4c79694830edf3c02001d5:docs/content/docs/importing-existing-connections.mdx:curl-auth-header:247786f40ade6a3a7287c4c79694830edf3c02001d5:docs/content/docs/importing-existing-connections.mdx:curl-auth-header:287diff --git a/ts/packages/cli/src/cli-main.ts b/ts/packages/cli/src/cli-main.tsindex 642a35435..439542ff5 100644--- a/ts/packages/cli/src/cli-main.ts+++ b/ts/packages/cli/src/cli-main.ts@@ -115,7 +115,7 @@ const layers = Layer.mergeAll(FetchHttpClient.layer,StdinLive,TerminalUILive,- Logger.pretty+ Logger.replace(Logger.defaultLogger, Logger.prettyLogger({ stderr: true }))) satisfies RequiredLayer;export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: number) => void) => {diff --git a/ts/packages/cli/src/commands/agent/commands/agent.whoami.cmd.ts b/ts/packages/cli/src/commands/agent/commands/agent.whoami.cmd.tsindex 759358414..84510acd1 100644--- a/ts/packages/cli/src/commands/agent/commands/agent.whoami.cmd.ts+++ b/ts/packages/cli/src/commands/agent/commands/agent.whoami.cmd.ts@@ -26,7 +26,7 @@ export const agentCmd$Whoami = Command.make('whoami', {}).pipe(`Status: ${summary.status}`,`Email: ${summary.email ?? 'unknown'}`,`Slug: ${summary.slug ?? 'unknown'}`,- `Default Org ID: ${summary.org_id ?? 'pending'}`,+ `Current Org ID: ${summary.org_id ?? 'pending'}`,`Project ID: ${summary.project_id ?? 'pending'}`,`Claimed By: ${summary.claimed_by ?? 'not claimed'}`,].join('\n'),diff --git a/ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts b/ts/packages/cli/src/commands/connections/commands/connections.list.cmd.tsindex e8ee0da0f..435d41139 100644--- a/ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts+++ b/ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts@@ -9,13 +9,20 @@ import {resolveCommandProject,} from 'src/services/command-project';import { TerminalUI } from 'src/services/terminal-ui';+import {+ getConnectedAccountPermissionGroup,+ getConsumerPermissionSnapshot,+} from 'src/services/tool-permissions';const toolkit = Options.text('toolkit').pipe(Options.withDescription('Filter by toolkit slug (e.g. "gmail")'),Options.optional);-const formatConnectionsJson = (items: ReadonlyArray<ConnectedAccountItem>): string => {+const formatConnectionsJson = (+ items: ReadonlyArray<ConnectedAccountItem>,+ permissionGroups: ReadonlyMap<string, string | undefined> = new Map()+): string => {const toolkitCounts = items.reduce<Map<string, number>>((acc, item) => {acc.set(item.toolkit.slug, (acc.get(item.toolkit.slug) ?? 0) + 1);return acc;@@ -30,6 +37,7 @@ const formatConnectionsJson = (items: ReadonlyArray<ConnectedAccountItem>): stristatus: item.status,...(includeAlias ? { alias: item.alias ?? null } : {}),...(item.word_id != null ? { word_id: item.word_id } : {}),+ permission_group: permissionGroups.get(item.id) ?? null,};if (!acc[toolkit]) {@@ -72,8 +80,23 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit}));const result = yield* decodeConnectedAccountListWithFallback(rawResult);+ const permissionSnapshot = yield* getConsumerPermissionSnapshot({+ orgId: resolvedProject.orgId,+ projectId: resolvedProject.projectId,+ consumerUserId,+ connectedAccountIds: result.items.map(item => item.id),+ });+ const permissionGroups = new Map(+ result.items.map(item => [+ item.id,+ getConnectedAccountPermissionGroup({+ snapshot: permissionSnapshot,+ connectedAccountId: item.id,+ }),+ ])+ );- yield* ui.output(formatConnectionsJson(result.items), { force: true });+ yield* ui.output(formatConnectionsJson(result.items, permissionGroups), { force: true });})).pipe(Command.withDescription(diff --git a/ts/packages/cli/src/commands/init.cmd.ts b/ts/packages/cli/src/commands/init.cmd.tsindex d3818c1cc..486dd2480 100644--- a/ts/packages/cli/src/commands/init.cmd.ts+++ b/ts/packages/cli/src/commands/init.cmd.ts@@ -33,7 +33,7 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';const yesOpt = Options.boolean('yes').pipe(Options.withAlias('y'),Options.withDefault(false),- Options.withDescription('Auto-select the default org project, else first developer project')+ Options.withDescription('Auto-select the current org project, else first developer project'));// ---------------------------------------------------------------------------diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.tsindex 5a0ee15a9..d68f0651c 100644--- a/ts/packages/cli/src/commands/login.cmd.ts+++ b/ts/packages/cli/src/commands/login.cmd.ts@@ -1,4 +1,6 @@+import path from 'node:path';import { Command, Options } from '@effect/cli';+import { FileSystem } from '@effect/platform';import { DateTime, Effect, Option, Schedule } from 'effect';import open from 'open';import {@@ -6,16 +8,19 @@ import {getSessionInfo,getSessionInfoByUserApiKey,listOrganizations,+ type OrganizationSummary,type SessionInfoResponse,} from 'src/services/composio-clients';import { ComposioUserContext } from 'src/services/user-context';import { TerminalUI } from 'src/services/terminal-ui';import { commandHintStep } from 'src/services/command-hints';import { runOrgSelection } from 'src/effects/select-org-project';+import { setupCacheDir } from 'src/effects/setup-cache-dir';import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';import { APP_VERSION } from 'src/constants';+import { isInteractiveTerminal } from 'src/utils/stdio';import {ensureAgentSignupAllowed,getOrSignupReadyAgent,@@ -28,6 +33,11 @@ export const noBrowser = Options.boolean('no-browser').pipe(Options.withDescription('Login without browser interaction'));+const pollOpt = Options.boolean('poll').pipe(+ Options.withDefault(false),+ Options.withDescription('Poll the most recent pending browser login and complete it')+);+const noWait = Options.boolean('no-wait').pipe(Options.withDefault(false),Options.withDescription(@@ -36,7 +46,7 @@ const noWait = Options.boolean('no-wait').pipe();const keyOpt = Options.text('key').pipe(- Options.withDescription('Complete login using session key from composio login --no-wait'),+ Options.withDescription('Poll and complete login using the session key from composio login'),Options.optional);@@ -46,14 +56,14 @@ const userApiKeyOpt = Options.text('user-api-key').pipe();const orgOpt = Options.text('org').pipe(- Options.withDescription('Default organization ID or name to store for CLI commands'),+ Options.withDescription('Current organization ID or name to store for CLI commands'),Options.optional);const yesOpt = Options.boolean('yes').pipe(Options.withAlias('y'),Options.withDefault(false),- Options.withDescription('Skip org picker; use session default org')+ Options.withDescription('Skip org picker; use current org'));const noSkillInstall = Options.boolean('no-skill-install').pipe(@@ -66,6 +76,152 @@ const agentOpt = Options.boolean('agent').pipe(Options.withDescription('Sign up or log in using a Composio agent identity'));+const PENDING_LOGIN_FILE_NAME = 'pending-login-session.json';+const PENDING_LOGIN_TTL_MS = 10 * 60 * 1000;+const LOGIN_POLL_INTERVAL_SECONDS = 5;+const LOGIN_POLL_TIMEOUT_SECONDS = 10 * 60;+const LOGIN_POLL_RETRIES = Math.ceil(LOGIN_POLL_TIMEOUT_SECONDS / LOGIN_POLL_INTERVAL_SECONDS);++type PendingLoginSession = {+ readonly key: string;+ readonly loginUrl: string;+ readonly expiresAt: string;+ readonly cachedAt: string;+};++const pendingLoginPath = Effect.gen(function* () {+ const cacheDir = yield* setupCacheDir;+ return path.join(cacheDir, PENDING_LOGIN_FILE_NAME);+});++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null;++const parsePendingLoginSession = (raw: string): PendingLoginSession => {+ const parsed: unknown = JSON.parse(raw);+ if (+ !isRecord(parsed) ||+ typeof parsed.key !== 'string' ||+ typeof parsed.loginUrl !== 'string' ||+ typeof parsed.expiresAt !== 'string' ||+ typeof parsed.cachedAt !== 'string'+ ) {+ throw new Error('Pending login cache is invalid');+ }+ return {+ key: parsed.key,+ loginUrl: parsed.loginUrl,+ expiresAt: parsed.expiresAt,+ cachedAt: parsed.cachedAt,+ };+};++const writePendingLoginSession = (session: Omit<PendingLoginSession, 'cachedAt'>) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const filePath = yield* pendingLoginPath;+ const payload: PendingLoginSession = {+ ...session,+ cachedAt: new Date().toISOString(),+ };+ yield* fs.writeFileString(filePath, `${JSON.stringify(payload, null, 2)}\n`);+ });++const clearPendingLoginSession = Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const filePath = yield* pendingLoginPath;+ yield* fs.remove(filePath).pipe(Effect.catchAll(() => Effect.void));+});++const readPendingLoginSession = Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const filePath = yield* pendingLoginPath;+ const exists = yield* fs.exists(filePath);+ if (!exists) {+ return yield* Effect.fail(+ new Error('No pending login found. Run `composio login < /dev/null` first.')+ );+ }++ const session = yield* fs+ .readFileString(filePath, 'utf8')+ .pipe(Effect.map(parsePendingLoginSession));+ const cachedAt = Date.parse(session.cachedAt);+ if (!Number.isFinite(cachedAt) || Date.now() - cachedAt > PENDING_LOGIN_TTL_MS) {+ yield* clearPendingLoginSession;+ return yield* Effect.fail(+ new Error('Pending login expired. Run `composio login < /dev/null` again.')+ );+ }++ return session;+});++const formatNonInteractiveLoginInstructions = (params: {+ readonly loginUrl: string;+ readonly pollCommand: string;+}) => `Open this URL in your browser to log in:++ ${params.loginUrl}++Then run this command to complete login:++ ${params.pollCommand}++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.`;++const formatPollLoginComplete = (params: {+ readonly email?: string;+ readonly defaultOrgId: string;+ readonly defaultOrgName?: string;+ readonly organizations: ReadonlyArray<OrganizationSummary>;+}) => {+ const orgLines =+ params.organizations.length > 0+ ? params.organizations+ .map(org => ` ${org.id === params.defaultOrgId ? '*' : '-'} ${org.name} (${org.id})`)+ .join('\n')+ : ' No organizations were returned for this account.';++ return `Login complete${params.email ? ` for ${params.email}` : ''}.++Current org:++ ${params.defaultOrgName ?? params.defaultOrgId} (${params.defaultOrgId})++Available organizations:++${orgLines}++The CLI selected the first organization as your current org. To choose a different current org, run:++ composio orgs switch --org-id <org_id>`;+};++const serializePollLoginResult = (params: {+ readonly email?: string;+ readonly defaultOrgId: string;+ readonly defaultOrgName?: string;+ readonly organizations: ReadonlyArray<OrganizationSummary>;+}) =>+ JSON.stringify(+ {+ email: params.email ?? null,+ current_org: {+ id: params.defaultOrgId,+ name: params.defaultOrgName ?? params.defaultOrgId,+ },+ organizations: params.organizations.map(org => ({+ id: org.id,+ name: org.name,+ selected: org.id === params.defaultOrgId,+ })),+ switch_command: 'composio orgs switch --org-id <org_id>',+ },+ null,+ 2+ );+const formatLoginSuccessMessage = (params: { email?: string; orgName?: string }): string => {const { email, orgName } = params;if (email && orgName) {@@ -93,7 +249,7 @@ const emitLoginComplete = (params: {yield* ui.log.success(formatLoginSuccessMessage({ email, orgName }));if (!skipHints) {yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));- yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));+ yield* ui.log.info(commandHintStep('Switch your current org', 'root.orgs.switch'));}yield* ui.output(@@ -267,7 +423,14 @@ const storeCredentials = (params: {* When noWait is false: polls until session is linked (same as browser flow).* When noWait is true: checks once and fails if not linked.*/-const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPicker: boolean }) =>+const loginWithKey = (params: {+ key: string;+ noWait: boolean;+ skipOrgProjectPicker: boolean;+ pollRetries?: number;+ defaultToFirstOrg?: boolean;+ skipOutput?: boolean;+}) =>Effect.gen(function* () {const ui = yield* TerminalUI;const ctx = yield* ComposioUserContext;@@ -307,8 +470,8 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick);}),Schedule.exponential('0.3 seconds').pipe(- Schedule.intersect(Schedule.recurs(15)),- Schedule.intersect(Schedule.spaced('5 seconds'))+ Schedule.intersect(Schedule.recurs(params.pollRetries ?? 15)),+ Schedule.intersect(Schedule.spaced(`${LOGIN_POLL_INTERVAL_SECONDS} seconds`)))).pipe(Effect.tap(() => spinner.stop('Login successful')),@@ -323,8 +486,24 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPickuserApiKey: uakApiKey,});+ const organizations = params.defaultToFirstOrg+ ? yield* listOrganizations({+ baseURL: ctx.data.baseURL,+ apiKey: uakApiKey,+ }).pipe(+ Effect.map(response => response.data),+ Effect.catchAll(error =>+ Effect.gen(function* () {+ yield* Effect.logDebug('Failed to list organizations after login:', error);+ return [] as ReadonlyArray<OrganizationSummary>;+ })+ )+ )+ : [];+ const defaultOrg = params.defaultToFirstOrg ? organizations[0] : undefined;const xProjectId = uakSessionInfo.project.nano_id;- const xOrgId = uakSessionInfo.project.org.id;+ const xOrgId = defaultOrg?.id ?? uakSessionInfo.project.org.id;+ const xOrgName = defaultOrg?.name ?? uakSessionInfo.project.org.name;const willRunPicker = !params.skipOrgProjectPicker;yield* storeCredentials({@@ -334,7 +513,7 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPickinitialProjectId: xProjectId,fallbackEmail: linkedSession.account.email,skipHints: willRunPicker,- skipOutput: willRunPicker,+ skipOutput: true,});if (willRunPicker) {@@ -345,7 +524,7 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPickEffect.catchAll(error =>Effect.gen(function* () {yield* Effect.logDebug('Org picker failed:', error);- yield* ui.log.warn('Could not load org list. Using session default org.');+ yield* ui.log.warn('Could not load org list. Using current org.');return undefined;}))@@ -369,7 +548,28 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPickorgId: finalOrgId,orgName: finalOrgName,});+ return {+ email: linkedSession.account.email ?? undefined,+ orgId: finalOrgId,+ orgName: finalOrgName,+ organizations,+ };+ }++ if (!params.skipOutput) {+ yield* emitLoginComplete({+ email: linkedSession.account.email ?? undefined,+ orgId: xOrgId,+ orgName: xOrgName,+ });}++ return {+ email: linkedSession.account.email ?? undefined,+ orgId: xOrgId,+ orgName: xOrgName,+ organizations,+ };});/**@@ -403,8 +603,34 @@ export const browserLogin = (params: {yield* Effect.logDebug(`Created session: ${session.id}`);const url = `${ctx.data.webURL}?cliKey=${session.id}`;+ const pollCommand = 'composio login --poll';+ const expiresAt = DateTime.formatIso(session.expiresAt);+ yield* writePendingLoginSession({+ key: session.id,+ loginUrl: url,+ expiresAt,+ });++ const canPrompt = isInteractiveTerminal();+ const effectiveNoWait = params.noWait || !canPrompt;+ const effectiveNoBrowser = params.noBrowser || effectiveNoWait;++ if (effectiveNoWait) {+ const loginInstructions = formatNonInteractiveLoginInstructions({+ loginUrl: url,+ pollCommand,+ });++ if (canPrompt) {+ yield* ui.log.info('Please login using the following URL:');+ yield* ui.note(url, 'Login URL');+ yield* ui.note(loginInstructions, 'Login instructions');+ }++ yield* ui.output(loginInstructions);+ return;+ }- const effectiveNoBrowser = params.noBrowser || params.noWait;if (effectiveNoBrowser) {yield* ui.log.info('Please login using the following URL:');} else {@@ -413,19 +639,6 @@ export const browserLogin = (params: {yield* ui.note(url, 'Login URL');- if (params.noWait) {- const loginInfo = {- status: 'pending',- message: 'Complete login by opening the URL',- login_url: url,- cli_key: session.id,- expires_at: DateTime.formatIso(session.expiresAt),- };- yield* ui.note(JSON.stringify(loginInfo, null, 2), 'Login info');- yield* ui.output(JSON.stringify(loginInfo, null, 2));- return;- }-yield* ui.output(url);if (!effectiveNoBrowser) {@@ -499,7 +712,7 @@ export const browserLogin = (params: {Effect.catchAll(error =>Effect.gen(function* () {yield* Effect.logDebug('Org picker failed:', error);- yield* ui.log.warn('Could not load org list. Using session default org.');+ yield* ui.log.warn('Could not load org list. Using current org.');return undefined;}))@@ -534,9 +747,9 @@ export const browserLogin = (params: {* Use --no-wait to print login URL and session info (JSON) then exit without opening browser or waiting.* Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;* with --no-wait, checks once and fails if not linked.- * Use --user-api-key to log in directly without a browser flow, and --org to override the default org.+ * Use --user-api-key to log in directly without a browser flow, and --org to override the current org.* Use --agent to sign up or log in using a Composio agent identity.- * Use -y to skip org picker and use session default org.+ * Use -y to skip org picker and use current org.** @example* ```bash@@ -555,6 +768,7 @@ export const loginCmd = Command.make('login',{noBrowser,+ poll: pollOpt,noWait,key: keyOpt,userApiKey: userApiKeyOpt,@@ -563,17 +777,31 @@ export const loginCmd = Command.make(noSkillInstall,agent: agentOpt,},- ({ noBrowser, noWait, key, userApiKey, org, yes, noSkillInstall, agent }) =>+ ({ noBrowser, poll, noWait, key, userApiKey, org, yes, noSkillInstall, agent }) =>Effect.gen(function* () {const ui = yield* TerminalUI;const ctx = yield* ComposioUserContext;+ const canPrompt = isInteractiveTerminal();- yield* ui.intro('composio login');+ if (canPrompt) {+ yield* ui.intro('composio login');+ }if (Option.isSome(key) && Option.isSome(userApiKey)) {return yield* Effect.fail(new Error('Use either `--key` or `--user-api-key`, not both.'));}+ if (+ poll &&+ (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey) || agent)+ ) {+ return yield* Effect.fail(+ new Error(+ '`--poll` cannot be combined with browser, session, direct-login, or agent flags.'+ )+ );+ }+if (agent && (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey))) {return yield* Effect.fail(new Error('`--agent` cannot be combined with browser, session, or direct-login flags.')@@ -592,6 +820,34 @@ export const loginCmd = Command.make();}+ if (poll) {+ const pendingLogin = yield* readPendingLoginSession;+ const loginResult = yield* loginWithKey({+ key: pendingLogin.key,+ noWait: false,+ skipOrgProjectPicker: true,+ pollRetries: LOGIN_POLL_RETRIES,+ defaultToFirstOrg: true,+ skipOutput: true,+ });+ yield* clearPendingLoginSession;+ const pollSummaryParams = {+ email: loginResult.email,+ defaultOrgId: loginResult.orgId,+ defaultOrgName: loginResult.orgName,+ organizations: loginResult.organizations,+ };+ const pollSummary = formatPollLoginComplete(pollSummaryParams);+ if (canPrompt) {+ yield* ui.note(pollSummary, 'Login complete');+ }+ yield* ui.output(serializePollLoginResult(pollSummaryParams), { force: true });+ if (!noSkillInstall && canPrompt) {+ yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });+ }+ return;+ }+if (agent) {return yield* handleAgentAuthError(Effect.gen(function* () {@@ -603,7 +859,7 @@ export const loginCmd = Command.make(`Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`);yield* ui.output(JSON.stringify({ ...summary, logged_in: true }));- if (!noSkillInstall) {+ if (!noSkillInstall && canPrompt) {yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });}})@@ -616,7 +872,7 @@ export const loginCmd = Command.make(noWait,skipOrgProjectPicker: true,});- if (!noSkillInstall) {+ if (!noSkillInstall && canPrompt) {yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });}return;@@ -627,7 +883,7 @@ export const loginCmd = Command.make(userApiKey: userApiKey.value,org: Option.getOrUndefined(org),});- if (!noSkillInstall) {+ if (!noSkillInstall && canPrompt) {yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });}return;@@ -651,7 +907,7 @@ export const loginCmd = Command.make(skipOrgProjectPicker: yes,});- if (!noSkillInstall && !noWait) {+ if (!noSkillInstall && !noWait && canPrompt) {yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });}})diff --git a/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts b/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.tsindex 073b6fb9c..042f50d12 100644--- a/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts+++ b/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts@@ -31,14 +31,15 @@ export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId,}yield* ui.note(- 'This updates your default org for CLI commands. Use `composio dev init` for local developer project setup.',- 'Global defaults'+ 'This updates your current org for CLI commands. Use `composio dev init` for local developer project setup.',+ 'Current org');const result = yield* runOrgSelection({apiKey,baseURL: ctx.data.baseURL,explicitOrgId: Option.getOrUndefined(orgId),+ currentOrgId: Option.getOrUndefined(ctx.data.orgId),limit,});@@ -49,13 +50,13 @@ export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId,yield* ctx.login(apiKey, result.id, Option.getOrUndefined(ctx.data.testUserId));- yield* ui.log.success(`Updated default org to "${result.name}".`);+ yield* ui.log.success(`Updated current org to "${result.name}".`);yield* ui.output(JSON.stringify({scope: 'global',org_id: result.id,}));- yield* ui.outro('Default org updated.');+ yield* ui.outro('Current org updated.');})-).pipe(Command.withDescription('Switch default organization context.'));+).pipe(Command.withDescription('Switch current organization context.'));diff --git a/ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts b/ts/packages/cli/src/commands/projects/commands/projects.list.cmd.tsindex d4b2396f2..f1d40cf7d 100644--- a/ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts+++ b/ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts@@ -31,7 +31,7 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,const resolvedOrgId = Option.getOrUndefined(orgId) ?? Option.getOrUndefined(ctx.data.orgId);if (!resolvedOrgId) {- yield* ui.log.warn('No default org is configured.');+ yield* ui.log.warn('No current org is configured.');yield* ui.outro('Hint: run `composio orgs switch` first, or pass `--org-id`.');return;}@@ -66,7 +66,7 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,yield* ui.outro(['Hint: run `composio dev init` in a directory to bind it to a developer project.',- 'Run `composio orgs switch` to change your default org.',+ 'Run `composio orgs switch` to change your current org.',].join('\n'));diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.tsindex 11761dcd3..cbe096477 100644--- a/ts/packages/cli/src/commands/root-help.ts+++ b/ts/packages/cli/src/commands/root-help.ts@@ -165,7 +165,7 @@ const ACCOUNT_COMMANDS: ReadonlyArray<TaggedValue<CompactCommand>> = [tagged({ name: 'login', description: 'Log in to Composio' }),tagged({ name: 'logout', description: 'Log out from Composio' }),tagged({ name: 'whoami', description: 'Show current account info' }),- tagged({ name: 'orgs', description: 'Manage default organization context (list, switch)' }),+ tagged({ name: 'orgs', description: 'Manage current organization context (list, switch)' }),tagged({ name: 'version', description: 'Display CLI version' }),tagged({ name: 'upgrade', description: 'Upgrade CLI to the latest version' }),tagged({ name: 'config', description: 'View and manage CLI configuration' }),@@ -829,13 +829,13 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHellogin: {usage:- 'composio login [--no-browser] [--no-wait] [--key text] [--user-api-key text] [--org text] [-y, --yes] [--no-skill-install]',+ 'composio login [--no-browser] [--poll] [--no-wait] [--key text] [--user-api-key text] [--org text] [-y, --yes] [--no-skill-install]',description:'Log in to the Composio CLI session. By default, also installs the composio-cli skill for Claude Code.',options: [{name: '--key <text>',- description: 'Complete login using session key from composio login --no-wait',+ description: 'Poll and complete login using the session key from composio login',},{name: '--user-api-key <text>',@@ -843,13 +843,17 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHel},{name: '--org <text>',- description: 'Default organization ID or name to store for CLI commands',+ description: 'Current organization ID or name to store for CLI commands',},],flags: [{ name: '--no-browser', description: 'Login without browser interaction' },+ {+ name: '--poll',+ description: 'Poll the cached pending login key for up to 10 minutes',+ },{ name: '--no-wait', description: 'Print login URL and session info, then exit' },- { name: '-y, --yes', description: 'Skip org picker; use session default org' },+ { name: '-y, --yes', description: 'Skip org picker; use current org' },{name: '--no-skill-install',description: 'Skip installing the composio-cli skill for Claude Code',@@ -1015,7 +1019,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHeldescription: 'Initialize this directory with a developer project.',flags: [{ name: '--no-browser', description: 'Login without browser interaction' },- { name: '-y, --yes', description: 'Auto-select the default org project' },+ { name: '-y, --yes', description: 'Auto-select the current org project' },],},'dev playground-execute': {diff --git a/ts/packages/cli/src/commands/run.cmd.ts b/ts/packages/cli/src/commands/run.cmd.tsindex 2bab004d0..a290baaac 100644--- a/ts/packages/cli/src/commands/run.cmd.ts+++ b/ts/packages/cli/src/commands/run.cmd.ts@@ -38,9 +38,7 @@ const debug = Options.boolean('debug').pipe(Options.withDefault(false));const logsOff = Options.boolean('logs-off').pipe(- Options.withDescription(- 'Compatibility flag. Helper logs are written to the run log file instead of stderr.'- ),+ Options.withDescription('Hide helper streaming logs; keep them only in the run log file.'),Options.withDefault(false));const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(diff --git a/ts/packages/cli/src/commands/signup.cmd.ts b/ts/packages/cli/src/commands/signup.cmd.tsindex 29debd27e..bf36614bb 100644--- a/ts/packages/cli/src/commands/signup.cmd.ts+++ b/ts/packages/cli/src/commands/signup.cmd.ts@@ -56,7 +56,7 @@ export const runAgentSignup = (params: {`Status: ${summary.status}`,`Email: ${summary.email ?? 'unknown'}`,`Slug: ${summary.slug ?? 'unknown'}`,- `Default Org ID: ${summary.org_id ?? 'pending'}`,+ `Current Org ID: ${summary.org_id ?? 'pending'}`,`Project ID: ${summary.project_id ?? 'pending'}`,`Agent key: stored in ~/.composio/agent.json`,].join('\n'),diff --git a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.tsindex 3ebe01594..275061780 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts@@ -583,6 +583,8 @@ const emitExecuteFailureTelemetry = (params: {}});+const writeExecuteStdout = (ui: TerminalUI, data: string) => ui.output(data, { force: true });+export const showToolsExecuteInputHelp = (toolSlug: string) =>Effect.gen(function* () {if (!(yield* requireAuth)) return;@@ -621,7 +623,8 @@ export const showToolsExecuteInputHelp = (toolSlug: string) =>yield* ui.note(formatToolInputParameters(tool), `Execute Help: ${tool.slug}`);yield* ui.log.step(`Run:\n> composio execute "${tool.slug}" -d '{"key":"value"}'`);- yield* ui.output(+ yield* writeExecuteStdout(+ ui,JSON.stringify({ slug: tool.slug, input_parameters: tool.input_parameters }, null, 2));});@@ -932,7 +935,8 @@ const emitCachedSchema = (yield* ui.log.message(`Schema saved, inspect keys like: jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}' ${definition.schemaPath}`);- yield* ui.output(+ yield* writeExecuteStdout(+ ui,JSON.stringify({slug,@@ -1239,7 +1243,8 @@ const runConnectedToolkitFailFast = (params: {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.`;yield* params.ui.log.error(message);yield* params.ui.note(connectionTips(params.slug, params.surface), 'Tips');- yield* params.ui.output(+ yield* writeExecuteStdout(+ params.ui,JSON.stringify({successful: false,@@ -1352,7 +1357,7 @@ const runExecuteWithSpinner = (params: {? 'No tool was executed. Local validation was skipped.': 'No tool was executed. Arguments were validated locally only.');- yield* params.ui.output(JSON.stringify(summary, ciRedactReplacer, 2));+ yield* writeExecuteStdout(params.ui, JSON.stringify(summary, ciRedactReplacer, 2));yield* appendCliSessionHistory({orgId:params.resolvedProject.projectType === 'CONSUMER'@@ -1398,7 +1403,8 @@ const runExecuteWithSpinner = (params: {projectMode: params.projectMode,stage: 'execution',});- yield* params.ui.output(+ yield* writeExecuteStdout(+ params.ui,JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2));yield* appendCliSessionHistory({@@ -1448,7 +1454,7 @@ const runExecuteWithSpinner = (params: {stage: 'execution',logId: result.logId,});- yield* params.ui.output(JSON.stringify(result, ciRedactReplacer, 2));+ yield* writeExecuteStdout(params.ui, JSON.stringify(result, ciRedactReplacer, 2));return yield* Effect.fail(new ToolExecutionError(summary.error));}@@ -1464,7 +1470,7 @@ const runExecuteWithSpinner = (params: {yield* params.ui.log.message(`Response stored in ${output.summary.outputFilePath} (${output.summary.tokenCount} tokens)`);- yield* params.ui.output(JSON.stringify(output.summary, ciRedactReplacer, 2));+ yield* writeExecuteStdout(params.ui, JSON.stringify(output.summary, ciRedactReplacer, 2));yield* appendCliSessionHistory({orgId:params.resolvedProject.projectType === 'CONSUMER'@@ -1488,8 +1494,7 @@ const runExecuteWithSpinner = (params: {return;}- yield* params.ui.log.message(`Response\n${output.json}`);- yield* params.ui.output(output.json);+ yield* writeExecuteStdout(params.ui, output.json);yield* appendCliSessionHistory({orgId:params.resolvedProject.projectType === 'CONSUMER'@@ -1867,7 +1872,8 @@ const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>yield* ui.log.message(`Parallel execute completed: ${results.filter(result => result.successful).length}/${results.length} successful`);- yield* ui.output(+ yield* writeExecuteStdout(+ ui,JSON.stringify({successful,@@ -2041,7 +2047,8 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>yield* ui.log.message(`Parallel execute completed: ${results.filter(result => result.successful).length}/${results.length} successful`);- yield* ui.output(+ yield* writeExecuteStdout(+ ui,JSON.stringify({successful,diff --git a/ts/packages/cli/src/commands/whoami.cmd.ts b/ts/packages/cli/src/commands/whoami.cmd.tsindex 06857837b..3471c6b97 100644--- a/ts/packages/cli/src/commands/whoami.cmd.ts+++ b/ts/packages/cli/src/commands/whoami.cmd.ts@@ -5,6 +5,7 @@ import { ComposioUserContext } from 'src/services/user-context';import { TerminalUI } from 'src/services/terminal-ui';import { commandHintStep } from 'src/services/command-hints';import { readStoredAgentIdentity } from 'src/services/agents';+import { getOrgEnhancedControlsStatus } from 'src/services/tool-permissions';/*** CLI command to display your account information.@@ -27,8 +28,6 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(onNone: () => ui.log.warn('You are not logged in yet. Please run `composio login`.'),onSome: apiKey =>Effect.gen(function* () {- const defaultOrgId = Option.getOrUndefined(ctx.data.orgId);- const testUserId = Option.getOrUndefined(ctx.data.testUserId);const sessionInfo = yield* getSessionInfoByUserApiKey({baseURL: ctx.data.baseURL,userApiKey: apiKey,@@ -39,6 +38,14 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(const orgName = Option.map(sessionInfo, info => info.project.org.name).pipe(Option.getOrUndefined);+ const enhancedControls = yield* Option.match(sessionInfo, {+ onNone: () => Effect.succeed(undefined),+ onSome: info =>+ getOrgEnhancedControlsStatus({+ orgId: info.project.org.id,+ projectId: info.project.nano_id,+ }),+ });const storedAgent = yield* readStoredAgentIdentity;const isStoredAgentKey = Option.match(storedAgent, {onNone: () => false,@@ -51,9 +58,8 @@ export const whoamiCmd = Command.make('whoami', {}).pipe([`Type: ${accountType}`,`Email: ${email ?? 'unknown'}`,- `Default Org: ${orgName ?? 'unknown'}`,- `Default Org ID: ${defaultOrgId ?? 'not set'}`,- `Test User ID: ${testUserId ?? 'not set'}`,+ `Current Org: ${orgName ?? 'unknown'}`,+ `Enhanced Controls: ${enhancedControls?.remoteEnabled ? 'on' : 'off'}`,].join('\n'),'Global User Context');@@ -67,9 +73,8 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(JSON.stringify({account_type: accountType,email: email ?? null,- default_org_name: orgName ?? null,- default_org_id: defaultOrgId ?? null,- test_user_id: testUserId ?? null,+ current_org_name: orgName ?? null,+ enhanced_controls_enabled: enhancedControls?.remoteEnabled ?? null,}));}),diff --git a/ts/packages/cli/src/effects/select-org-project.ts b/ts/packages/cli/src/effects/select-org-project.tsindex 9188932a2..25662e3a7 100644--- a/ts/packages/cli/src/effects/select-org-project.ts+++ b/ts/packages/cli/src/effects/select-org-project.ts@@ -6,13 +6,33 @@ import { clampLimit } from 'src/ui/clamp-limit';const DEFAULT_LIMIT = 50;/** Prompts user to select an org, or auto-selects if only one. */-const selectOrganization = (organizations: ReadonlyArray<OrganizationSummary>) =>+const selectOrganization = (params: {+ organizations: ReadonlyArray<OrganizationSummary>;+ currentOrgId?: string;+}) =>Effect.gen(function* () {const ui = yield* TerminalUI;+ const { organizations, currentOrgId } = params;if (organizations.length === 0) return undefined;if (organizations.length === 1) return organizations[0];- return yield* ui.select('Select a default organization (global scope):', [- ...organizations.map(org => ({ value: org, label: org.name, hint: org.id })),++ const currentOrganization = currentOrgId+ ? organizations.find(org => org.id === currentOrgId)+ : undefined;+ const orderedOrganizations = currentOrganization+ ? [currentOrganization, ...organizations.filter(org => org.id !== currentOrganization.id)]+ : organizations;++ if (currentOrganization) {+ yield* ui.log.info(`Current org: "${currentOrganization.name}" (${currentOrganization.id})`);+ }++ return yield* ui.select('Select current organization:', [+ ...orderedOrganizations.map(org => ({+ value: org,+ label: org.name,+ hint: org.id === currentOrgId ? `${org.id} (current)` : org.id,+ })),]);});@@ -20,11 +40,12 @@ export const runOrgSelection = (params: {apiKey: string;baseURL: string;explicitOrgId?: string;+ currentOrgId?: string;limit?: number;}) =>Effect.gen(function* () {const ui = yield* TerminalUI;- const { apiKey, baseURL, explicitOrgId, limit = DEFAULT_LIMIT } = params;+ const { apiKey, baseURL, explicitOrgId, currentOrgId, limit = DEFAULT_LIMIT } = params;const clampedLimit = clampLimit(limit);const selectedOrganization =@@ -38,7 +59,10 @@ export const runOrgSelection = (params: {});yield* ui.log.info(`Loaded ${organizations.data.length} orgs`);if (organizations.data.length === 0) return undefined;- return yield* selectOrganization(organizations.data);+ return yield* selectOrganization({+ organizations: organizations.data,+ currentOrgId,+ });});if (!selectedOrganization) {diff --git a/ts/packages/cli/src/services/command-project.ts b/ts/packages/cli/src/services/command-project.tsindex a4be2f593..4e729e3b0 100644--- a/ts/packages/cli/src/services/command-project.ts+++ b/ts/packages/cli/src/services/command-project.ts@@ -130,7 +130,7 @@ export const resolveCommandProject = (params: { mode: ProjectMode; projectName?:export const formatResolveCommandProjectError = (error: unknown): Error => {if (error instanceof MissingDefaultOrgError) {return new Error(- 'No default org configured. Run `composio login` or `composio dev orgs switch`.'+ 'No current org configured. Run `composio login` or `composio dev orgs switch`.');}if (error instanceof MissingDeveloperProjectError) {diff --git a/ts/packages/cli/src/services/run-helpers-runtime.ts b/ts/packages/cli/src/services/run-helpers-runtime.tsindex 3b982db31..4f9967596 100644--- a/ts/packages/cli/src/services/run-helpers-runtime.ts+++ b/ts/packages/cli/src/services/run-helpers-runtime.ts@@ -311,10 +311,20 @@ export const installRunHelpers = async ({}};+ const shouldStreamHelperLog = (step: string, formattedLine: string | null): boolean => {+ if (helperContext.logsOff === true) return false;+ if (helperContext.debug === true) return true;+ return formattedLine !== null && (step.startsWith('subAgent.') || step.startsWith('agent.'));+ };+const helperDebugLog = (step: string, details: Record<string, unknown> = {}) => {- const line = formatHelperDebugEvent(step, details);+ const formattedLine = formatHelperDebugEvent(step, details);const elapsedMs = Date.now() - perfDebugStart;- appendRunLogLine(line ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);+ const line = formattedLine ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`;+ appendRunLogLine(line);+ if (shouldStreamHelperLog(step, formattedLine)) {+ process.stderr.write(`${line}\n`);+ }};const parseJson = (text: string): unknown => {diff --git a/ts/packages/cli/src/services/terminal-ui.ts b/ts/packages/cli/src/services/terminal-ui.tsindex 3421ee445..433f7436f 100644--- a/ts/packages/cli/src/services/terminal-ui.ts+++ b/ts/packages/cli/src/services/terminal-ui.ts@@ -1,6 +1,7 @@import process from 'node:process';import * as p from '@clack/prompts';import { Context, Effect, Exit, Layer } from 'effect';+import { canRenderTerminalDecoration, isInteractiveTerminal } from 'src/utils/stdio';// ---------------------------------------------------------------------------// SpinnerHandle — returned by `useMakeSpinner` for manual control@@ -30,10 +31,7 @@ export interface TerminalUI {** Use this for values that scripts should capture (API keys, version strings, etc.).*/- readonly output: (- data: string,- options?: { readonly force?: boolean }- ) => Effect.Effect<void>;+ readonly output: (data: string, options?: { readonly force?: boolean }) => Effect.Effect<void>;/** Display a session start marker (e.g., `┌ title`). Writes to stderr. */readonly intro: (title: string) => Effect.Effect<void>;@@ -114,15 +112,22 @@ export const TerminalUI = Context.GenericTag<TerminalUI>('services/TerminalUI');// ---------------------------------------------------------------------------/**- * Whether the CLI is running interactively (stdout is a TTY).- * When piped (stdout is NOT a TTY), all decoration is suppressed and only- * `output()` writes raw data to stdout for machine consumption.+ * Whether the CLI can prompt for human input. Human-only prompts are shown only+ * when stdin/stdout/stderr are all TTYs; agent and shell pipelines get+ * non-interactive behavior.*/-const isInteractive = !!process.stdout.isTTY;+const canPrompt = isInteractiveTerminal();-/** Run a decoration side-effect only in interactive mode. */+/**+ * Whether the CLI can render auxiliary UI. Logs, notes, and spinners only need+ * stderr, so they can still be shown when stdin is redirected from /dev/null or+ * stdout is reserved for machine-readable JSON/data.+ */+const canDecorate = canRenderTerminalDecoration();++/** Run a decoration side-effect only when stderr is a terminal. */function decorate(fn: () => void): void {- if (isInteractive) fn();+ if (canDecorate) fn();}function createClackSpinnerHandle(@@ -158,7 +163,7 @@ const silentSpinnerHandle: SpinnerHandle = {const makeLive: TerminalUI = {output: (data, options) =>Effect.sync(() => {- if (options?.force || !isInteractive) {+ if (options?.force || !canPrompt) {process.stdout.write(`${data}\n`);}}),@@ -190,7 +195,7 @@ const makeLive: TerminalUI = {message: string,options: ReadonlyArray<{ value: unknown; label: string; hint?: string }>) =>- isInteractive+ canPrompt? Effect.promise(async () => {const result = await p.select({message,@@ -205,7 +210,7 @@ const makeLive: TerminalUI = {: Effect.succeed(options[0].value)) as TerminalUI['select'],confirm: (message, options) =>- isInteractive+ canPrompt? Effect.promise(async () => {const result = await p.confirm({message,@@ -218,7 +223,7 @@ const makeLive: TerminalUI = {: Effect.succeed(options?.defaultValue ?? true),withSpinner: (message, effect, options) =>- isInteractive+ canDecorate? Effect.acquireUseRelease(Effect.sync(() => {const s = p.spinner({ output: process.stderr });@@ -242,7 +247,7 @@ const makeLive: TerminalUI = {: effect,useMakeSpinner: (message, use) =>- isInteractive+ canDecorate? Effect.acquireUseRelease(Effect.sync(() => {const s = p.spinner({ output: process.stderr });diff --git a/ts/packages/cli/src/services/tool-permissions.ts b/ts/packages/cli/src/services/tool-permissions.tsindex c5cffd614..e03105a80 100644--- a/ts/packages/cli/src/services/tool-permissions.ts+++ b/ts/packages/cli/src/services/tool-permissions.ts@@ -319,6 +319,52 @@ const permissionField = (toolSlug: string, connectedAccountId?: string) =>const accountPermissionField = (connectedAccountId?: string) =>`*:${connectedAccountId ?? NO_CONNECTED_ACCOUNT}`;+export const getOrgEnhancedControlsStatus = (params: {+ readonly orgId: string;+ readonly projectId: string;+}) =>+ Effect.gen(function* () {+ const userContext = yield* ComposioUserContext;+ const apiKey = Option.getOrUndefined(userContext.data.apiKey);+ if (!apiKey) return undefined;++ const config = yield* Effect.tryPromise(() =>+ fetchJson<ConsumerConfigResponse>({+ baseURL: userContext.data.baseURL,+ apiKey,+ orgId: params.orgId,+ projectId: params.projectId,+ path: '/api/v3.1/org/consumer/config',+ })+ );+ const remoteEnabled = readEnhancedControlsFlag(config);+ const platformSupported = isEnhancedControlsPlatformSupported();+ return {+ enabled: remoteEnabled && platformSupported,+ remoteEnabled,+ platformSupported,+ };+ }).pipe(+ Effect.catchAll(error =>+ Effect.gen(function* () {+ yield* Effect.logDebug('Failed to read enhanced controls status', error);+ return undefined;+ })+ )+ );++export const getConnectedAccountPermissionGroup = (params: {+ readonly snapshot?: ConsumerPermissionSnapshot;+ readonly connectedAccountId?: string;+}): PermissionOverrideState | PermissionDefaultMode | undefined => {+ if (!params.snapshot?.enhancedControlsEnabled || !params.snapshot.permissions) return undefined;+ return (+ params.snapshot.permissions.overrides?.[accountPermissionField(params.connectedAccountId)] ??+ params.snapshot.permissions.default ??+ 'allow_all'+ );+};+const resolvePermissionState = (params: GateParams): PermissionOverrideState | PermissionDefaultMode => {diff --git a/ts/packages/cli/src/services/update-check.ts b/ts/packages/cli/src/services/update-check.tsindex 1763cb270..1f2ff9699 100644--- a/ts/packages/cli/src/services/update-check.ts+++ b/ts/packages/cli/src/services/update-check.ts@@ -5,6 +5,7 @@ import { dirname, join } from 'node:path';import semver from 'semver';import { bold, cyanBright, dim } from 'src/ui/colors';import { APP_VERSION, GITHUB_REPO } from '../constants';+import { isInteractiveTerminal } from 'src/utils/stdio';import { resolveInstalledCliVersion } from './run-companion-modules';/**@@ -50,6 +51,7 @@ export interface UpdateCheckConfig {readonly binaryAssetName: string | undefined;readonly accessToken: string | undefined;readonly fetchFn: (url: string, init?: RequestInit) => Promise<Response>;+ readonly isInteractive: () => boolean;}const _home = join(homedir(), '.composio');@@ -73,6 +75,7 @@ const defaultConfig: UpdateCheckConfig = {binaryAssetName: getCurrentBinaryAssetName(),accessToken: process.env.COMPOSIO_GITHUB_ACCESS_TOKEN,fetchFn: fetch,+ isInteractive: isInteractiveTerminal,};// ── Pure helpers ────────────────────────────────────────────────────────@@ -123,6 +126,8 @@ export function createUpdateChecker(config: UpdateCheckConfig) {*/function showUpdateNotice(): void {try {+ if (!config.isInteractive()) return;+const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));if (!state.latestVersion || !semver.valid(state.latestVersion)) return;if (state.latestVersion === config.currentVersion) return;diff --git a/ts/packages/cli/src/utils/stdio.ts b/ts/packages/cli/src/utils/stdio.tsnew file mode 100644index 000000000..2060a05df--- /dev/null+++ b/ts/packages/cli/src/utils/stdio.ts@@ -0,0 +1,39 @@+import process from 'node:process';++export type TtyLikeStream = {+ readonly isTTY?: boolean;+};++export type InteractiveStdio = {+ readonly stdin?: TtyLikeStream;+ readonly stdout?: TtyLikeStream;+ readonly stderr?: TtyLikeStream;+};++const getStdio = (stdio: InteractiveStdio = {}) => ({+ stdin: stdio.stdin ?? process.stdin,+ stdout: stdio.stdout ?? process.stdout,+ stderr: stdio.stderr ?? process.stderr,+});++/**+ * True only when the CLI is attached to a human terminal for input, data output,+ * and decoration output. Agent/shell pipelines typically fail at least one of+ * these checks, so human-only prompts/notices should stay silent there.+ */+export const isInteractiveTerminal = (stdio: InteractiveStdio = {}): boolean => {+ const { stdin, stdout, stderr } = getStdio(stdio);++ return Boolean(stdin.isTTY && stdout.isTTY && stderr.isTTY);+};++/**+ * True when stderr can render terminal decoration such as logs, notes, and+ * spinners. Unlike prompts/notices, decoration only needs stderr; stdout can+ * remain clean for JSON/data and stdin can be redirected from /dev/null.+ */+export const canRenderTerminalDecoration = (stdio: InteractiveStdio = {}): boolean => {+ const { stderr } = getStdio(stdio);++ return Boolean(stderr.isTTY);+};diff --git a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.tsindex cd82c60b7..d1a4bfdd9 100644--- a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts@@ -179,7 +179,7 @@ describe('CLI: composio dev connected-accounts list', () => {it.scoped('warns user to login', () =>Effect.gen(function* () {const error = yield* Effect.flip(cli(['dev', 'connected-accounts', 'list']));- expect(String(error)).toContain('No default org configured');+ expect(String(error)).toContain('No current org configured');}));}diff --git a/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts b/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.tsindex 116e58875..269db9186 100644--- a/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts@@ -12,7 +12,7 @@ const parseJsonFromLines = (lines: ReadonlyArray<string>) => {const line = lines[i];if (!line) continue;try {- return JSON.parse(line) as Record<string, Array<Record<string, string>>>;+ return JSON.parse(line) as Record<string, Array<Record<string, unknown>>>;} catch {// continue}@@ -134,10 +134,10 @@ describe('CLI: composio connections list', () => {const parsed = parseJsonFromLines(lines);expect(parsed).toEqual({- gmail: [{ status: 'ACTIVE' }],+ gmail: [{ status: 'ACTIVE', permission_group: null }],github: [- { status: 'ACTIVE', alias: 'work', word_id: 'castle' },- { status: 'FAILED', alias: 'personal', word_id: 'forest' },+ { status: 'ACTIVE', alias: 'work', word_id: 'castle', permission_group: null },+ { status: 'FAILED', alias: 'personal', word_id: 'forest', permission_group: null },],});})@@ -161,10 +161,10 @@ describe('CLI: composio connections list', () => {const parsed = parseJsonFromLines(lines);expect(parsed).toEqual({- gmail: [{ status: 'ACTIVE' }],+ gmail: [{ status: 'ACTIVE', permission_group: null }],github: [- { status: 'ACTIVE', alias: 'work', word_id: 'castle' },- { status: 'FAILED', alias: 'personal', word_id: 'forest' },+ { status: 'ACTIVE', alias: 'work', word_id: 'castle', permission_group: null },+ { status: 'FAILED', alias: 'personal', word_id: 'forest', permission_group: null },],});})@@ -183,8 +183,8 @@ describe('CLI: composio connections list', () => {expect(parsed).toEqual({github: [- { status: 'ACTIVE', alias: 'work', word_id: 'castle' },- { status: 'FAILED', alias: 'personal', word_id: 'forest' },+ { status: 'ACTIVE', alias: 'work', word_id: 'castle', permission_group: null },+ { status: 'FAILED', alias: 'personal', word_id: 'forest', permission_group: null },],});})diff --git a/ts/packages/cli/test/src/commands/login.cmd.test.ts b/ts/packages/cli/test/src/commands/login.cmd.test.tsindex 0b4bcdc11..b1b7fc0cb 100644--- a/ts/packages/cli/test/src/commands/login.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/login.cmd.test.ts@@ -14,6 +14,25 @@ const mockFetchResponse = (body: unknown, status = 200) =>headers: { 'Content-Type': 'application/json' },});+const setTtyState = (state: { stdin: boolean; stdout: boolean; stderr: boolean }) => {+ const descriptors = {+ stdin: Object.getOwnPropertyDescriptor(process.stdin, 'isTTY'),+ stdout: Object.getOwnPropertyDescriptor(process.stdout, 'isTTY'),+ stderr: Object.getOwnPropertyDescriptor(process.stderr, 'isTTY'),+ };+ Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: state.stdin });+ Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: state.stdout });+ Object.defineProperty(process.stderr, 'isTTY', { configurable: true, value: state.stderr });+ return () => {+ if (descriptors.stdin) Object.defineProperty(process.stdin, 'isTTY', descriptors.stdin);+ else delete (process.stdin as { isTTY?: boolean }).isTTY;+ if (descriptors.stdout) Object.defineProperty(process.stdout, 'isTTY', descriptors.stdout);+ else delete (process.stdout as { isTTY?: boolean }).isTTY;+ if (descriptors.stderr) Object.defineProperty(process.stderr, 'isTTY', descriptors.stderr);+ else delete (process.stderr as { isTTY?: boolean }).isTTY;+ };+};+// ── Tests ────────────────────────────────────────────────────────────────────describe('CLI: composio login', () => {@@ -30,6 +49,7 @@ describe('CLI: composio login', () => {const output = lines.join('\n');expect(output).toContain('--no-browser');expect(output).toContain('--no-wait');+ expect(output).toContain('--poll');expect(output).toContain('--key');expect(output).toContain('--user-api-key');expect(output).toContain('--org');@@ -41,6 +61,47 @@ describe('CLI: composio login', () => {});});+ layer(TestLive())(it => {+ it.scoped('[When] stdin is non-interactive [Then] login prints agent instructions', () =>+ Effect.gen(function* () {+ const restoreTty = setTtyState({ stdin: false, stdout: true, stderr: true });+ try {+ yield* cli(['login']);+ } finally {+ restoreTty();+ }++ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');+ expect(output).toContain('Open this URL in your browser to log in:');+ expect(output).toContain(+ 'https://dashboard.composio.dev/?cliKey=te00st11-d0c4-4efa-8117-c638886063e0'+ );+ expect(output).toContain('Then run this command to complete login:');+ expect(output).toContain('composio login --poll');+ expect(output).toContain('hint: For agents:');+ expect(output).toContain('cached login key');+ expect(output).toContain('polls for up to 10 minutes');+ expect(output).not.toContain('Expires at:');+ expect(output).toContain('Do not ask the user whether to poll');++ const fs = yield* FileSystem.FileSystem;+ const cacheDir = yield* setupCacheDir;+ const pendingLoginRaw = yield* fs.readFileString(+ path.join(cacheDir, 'pending-login-session.json'),+ 'utf8'+ );+ const pendingLogin = JSON.parse(pendingLoginRaw) as Record<string, unknown>;+ expect(pendingLogin.key).toBe('te00st11-d0c4-4efa-8117-c638886063e0');++ expect(output).not.toContain('-- composio login --');+ expect(output).not.toContain('Please login using the following URL');+ expect(output).not.toContain('Login URL');+ expect(output).not.toContain('Login instructions');+ expect(output).not.toContain('Installed composio-cli skill');+ })+ );+ });+layer(TestLive())(it => {it.scoped('[When] logging in with --user-api-key --org [Then] stores the chosen org', () =>Effect.gen(function* () {@@ -63,7 +124,7 @@ describe('CLI: composio login', () => {email: '[email protected]',created_at: '2026-01-01T00:00:00.000Z',updated_at: '2026-01-01T00:00:00.000Z',- org: { id: 'org_default', name: 'Default Org', plan: 'enterprise' },+ org: { id: 'org_default', name: 'Example Org', plan: 'enterprise' },},org_member: {id: 'member_123',@@ -80,7 +141,7 @@ describe('CLI: composio login', () => {expect(new Headers(init?.headers).get('x-user-api-key')).toBe('uak_direct_key');return mockFetchResponse({organizations: [- { id: 'org_default', name: 'Default Org' },+ { id: 'org_default', name: 'Example Org' },{ id: 'org_selected', name: 'Selected Org' },],});diff --git a/ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts b/ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.tsindex 9bc4213b3..17cf2a436 100644--- a/ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts@@ -43,7 +43,7 @@ describe('CLI: composio dev projects list', () => {expect(output).toContain('Hint: run `composio dev init` in a directory to bind it to a developer project.');- expect(output).toContain('Run `composio orgs switch` to change your default org.');+ expect(output).toContain('Run `composio orgs switch` to change your current org.');}));});diff --git a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.tsindex 679f253ba..075f654d9 100644--- a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts@@ -147,8 +147,10 @@ describe('CLI: composio execute', () => {'{"recipient":"a"}',]);const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const outputText = lines.join('\n');const output = parseLastJson(lines);+ expect(outputText).not.toContain('Response\n{');// Response flows through real ToolsExecutorLive → mock session.executeexpect(output.successful).toBe(true);expect(output.data.tool_slug).toBe('GMAIL_SEND_EMAIL');diff --git a/ts/packages/cli/test/src/commands/whoami.cmd.test.ts b/ts/packages/cli/test/src/commands/whoami.cmd.test.tsindex fd1086d3e..f4557ac86 100644--- a/ts/packages/cli/test/src/commands/whoami.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/whoami.cmd.test.ts@@ -24,9 +24,8 @@ describe('CLI: composio whoami', () => {expect(output).not.toContain(`api_key_from_test_config_provider`);expect(output).not.toContain(`global_user_api_key`);expect(output).toContain(`"email":null`);- expect(output).toContain(`"default_org_name":null`);- expect(output).toContain(`"default_org_id":null`);- expect(output).toContain(`"test_user_id":null`);+ expect(output).toContain(`"current_org_name":null`);+ expect(output).not.toContain(`"test_user_id"`);}));});@@ -42,9 +41,8 @@ describe('CLI: composio whoami', () => {expect(output).not.toContain(`api_key_from_test_fixture`);expect(output).not.toContain(`global_user_api_key`);expect(output).toContain(`"email":null`);- expect(output).toContain(`"default_org_name":null`);- expect(output).toContain(`"default_org_id":null`);- expect(output).toContain(`"test_user_id":null`);+ expect(output).toContain(`"current_org_name":null`);+ expect(output).not.toContain(`"test_user_id"`);}));});@@ -90,7 +88,10 @@ describe('CLI: composio whoami', () => {const lines = yield* MockConsole.getLines();const output = lines.join('\n');expect(output).toContain(`"email":"[email protected]"`);- expect(output).toContain(`"default_org_name":"Acme Org"`);+ expect(output).toContain(`"current_org_name":"Acme Org"`);+ expect(output).toContain('Current Org: Acme Org');+ expect(output).not.toContain('Default Org');+ expect(output).not.toContain('Test User ID');}));});diff --git a/ts/packages/cli/test/src/services/update-check.test.ts b/ts/packages/cli/test/src/services/update-check.test.tsindex 73ce19280..f0e810277 100644--- a/ts/packages/cli/test/src/services/update-check.test.ts+++ b/ts/packages/cli/test/src/services/update-check.test.ts@@ -31,6 +31,7 @@ function makeConfig(overrides?: Partial<UpdateCheckConfig>): UpdateCheckConfig {binaryAssetName: 'composio-darwin-aarch64.zip',accessToken: undefined,fetchFn: () => Promise.reject(new Error('fetch not configured')),+ isInteractive: () => true,...overrides,};}@@ -184,6 +185,16 @@ describe('showUpdateNotice', () => {expect(output).toContain('composio upgrade');});+ it('does not print upgrade hint in non-interactive environments', () => {+ const config = makeConfig({ currentVersion: '0.2.0', isInteractive: () => false });+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });+ const { showUpdateNotice } = createUpdateChecker(config);++ showUpdateNotice();++ expect(stderrSpy).not.toHaveBeenCalled();+ });+it('silently ignores corrupt state file', () => {const config = makeConfig();mkdirSync(dirname(config.stateFile), { recursive: true });diff --git a/ts/packages/cli/test/src/utils/stdio.test.ts b/ts/packages/cli/test/src/utils/stdio.test.tsnew file mode 100644index 000000000..9ce69e156--- /dev/null+++ b/ts/packages/cli/test/src/utils/stdio.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';+import { canRenderTerminalDecoration, isInteractiveTerminal } from 'src/utils/stdio';++describe('stdio helpers', () => {+ it('requires all streams to be TTYs for interactive prompts', () => {+ expect(+ isInteractiveTerminal({+ stdin: { isTTY: false },+ stdout: { isTTY: true },+ stderr: { isTTY: true },+ })+ ).toBe(false);+ });++ it('allows terminal decoration when only stderr is a TTY', () => {+ expect(+ canRenderTerminalDecoration({+ stdin: { isTTY: false },+ stdout: { isTTY: true },+ stderr: { isTTY: true },+ })+ ).toBe(true);+ });++ it('suppresses terminal decoration when stderr is not a TTY', () => {+ expect(+ canRenderTerminalDecoration({+ stdin: { isTTY: true },+ stdout: { isTTY: true },+ stderr: { isTTY: false },+ })+ ).toBe(false);+ });+});