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
chore: fix link behavior, disable caching, improve search steps (#3038)
Rahul Tarak4d7bc9873a0a
diff --git a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.tsindex bafae296c..f9608e12e 100644--- a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts+++ b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts@@ -36,11 +36,6 @@ const projectName = Options.text('project-name').pipe(Options.withDescription('Developer project name override for this command'));-const noBrowser = Options.boolean('no-browser').pipe(- Options.withDefault(false),- Options.withDescription('Skip auto-opening the browser')-);-const noWait = Options.boolean('no-wait').pipe(Options.withDefault(false),Options.withDescription('Do not wait for authorization; only print link info')@@ -49,19 +44,13 @@ const noWait = Options.boolean('no-wait').pipe(const showRedirectUrl = (ui: TerminalUI,redirectUrl: string,- noBrowser: boolean,options?: { readonly emitRaw?: boolean }) =>Effect.gen(function* () {- if (noBrowser) {- yield* ui.log.info('Please authorize using the following URL:');- } else {- yield* ui.log.step('Redirecting you to the authorization page');- }-+ yield* ui.log.step('Redirecting you to the authorization page');yield* ui.note(redirectUrl, 'Redirect URL');if (options?.emitRaw) {- yield* ui.output(redirectUrl, noBrowser ? { force: true } : undefined);+ yield* ui.output(redirectUrl);}});@@ -69,35 +58,32 @@ const waitForActiveConnection = (ui: TerminalUI,client: RawComposioClient,connectedAccountId: string,- redirectUrl: string,- noBrowser: boolean+ redirectUrl: string) =>Effect.gen(function* () {- yield* showRedirectUrl(ui, redirectUrl, noBrowser, { emitRaw: noBrowser });-- if (!noBrowser) {- let urlSchemeValid = false;- try {- const parsed = new URL(redirectUrl);- urlSchemeValid = parsed.protocol === 'https:' || parsed.protocol === 'http:';- } catch {- // ignore- }+ yield* showRedirectUrl(ui, redirectUrl);++ let urlSchemeValid = false;+ try {+ const parsed = new URL(redirectUrl);+ urlSchemeValid = parsed.protocol === 'https:' || parsed.protocol === 'http:';+ } catch {+ // ignore+ }- if (!urlSchemeValid) {- yield* ui.log.warn(`Redirect URL has an unexpected scheme: ${redirectUrl}`);- yield* ui.log.info('Open the URL manually if you trust the source.');- } else {- yield* Effect.tryPromise(() => open(redirectUrl, { wait: false })).pipe(- Effect.catchAll(error =>- Effect.gen(function* () {- yield* Effect.logDebug('Failed to open browser:', error);- yield* ui.log.warn('Could not open the browser automatically.');- yield* ui.log.info('Tip: try using `--no-browser` and open the URL manually.');- })- )- );- }+ if (!urlSchemeValid) {+ yield* ui.log.warn(`Redirect URL has an unexpected scheme: ${redirectUrl}`);+ yield* ui.log.info('Open the URL manually if you trust the source.');+ } else {+ yield* Effect.tryPromise(() => open(redirectUrl, { wait: false })).pipe(+ Effect.catchAll(error =>+ Effect.gen(function* () {+ yield* Effect.logDebug('Failed to open browser:', error);+ yield* ui.log.warn('Could not open the browser automatically.');+ yield* ui.log.info('Open the URL above manually.');+ })+ )+ );}yield* ui.useMakeSpinner('Waiting for authentication...', spinner =>@@ -168,7 +154,7 @@ const validateLinkResponse = (});});-const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boolean) =>+const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string) =>Effect.gen(function* () {const userContext = yield* ComposioUserContext;const webURL = userContext.data.webURL.replace(/\/+$/, '');@@ -192,14 +178,12 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boo`Composio does not manage auth for "${toolkitSlug}" — opening the dashboard to connect manually.`);- if (!noBrowser) {- yield* Effect.tryPromise(() => open(dashboardUrl, { wait: false })).pipe(- Effect.catchAll(() => ui.log.warn('Could not open the browser automatically.'))- );- }+ yield* Effect.tryPromise(() => open(dashboardUrl, { wait: false })).pipe(+ Effect.catchAll(() => ui.log.warn('Could not open the browser automatically.'))+ );yield* ui.note(dashboardUrl, 'Dashboard URL');- yield* ui.output(dashboardUrl, noBrowser ? { force: true } : undefined);+ yield* ui.output(dashboardUrl);});const runConnectedAccountsLink = (params: {@@ -207,7 +191,6 @@ const runConnectedAccountsLink = (params: {authConfig: Option.Option<string>;userId: Option.Option<string>;projectName: Option.Option<string>;- noBrowser: boolean;noWait: boolean;rootOnly: boolean;}) =>@@ -318,7 +301,7 @@ const runConnectedAccountsLink = (params: {const { connectedAccountId: connId, redirectUrl } = validatedLink.value;if (params.noWait) {- yield* showRedirectUrl(ui, redirectUrl, params.noBrowser);+ yield* showRedirectUrl(ui, redirectUrl);yield* ui.output(JSON.stringify({@@ -334,7 +317,7 @@ const runConnectedAccountsLink = (params: {{ force: true });} else {- yield* waitForActiveConnection(ui, client, connId, redirectUrl, params.noBrowser);+ yield* waitForActiveConnection(ui, client, connId, redirectUrl);}return;}@@ -382,7 +365,7 @@ const runConnectedAccountsLink = (params: {const slug = extractSlug(error);if (slug === 'ToolRouterV2_NoManagedAuth') {- yield* handleNoManagedAuth(ui, toolkitSlug, params.noBrowser);+ yield* handleNoManagedAuth(ui, toolkitSlug);return Option.none();}@@ -407,7 +390,7 @@ const runConnectedAccountsLink = (params: {const { connectedAccountId: connAccountId, redirectUrl } = validatedLink.value;if (params.noWait) {- yield* showRedirectUrl(ui, redirectUrl, params.noBrowser);+ yield* showRedirectUrl(ui, redirectUrl);yield* ui.output(JSON.stringify({@@ -436,7 +419,7 @@ const runConnectedAccountsLink = (params: {},}).pipe(Effect.catchAll(() => Effect.void));} else {- yield* waitForActiveConnection(ui, client, connAccountId, redirectUrl, params.noBrowser);+ yield* waitForActiveConnection(ui, client, connAccountId, redirectUrl);yield* appendCliSessionHistory({orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,consumerUserId:@@ -454,14 +437,13 @@ const runConnectedAccountsLink = (params: {export const connectedAccountsCmd$Link = Command.make('link',- { toolkit, authConfig, userId, projectName, noBrowser, noWait },- ({ toolkit, authConfig, userId, projectName, noBrowser, noWait }) =>+ { toolkit, authConfig, userId, projectName, noWait },+ ({ toolkit, authConfig, userId, projectName, noWait }) =>runConnectedAccountsLink({toolkit,authConfig,userId,projectName,- noBrowser,noWait,rootOnly: false,})@@ -473,7 +455,6 @@ export const connectedAccountsCmd$Link = Command.make('','Examples:',' composio link github',- ' composio link gmail --no-browser Print the auth URL instead of opening it','','See also:',' composio search "<query>" Find tools to use after linking',@@ -484,14 +465,13 @@ export const connectedAccountsCmd$Link = Command.make(export const rootConnectedAccountsCmd$Link = Command.make('link',- { toolkit, noBrowser, noWait },- ({ toolkit, noBrowser, noWait }) =>+ { toolkit, noWait },+ ({ toolkit, noWait }) =>runConnectedAccountsLink({toolkit,authConfig: Option.none(),userId: Option.none(),projectName: Option.none(),- noBrowser,noWait,rootOnly: true,})@@ -503,7 +483,6 @@ export const rootConnectedAccountsCmd$Link = Command.make('','Examples:',' composio link github',- ' composio link gmail --no-browser Print the auth URL instead of opening it','','See also:',' composio search "<query>" Find tools to use after linking',diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.tsindex 1ab9e2fc7..a25fd7a3e 100644--- a/ts/packages/cli/src/commands/index.ts+++ b/ts/packages/cli/src/commands/index.ts@@ -24,6 +24,7 @@ import { rootToolsCmd$Search } from './tools/commands/tools.search.cmd';import { rootToolsCmd$Execute } from './tools/commands/tools.execute.cmd';import { rootToolsCmd } from './tools/tools.cmd';import { rootConnectedAccountsCmd$Link } from './connected-accounts/commands/connected-accounts.link.cmd';+import { orgsCmd } from './orgs/orgs.cmd';import { renderCommandHintGraph } from 'src/services/command-hints';import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';import { ComposioUserContext } from 'src/services/user-context';@@ -51,6 +52,7 @@ const $cmd = $defaultCmd.pipe(rootConnectedAccountsCmd$Link,rootToolsCmd$Execute,generateCmd,+ orgsCmd,]));export const rootCommand = $cmd;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 db2bec04d..073b6fb9c 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@@ -21,7 +21,7 @@ export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId,const ui = yield* TerminalUI;const ctx = yield* ComposioUserContext;- yield* ui.intro('composio dev orgs switch');+ yield* ui.intro('composio orgs switch');const apiKey = Option.getOrUndefined(ctx.data.apiKey);if (!apiKey) {diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.tsindex 51125bf2f..daf567c0d 100644--- a/ts/packages/cli/src/commands/root-help.ts+++ b/ts/packages/cli/src/commands/root-help.ts@@ -54,7 +54,7 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [{name: 'link',description: 'Connect your account for a toolkit/app.',- usage: 'link [<toolkit>] [--no-browser]',+ usage: 'link [<toolkit>]',options: [{ name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' }],},{@@ -98,7 +98,7 @@ const DEVELOPER_COMMANDS: ReadonlyArray<CompactCommand> = [{name: 'dev',description:- 'Developer workflows and management: init, execute, logs, orgs, projects, toolkits, accounts, and triggers.',+ 'Developer workflows and management: init, logs, projects, toolkits, accounts, and triggers.',},{name: 'generate',@@ -112,6 +112,7 @@ const ACCOUNT_COMMANDS: ReadonlyArray<CompactCommand> = [{ name: 'login', description: 'Log in to Composio' },{ name: 'logout', description: 'Log out from Composio' },{ name: 'whoami', description: 'Show current account info' },+ { name: 'orgs', description: 'Manage default organization context (list, switch)' },{ name: 'version', description: 'Display CLI version' },{ name: 'upgrade', description: 'Upgrade CLI to the latest version' },];@@ -255,18 +256,17 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {],},link: {- usage: 'composio link [<toolkit>] [--no-browser] [--no-wait]',+ usage: 'composio link [<toolkit>] [--no-wait]',description:'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf. Opens a browser for OAuth authorization and waits for confirmation.',args: [{ name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' }],flags: [- { name: '--no-browser', description: 'Print the auth URL instead of opening a browser' },{name: '--no-wait',description: 'Print link info and exit without waiting for authorization',},],- examples: ['composio link github', 'composio link gmail --no-browser'],+ examples: ['composio link github'],seeAlso: ['composio search "<query>" Find tools to use after linking',"composio execute <slug> -d '{ ... }' Execute a tool with your connected account",diff --git a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.tsindex dd08cc18d..3f23d26b4 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts@@ -146,15 +146,26 @@ const collectToolsForResult = (params: {return toolsList;};-const buildSearchCta = (params: {+const buildSearchNextSteps = (params: {firstSlug?: string;firstToolkit?: string;firstDataArg: string;rootOnly: boolean;}) => {- const cta: Array<{ action: string; command: string }> = [];+ const steps: Array<{ action: string; command: string }> = [];+ if (params.firstToolkit) {+ steps.push({+ action: 'Link a user account',+ command: params.rootOnly+ ? commandHintExample('root.link', { toolkit: String(params.firstToolkit).toLowerCase() })+ : commandHintExample('dev.connectedAccounts.link', {+ toolkit: String(params.firstToolkit).toLowerCase(),+ userId: '<user-id>',+ }),+ });+ }if (params.firstSlug) {- cta.push({+ steps.push({action: 'Execute a tool',command: params.rootOnly? commandHintExample('root.execute', { slug: params.firstSlug, data: params.firstDataArg })@@ -165,25 +176,14 @@ const buildSearchCta = (params: {}),});}- if (params.firstToolkit) {- cta.push({- action: 'Connect a user account',- command: params.rootOnly- ? commandHintExample('root.link', { toolkit: String(params.firstToolkit).toLowerCase() })- : commandHintExample('dev.connectedAccounts.link', {- toolkit: String(params.firstToolkit).toLowerCase(),- userId: '<user-id>',- }),- });- }- return cta;+ return steps;};const buildSearchJsonPayload = (params: {searchResponse: SearchResponseRecord;cacheScope: { orgId?: string; consumerUserId?: string };projectScope: { orgId: string; projectId: string };- cta: Array<{ action: string; command: string }>;+ nextSteps: Array<{ action: string; command: string }>;}) =>Effect.gen(function* () {const cacheDir = yield* setupCacheDir;@@ -222,7 +222,11 @@ const buildSearchJsonPayload = (params: {},connected_toolkits: connectedToolkits,...(params.searchResponse.error ? { error: params.searchResponse.error } : {}),- CTA: params.cta,+ next_steps: {+ guidance:+ 'You can directly proceed with these steps without waiting for the user to ask. Link accounts first if needed, then execute tools.',+ steps: params.nextSteps,+ },} as const;});@@ -262,6 +266,12 @@ const emitHumanSearchOutput = (params: {}if (params.firstSlug) {+ const linkHint = params.rootOnly+ ? commandHintStep('Link an account', 'root.link', { toolkit: '<toolkit>' })+ : commandHintStep('Link an account', 'dev.connectedAccounts.link', {+ toolkit: '<toolkit>',+ userId: '<user-id>',+ });const executeHint = params.rootOnly? commandHintStep('Execute a tool', 'root.execute', {slug: params.firstSlug,@@ -272,13 +282,7 @@ const emitHumanSearchOutput = (params: {userId: '<user-id>',data: params.firstDataArg,});- const linkHint = params.rootOnly- ? commandHintStep('Link an account', 'root.link', { toolkit: '<toolkit>' })- : commandHintStep('Link an account', 'dev.connectedAccounts.link', {- toolkit: '<toolkit>',- userId: '<user-id>',- });- yield* params.ui.log.step([executeHint, linkHint].join('\n'));+ yield* params.ui.log.step([linkHint, executeHint].join('\n'));}if (params.error) {@@ -422,7 +426,7 @@ const runToolsSearch = (params: {const firstDataArg =Object.keys(firstPayload).length === 0 ? '-d "{}"' : `-d '${firstPayloadJson}'`;- const cta = buildSearchCta({+ const nextSteps = buildSearchNextSteps({firstSlug,firstToolkit,firstDataArg,@@ -436,7 +440,7 @@ const runToolsSearch = (params: {consumerUserId: searchResult.historyScope?.consumerUserId,},projectScope: searchResult.projectScope,- cta,+ nextSteps,});yield* appendCliSessionHistory({@@ -490,9 +494,9 @@ export const toolsCmd$Search = Command.make(' composio search "list calendar events" --limit 5','','Next steps:',+ ' composio link <toolkit> Connect an account before executing tools'," composio execute <slug> -d '{ ... }' Run a tool from the results"," composio tools info <slug> Inspect a tool's schema before executing",- ' composio link <toolkit> Connect an account if execute tells you to',].join('\n')));@@ -524,9 +528,9 @@ export const rootToolsCmd$Search = Command.make(' composio search "list calendar events" --limit 5','','Next steps:',+ ' composio link <toolkit> Connect an account before executing tools'," composio execute <slug> -d '{ ... }' Run a tool from the results"," composio tools info <slug> Inspect a tool's schema before executing",- ' composio link <toolkit> Connect an account if execute tells you to',].join('\n')));diff --git a/ts/packages/cli/src/effects/app-config.ts b/ts/packages/cli/src/effects/app-config.tsindex 2137dcef9..8b0a7589e 100644--- a/ts/packages/cli/src/effects/app-config.ts+++ b/ts/packages/cli/src/effects/app-config.ts@@ -10,6 +10,7 @@ type APP_CONFIG = Config.Config.Wrap<{LOG_LEVEL: Option.Option<LogLevel.LogLevel>;ORG_ID: Option.Option<string>;PROJECT_ID: Option.Option<string>;+ DISABLE_CONNECTED_ACCOUNT_CACHE: boolean;}>;/**@@ -65,4 +66,9 @@ export const APP_CONFIG = {// The project ID for multi-project auth (overrides file-based config)PROJECT_ID: Config.option(Config.string('PROJECT_ID')),++ // Disable connected account cache (defaults to true — cache is off by default)+ DISABLE_CONNECTED_ACCOUNT_CACHE: Config.boolean('DISABLE_CONNECTED_ACCOUNT_CACHE').pipe(+ Config.withDefault(true)+ ),} satisfies APP_CONFIG;diff --git a/ts/packages/cli/src/services/consumer-short-term-cache.ts b/ts/packages/cli/src/services/consumer-short-term-cache.tsindex a9decce28..7a9051f24 100644--- a/ts/packages/cli/src/services/consumer-short-term-cache.ts+++ b/ts/packages/cli/src/services/consumer-short-term-cache.ts@@ -1,6 +1,7 @@import path from 'node:path';import { FileSystem } from '@effect/platform';import { Effect, Option } from 'effect';+import { APP_CONFIG } from 'src/effects/app-config';import { setupCacheDir } from 'src/effects/setup-cache-dir';import { NodeProcess } from 'src/services/node-process';import {@@ -112,9 +113,7 @@ const getAlwaysConnectedNoAuthToolkits = () =>const toolkitsRepository = yield* ComposioToolkitsRepository;const toolkits = yield* toolkitsRepository.getToolkits();- return toolkits- .filter(toolkit => toolkit.no_auth)- .map(toolkit => toolkit.slug.toLowerCase());+ return toolkits.filter(toolkit => toolkit.no_auth).map(toolkit => toolkit.slug.toLowerCase());});const normalizeCachedToolkits = (@@ -127,6 +126,10 @@ export const getFreshConsumerConnectedToolkitsFromCache = (params: {consumerUserId: string;}) =>Effect.gen(function* () {+ const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;+ if (disabled) {+ return Option.none<ReadonlyArray<string>>();+ }const state = yield* readCache();const entry = state[cacheKey(params.orgId, params.consumerUserId)];if (!entry) {@@ -194,6 +197,8 @@ export const refreshConsumerConnectedToolkitsCache = (params?: {readonly consumerUserId?: string;}) =>Effect.gen(function* () {+ const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;+ if (disabled) return;const scope = yield* resolveConsumerScope(params);if (!scope?.consumerUserId) {return;@@ -236,6 +241,8 @@ export const writeConsumerConnectedToolkitsCache = (params: {readonly toolkits: ReadonlyArray<string>;}) =>Effect.gen(function* () {+ const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;+ if (disabled) return;const noAuthToolkits = yield* getAlwaysConnectedNoAuthToolkits();const state = yield* readCache();const key = cacheKey(params.orgId, params.consumerUserId);@@ -271,6 +278,8 @@ export const getOrCreateProbablyMyCliSessionIdForCurrentCwd = (params?: {readonly consumerUserId?: string;}) =>Effect.gen(function* () {+ const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;+ if (disabled) return Option.none<string>();const scope = yield* resolveConsumerScope(params);if (!scope?.consumerUserId) {return Option.none<string>();diff --git a/ts/packages/cli/test/src/commands/$default.cmd.test.ts b/ts/packages/cli/test/src/commands/$default.cmd.test.tsindex 04e88d1d8..52008c87d 100644--- a/ts/packages/cli/test/src/commands/$default.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/$default.cmd.test.ts@@ -4,6 +4,17 @@ import { ValidationError, HelpDoc } from '@effect/cli';import { cli, pkg, TestLive, MockConsole } from 'test/__utils__';import { afterEach, vi } from 'vitest';+type CommandMismatchResult = {+ _tag: string;+ error: {+ _tag: string;+ value: {+ _tag: string;+ value: string;+ };+ };+};+describe('CLI: composio', () => {afterEach(() => {vi.unstubAllEnvs();@@ -15,14 +26,15 @@ describe('CLI: composio', () => {const args = ['--bar'];const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));+ const commandMismatch = result as CommandMismatchResult;- expect(result).toEqual(- ValidationError.commandMismatch(- HelpDoc.p(- "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'run', 'proxy', 'artifacts', 'install', 'dev', 'tools', 'search', 'link', 'execute', 'generate'"- )- )- );+ expect(result).toEqual(expect.any(Object));+ expect(commandMismatch._tag).toBe(ValidationError.commandMismatch(HelpDoc.p(''))._tag);+ expect(commandMismatch.error._tag).toBe('Paragraph');+ expect(commandMismatch.error.value._tag).toBe('Text');+ expect(commandMismatch.error.value.value).toContain('Invalid subcommand for composio');+ expect(commandMismatch.error.value.value).toContain("'generate'");+ expect(commandMismatch.error.value.value).toContain("'orgs'");}));});diff --git a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.tsindex b4493b5e7..1a81aa677 100644--- a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts@@ -5,6 +5,12 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';import type { TestLiveInput } from 'test/__utils__/services/test-layer';import type { ConnectedAccountItem } from 'src/models/connected-accounts';import { TerminalUI } from 'src/services/terminal-ui';+import open from 'open';+import { afterEach, vi } from 'vitest';++vi.mock('open', () => ({+ default: vi.fn(async () => undefined),+}));const extractJsonObject = (output: string): Record<string, unknown> | null => {const jsonMatch = output.match(/\{[\s\S]*"status"[\s\S]*\}/);@@ -70,6 +76,10 @@ const RecordingTerminalUI = TerminalUI.of({});describe('CLI: composio dev connected-accounts link', () => {+ afterEach(() => {+ vi.clearAllMocks();+ });+layer(TestLive({baseConfigProvider: testConfigProvider,@@ -79,7 +89,7 @@ describe('CLI: composio dev connected-accounts link', () => {)('[Given] valid toolkit link [Then] creates link and waits (default)', it => {it.scoped('creates link and waits for ACTIVE', () =>Effect.gen(function* () {- yield* cli(['link', 'gmail', '--no-browser']);+ yield* cli(['link', 'gmail']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const parsed = extractJsonObject(lines.join('\n'));@@ -87,6 +97,7 @@ describe('CLI: composio dev connected-accounts link', () => {expect(parsed?.status).toBe('success');expect(parsed?.connected_account_id).toBe('con_test_link');expect(parsed?.toolkit).toBe('gmail');+ expect(vi.mocked(open)).toHaveBeenCalledOnce();}));});@@ -98,15 +109,24 @@ describe('CLI: composio dev connected-accounts link', () => {fixture: 'global-test-user-id',terminalUI: RecordingTerminalUI,})- )('[Given] --no-browser [Then] emits a forced raw redirect URL for merged-stream shells', it => {- it.scoped('forces the redirect URL through output()', () =>+ )('[Given] --no-wait [Then] emits a forced JSON payload for merged-stream shells', it => {+ it.scoped('forces the pending JSON payload through output()', () =>Effect.gen(function* () {- yield* cli(['link', 'gmail', '--no-browser']);+ yield* cli(['link', 'gmail', '--no-wait']);const lines = yield* MockConsole.getLines({ stripAnsi: true });- const output = lines.join('\n');+ const forcedLine = lines+ .map(line => {+ try {+ return JSON.parse(line) as { channel?: string; data?: string };+ } catch {+ return null;+ }+ })+ .find(line => line?.channel === 'FORCED');- expect(output).toContain('"channel":"FORCED"');- expect(output).toContain('https://app.composio.dev/link?token=lt_test_token');+ expect(forcedLine).toBeTruthy();+ expect(forcedLine?.data).toContain('"status": "pending"');+ expect(vi.mocked(open)).not.toHaveBeenCalled();}));});@@ -118,10 +138,10 @@ describe('CLI: composio dev connected-accounts link', () => {fixture: 'global-test-user-id',terminalUI: RecordingTerminalUI,})- )('[Given] --no-browser --no-wait [Then] stdout remains JSON-only', it => {+ )('[Given] --no-wait [Then] stdout remains JSON-only', it => {it.scoped('does not emit the raw redirect URL before the pending JSON payload', () =>Effect.gen(function* () {- yield* cli(['link', 'gmail', '--no-browser', '--no-wait']);+ yield* cli(['link', 'gmail', '--no-wait']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const forcedLines = lines.map(line => {@@ -140,18 +160,13 @@ describe('CLI: composio dev connected-accounts link', () => {);});- layer(- TestLive({- baseConfigProvider: testConfigProvider,- connectedAccountsData,- fixture: 'global-test-user-id',- })- )('[Given] no API key [Then] warns user to login', it => {+ layer(TestLive())('[Given] no API key [Then] warns user to login', it => {it.scoped('warns user to login', () =>Effect.gen(function* () {- yield* cli(['link', 'gmail', '--no-browser']);+ yield* cli(['link', 'gmail']);const lines = yield* MockConsole.getLines({ stripAnsi: true });- expect(lines.length).toBeGreaterThan(0);+ const output = lines.join('\n');+ expect(output).toContain('not logged in');}));});@@ -165,7 +180,7 @@ describe('CLI: composio dev connected-accounts link', () => {)('[Given] composio link [Then] works for consumer toolkit linking', it => {it.scoped('root link works for consumer toolkit linking only', () =>Effect.gen(function* () {- yield* cli(['link', 'gmail', '--no-browser']);+ yield* cli(['link', 'gmail']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const parsed = extractJsonObject(lines.join('\n'));@@ -185,7 +200,7 @@ describe('CLI: composio dev connected-accounts link', () => {)('[Given] --no-wait [Then] outputs valid JSON parseable by jq', it => {it.scoped('prints JSON with status pending, connected_account_id, redirect_url', () =>Effect.gen(function* () {- yield* cli(['link', 'gmail', '--no-browser', '--no-wait']);+ yield* cli(['link', 'gmail', '--no-wait']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const parsed = extractJsonObject(lines.join('\n'));@@ -215,7 +230,7 @@ describe('CLI: composio dev connected-accounts link', () => {it => {it.scoped('reports the incomplete response instead of waiting with empty values', () =>Effect.gen(function* () {- yield* cli(['link', 'gmail', '--no-browser']);+ yield* cli(['link', 'gmail']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const parsed = extractJsonObject(lines.join('\n'));@@ -237,7 +252,7 @@ describe('CLI: composio dev connected-accounts link', () => {'prints JSON with status success, message, connected_account_id, toolkit, redirect_url',() =>Effect.gen(function* () {- yield* cli(['link', 'gmail', '--no-browser']);+ yield* cli(['link', 'gmail']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const parsed = extractJsonObject(lines.join('\n'));diff --git a/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.tsindex ffa67fb43..19b029916 100644--- a/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts@@ -53,6 +53,49 @@ const testLiveOptions = {fixture: 'global-test-user-id' as const,};+const extractFirstJsonObject = (output: string): Record<string, unknown> | null => {+ const start = output.indexOf('{');+ if (start < 0) return null;++ let depth = 0;+ let inString = false;+ let escaped = false;++ for (let i = start; i < output.length; i += 1) {+ const char = output[i];++ if (inString) {+ if (escaped) {+ escaped = false;+ } else if (char === '\\') {+ escaped = true;+ } else if (char === '"') {+ inString = false;+ }+ continue;+ }++ if (char === '"') {+ inString = true;+ continue;+ }++ if (char === '{') {+ depth += 1;+ continue;+ }++ if (char === '}') {+ depth -= 1;+ if (depth === 0) {+ return JSON.parse(output.slice(start, i + 1)) as Record<string, unknown>;+ }+ }+ }++ return null;+};+describe('CLI: composio search', () => {layer(TestLive(testLiveOptions))('[Given] query "send" [Then] returns JSON by default', it => {it.scoped('returns JSON payload by default', () =>@@ -60,18 +103,18 @@ describe('CLI: composio search', () => {yield* cli(['search', 'send']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');-- expect(output).toContain('"results"');- expect(output).toContain('"tool_schemas"');- expect(output).toContain('"primary"');- expect(output).toContain('"related_tools_path_format"');- expect(output).toContain('"connected_toolkits"');- expect(output).toContain('"CTA"');- expect(output).not.toContain('"session"');- expect(output).not.toContain('"time_info"');- expect(output).not.toContain('"next_steps_guidance"');- expect(output).not.toContain('"success"');- expect(output).not.toContain('"error"');+ const parsed = extractFirstJsonObject(output);++ expect(parsed).not.toBeNull();+ expect(parsed).toHaveProperty('results');+ expect(parsed).toHaveProperty('tool_schemas');+ expect(parsed).toHaveProperty('connected_toolkits');+ expect(parsed).toHaveProperty('next_steps');+ expect(parsed).not.toHaveProperty('session');+ expect(parsed).not.toHaveProperty('time_info');+ expect(parsed).not.toHaveProperty('next_steps_guidance');+ expect(parsed).not.toHaveProperty('success');+ expect(parsed).not.toHaveProperty('error');expect(output).toContain('GMAIL_SEND_EMAIL');expect(output).toContain('SLACK_SEND_MESSAGE');expect(output).toContain('~/.composio/tool_definitions/GMAIL_SEND_EMAIL.json');@@ -151,25 +194,27 @@ describe('CLI: composio search', () => {);layer(TestLive(testLiveOptions))(- '[Given] search --json [Then] JSON output includes full tool-router payload and CTA',+ '[Given] search --json [Then] JSON output includes full tool-router payload and next steps',it => {- it.scoped('prints full search response with CTA for jq', () =>+ it.scoped('prints full search response with next steps for jq', () =>Effect.gen(function* () {yield* cli(['search', 'send', '--json']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');-- expect(output).toContain('"results"');- expect(output).toContain('"tool_schemas"');- expect(output).toContain('"connected_toolkits"');- expect(output).toContain('"CTA"');- expect(output).not.toContain('"session"');- expect(output).not.toContain('"time_info"');- expect(output).not.toContain('"next_steps_guidance"');- expect(output).not.toContain('"success"');- expect(output).not.toContain('"error"');+ const parsed = extractFirstJsonObject(output);++ expect(parsed).not.toBeNull();+ expect(parsed).toHaveProperty('results');+ expect(parsed).toHaveProperty('tool_schemas');+ expect(parsed).toHaveProperty('connected_toolkits');+ expect(parsed).toHaveProperty('next_steps');+ expect(parsed).not.toHaveProperty('session');+ expect(parsed).not.toHaveProperty('time_info');+ expect(parsed).not.toHaveProperty('next_steps_guidance');+ expect(parsed).not.toHaveProperty('success');+ expect(parsed).not.toHaveProperty('error');expect(output).toContain('"Execute a tool"');- expect(output).toContain('"Connect a user account"');+ expect(output).toContain('"Link a user account"');expect(output).toContain('composio execute');expect(output).toContain('composio link gmail');})@@ -244,9 +289,9 @@ describe('CLI: composio search', () => {);layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(- '[Given] search with schema properties [Then] CTA has valid payload and lowercase link',+ '[Given] search with schema properties [Then] next steps have valid payload and lowercase link',it => {- it.scoped('CTA uses valid payload from input_schema and lowercase toolkit', () =>+ it.scoped('next steps use valid payload from input_schema and lowercase toolkit', () =>Effect.gen(function* () {const live = TestLive({baseConfigProvider: testConfigProvider,@@ -277,42 +322,46 @@ describe('CLI: composio search', () => {yield* cli(['search', 'send']).pipe(Effect.provide(live));const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');-- const ctaMatch = output.match(/"CTA":\s*\[([\s\S]*?)\]/);- expect(ctaMatch).toBeTruthy();- const ctaJson = `[${ctaMatch![1]}]`;- const cta = JSON.parse(ctaJson) as Array<{ action: string; command: string }>;-- const executeCta = cta.find(c => c.action === 'Execute a tool');- expect(executeCta).toBeTruthy();- expect(executeCta!.command).toContain('composio execute "GMAIL_SEND_EMAIL"');- expect(executeCta!.command).toMatch(/-d '\{"to":"","subject":"","body":""\}'/);-- const linkCta = cta.find(c => c.action === 'Connect a user account');- expect(linkCta).toBeTruthy();- expect(linkCta!.command).toBe('composio link gmail');+ const parsed = extractFirstJsonObject(output);+ const nextSteps = parsed?.next_steps as+ | {+ steps?: Array<{ action: string; command: string }>;+ }+ | undefined;++ expect(nextSteps?.steps).toBeTruthy();++ const executeStep = nextSteps?.steps?.find(step => step.action === 'Execute a tool');+ expect(executeStep).toBeTruthy();+ expect(executeStep!.command).toContain('composio execute "GMAIL_SEND_EMAIL"');+ expect(executeStep!.command).toMatch(/-d '\{"to":"","subject":"","body":""\}'/);++ const linkStep = nextSteps?.steps?.find(step => step.action === 'Link a user account');+ expect(linkStep).toBeTruthy();+ expect(linkStep!.command).toBe('composio link gmail');}));});layer(TestLive(testLiveOptions))(- '[Given] search with empty schema [Then] CTA execute uses -d "{}"',+ '[Given] search with empty schema [Then] next steps execute uses -d "{}"',it => {- it.scoped('CTA uses -d "{}" when no schema properties', () =>+ it.scoped('next steps use -d "{}" when no schema properties', () =>Effect.gen(function* () {yield* cli(['search', 'send']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');-- const ctaMatch = output.match(/"CTA":\s*\[([\s\S]*?)\]/);- expect(ctaMatch).toBeTruthy();- const ctaJson = `[${ctaMatch![1]}]`;- const cta = JSON.parse(ctaJson) as Array<{ action: string; command: string }>;-- const executeCta = cta.find(c => c.action === 'Execute a tool');- expect(executeCta).toBeTruthy();- expect(executeCta!.command).toContain('-d "{}"');+ const parsed = extractFirstJsonObject(output);+ const nextSteps = parsed?.next_steps as+ | {+ steps?: Array<{ action: string; command: string }>;+ }+ | undefined;++ const executeStep = nextSteps?.steps?.find(step => step.action === 'Execute a tool');+ expect(executeStep).toBeTruthy();+ expect(executeStep!.command).toContain('-d "{}"');}));}diff --git a/ts/packages/cli/test/src/services/config.test.ts b/ts/packages/cli/test/src/services/config.test.tsindex 1ddf41158..a606c069c 100644--- a/ts/packages/cli/test/src/services/config.test.ts+++ b/ts/packages/cli/test/src/services/config.test.ts@@ -30,6 +30,7 @@ describe('Config', () => {LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,WEB_URL: 'https://dashboard.composio.dev/',}));@@ -57,6 +58,7 @@ describe('Config', () => {LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,WEB_URL: 'https://dashboard.composio.dev/',}));@@ -86,6 +88,33 @@ describe('Config', () => {LOG_LEVEL: Option.some(LogLevel.Info),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );+ });++ it('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () => {+ const map = new Map([['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false']]) satisfies Map<+ string,+ string+ >;++ const actual = Effect.runSync(+ withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.none(),+ BASE_URL: 'https://backend.composio.dev',+ WEB_URL: 'https://dashboard.composio.dev/',+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: false,}));});@@ -108,6 +137,7 @@ describe('Config', () => {LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,}));});@@ -130,6 +160,7 @@ describe('Config', () => {LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,}));});@@ -155,6 +186,7 @@ describe('Config', () => {LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,}));});@@ -180,6 +212,7 @@ describe('Config', () => {LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,}));});@@ -202,6 +235,7 @@ describe('Config', () => {LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,}));});@@ -312,6 +346,7 @@ describe('Config', () => {LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,}));});@@ -337,6 +372,7 @@ describe('Config', () => {LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,}));});@@ -363,6 +399,30 @@ describe('Config', () => {LOG_LEVEL: Option.some(LogLevel.Info),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );+ });++ it('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () => {+ vi.stubEnv('COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false');++ const actual = Effect.runSync(+ withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.none(),+ BASE_URL: 'https://backend.composio.dev',+ WEB_URL: 'https://dashboard.composio.dev/',+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: false,}));});@@ -385,6 +445,7 @@ describe('Config', () => {LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,}));});@@ -409,6 +470,7 @@ describe('Config', () => {LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,}));});diff --git a/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts b/ts/packages/cli/test/src/services/consumer-short-term-cache.test.tsindex c23378e87..ca6ab9583 100644--- a/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts+++ b/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts@@ -10,21 +10,50 @@ import {} from 'src/services/consumer-short-term-cache';import { TestLive } from 'test/__utils__';-const testConfigProvider = ConfigProvider.fromMap(- new Map([- ['COMPOSIO_USER_API_KEY', 'test_api_key'],- ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],- ])-).pipe(extendConfigProvider);+const makeTestConfigProvider = (entries: Array<[string, string]>) =>+ ConfigProvider.fromMap(+ new Map([+ ['COMPOSIO_USER_API_KEY', 'test_api_key'],+ ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],+ ...entries,+ ])+ ).pipe(extendConfigProvider);++const defaultTestConfigProvider = makeTestConfigProvider([]);+const cacheEnabledTestConfigProvider = makeTestConfigProvider([+ ['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false'],+]);describe('consumer short-term cache', () => {afterEach(() => {vi.restoreAllMocks();});+ layer(TestLive({ baseConfigProvider: defaultTestConfigProvider }))(+ '[Given] the default cache config [Then] connected-account cache stays disabled',+ it => {+ it.scoped('returns none even after a write is attempted', () =>+ Effect.gen(function* () {+ yield* writeConsumerConnectedToolkitsCache({+ orgId: 'org_test',+ consumerUserId: 'consumer-user-test',+ toolkits: ['github'],+ });++ const cached = yield* getFreshConsumerConnectedToolkitsFromCache({+ orgId: 'org_test',+ consumerUserId: 'consumer-user-test',+ });++ expect(cached).toEqual(Option.none());+ })+ );+ }+ );+layer(TestLive({- baseConfigProvider: testConfigProvider,+ baseConfigProvider: cacheEnabledTestConfigProvider,toolkitsData: {toolkits: [{@@ -88,7 +117,7 @@ describe('consumer short-term cache', () => {layer(TestLive({- baseConfigProvider: testConfigProvider,+ baseConfigProvider: cacheEnabledTestConfigProvider,toolkitsData: {toolkits: [{