@devries-cameron20 / composio-1 / commits / 1344e1cd3
Fork 0

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

Make root search/link/execute consumer-only (#2971)

## Summary - make top-level `composio search`, `composio link`, and `composio execute` consumer-only - keep developer-scoped usage under `composio manage ...` - remove developer-only flags from root help and add short related-command hints - use `consumer_user_id` from consumer project resolve and stop showing internal test-user/project diagnostics on consumer flows ## Testing - `pnpm -C ts/packages/cli exec tsc --noEmit -p ./tsconfig.src.json` - `pnpm -C ts/packages/cli test -- --runInBand` will show you the top level commands working ``` export COMPOSIO_BASE_URL="https://apollo-k05mgspn8-composio.vercel.app/" export COMPOSIO_WEB_URL="https://dashboard-git-t3code-cli-landing-redesign-composio.vercel.app/" pnpm -C ts/packages/cli run cli -- login ``` --------- Co-authored-by: jkomyno <12381818+jkomyno@users.noreply.github.com>

Rahul Tarak committed Mar 20, 2026 at 16:13 UTC 1344e1cd343d90412a73f1a190dd9831ee7eda8e
54 files changed +1535 -1192
ts/packages/cli/package.json
+1 -1
@@ -35,7 +35,7 @@
35 "table:metrics": "bun run ./scripts/optimize-metrics-table.ts",
36 "mock": "bun run ./scripts/copy-mocks-from-cache.ts",
37 "prebuild": "pnpm run typecheck",
38 - "build": "bun run --bun tsdown",
38 + "build": "pnpm exec tsdown",
39 "bin": "./dist/composio",
40 "test": "vitest run",
41 "prepublishOnly": "pnpm run build && pnpm run build:binary",
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+272 -157
@@ -5,10 +5,14 @@ import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { ComposioUserContext } from 'src/services/user-context';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { requireAuth } from 'src/effects/require-auth';
8 -import { handleHttpServerError } from 'src/effects/handle-http-error';
8 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
9 import { extractMessage } from 'src/utils/api-error-extraction';
10 import { ProjectContext } from 'src/services/project-context';
11 +import { ComposioClientSingleton } from 'src/services/composio-clients';
12 +import {
13 + resolveCommandProject,
14 + formatResolveCommandProjectError,
15 +} from 'src/services/command-project';
16
17 const toolkit = Args.text({ name: 'toolkit' }).pipe(
18 Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
@@ -21,10 +25,15 @@ const authConfig = Options.text('auth-config').pipe(
25 );
26
27 const userId = Options.text('user-id').pipe(
24 - Options.withDescription('User ID for the connection (falls back to project test_user_id)'),
28 + Options.withDescription('Developer-project user ID override'),
29 Options.optional
30 );
31
32 +const projectName = Options.text('project-name').pipe(
33 + Options.optional,
34 + Options.withDescription('Developer project name override for this command')
35 +);
36 +
37 const noBrowser = Options.boolean('no-browser').pipe(
38 Options.withDefault(false),
39 Options.withDescription('Skip auto-opening the browser')
@@ -35,10 +44,6 @@ const noWait = Options.boolean('no-wait').pipe(
44 Options.withDescription('Do not wait for authorization; only print link info')
45 );
46
38 -/**
39 - * Open the browser and poll until the connected account becomes ACTIVE.
40 - * On success, outputs valid JSON to stdout for piping (e.g. to jq).
41 - */
47 const waitForActiveConnection = (
48 ui: TerminalUI,
49 repo: ComposioToolkitsRepository,
@@ -47,17 +52,15 @@ const waitForActiveConnection = (
52 noBrowser: boolean
53 ) =>
54 Effect.gen(function* () {
50 - // Display the redirect URL (interactive only)
55 yield* ui.note(redirectUrl, 'Redirect URL');
56
57 if (!noBrowser) {
54 - // Validate URL scheme before opening — prevent non-HTTPS redirects
58 let urlSchemeValid = false;
59 try {
60 const parsed = new URL(redirectUrl);
61 urlSchemeValid = parsed.protocol === 'https:' || parsed.protocol === 'http:';
62 } catch {
60 - // Malformed URL — fall through to the warning below
63 + // ignore
64 }
65
66 if (!urlSchemeValid) {
@@ -76,21 +79,17 @@ const waitForActiveConnection = (
79 }
80 }
81
79 - // Poll until the connected account becomes ACTIVE
82 yield* ui.useMakeSpinner('Waiting for authentication...', spinner =>
83 Effect.retry(
84 Effect.gen(function* () {
85 const account = yield* repo.getConnectedAccount(connectedAccountId);
84 -
86 if (account.status === 'ACTIVE') {
87 return account;
88 }
88 -
89 return yield* Effect.fail(
90 new Error(`Connection status is still '${account.status}', waiting for 'ACTIVE'`)
91 );
92 }),
93 - // Exponential backoff: start with 0.3s, max 5s, up to 15 retries
93 Schedule.exponential('0.3 seconds').pipe(
94 Schedule.intersect(Schedule.recurs(15)),
95 Schedule.intersect(Schedule.spaced('5 seconds'))
@@ -121,174 +120,290 @@ const waitForActiveConnection = (
120 );
121 });
122
124 -/**
125 - * Link an external account via OAuth redirect.
126 - *
127 - * Two modes:
128 - * - **Tool Router** (default): `composio manage connected-accounts link <toolkit>`
129 - * - **Legacy**: `composio manage connected-accounts link --auth-config <id>`
130 - *
131 - * @example
132 - * ```bash
133 - * composio manage connected-accounts link github
134 - * composio manage connected-accounts link gmail --user-id "alice"
135 - * composio manage connected-accounts link --auth-config "ac_..." --user-id "default"
136 - * ```
137 - */
138 -export const connectedAccountsCmd$Link = Command.make(
139 - 'link',
140 - { toolkit, authConfig, userId, noBrowser, noWait },
141 - ({ toolkit, authConfig, userId, noBrowser, noWait }) =>
142 - Effect.gen(function* () {
143 - if (!(yield* requireAuth)) return;
123 +const validateLinkResponse = (
124 + ui: TerminalUI,
125 + linkResponse: {
126 + connected_account_id?: string | null;
127 + redirect_url?: string | null;
128 + }
129 +) =>
130 + Effect.gen(function* () {
131 + const connectedAccountId = linkResponse.connected_account_id;
132 + const redirectUrl = linkResponse.redirect_url;
133
145 - const ui = yield* TerminalUI;
146 - const repo = yield* ComposioToolkitsRepository;
147 - const projectContext = yield* ProjectContext;
148 - const userContext = yield* ComposioUserContext;
149 - const resolvedProjectContext = yield* projectContext.resolve;
150 - const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
134 + if (!connectedAccountId || !redirectUrl) {
135 + yield* ui.log.error(
136 + 'The API returned an incomplete link response (missing connected_account_id or redirect_url).'
137 + );
138 + yield* Effect.logDebug('Link response:', linkResponse);
139 + return Option.none();
140 + }
141 +
142 + return Option.some({
143 + connectedAccountId,
144 + redirectUrl,
145 + });
146 + });
147 +
148 +const runConnectedAccountsLink = (params: {
149 + toolkit: Option.Option<string>;
150 + authConfig: Option.Option<string>;
151 + userId: Option.Option<string>;
152 + projectName: Option.Option<string>;
153 + noBrowser: boolean;
154 + noWait: boolean;
155 + rootOnly: boolean;
156 +}) =>
157 + Effect.gen(function* () {
158 + if (!(yield* requireAuth)) return;
159 +
160 + const ui = yield* TerminalUI;
161 + const repo = yield* ComposioToolkitsRepository;
162 + const clientSingleton = yield* ComposioClientSingleton;
163 + const projectContext = yield* ProjectContext;
164 + const userContext = yield* ComposioUserContext;
165 +
166 + if (params.rootOnly) {
167 + if (Option.isSome(params.authConfig)) {
168 + return yield* Effect.fail(
169 + new Error(
170 + 'Top-level `composio link` is consumer-only and does not accept `--auth-config`. Use `composio manage connected-accounts link --auth-config ...` for developer-scoped usage.'
171 + )
172 + );
173 + }
174 + }
175 +
176 + if (Option.isSome(params.toolkit) && Option.isSome(params.authConfig)) {
177 + yield* ui.log.error(
178 + 'Cannot use both <toolkit> and --auth-config. Choose one:\n' +
179 + ' Tool Router: composio manage connected-accounts link <toolkit>\n' +
180 + ' Legacy: composio manage connected-accounts link --auth-config <id>'
181 + );
182 + return;
183 + }
184 +
185 + if (Option.isNone(params.toolkit) && Option.isNone(params.authConfig)) {
186 + yield* ui.log.error(
187 + params.rootOnly
188 + ? 'Missing argument. Provide a toolkit slug:\n composio link github'
189 + : 'Missing argument. Provide a toolkit slug or --auth-config:\n' +
190 + ' composio manage connected-accounts link github\n' +
191 + ' composio manage connected-accounts link --auth-config "ac_..."'
192 + );
193 + return;
194 + }
195 +
196 + if (Option.isSome(params.authConfig)) {
197 + const authConfigId = params.authConfig.value;
198 + const resolvedProjectContext = yield* projectContext.resolve.pipe(
199 + Effect.catchAll(() => Effect.succeed(Option.none()))
200 + );
201 + const localTestUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
202 const globalTestUserId = userContext.data.testUserId;
152 - const resolvedUserId = Option.match(userId, {
203 + const resolvedUserId = Option.match(params.userId, {
204 onSome: value => Option.some(value),
154 - onNone: () => Option.orElse(testUserId, () => globalTestUserId),
205 + onNone: () => Option.orElse(localTestUserId, () => globalTestUserId),
206 });
207 if (Option.isNone(resolvedUserId)) {
208 return yield* Effect.fail(
209 new Error('Missing user id. Provide --user-id or run composio init to set test_user_id.')
210 );
211 }
161 - if (Option.isNone(userId) && Option.isSome(testUserId)) {
162 - yield* ui.log.warn(`Using test user id "${testUserId.value}"`);
163 - } else if (Option.isNone(userId) && Option.isSome(globalTestUserId)) {
164 - yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
165 - }
166 -
167 - // Validate: exactly one of <toolkit> or --auth-config must be provided
168 - if (Option.isSome(toolkit) && Option.isSome(authConfig)) {
212 + if (Option.isNone(params.projectName) && Option.isNone(resolvedProjectContext)) {
213 yield* ui.log.error(
170 - 'Cannot use both <toolkit> and --auth-config. Choose one:\n' +
171 - ' Tool Router: composio manage connected-accounts link <toolkit>\n' +
172 - ' Legacy: composio manage connected-accounts link --auth-config <id>'
214 + '`--auth-config` is developer-project scoped. Pass `--project-name <name>` or run from a directory initialized with `composio init`.'
215 );
216 return;
217 }
176 -
177 - if (Option.isNone(toolkit) && Option.isNone(authConfig)) {
178 - yield* ui.log.error(
179 - 'Missing argument. Provide a toolkit slug or --auth-config:\n' +
180 - ' composio manage connected-accounts link github\n' +
181 - ' composio manage connected-accounts link --auth-config "ac_..."'
182 - );
183 - return;
218 + if (Option.isNone(params.userId) && Option.isSome(localTestUserId)) {
219 + yield* ui.log.warn(`Using test user id "${localTestUserId.value}"`);
220 + } else if (Option.isNone(params.userId) && Option.isSome(globalTestUserId)) {
221 + yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
222 }
185 -
186 - if (Option.isSome(authConfig)) {
187 - // Path A: Legacy flow — use existing client.link.create()
188 - const linkOpt = yield* ui
189 - .withSpinner(
190 - 'Creating link session...',
191 - repo.createConnectedAccountLink({
192 - auth_config_id: authConfig.value,
223 + const resolvedProject = yield* resolveCommandProject({
224 + mode: 'developer',
225 + projectName: Option.getOrUndefined(params.projectName),
226 + }).pipe(Effect.mapError(formatResolveCommandProjectError));
227 + const client = yield* clientSingleton.getFor({
228 + orgId: resolvedProject.orgId,
229 + projectId: resolvedProject.projectId,
230 + });
231 + const linkOpt = yield* ui
232 + .withSpinner(
233 + 'Creating link session...',
234 + Effect.tryPromise(() =>
235 + client.link.create({
236 + auth_config_id: authConfigId,
237 user_id: resolvedUserId.value,
238 })
239 )
196 - .pipe(
197 - Effect.asSome,
198 - Effect.catchTag(
199 - 'services/HttpServerError',
200 - handleHttpServerError(ui, {
201 - fallbackMessage: `Failed to create link for auth config "${authConfig.value}".`,
202 - hint: 'Browse available auth configs:\n> composio manage auth-configs list',
203 - fallbackValue: Option.none(),
204 - })
205 - )
206 - );
240 + )
241 + .pipe(
242 + Effect.asSome,
243 + Effect.catchAll(error =>
244 + Effect.gen(function* () {
245 + const message =
246 + extractMessage(error) ?? `Failed to create link for auth config "${authConfigId}".`;
247 + yield* ui.log.error(message);
248 + yield* ui.log.step(
249 + 'Browse available auth configs:\n> composio manage auth-configs list'
250 + );
251 + return Option.none();
252 + })
253 + )
254 + );
255
208 - if (Option.isNone(linkOpt)) {
209 - return;
210 - }
256 + if (Option.isNone(linkOpt)) return;
257
212 - const { connected_account_id: connId, redirect_url: redirectUrl } = linkOpt.value;
258 + const validatedLink = yield* validateLinkResponse(ui, linkOpt.value);
259 + if (Option.isNone(validatedLink)) return;
260
214 - if (noWait) {
215 - yield* ui.note(redirectUrl, 'Redirect URL');
216 - yield* ui.output(
217 - JSON.stringify(
218 - {
219 - status: 'pending',
220 - message: 'Complete authorization by opening the URL',
221 - connected_account_id: connId,
222 - redirect_url: redirectUrl,
223 - },
224 - null,
225 - 2
226 - )
227 - );
228 - } else {
229 - yield* waitForActiveConnection(ui, repo, connId, redirectUrl, noBrowser);
230 - }
261 + const { connectedAccountId: connId, redirectUrl } = validatedLink.value;
262 + if (params.noWait) {
263 + yield* ui.note(redirectUrl, 'Redirect URL');
264 + yield* ui.output(
265 + JSON.stringify(
266 + {
267 + status: 'pending',
268 + message: 'Complete authorization by opening the URL',
269 + connected_account_id: connId,
270 + redirect_url: redirectUrl,
271 + project_type: resolvedProject.projectType,
272 + },
273 + null,
274 + 2
275 + )
276 + );
277 } else {
232 - // Path B: Tool Router flow — toolkit is guaranteed Some (validated above)
233 - const toolkitSlug = Option.getOrThrow(toolkit);
278 + yield* waitForActiveConnection(ui, repo, connId, redirectUrl, params.noBrowser);
279 + }
280 + return;
281 + }
282
235 - const linkOpt = yield* ui
236 - .withSpinner(
237 - `Linking ${toolkitSlug}...`,
238 - Effect.gen(function* () {
239 - const { client, sessionId } = yield* resolveToolRouterSession(resolvedUserId.value, {
240 - manageConnections: true,
241 - });
242 - return yield* Effect.tryPromise(() =>
243 - client.toolRouter.session.link(sessionId, { toolkit: toolkitSlug })
244 - );
245 - })
246 - )
247 - .pipe(
248 - Effect.asSome,
249 - Effect.catchAll(error =>
250 - Effect.gen(function* () {
251 - const message =
252 - extractMessage(error) ?? `Failed to create link for toolkit "${toolkitSlug}".`;
253 - yield* ui.log.error(message);
254 - yield* Effect.logDebug('Link error:', error);
255 - yield* ui.log.step('Browse available toolkits:\n> composio manage toolkits list');
256 - return Option.none();
257 - })
258 - )
283 + const toolkitSlug = Option.getOrThrow(params.toolkit);
284 + const resolvedProject = yield* resolveCommandProject({
285 + mode: 'consumer',
286 + projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
287 + }).pipe(Effect.mapError(formatResolveCommandProjectError));
288 + const resolvedUserId =
289 + resolvedProject.projectType === 'CONSUMER'
290 + ? Option.fromNullable(resolvedProject.consumerUserId)
291 + : Option.match(params.userId, {
292 + onSome: value => Option.some(value),
293 + onNone: () => userContext.data.testUserId,
294 + });
295 + if (Option.isNone(resolvedUserId)) {
296 + return yield* Effect.fail(
297 + new Error(
298 + 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
299 + )
300 + );
301 + }
302 + const client = yield* clientSingleton.getFor({
303 + orgId: resolvedProject.orgId,
304 + projectId: resolvedProject.projectId,
305 + });
306 +
307 + const linkOpt = yield* ui
308 + .withSpinner(
309 + `Linking ${toolkitSlug}...`,
310 + Effect.gen(function* () {
311 + const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
312 + manageConnections: true,
313 + });
314 + return yield* Effect.tryPromise(() =>
315 + client.toolRouter.session.link(sessionId, { toolkit: toolkitSlug })
316 );
317 + })
318 + )
319 + .pipe(
320 + Effect.asSome,
321 + Effect.catchAll(error =>
322 + Effect.gen(function* () {
323 + const message =
324 + extractMessage(error) ?? `Failed to create link for toolkit "${toolkitSlug}".`;
325 + yield* ui.log.error(message);
326 + yield* Effect.logDebug('Link error:', error);
327 + yield* ui.log.step('Browse available toolkits:\n> composio manage toolkits list');
328 + return Option.none();
329 + })
330 + )
331 + );
332
261 - if (Option.isNone(linkOpt)) {
262 - return;
263 - }
333 + if (Option.isNone(linkOpt)) return;
334
265 - const { connected_account_id: connAccountId, redirect_url: redirectUrl } = linkOpt.value;
266 - if (!connAccountId || !redirectUrl) {
267 - yield* ui.log.error(
268 - 'The API returned an incomplete link response (missing connected_account_id or redirect_url).'
269 - );
270 - yield* Effect.logDebug('Link response:', linkOpt.value);
271 - return;
272 - }
335 + const validatedLink = yield* validateLinkResponse(ui, linkOpt.value);
336 + if (Option.isNone(validatedLink)) return;
337
274 - if (noWait) {
275 - yield* ui.note(redirectUrl, 'Redirect URL');
276 - yield* ui.output(
277 - JSON.stringify(
278 - {
279 - status: 'pending',
280 - message: 'Complete authorization by opening the URL',
281 - connected_account_id: connAccountId,
282 - redirect_url: redirectUrl,
283 - toolkit: toolkitSlug,
284 - },
285 - null,
286 - 2
287 - )
288 - );
289 - } else {
290 - yield* waitForActiveConnection(ui, repo, connAccountId, redirectUrl, noBrowser);
291 - }
292 - }
338 + const { connectedAccountId: connAccountId, redirectUrl } = validatedLink.value;
339 +
340 + if (params.noWait) {
341 + yield* ui.note(redirectUrl, 'Redirect URL');
342 + yield* ui.output(
343 + JSON.stringify(
344 + {
345 + status: 'pending',
346 + message: 'Complete authorization by opening the URL',
347 + connected_account_id: connAccountId,
348 + redirect_url: redirectUrl,
349 + toolkit: toolkitSlug,
350 + project_type: resolvedProject.projectType,
351 + },
352 + null,
353 + 2
354 + )
355 + );
356 + } else {
357 + yield* waitForActiveConnection(ui, repo, connAccountId, redirectUrl, params.noBrowser);
358 + }
359 + });
360 +
361 +export const connectedAccountsCmd$Link = Command.make(
362 + 'link',
363 + { toolkit, authConfig, userId, projectName, noBrowser, noWait },
364 + ({ toolkit, authConfig, userId, projectName, noBrowser, noWait }) =>
365 + runConnectedAccountsLink({
366 + toolkit,
367 + authConfig,
368 + userId,
369 + projectName,
370 + noBrowser,
371 + noWait,
372 + rootOnly: false,
373 })
294 -).pipe(Command.withDescription('Link an external account via OAuth redirect.'));
374 +).pipe(
375 + Command.withDescription(
376 + [
377 + 'Link an external account via OAuth redirect.',
378 + '',
379 + 'Related:',
380 + ' composio search "<query>"',
381 + " composio execute <slug> -d '{}'",
382 + ].join('\n')
383 + )
384 +);
385 +
386 +export const rootConnectedAccountsCmd$Link = Command.make(
387 + 'link',
388 + { toolkit, noBrowser, noWait },
389 + ({ toolkit, noBrowser, noWait }) =>
390 + runConnectedAccountsLink({
391 + toolkit,
392 + authConfig: Option.none(),
393 + userId: Option.none(),
394 + projectName: Option.none(),
395 + noBrowser,
396 + noWait,
397 + rootOnly: true,
398 + })
399 +).pipe(
400 + Command.withDescription(
401 + [
402 + 'Link an external account via OAuth redirect.',
403 + '',
404 + 'Related:',
405 + ' composio search "<query>"',
406 + " composio execute <slug> -d '{}'",
407 + ].join('\n')
408 + )
409 +);
ts/packages/cli/src/commands/index.ts
+25 -22
@@ -14,6 +14,10 @@ import { generateCmd } from './generate/generate.cmd';
14 import { manageCmd } from './manage/manage.cmd';
15 import { showToolsExecuteInputHelp } from './tools/commands/tools.execute.cmd';
16 import { printRootHelp } from './root-help';
17 +import { rootToolsCmd$Search } from './tools/commands/tools.search.cmd';
18 +import { rootToolsCmd$Execute } from './tools/commands/tools.execute.cmd';
19 +import { rootConnectedAccountsCmd$Link } from './connected-accounts/commands/connected-accounts.link.cmd';
20 +import { triggersCmd$Listen } from './triggers/commands/triggers.listen.cmd';
21
22 const $cmd = $defaultCmd.pipe(
23 Command.withSubcommands([
@@ -24,6 +28,10 @@ const $cmd = $defaultCmd.pipe(
28 logoutCmd,
29 installCmd,
30 initCmd,
31 + rootToolsCmd$Search,
32 + rootConnectedAccountsCmd$Link,
33 + rootToolsCmd$Execute,
34 + triggersCmd$Listen,
35 generateCmd,
36 manageCmd,
37 ])
@@ -32,13 +40,14 @@ export const rootCommand = $cmd;
40
41 const parseExecuteInputHelpSlug = (argv: ReadonlyArray<string>): string | undefined => {
42 const args = argv.slice(2);
35 - if (args.length < 4) return undefined;
36 - if (args[0] !== 'manage' || args[1] !== 'tools' || args[2] !== 'execute') return undefined;
43 + const isRootExecute = args[0] === 'execute';
44 + const isManageExecute = args[0] === 'manage' && args[1] === 'tools' && args[2] === 'execute';
45 + if (!isRootExecute && !isManageExecute) return undefined;
46
47 const hasHelp = args.includes('--help') || args.includes('-h');
48 if (!hasHelp) return undefined;
49
41 - const tail = args.slice(3);
50 + const tail = isRootExecute ? args.slice(1) : args.slice(3);
51 for (let i = 0; i < tail.length; i += 1) {
52 const token = tail[i];
53 if (!token) continue;
@@ -55,11 +64,21 @@ const parseExecuteInputHelpSlug = (argv: ReadonlyArray<string>): string | undefi
64 }
65
66 // Skip known execute option values.
58 - if (token === '--data' || token === '-d' || token === '--user-id') {
67 + if (
68 + token === '--data' ||
69 + token === '-d' ||
70 + token === '--user-id' ||
71 + token === '--project-name'
72 + ) {
73 i += 1;
74 continue;
75 }
62 - if (token.startsWith('--data=') || token.startsWith('-d=') || token.startsWith('--user-id=')) {
76 + if (
77 + token.startsWith('--data=') ||
78 + token.startsWith('-d=') ||
79 + token.startsWith('--user-id=') ||
80 + token.startsWith('--project-name=')
81 + ) {
82 continue;
83 }
84
@@ -83,22 +102,6 @@ const normalizeVersionShortFlag = (argv: ReadonlyArray<string>): ReadonlyArray<s
102 return argv;
103 };
104
86 -const ALIAS_TO_PARENT: Record<string, ReadonlyArray<string>> = {
87 - search: ['manage', 'tools'],
88 - execute: ['manage', 'tools'],
89 - link: ['manage', 'connected-accounts'],
90 - listen: ['manage', 'triggers'],
91 -};
92 -
93 -const normalizeAliases = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
94 - const args = argv.slice(2);
95 - if (args.length === 0) return argv;
96 - const first = args[0];
97 - const parents = first && ALIAS_TO_PARENT[first];
98 - if (!parents) return argv;
99 - return [...argv.slice(0, 2), ...parents, ...args];
100 -};
101 -
105 const isRootHelp = (argv: ReadonlyArray<string>): boolean => {
106 const args = argv.slice(2);
107 return args.length === 1 && (args[0] === '--help' || args[0] === '-h');
@@ -113,7 +116,7 @@ export const runWithConfig = Effect.gen(function* () {
116 });
117
118 return (argv: ReadonlyArray<string>) => {
116 - const normalizedArgv = normalizeAliases(normalizeVersionShortFlag(argv));
119 + const normalizedArgv = normalizeVersionShortFlag(argv);
120 if (isRootHelp(normalizedArgv)) {
121 return printRootHelp();
122 }
ts/packages/cli/src/commands/init.cmd.ts
+7 -7
@@ -18,7 +18,7 @@ import { browserLogin, noBrowser as noBrowserOpt } from 'src/commands/login.cmd'
18 import { setupCacheDir } from 'src/effects/setup-cache-dir';
19
20 /**
21 - * `composio init` — Initialize a Composio project in the current directory.
21 + * `composio init` — Initialize a developer project in the current directory.
22 *
23 * ## Behavior
24 *
@@ -33,7 +33,7 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
33 const yesOpt = Options.boolean('yes').pipe(
34 Options.withAlias('y'),
35 Options.withDefault(false),
36 - Options.withDescription('Auto-select default org/project, else first project')
36 + Options.withDescription('Auto-select the default org project, else first developer project')
37 );
38
39 // ---------------------------------------------------------------------------
@@ -236,7 +236,7 @@ export const initCmd = CliCommand.make(
236
237 yield* initInteractiveFlow({ composioDir, noBrowser, yes });
238 })
239 -).pipe(CliCommand.withDescription('Initialize a Composio project in the current directory.'));
239 +).pipe(CliCommand.withDescription('Initialize this directory with a developer project.'));
240
241 /**
242 * Interactive init flow — handles login, project selection, wizard, install.
@@ -304,7 +304,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
304 return;
305 }
306
307 - // 3. Select a project
307 + // 3. Select a developer project
308 const orgProjectToKeys = (p: OrgProject): ProjectKeys => ({
309 orgId: p.org_id,
310 projectId: p.id,
@@ -322,12 +322,12 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
322 defaultProjectId: projectIdValue,
323 }) ?? orgProjects.data[0])
324 : yield* ui.select<OrgProject>(
325 - 'Select a project:',
325 + 'Select a developer project:',
326 orgProjects.data.map(p => ({ value: p, label: p.name, hint: p.id }))
327 );
328
329 const selected = orgProjectToKeys(selectedProject);
330 - yield* ui.log.step(`Using project "${selectedProject.name}"`);
330 + yield* ui.log.step(`Using developer project "${selectedProject.name}"`);
331
332 // 4. Write project config
333 yield* writeProjectConfig(composioDir, selected);
@@ -348,7 +348,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
348
349 yield* ui.log.success(`Project initialized in ${composioDir}/`);
350 yield* ui.log.info(
351 - 'To switch your default global org/project later, run `composio manage orgs switch`.'
351 + 'This directory will use the selected developer project for manage/listen flows.'
352 );
353 yield* ui.output(makeOutputJson(selected, composioDir));
354 yield* ui.outro('');
ts/packages/cli/src/commands/login.cmd.ts
+24 -55
@@ -9,7 +9,7 @@ import {
9 } from 'src/services/composio-clients';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { TerminalUI } from 'src/services/terminal-ui';
12 -import { runOrgProjectSelection } from 'src/effects/select-org-project';
12 +import { runOrgSelection } from 'src/effects/select-org-project';
13
14 export const noBrowser = Options.boolean('no-browser').pipe(
15 Options.withDefault(false),
@@ -31,7 +31,7 @@ const keyOpt = Options.text('key').pipe(
31 const yesOpt = Options.boolean('yes').pipe(
32 Options.withAlias('y'),
33 Options.withDefault(false),
34 - Options.withDescription('Skip org/project picker; use session defaults')
34 + Options.withDescription('Skip org picker; use session default org')
35 );
36
37 /**
@@ -47,9 +47,9 @@ const storeCredentials = (params: {
47 initialOrgId: string;
48 initialProjectId: string;
49 fallbackEmail: string;
50 - /** When true, skip the init/switch hints and outro (shown later after org/project picker). */
50 + /** When true, skip the init/switch hints and outro (shown later after org picker). */
51 skipHints?: boolean;
52 - /** When true, skip JSON output (emitted later after org/project picker with final selection). */
52 + /** When true, skip JSON output (emitted later after org picker with final selection). */
53 skipOutput?: boolean;
54 }) =>
55 Effect.gen(function* () {
@@ -92,7 +92,6 @@ const storeCredentials = (params: {
92 // The initial IDs come from the linked session response (which may use session-level
93 // identifiers rather than the actual org/project IDs).
94 const orgId = sessionInfo?.project.org.id ?? initialOrgId;
95 - const projectId = sessionInfo?.project.nano_id ?? initialProjectId;
95 const sessionUserId = sessionInfo?.org_member.user_id ?? sessionInfo?.org_member.id;
96 const testUserId = sessionUserId
97 ? `pg-test-${sessionUserId}`
@@ -102,15 +101,9 @@ const storeCredentials = (params: {
101 if (initialOrgId !== orgId) {
102 yield* Effect.logDebug(`orgId corrected: ${initialOrgId} -> ${orgId} (from session/info)`);
103 }
105 - if (initialProjectId !== projectId) {
106 - yield* Effect.logDebug(
107 - `projectId corrected: ${initialProjectId} -> ${projectId} (from session/info)`
108 - );
109 - }
104 }
105
112 - // Store UAK + org/project IDs in user_data.json
113 - yield* ctx.login(uakApiKey, orgId, projectId, testUserId);
106 + yield* ctx.login(uakApiKey, orgId, testUserId);
107
108 const email = sessionInfo?.org_member.email || fallbackEmail || undefined;
109 yield* ui.log.success(email ? `Logged in as ${email}` : 'Logged in successfully');
@@ -118,9 +111,7 @@ const storeCredentials = (params: {
111 yield* ui.log.info(
112 'Run `composio init` in your project directory to set up project context.'
113 );
121 - yield* ui.log.info(
122 - 'To switch your default global org/project later, run `composio manage orgs switch`.'
123 - );
114 + yield* ui.log.info('To switch your default org later, run `composio manage orgs switch`.');
115 }
116
117 // Emit structured JSON for piped/scripted consumption (agent-native)
@@ -129,9 +120,7 @@ const storeCredentials = (params: {
120 JSON.stringify({
121 email,
122 org_id: orgId,
132 - project_id: projectId,
123 org_name: sessionInfo?.project.org.name ?? '',
134 - project_name: sessionInfo?.project.name ?? '',
124 })
125 );
126 }
@@ -219,14 +208,14 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
208 });
209
210 if (willRunPicker) {
222 - const result = yield* runOrgProjectSelection({
211 + const result = yield* runOrgSelection({
212 apiKey: uakApiKey,
213 baseURL: ctx.data.baseURL,
214 }).pipe(
215 Effect.catchAll(error =>
216 Effect.gen(function* () {
228 - yield* Effect.logDebug('Org/project picker failed:', error);
229 - yield* ui.log.warn('Could not load org/project list. Using session defaults.');
217 + yield* Effect.logDebug('Org picker failed:', error);
218 + yield* ui.log.warn('Could not load org list. Using session default org.');
219 return undefined;
220 })
221 )
@@ -236,33 +225,24 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
225 const testUserId = sessionUserId ? `pg-test-${sessionUserId}` : undefined;
226 yield* ctx.login(
227 uakApiKey,
239 - result.org.id,
240 - result.project.id,
228 + result.id,
229 testUserId ?? Option.getOrUndefined(ctx.data.testUserId)
230 );
243 - yield* ui.log.success(
244 - `Default org/project set to "${result.org.name}" / "${result.project.name}".`
245 - );
231 + yield* ui.log.success(`Default org set to "${result.name}".`);
232 }
247 - const finalOrgId = result?.org.id ?? xOrgId;
248 - const finalProjectId = result?.project.id ?? xProjectId;
249 - const finalOrgName = result?.org.name ?? uakSessionInfo.project.org.name ?? '';
250 - const finalProjectName = result?.project.name ?? uakSessionInfo.project.name ?? '';
233 + const finalOrgId = result?.id ?? xOrgId;
234 + const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';
235 yield* ui.output(
236 JSON.stringify({
237 email: linkedSession.account.email ?? undefined,
238 org_id: finalOrgId,
255 - project_id: finalProjectId,
239 org_name: finalOrgName,
257 - project_name: finalProjectName,
240 })
241 );
242 yield* ui.log.info(
243 'Run `composio init` in your project directory to set up project context.'
244 );
263 - yield* ui.log.info(
264 - 'To switch your default global org/project later, run `composio manage orgs switch`.'
265 - );
245 + yield* ui.log.info('To switch your default org later, run `composio manage orgs switch`.');
246 yield* ui.outro("You're all set!");
247 }
248 });
@@ -387,14 +367,14 @@ export const browserLogin = (params: {
367 });
368
369 if (willRunPicker) {
390 - const result = yield* runOrgProjectSelection({
370 + const result = yield* runOrgSelection({
371 apiKey: uakApiKey,
372 baseURL: ctx.data.baseURL,
373 }).pipe(
374 Effect.catchAll(error =>
375 Effect.gen(function* () {
396 - yield* Effect.logDebug('Org/project picker failed:', error);
397 - yield* ui.log.warn('Could not load org/project list. Using session defaults.');
376 + yield* Effect.logDebug('Org picker failed:', error);
377 + yield* ui.log.warn('Could not load org list. Using session default org.');
378 return undefined;
379 })
380 )
@@ -404,34 +384,24 @@ export const browserLogin = (params: {
384 const testUserId = sessionUserId ? `pg-test-${sessionUserId}` : undefined;
385 yield* ctx.login(
386 uakApiKey,
407 - result.org.id,
408 - result.project.id,
387 + result.id,
388 testUserId ?? Option.getOrUndefined(ctx.data.testUserId)
389 );
411 - yield* ui.log.success(
412 - `Default org/project set to "${result.org.name}" / "${result.project.name}".`
413 - );
390 + yield* ui.log.success(`Default org set to "${result.name}".`);
391 }
415 - // Emit JSON with final org/project (from picker or session) for piped/scripted consumption
416 - const finalOrgId = result?.org.id ?? xOrgId;
417 - const finalProjectId = result?.project.id ?? xProjectId;
418 - const finalOrgName = result?.org.name ?? uakSessionInfo.project.org.name ?? '';
419 - const finalProjectName = result?.project.name ?? uakSessionInfo.project.name ?? '';
392 + const finalOrgId = result?.id ?? xOrgId;
393 + const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';
394 yield* ui.output(
395 JSON.stringify({
396 email: linkedSession.account.email ?? undefined,
397 org_id: finalOrgId,
424 - project_id: finalProjectId,
398 org_name: finalOrgName,
426 - project_name: finalProjectName,
399 })
400 );
401 yield* ui.log.info(
402 'Run `composio init` in your project directory to set up project context.'
403 );
432 - yield* ui.log.info(
433 - 'To switch your default global org/project later, run `composio manage orgs switch`.'
434 - );
404 + yield* ui.log.info('To switch your default org later, run `composio manage orgs switch`.');
405 yield* ui.outro("You're all set!");
406 }
407 });
@@ -444,7 +414,7 @@ export const browserLogin = (params: {
414 * Use --no-wait to print login URL and session info (JSON) then exit without opening browser or waiting.
415 * Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;
416 * with --no-wait, checks once and fails if not linked.
447 - * Use -y to skip org/project picker and use session defaults.
417 + * Use -y to skip org picker and use session default org.
418 *
419 * @example
420 * ```bash
@@ -476,8 +446,7 @@ export const loginCmd = Command.make(
446 }
447
448 if (ctx.isLoggedIn()) {
479 - // Allow re-login when orgId/projectId are not yet set (old CLI login without multi-project support)
480 - if (Option.isSome(ctx.data.orgId) && Option.isSome(ctx.data.projectId)) {
449 + if (Option.isSome(ctx.data.orgId)) {
450 yield* ui.log.warn(`You're already logged in!`);
451 yield* ui.outro(
452 'If you want to log in with a different account, please run `composio logout` first.'
ts/packages/cli/src/commands/manage/manage.cmd.ts
+3 -1
@@ -22,7 +22,9 @@ import { projectsCmd } from '../projects/projects.cmd';
22 * ```
23 */
24 export const manageCmd = Command.make('manage').pipe(
25 - Command.withDescription('Manage Composio resources — toolkits, tools, accounts, triggers, logs, orgs, and projects.'),
25 + Command.withDescription(
26 + 'Developer/admin workflows: orgs, toolkits, tools, accounts, triggers, logs, auth configs, and deprecated project commands.'
27 + ),
28 Command.withSubcommands([
29 toolkitsCmd,
30 toolsCmd,
ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts
+46 -65
@@ -1,7 +1,7 @@
1 import { Command, Options } from '@effect/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 -import { runOrgProjectSelection } from 'src/effects/select-org-project';
4 +import { runOrgSelection } from 'src/effects/select-org-project';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { ComposioUserContext } from 'src/services/user-context';
7
@@ -10,71 +10,52 @@ const orgId = Options.text('org-id').pipe(
10 Options.withDescription('Organization ID to use as global default')
11 );
12
13 -const projectId = Options.text('project-id').pipe(
14 - Options.optional,
15 - Options.withDescription('Project ID to use as global default')
16 -);
17 -
13 const limit = Options.integer('limit').pipe(
14 Options.withDefault(50),
20 - Options.withDescription('Max org/projects to fetch from API (default: 50)')
15 + Options.withDescription('Max orgs to fetch from API (default: 50)')
16 );
17
23 -export const orgsCmd$Switch = Command.make(
24 - 'switch',
25 - { orgId, projectId, limit },
26 - ({ orgId, projectId, limit }) =>
27 - Effect.gen(function* () {
28 - if (!(yield* requireAuth)) return;
29 -
30 - const ui = yield* TerminalUI;
31 - const ctx = yield* ComposioUserContext;
32 - yield* ui.intro('composio manage orgs switch');
33 -
34 - const apiKey = Option.getOrUndefined(ctx.data.apiKey);
35 - if (!apiKey) {
36 - yield* ui.log.warn('No user API key found. Run `composio login` first.');
37 - yield* ui.outro('');
38 - return;
39 - }
40 -
41 - yield* ui.note(
42 - 'This updates your default global org/project context for CLI commands. Use `composio init` for per-project local overrides.',
43 - 'Global defaults'
44 - );
45 -
46 - const result = yield* runOrgProjectSelection({
47 - apiKey,
48 - baseURL: ctx.data.baseURL,
49 - explicitOrgId: Option.getOrUndefined(orgId),
50 - explicitProjectId: Option.getOrUndefined(projectId),
51 - limit,
52 - });
53 -
54 - if (!result) {
55 - yield* ui.outro('No org selected.');
56 - return;
57 - }
58 -
59 - const { org: selectedOrganization, project: selectedProject } = result;
60 -
61 - yield* ctx.login(
62 - apiKey,
63 - selectedOrganization.id,
64 - selectedProject.id,
65 - Option.getOrUndefined(ctx.data.testUserId)
66 - );
67 -
68 - yield* ui.log.success(
69 - `Updated global defaults to "${selectedOrganization.name}" / "${selectedProject.name}".`
70 - );
71 - yield* ui.output(
72 - JSON.stringify({
73 - scope: 'global',
74 - org_id: selectedOrganization.id,
75 - project_id: selectedProject.id,
76 - })
77 - );
78 - yield* ui.outro('Global org/project defaults updated.');
79 - })
80 -).pipe(Command.withDescription('Switch default global organization/project context.'));
18 +export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId, limit }) =>
19 + Effect.gen(function* () {
20 + if (!(yield* requireAuth)) return;
21 +
22 + const ui = yield* TerminalUI;
23 + const ctx = yield* ComposioUserContext;
24 + yield* ui.intro('composio manage orgs switch');
25 +
26 + const apiKey = Option.getOrUndefined(ctx.data.apiKey);
27 + if (!apiKey) {
28 + yield* ui.log.warn('No user API key found. Run `composio login` first.');
29 + yield* ui.outro('');
30 + return;
31 + }
32 +
33 + yield* ui.note(
34 + 'This updates your default org for CLI commands. Use `composio init` for local developer project setup.',
35 + 'Global defaults'
36 + );
37 +
38 + const result = yield* runOrgSelection({
39 + apiKey,
40 + baseURL: ctx.data.baseURL,
41 + explicitOrgId: Option.getOrUndefined(orgId),
42 + limit,
43 + });
44 +
45 + if (!result) {
46 + yield* ui.outro('No org selected.');
47 + return;
48 + }
49 +
50 + yield* ctx.login(apiKey, result.id, Option.getOrUndefined(ctx.data.testUserId));
51 +
52 + yield* ui.log.success(`Updated default org to "${result.name}".`);
53 + yield* ui.output(
54 + JSON.stringify({
55 + scope: 'global',
56 + org_id: result.id,
57 + })
58 + );
59 + yield* ui.outro('Default org updated.');
60 + })
61 +).pipe(Command.withDescription('Switch default organization context.'));
ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts
+8 -11
@@ -37,9 +37,6 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,
37 }
38
39 const clampedLimit = clampLimit(limit);
40 - const defaultOrgId = Option.getOrUndefined(ctx.data.orgId);
41 - const defaultProjectId = Option.getOrUndefined(ctx.data.projectId);
42 -
40 const projects = yield* ui.withSpinner(
41 'Loading projects...',
42 listOrganizationProjects({
@@ -56,19 +53,20 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,
53
54 if (projects.data.length === 0) {
55 yield* ui.log.warn('No projects found.');
59 - yield* ui.outro('Hint: run `composio manage orgs switch` to switch org/project defaults.');
56 + yield* ui.outro(
57 + 'Hint: run `composio init` in a directory to bind it to a developer project.'
58 + );
59 return;
60 }
61
62 const lines = projects.data.map(project => {
64 - const isSelected = defaultOrgId === resolvedOrgId && defaultProjectId === project.id;
65 - return `${isSelected ? '✓' : ' '} ${project.name} (${project.id})`;
63 + return ` ${project.name} (${project.id})`;
64 });
65 yield* ui.log.step(lines.join('\n'));
66 yield* ui.outro(
67 [
70 - 'Hint: run `composio manage projects switch` to switch the default global project.',
71 - 'Run `composio manage orgs switch` to switch org and project together.',
68 + 'Hint: run `composio init` in a directory to bind it to a developer project.',
69 + 'Run `composio manage orgs switch` to change your default org.',
70 ].join('\n')
71 );
72
@@ -77,10 +75,9 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,
75 projects.data.map(project => ({
76 id: project.id,
77 name: project.name,
80 - is_selected_global_project:
81 - defaultOrgId === resolvedOrgId && defaultProjectId === project.id,
78 + is_selected_global_project: false,
79 }))
80 )
81 );
82 })
86 -).pipe(Command.withDescription('List projects and show current global selection.'));
83 +).pipe(Command.withDescription('List developer projects for the current organization.'));
ts/packages/cli/src/commands/projects/commands/projects.switch.cmd.ts
+9 -126
@@ -1,132 +1,15 @@
1 -import { Command, Options } from '@effect/cli';
2 -import { Effect, Option } from 'effect';
3 -import { requireAuth } from 'src/effects/require-auth';
1 +import { Command } from '@effect/cli';
2 +import { Effect } from 'effect';
3 import { TerminalUI } from 'src/services/terminal-ui';
5 -import {
6 - listOrganizationProjects,
7 - type OrganizationProjectSummary,
8 -} from 'src/services/composio-clients';
9 -import { ComposioUserContext } from 'src/services/user-context';
10 -import { clampLimit } from 'src/ui/clamp-limit';
4
12 -const orgId = Options.text('org-id').pipe(
13 - Options.optional,
14 - Options.withDescription('Organization ID to use while switching project')
15 -);
16 -
17 -const projectId = Options.text('project-id').pipe(
18 - Options.optional,
19 - Options.withDescription('Project ID to use as global default')
20 -);
21 -
22 -const limit = Options.integer('limit').pipe(
23 - Options.withDefault(50),
24 - Options.withDescription('Max projects to fetch from API (default: 50)')
25 -);
26 -
27 -const selectProject = (params: {
28 - projects: ReadonlyArray<OrganizationProjectSummary>;
29 - selectedProjectId?: string;
30 -}) =>
31 - Effect.gen(function* () {
32 - const { projects, selectedProjectId } = params;
33 - const ui = yield* TerminalUI;
34 - if (projects.length === 0) return undefined;
35 -
36 - if (selectedProjectId) {
37 - const explicitMatch = projects.find(project => project.id === selectedProjectId);
38 - if (explicitMatch) return explicitMatch;
39 - }
40 -
41 - if (projects.length === 1) return projects[0];
42 -
43 - return yield* ui.select('Select a default project (global scope):', [
44 - ...projects.map(project => ({
45 - value: project,
46 - label: project.name,
47 - hint: project.id,
48 - })),
49 - ]);
50 - });
51 -
52 -export const projectsCmd$Switch = Command.make(
53 - 'switch',
54 - { orgId, projectId, limit },
55 - ({ orgId, projectId, limit }) =>
5 +export const projectsCmd$Switch = Command.make('switch', {}).pipe(
6 + Command.withDescription('Deprecated. Global developer project switching is no longer supported.'),
7 + Command.withHandler(() =>
8 Effect.gen(function* () {
57 - if (!(yield* requireAuth)) return;
58 -
9 const ui = yield* TerminalUI;
60 - const ctx = yield* ComposioUserContext;
61 - yield* ui.intro('composio manage projects switch');
62 -
63 - const apiKey = Option.getOrUndefined(ctx.data.apiKey);
64 - if (!apiKey) {
65 - yield* ui.log.warn('No user API key found. Run `composio login` first.');
66 - yield* ui.outro('');
67 - return;
68 - }
69 -
70 - const resolvedOrgId = Option.getOrUndefined(orgId) ?? Option.getOrUndefined(ctx.data.orgId);
71 - if (!resolvedOrgId) {
72 - yield* ui.log.warn('No default org is configured.');
73 - yield* ui.log.info('Run `composio manage orgs switch` to select org and project globally.');
74 - yield* ui.outro('');
75 - return;
76 - }
77 -
78 - const clampedLimit = clampLimit(limit);
79 - const explicitProjectId = Option.getOrUndefined(projectId);
80 -
81 - yield* ui.note(
82 - 'This updates your default global project context. To switch organization, use `composio manage orgs switch`.',
83 - 'Global defaults'
84 - );
85 - yield* ui.log.info(`Using organization: ${resolvedOrgId}`);
86 -
87 - const projects = yield* listOrganizationProjects({
88 - baseURL: ctx.data.baseURL,
89 - apiKey,
90 - orgId: resolvedOrgId,
91 - limit: clampedLimit,
92 - });
93 - yield* ui.log.info(`Loaded ${projects.data.length} projects`);
94 -
95 - if (projects.data.length === 0) {
96 - yield* ui.log.warn('No projects found for the selected org.');
97 - yield* ui.log.info('Use `composio manage orgs switch` to switch to another organization.');
98 - yield* ui.outro('No projects available.');
99 - return;
100 - }
101 -
102 - const selectedProject = yield* selectProject({
103 - projects: projects.data,
104 - selectedProjectId: explicitProjectId,
105 - });
106 -
107 - if (!selectedProject) {
108 - yield* ui.log.warn('No project selected.');
109 - yield* ui.outro('No project selected.');
110 - return;
111 - }
112 - yield* ui.log.info(`Selected project: "${selectedProject.name}" (${selectedProject.id})`);
113 -
114 - yield* ctx.login(
115 - apiKey,
116 - resolvedOrgId,
117 - selectedProject.id,
118 - Option.getOrUndefined(ctx.data.testUserId)
10 + yield* ui.log.error(
11 + 'Global developer project switching is no longer supported. Run `composio init` in a directory to bind it to a developer project.'
12 );
120 -
121 - yield* ui.log.success(`Updated global default project to "${selectedProject.name}".`);
122 - yield* ui.log.info('To switch organization as well, run `composio manage orgs switch`.');
123 - yield* ui.output(
124 - JSON.stringify({
125 - scope: 'global',
126 - org_id: resolvedOrgId,
127 - project_id: selectedProject.id,
128 - })
129 - );
130 - yield* ui.outro('Global project default updated.');
13 })
132 -).pipe(Command.withDescription('Switch default global project context.'));
14 + )
15 +);
ts/packages/cli/src/commands/root-help.ts
+8 -12
@@ -38,7 +38,7 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [
38 name: '--key',
39 description: 'Complete login using session key from --no-wait',
40 },
41 - { name: '-y, --yes', description: 'Skip org/project picker; use session defaults' },
41 + { name: '-y, --yes', description: 'Skip org picker; use session default org' },
42 ],
43 },
44 {
@@ -48,42 +48,38 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [
48 },
49 {
50 name: 'init',
51 - description: 'Initialize a Composio project in the current directory.',
51 + description: 'Initialize this directory with a developer project.',
52 usage: 'init [--no-browser] [-y, --yes]',
53 options: [
54 { name: '--no-browser', description: 'Skip opening browser for auth' },
55 - { name: '-y, --yes', description: 'Auto-select default org/project' },
55 + { name: '-y, --yes', description: 'Auto-select the default developer project' },
56 ],
57 },
58 {
59 name: 'search',
60 description: 'Search tools by use case across toolkits/apps.',
61 - usage: 'search <query> [--toolkits text] [--user-id text] [--limit integer]',
61 + usage: 'search <query> [--toolkits text] [--limit integer]',
62 options: [
63 { name: '<query>', description: 'Semantic use-case query (e.g. "send emails")' },
64 { name: '--toolkits', description: 'Filter by toolkit slugs, comma-separated' },
65 - { name: '--user-id', description: 'User ID (falls back to project/global test_user_id)' },
65 { name: '--limit', description: 'Number of results per page (1-1000)' },
66 ],
67 },
68 {
69 name: 'execute',
70 description: 'Execute a tool.',
72 - usage: 'execute <slug> [-d, --data text] [--user-id text]',
71 + usage: 'execute <slug> [-d, --data text]',
72 options: [
73 { name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },
74 { name: '-d, --data', description: 'JSON arguments, @file, or - for stdin' },
76 - { name: '--user-id', description: 'User ID (falls back to project test_user_id)' },
75 ],
76 },
77 {
78 name: 'link',
79 description: 'Connect a user account for a toolkit/app.',
82 - usage: 'link [<toolkit>] [--auth-config text] [--user-id text] [--no-browser]',
80 + usage: 'link [<toolkit>] [--no-browser]',
81 options: [
82 { name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' },
85 - { name: '--auth-config', description: 'Auth config ID (legacy flow)' },
86 - { name: '--user-id', description: 'User ID for the connection' },
83 { name: '--no-browser', description: 'Skip auto-opening the browser' },
84 ],
85 },
@@ -117,7 +113,7 @@ const ADVANCED_COMMANDS: ReadonlyArray<{ name: string; description: string }> =
113 {
114 name: 'manage',
115 description:
120 - 'Manage Composio resources — toolkits, tools, accounts, triggers, logs, orgs, and projects.',
116 + 'Developer/admin workflows: orgs, toolkits, triggers, auth configs, logs, and deprecated project commands.',
117 },
118 ];
119
@@ -150,7 +146,7 @@ export function printRootHelp(): Effect.Effect<void> {
146
147 const lines: string[] = [
148 '',
153 - 'Connect AI agents to external tools. Link accounts, discover tools, and execute them.',
149 + 'Connect AI agents to external tools. `search`, `link`, and `execute` use your org consumer project by default. `init`, `listen`, and `manage` use developer project context.',
150 '',
151 bold('USAGE'),
152 ` ${name} <command> [options]`,
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts
+4 -2
@@ -1,6 +1,6 @@
1 import { Args, Command, Options } from '@effect/cli';
2 import { Effect, Option } from 'effect';
3 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
3 +import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
@@ -46,6 +46,7 @@ export const toolkitsCmd$Info = Command.make(
46 const ui = yield* TerminalUI;
47 const projectContext = yield* ProjectContext;
48 const userContext = yield* ComposioUserContext;
49 + const clientSingleton = yield* ComposioClientSingleton;
50
51 // Missing slug guard
52 if (Option.isNone(slug)) {
@@ -85,7 +86,8 @@ export const toolkitsCmd$Info = Command.make(
86 .pipe(Effect.option);
87
88 if (Option.isSome(resolvedUserId)) {
88 - const { client, sessionId } = yield* resolveToolRouterSession(resolvedUserId.value);
89 + const client = yield* clientSingleton.get();
90 + const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);
91 const sessionToolkits = yield* Effect.tryPromise(() =>
92 client.toolRouter.session.toolkits(sessionId, { toolkits: [slugValue] })
93 );
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+6 -2
@@ -4,7 +4,7 @@ import { Effect, Option } from 'effect';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
7 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 +import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
8 import { ProjectContext } from 'src/services/project-context';
9 import { ComposioUserContext } from 'src/services/user-context';
10 import { clampLimit } from 'src/ui/clamp-limit';
@@ -57,6 +57,7 @@ export const toolkitsCmd$List = Command.make(
57
58 const ui = yield* TerminalUI;
59 const repo = yield* ComposioToolkitsRepository;
60 + const clientSingleton = yield* ComposioClientSingleton;
61 const projectContext = yield* ProjectContext;
62 const userContext = yield* ComposioUserContext;
63
@@ -95,7 +96,10 @@ export const toolkitsCmd$List = Command.make(
96
97 // Resolve session context in parallel with catalog fetch (saves one round trip).
98 const sessionContextEffect = Option.isSome(resolvedUserId)
98 - ? resolveToolRouterSession(resolvedUserId.value).pipe(
99 + ? Effect.gen(function* () {
100 + const client = yield* clientSingleton.get();
101 + return yield* resolveToolRouterSession(client, resolvedUserId.value);
102 + }).pipe(
103 Effect.catchAll(error =>
104 Effect.logDebug('Failed to create session:', error).pipe(Effect.as(undefined))
105 )
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+146 -128
@@ -12,7 +12,6 @@ import {
12 ToolsExecutor,
13 } from 'src/services/tools-executor';
14 import type { ToolExecuteParams } from 'src/services/tools-executor';
15 -import { ProjectContext } from 'src/services/project-context';
15 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
16 import { ComposioUserContext } from 'src/services/user-context';
17 import {
@@ -23,6 +22,11 @@ import {
22 import { bold } from 'src/ui/colors';
23 import { handleHttpServerError } from 'src/effects/handle-http-error';
24 import { formatToolInputParameters } from '../format';
25 +import { ComposioClientSingleton } from 'src/services/composio-clients';
26 +import {
27 + resolveCommandProject,
28 + formatResolveCommandProjectError,
29 +} from 'src/services/command-project';
30
31 const slug = Args.text({ name: 'slug' }).pipe(
32 Args.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')
@@ -36,7 +40,12 @@ const data = Options.text('data').pipe(
40
41 const userId = Options.text('user-id').pipe(
42 Options.optional,
39 - Options.withDescription('User ID to execute the tool for (falls back to project test_user_id)')
43 + Options.withDescription('Developer-project user ID override')
44 +);
45 +
46 +const projectName = Options.text('project-name').pipe(
47 + Options.optional,
48 + Options.withDescription('Developer project name override for this command')
49 );
50
51 const resolveInput = (input: Option.Option<string>) =>
@@ -83,38 +92,33 @@ const parseArguments = (raw: string) =>
92 return parsed as Record<string, unknown>;
93 });
94
86 -/**
87 - * Derive the toolkit slug from a tool slug.
88 - * e.g. "GMAIL_CREATE_EMAIL_DRAFT" → "gmail", "GITHUB_GET_REPOS" → "github"
89 - *
90 - * Returns `undefined` for meta tool slugs (COMPOSIO_*) since they don't map
91 - * to a real toolkit and would produce misleading connection tips.
92 - */
95 const toolkitFromToolSlug = (toolSlug: string): string | undefined => {
96 const idx = toolSlug.indexOf('_');
97 if (idx <= 0) return toolSlug.toLowerCase();
98 const prefix = toolSlug.slice(0, idx).toLowerCase();
97 - // Meta tools (COMPOSIO_*) are internal and don't correspond to a real toolkit.
99 if (prefix === 'composio') return undefined;
100 return prefix;
101 };
102
102 -const connectionTips = (toolSlug: string, userId: string) => {
103 +const connectionTips = (toolSlug: string, surface: 'root' | 'manage') => {
104 const toolkit = toolkitFromToolSlug(toolSlug);
105 if (!toolkit) {
105 - return `Retry: ${bold(`composio manage tools execute ${toolSlug} ...`)}`;
106 + return `Retry: ${bold(`composio execute ${toolSlug} ...`)}`;
107 }
108 return [
108 - `Link the toolkit first: ${bold(`composio manage connected-accounts link ${toolkit} --user-id ${userId}`)}`,
109 - `Then retry: ${bold(`composio manage tools execute ${toolSlug} ...`)}`,
109 + `Link the toolkit first: ${bold(
110 + surface === 'root'
111 + ? `composio link ${toolkit}`
112 + : `composio manage connected-accounts link ${toolkit} --user-id "<user-id>"`
113 + )}`,
114 + `Then retry: ${bold(
115 + surface === 'root'
116 + ? `composio execute ${toolSlug} ...`
117 + : `composio manage tools execute ${toolSlug} ...`
118 + )}`,
119 ].join('\n');
120 };
121
113 -/**
114 - * JSON.stringify replacer that redacts ID-like string values in CI.
115 - * Fields named "id", ending with "Id", or ending with "_id" are redacted.
116 - * The "logId" field preserves its "log_" prefix.
117 - */
122 const ciRedactReplacer = (_key: string, value: unknown): unknown => {
123 if (typeof value !== 'string') return value;
124 if (_key === 'logId') return redact({ value, prefix: 'log_' });
@@ -172,10 +176,6 @@ const normalizeError = (error: unknown): unknown => {
176 return current;
177 };
178
175 -/**
176 - * Show execute-focused help for a specific tool slug.
177 - * This prints only input parameters (data payload schema).
178 - */
179 export const showToolsExecuteInputHelp = (toolSlug: string) =>
180 Effect.gen(function* () {
181 if (!(yield* requireAuth)) return;
@@ -198,7 +198,7 @@ export const showToolsExecuteInputHelp = (toolSlug: string) =>
198 Effect.map(r =>
199 r.items.map(s => ({
200 label: `${s.slug} — ${s.description}`,
201 - command: `> composio manage tools execute "${s.slug}" --help`,
201 + command: `> composio execute "${s.slug}" --help`,
202 }))
203 )
204 ),
@@ -210,28 +210,19 @@ export const showToolsExecuteInputHelp = (toolSlug: string) =>
210 const tool = toolOpt.value;
211
212 yield* ui.note(formatToolInputParameters(tool), `Execute Help: ${tool.slug}`);
213 - yield* ui.log.step(
214 - `Run:\n> composio manage tools execute "${tool.slug}" --user-id "<user-id>" -d '{"key":"value"}'`
215 - );
213 + yield* ui.log.step(`Run:\n> composio execute "${tool.slug}" -d '{"key":"value"}'`);
214 yield* ui.output(
215 JSON.stringify({ slug: tool.slug, input_parameters: tool.input_parameters }, null, 2)
216 );
217 });
218
221 -/**
222 - * Display a user-friendly error message for tool execution failures.
223 - *
224 - * Returns a structured error summary suitable for `ui.output()` in piped mode.
225 - */
219 const handleExecutionError = (
220 ui: TerminalUI,
221 error: unknown,
229 - context: { toolSlug: string; userId: string }
222 + context: { toolSlug: string; surface: 'root' | 'manage' }
223 ) =>
224 Effect.gen(function* () {
225 const normalized = normalizeError(error);
233 -
234 - // ActionExecuteConnectedAccountNotFoundError stores the API payload in `.details`
226 const connAccountDetails =
227 normalized instanceof ActionExecuteConnectedAccountNotFoundError
228 ? normalized.details
@@ -244,10 +235,8 @@ const handleExecutionError = (
235 const slugValue = apiDetails?.slug ?? extractSlug(error) ?? extractSlug(connAccountDetails);
236 const message = extractMessage(apiDetails) ?? extractMessage(normalized) ?? 'Unknown error';
237
247 - // Display the primary error message
238 yield* ui.log.error(message);
239
250 - // Show API error details when available
240 const detailsObject =
241 apiDetails ??
242 (normalized instanceof ActionExecuteConnectedAccountNotFoundError &&
@@ -259,14 +248,10 @@ const handleExecutionError = (
248 yield* ui.note(formatUnknownObject(redactRequestId(detailsObject)), 'Error details');
249 }
250
262 - // No-connection tips — the executor already classifies these into
263 - // ActionExecuteConnectedAccountNotFoundError, so check the typed error
264 - // instead of re-inspecting the slug.
251 if (normalized instanceof ActionExecuteConnectedAccountNotFoundError) {
266 - yield* ui.note(connectionTips(context.toolSlug, context.userId), 'Tips');
252 + yield* ui.note(connectionTips(context.toolSlug, context.surface), 'Tips');
253 }
254
269 - // Return structured summary for piped output
255 return { error: message, slug: slugValue };
256 });
257
@@ -275,94 +260,127 @@ class ToolExecutionError {
260 constructor(readonly message: string) {}
261 }
262
278 -/**
279 - * Execute a tool with JSON arguments.
280 - *
281 - * @example
282 - * ```bash
283 - * composio manage tools execute GITHUB_GET_REPOS -d '{"owner":"composio"}'
284 - * echo '{"owner":"composio"}' | composio manage tools execute GITHUB_GET_REPOS
285 - * ```
286 - */
287 -export const toolsCmd$Execute = Command.make(
288 - 'execute',
289 - { slug, data, userId },
290 - ({ slug, data, userId }) =>
291 - Effect.gen(function* () {
292 - if (!(yield* requireAuth)) return;
293 -
294 - const ui = yield* TerminalUI;
295 - const executor = yield* ToolsExecutor;
296 - const projectContext = yield* ProjectContext;
297 - const userContext = yield* ComposioUserContext;
298 - const resolvedProjectContext = yield* projectContext.resolve;
299 - const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
300 - const globalTestUserId = userContext.data.testUserId;
301 - const resolvedUserId = Option.match(userId, {
302 - onSome: value => Option.some(value),
303 - onNone: () => Option.orElse(testUserId, () => globalTestUserId),
304 - });
305 - if (Option.isNone(resolvedUserId)) {
306 - return yield* Effect.fail(
307 - new Error('Missing user id. Provide --user-id or run composio init to set test_user_id.')
308 - );
309 - }
310 - if (Option.isNone(userId) && Option.isSome(testUserId)) {
311 - yield* ui.log.warn(`Using test user id "${testUserId.value}"`);
312 - } else if (Option.isNone(userId) && Option.isSome(globalTestUserId)) {
313 - yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
314 - }
263 +const runToolsExecute = (params: {
264 + slug: string;
265 + data: Option.Option<string>;
266 + userId: Option.Option<string>;
267 + projectName: Option.Option<string>;
268 + rootOnly: boolean;
269 +}) =>
270 + Effect.gen(function* () {
271 + if (!(yield* requireAuth)) return;
272 +
273 + const ui = yield* TerminalUI;
274 + const executor = yield* ToolsExecutor;
275 + const clientSingleton = yield* ComposioClientSingleton;
276 + const userContext = yield* ComposioUserContext;
277 +
278 + const input = yield* resolveInput(params.data);
279 + const args = yield* parseArguments(input);
280 + const resolvedProject = yield* resolveCommandProject({
281 + mode: 'consumer',
282 + projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
283 + }).pipe(Effect.mapError(formatResolveCommandProjectError));
284 + const resolvedUserId =
285 + resolvedProject.projectType === 'CONSUMER'
286 + ? Option.fromNullable(resolvedProject.consumerUserId)
287 + : Option.match(params.userId, {
288 + onSome: value => Option.some(value),
289 + onNone: () => userContext.data.testUserId,
290 + });
291 + if (Option.isNone(resolvedUserId)) {
292 + return yield* Effect.fail(
293 + new Error(
294 + 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
295 + )
296 + );
297 + }
298 + const client = yield* clientSingleton.getFor({
299 + orgId: resolvedProject.orgId,
300 + projectId: resolvedProject.projectId,
301 + });
302 +
303 + const executeParams: ToolExecuteParams = {
304 + userId: resolvedUserId.value,
305 + arguments: args,
306 + client,
307 + };
308 +
309 + yield* ui.useMakeSpinner(`Executing tool "${params.slug}"...`, spinner =>
310 + Effect.gen(function* () {
311 + const resultEither = yield* executor
312 + .execute(params.slug, executeParams)
313 + .pipe(Effect.either);
314 +
315 + if (Either.isLeft(resultEither)) {
316 + yield* spinner.error();
317 + const summary = yield* handleExecutionError(ui, resultEither.left, {
318 + toolSlug: params.slug,
319 + surface: params.rootOnly ? 'root' : 'manage',
320 + });
321 + yield* ui.output(JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2));
322 + return yield* Effect.fail(new ToolExecutionError(summary.error));
323 + }
324 +
325 + const result = resultEither.right;
326
316 - const input = yield* resolveInput(data);
317 - const args = yield* parseArguments(input);
318 -
319 - const params: ToolExecuteParams = {
320 - userId: resolvedUserId.value,
321 - arguments: args,
322 - };
323 -
324 - yield* ui.useMakeSpinner(`Executing tool "${slug}"...`, spinner =>
325 - Effect.gen(function* () {
326 - const resultEither = yield* executor.execute(slug, params).pipe(Effect.either);
327 -
328 - // Hard failure: API threw an exception
329 - if (Either.isLeft(resultEither)) {
330 - yield* spinner.error();
331 - const summary = yield* handleExecutionError(ui, resultEither.left, {
332 - toolSlug: slug,
333 - userId: resolvedUserId.value,
334 - });
335 - yield* ui.output(
336 - JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
337 - );
338 - return yield* Effect.fail(new ToolExecutionError(summary.error));
339 - }
340 -
341 - const result = resultEither.right;
342 -
343 - // Soft failure: execution returned an error
344 - if (!result.successful) {
345 - const logId = result.logId
346 - ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
347 - : '';
348 - yield* spinner.error(`Execution failed${logId}`);
349 -
350 - const summary = yield* handleExecutionError(ui, result.error ?? result, {
351 - toolSlug: slug,
352 - userId: resolvedUserId.value,
353 - });
354 - yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));
355 - return yield* Effect.fail(new ToolExecutionError(summary.error));
356 - }
357 -
358 - // Success
327 + if (!result.successful) {
328 const logId = result.logId
329 ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
330 : '';
362 - yield* spinner.stop(`Execution successful${logId}`);
363 - yield* ui.log.message(`Response\n${JSON.stringify(result, ciRedactReplacer, 2)}`);
331 + yield* spinner.error(`Execution failed${logId}`);
332 +
333 + const summary = yield* handleExecutionError(ui, result.error ?? result, {
334 + toolSlug: params.slug,
335 + surface: params.rootOnly ? 'root' : 'manage',
336 + });
337 yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));
365 - })
366 - );
367 - })
368 -).pipe(Command.withDescription('Execute a tool by slug with JSON arguments.'));
338 + return yield* Effect.fail(new ToolExecutionError(summary.error));
339 + }
340 +
341 + const logId = result.logId
342 + ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
343 + : '';
344 + yield* spinner.stop(`Execution successful${logId}`);
345 + yield* ui.log.message(`Response\n${JSON.stringify(result, ciRedactReplacer, 2)}`);
346 + yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));
347 + })
348 + );
349 + });
350 +
351 +export const toolsCmd$Execute = Command.make(
352 + 'execute',
353 + { slug, data, userId, projectName },
354 + ({ slug, data, userId, projectName }) =>
355 + runToolsExecute({ slug, data, userId, projectName, rootOnly: false })
356 +).pipe(
357 + Command.withDescription(
358 + [
359 + 'Execute a tool by slug with JSON arguments.',
360 + '',
361 + 'Related:',
362 + ' composio search "<query>"',
363 + ' composio link <toolkit>',
364 + ].join('\n')
365 + )
366 +);
367 +
368 +export const rootToolsCmd$Execute = Command.make('execute', { slug, data }, ({ slug, data }) =>
369 + runToolsExecute({
370 + slug,
371 + data,
372 + userId: Option.none(),
373 + projectName: Option.none(),
374 + rootOnly: true,
375 + })
376 +).pipe(
377 + Command.withDescription(
378 + [
379 + 'Execute a tool by slug with JSON arguments.',
380 + '',
381 + 'Related:',
382 + ' composio search "<query>"',
383 + ' composio link <toolkit>',
384 + ].join('\n')
385 + )
386 +);
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+205 -168
@@ -7,8 +7,12 @@ import { resolveToolRouterSession } from 'src/effects/create-tool-router-session
7 import { buildMinimalPayloadFromSchema } from 'src/ui/build-minimal-payload';
8 import { formatToolsTable } from '../format';
9 import type { Tool } from 'src/models/tools';
10 -import { ProjectContext } from 'src/services/project-context';
10 import { ComposioUserContext } from 'src/services/user-context';
11 +import { ComposioClientSingleton } from 'src/services/composio-clients';
12 +import {
13 + resolveCommandProject,
14 + formatResolveCommandProjectError,
15 +} from 'src/services/command-project';
16
17 const query = Args.text({ name: 'query' }).pipe(
18 Args.withDescription(
@@ -23,7 +27,12 @@ const toolkits = Options.text('toolkits').pipe(
27
28 const userId = Options.text('user-id').pipe(
29 Options.optional,
26 - Options.withDescription('User ID for the session (falls back to project/global test_user_id)')
30 + Options.withDescription('Developer-project user ID override')
31 +);
32 +
33 +const projectName = Options.text('project-name').pipe(
34 + Options.optional,
35 + Options.withDescription('Developer project name override for this command')
36 );
37
38 const limit = Options.integer('limit').pipe(
@@ -31,181 +40,209 @@ const limit = Options.integer('limit').pipe(
40 Options.withDescription('Number of results per page (1-1000)')
41 );
42
34 -/**
35 - * Search tools semantically by use case.
36 - *
37 - * The query is interpreted semantically (not exact keyword matching), so you can
38 - * describe an outcome or workflow. The command returns the most relevant tools
39 - * for that use case and includes recommended guidance/plan steps to help execute it.
40 - *
41 - * @example
42 - * ```bash
43 - * composio manage tools search "send emails"
44 - * composio manage tools search "send emails" --toolkits "gmail,outlook"
45 - * composio manage tools search "messaging" --limit 5
46 - * ```
47 - */
48 -export const toolsCmd$Search = Command.make(
49 - 'search',
50 - { query, toolkits, userId, limit },
51 - ({ query, toolkits, userId, limit }) =>
52 - Effect.gen(function* () {
53 - if (!(yield* requireAuth)) return;
54 -
55 - const ui = yield* TerminalUI;
56 - const projectContext = yield* ProjectContext;
57 - const userContext = yield* ComposioUserContext;
58 - const resolvedProjectContext = yield* projectContext.resolve.pipe(
59 - Effect.catchAll(() => Effect.succeed(Option.none()))
60 - );
61 - const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
62 - const globalTestUserId = userContext.data.testUserId;
63 - const resolvedUserId = Option.match(userId, {
64 - onSome: value => Option.some(value),
65 - onNone: () => Option.orElse(testUserId, () => globalTestUserId),
66 - });
67 -
68 - if (Option.isNone(resolvedUserId)) {
69 - return yield* Effect.fail(
70 - new Error(
71 - 'Missing user id. Provide --user-id or run composio init to set test_user_id, or composio login to set global test_user_id.'
72 - )
73 - );
74 - }
75 -
76 - if (Option.isNone(userId) && Option.isSome(testUserId)) {
77 - yield* ui.log.warn(`Using test user id "${testUserId.value}"`);
78 - } else if (Option.isNone(userId) && Option.isSome(globalTestUserId)) {
79 - yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
80 - }
81 -
82 - const clampedLimit = clampLimit(limit);
83 - const toolkitFilter = Option.getOrUndefined(toolkits);
84 - const toolkitList =
85 - toolkitFilter && toolkitFilter.trim().length > 0
86 - ? toolkitFilter
87 - .split(',')
88 - .map(s => s.trim().toLowerCase())
89 - .filter(Boolean)
90 - : undefined;
91 -
92 - const searchResponse = yield* ui.withSpinner(
93 - `Searching tools for "${query}"...`,
94 - Effect.gen(function* () {
95 - const { client, sessionId } = yield* resolveToolRouterSession(resolvedUserId.value, {
96 - toolkits: toolkitList,
97 - });
98 - return yield* Effect.tryPromise(() =>
99 - client.toolRouter.session.search(sessionId, {
100 - queries: [{ use_case: query }],
101 - })
43 +const runToolsSearch = (params: {
44 + query: string;
45 + toolkits: Option.Option<string>;
46 + userId: Option.Option<string>;
47 + projectName: Option.Option<string>;
48 + limit: number;
49 + rootOnly: boolean;
50 +}) =>
51 + Effect.gen(function* () {
52 + if (!(yield* requireAuth)) return;
53 +
54 + const ui = yield* TerminalUI;
55 + const userContext = yield* ComposioUserContext;
56 +
57 + const clampedLimit = clampLimit(params.limit);
58 + const toolkitFilter = Option.getOrUndefined(params.toolkits);
59 + const toolkitList =
60 + toolkitFilter && toolkitFilter.trim().length > 0
61 + ? toolkitFilter
62 + .split(',')
63 + .map(s => s.trim().toLowerCase())
64 + .filter(Boolean)
65 + : undefined;
66 +
67 + const searchResponse = yield* ui.withSpinner(
68 + `Searching tools for "${params.query}"...`,
69 + Effect.gen(function* () {
70 + const resolvedProject = yield* resolveCommandProject({
71 + mode: 'consumer',
72 + projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
73 + }).pipe(Effect.mapError(formatResolveCommandProjectError));
74 + const resolvedUserId =
75 + resolvedProject.projectType === 'CONSUMER'
76 + ? Option.fromNullable(resolvedProject.consumerUserId)
77 + : Option.match(params.userId, {
78 + onSome: value => Option.some(value),
79 + onNone: () => userContext.data.testUserId,
80 + });
81 + if (Option.isNone(resolvedUserId)) {
82 + return yield* Effect.fail(
83 + new Error(
84 + 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
85 + )
86 );
103 - })
104 - );
105 -
106 - const toolkitSet = toolkitList && toolkitList.length > 0 ? new Set(toolkitList) : undefined;
107 -
108 - const mergedSlugs: string[] = [];
109 - const seen = new Set<string>();
110 - for (const item of searchResponse.results) {
111 - for (const slug of [...item.primary_tool_slugs, ...item.related_tool_slugs]) {
112 - if (!seen.has(slug)) {
113 - seen.add(slug);
114 - mergedSlugs.push(slug);
115 - }
87 }
117 - }
118 -
119 - const toolsList: Tool[] = [];
120 - for (const slug of mergedSlugs) {
121 - const schema = searchResponse.tool_schemas[slug];
122 - if (!schema) continue;
123 - if (toolkitSet && !toolkitSet.has(schema.toolkit.toLowerCase())) continue;
124 -
125 - toolsList.push({
126 - slug: schema.tool_slug,
127 - name: schema.tool_slug,
128 - description: schema.description ?? '',
129 - tags: [],
130 - available_versions: [],
131 - input_parameters: (schema.input_schema ?? {}) as Record<string, unknown>,
132 - output_parameters: (schema.output_schema ?? {}) as Record<string, unknown>,
133 - } as Tool);
134 -
135 - if (toolsList.length >= clampedLimit) break;
136 - }
137 -
138 - if (toolsList.length === 0) {
139 - yield* ui.log.warn(`No tools found matching "${query}". Try broadening your search.`);
140 - return;
141 - }
142 -
143 - const showing = toolsList.length;
144 - yield* ui.log.info(`Found ${showing} tools\n\n${formatToolsTable(toolsList)}`);
145 -
146 - const planSteps = Array.from(
147 - new Set(searchResponse.results.flatMap(result => result.recommended_plan_steps ?? []))
148 - );
149 - if (planSteps.length > 0) {
150 - yield* ui.log.info(`Plan:\n${planSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}`);
151 - } else if (searchResponse.next_steps_guidance.length > 0) {
152 - yield* ui.log.info(
153 - `Plan:\n${searchResponse.next_steps_guidance
154 - .map((step, i) => `${i + 1}. ${step}`)
155 - .join('\n')}`
156 - );
157 - }
158 -
159 - // Next step hint
160 - const firstSlug = toolsList[0]?.slug;
161 - if (firstSlug) {
162 - yield* ui.log.step(
163 - [
164 - 'Hints:',
165 - `> composio manage tools info "${firstSlug}"`,
166 - `> composio manage tools execute "${firstSlug}" --user-id "<user-id>" --arguments '{}'`,
167 - ].join('\n')
88 + const clientSingleton = yield* ComposioClientSingleton;
89 + const client = yield* clientSingleton.getFor({
90 + orgId: resolvedProject.orgId,
91 + projectId: resolvedProject.projectId,
92 + });
93 + const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
94 + toolkits: toolkitList,
95 + });
96 + return yield* Effect.tryPromise(() =>
97 + client.toolRouter.session.search(sessionId, {
98 + queries: [{ use_case: params.query }],
99 + })
100 );
101 + })
102 + );
103 +
104 + const toolkitSet = toolkitList && toolkitList.length > 0 ? new Set(toolkitList) : undefined;
105 +
106 + const mergedSlugs: string[] = [];
107 + const seen = new Set<string>();
108 + for (const item of searchResponse.results) {
109 + for (const slug of [...item.primary_tool_slugs, ...item.related_tool_slugs]) {
110 + if (!seen.has(slug)) {
111 + seen.add(slug);
112 + mergedSlugs.push(slug);
113 + }
114 }
115 + }
116 +
117 + const toolsList: Tool[] = [];
118 + for (const slug of mergedSlugs) {
119 + const schema = searchResponse.tool_schemas[slug];
120 + if (!schema) continue;
121 + if (toolkitSet && !toolkitSet.has(schema.toolkit.toLowerCase())) continue;
122 +
123 + toolsList.push({
124 + slug: schema.tool_slug,
125 + name: schema.tool_slug,
126 + description: schema.description ?? '',
127 + tags: [],
128 + available_versions: [],
129 + input_parameters: (schema.input_schema ?? {}) as Record<string, unknown>,
130 + output_parameters: (schema.output_schema ?? {}) as Record<string, unknown>,
131 + } as Tool);
132 +
133 + if (toolsList.length >= clampedLimit) break;
134 + }
135 +
136 + if (toolsList.length === 0) {
137 + yield* ui.log.warn(`No tools found matching "${params.query}". Try broadening your search.`);
138 + return;
139 + }
140 +
141 + const showing = toolsList.length;
142 + yield* ui.log.info(`Found ${showing} tools\n\n${formatToolsTable(toolsList)}`);
143 +
144 + const planSteps = Array.from(
145 + new Set(searchResponse.results.flatMap(result => result.recommended_plan_steps ?? []))
146 + );
147 + if (planSteps.length > 0) {
148 + yield* ui.log.info(`Plan:\n${planSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}`);
149 + } else if (searchResponse.next_steps_guidance.length > 0) {
150 + yield* ui.log.info(
151 + `Plan:\n${searchResponse.next_steps_guidance
152 + .map((step, i) => `${i + 1}. ${step}`)
153 + .join('\n')}`
154 + );
155 + }
156 +
157 + const firstSlug = toolsList[0]?.slug;
158 + const firstSchema =
159 + firstSlug && searchResponse.tool_schemas[firstSlug]
160 + ? searchResponse.tool_schemas[firstSlug]
161 + : undefined;
162 + const firstToolkit = firstSchema?.toolkit;
163 + const firstPayload = buildMinimalPayloadFromSchema(
164 + (firstSchema?.input_schema ?? {}) as Record<string, unknown>
165 + );
166 + const firstPayloadJson = JSON.stringify(firstPayload);
167 + const firstDataArg =
168 + Object.keys(firstPayload).length === 0 ? '-d "{}"' : `-d '${firstPayloadJson}'`;
169 +
170 + if (firstSlug) {
171 + const executeHint = params.rootOnly
172 + ? `> composio execute "${firstSlug}" ${firstDataArg}`
173 + : `> composio manage tools execute "${firstSlug}" --user-id "<user-id>" ${firstDataArg}`;
174 + const linkHint = params.rootOnly
175 + ? `> composio link <toolkit>`
176 + : `> composio manage connected-accounts link <toolkit> --user-id "<user-id>"`;
177 + yield* ui.log.step(['Hints:', executeHint, linkHint].join('\n'));
178 + }
179 +
180 + if (searchResponse.error) {
181 + yield* ui.log.warn(searchResponse.error);
182 + }
183 +
184 + const cta: Array<{ action: string; command: string }> = [];
185 + if (firstSlug) {
186 + cta.push({
187 + action: 'Execute a tool',
188 + command: params.rootOnly
189 + ? `composio execute "${firstSlug}" ${firstDataArg}`
190 + : `composio manage tools execute "${firstSlug}" --user-id "<user-id>" ${firstDataArg}`,
191 + });
192 + }
193 + if (firstToolkit) {
194 + cta.push({
195 + action: 'Connect a user account',
196 + command: params.rootOnly
197 + ? `composio link ${String(firstToolkit).toLowerCase()}`
198 + : `composio manage connected-accounts link ${String(firstToolkit).toLowerCase()} --user-id "<user-id>"`,
199 + });
200 + }
201
171 - if (searchResponse.error) {
172 - yield* ui.log.warn(searchResponse.error);
173 - }
202 + const outputForJq = {
203 + ...searchResponse,
204 + CTA: cta,
205 + };
206 + yield* ui.output(JSON.stringify(outputForJq, null, 2));
207 + });
208
175 - // For machine-readable output (e.g. piping to jq), expose the full API payload with CTA.
176 - const firstSchema =
177 - firstSlug && searchResponse.tool_schemas[firstSlug]
178 - ? searchResponse.tool_schemas[firstSlug]
179 - : undefined;
180 - const firstToolkit = firstSchema?.toolkit;
181 -
182 - const cta: Array<{ action: string; command: string }> = [];
183 - if (firstSlug) {
184 - const payload = buildMinimalPayloadFromSchema(
185 - firstSchema?.input_schema as Record<string, unknown>
186 - );
187 - const payloadJson = JSON.stringify(payload);
188 - const dataArg = Object.keys(payload).length === 0 ? '-d "{}"' : `-d '${payloadJson}'`;
189 - cta.push({
190 - action: 'Execute a tool',
191 - command: `composio execute "${firstSlug}" ${dataArg}`,
192 - });
193 - }
194 - if (firstToolkit) {
195 - cta.push({
196 - action: 'Connect a user account',
197 - command: `composio link ${String(firstToolkit).toLowerCase()}`,
198 - });
199 - }
209 +export const toolsCmd$Search = Command.make(
210 + 'search',
211 + { query, toolkits, userId, projectName, limit },
212 + ({ query, toolkits, userId, projectName, limit }) =>
213 + runToolsSearch({ query, toolkits, userId, projectName, limit, rootOnly: false })
214 +).pipe(
215 + Command.withDescription(
216 + [
217 + 'Semantically search tools by use case; returns best-fit tools plus recommended usage guidance.',
218 + '',
219 + 'Related:',
220 + ' composio link <toolkit>',
221 + " composio execute <slug> -d '{}'",
222 + ].join('\n')
223 + )
224 +);
225
201 - const outputForJq = {
202 - ...searchResponse,
203 - CTA: cta,
204 - };
205 - yield* ui.output(JSON.stringify(outputForJq, null, 2));
226 +export const rootToolsCmd$Search = Command.make(
227 + 'search',
228 + { query, toolkits, limit },
229 + ({ query, toolkits, limit }) =>
230 + runToolsSearch({
231 + query,
232 + toolkits,
233 + userId: Option.none(),
234 + projectName: Option.none(),
235 + limit,
236 + rootOnly: true,
237 })
238 ).pipe(
239 Command.withDescription(
209 - 'Semantically search tools by use case; returns best-fit tools plus recommended usage guidance.'
240 + [
241 + 'Semantically search tools by use case; returns best-fit tools plus recommended usage guidance.',
242 + '',
243 + 'Related:',
244 + ' composio link <toolkit>',
245 + " composio execute <slug> -d '{}'",
246 + ].join('\n')
247 )
248 );
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+7
@@ -14,6 +14,10 @@ import {
14 import { parseCsv } from '../parse-csv';
15 import { parseTriggerListenEvent } from '../parse';
16 import type { TriggerListenFilters } from '../types';
17 +import {
18 + resolveCommandProject,
19 + formatResolveCommandProjectError,
20 +} from 'src/services/command-project';
21
22 const toolkits = Options.text('toolkits').pipe(
23 Options.withDescription(
@@ -172,6 +176,9 @@ export const triggersCmd$Listen = Command.make(
176 if (!(yield* requireAuth)) return;
177
178 const ui = yield* TerminalUI;
179 + yield* resolveCommandProject({ mode: 'developer' }).pipe(
180 + Effect.mapError(formatResolveCommandProjectError)
181 + );
182 const fs = yield* FileSystem.FileSystem;
183 const realtime = yield* TriggersRealtime;
184 const runtime = yield* Effect.runtime<never>();
ts/packages/cli/src/commands/whoami.cmd.ts
-3
@@ -25,13 +25,11 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
25 onSome: () =>
26 Effect.gen(function* () {
27 const defaultOrgId = Option.getOrUndefined(ctx.data.orgId);
28 - const defaultProjectId = Option.getOrUndefined(ctx.data.projectId);
28 const testUserId = Option.getOrUndefined(ctx.data.testUserId);
29
30 yield* ui.note(
31 [
32 `Default Org ID: ${defaultOrgId ?? 'not set'}`,
34 - `Default Project ID: ${defaultProjectId ?? 'not set'}`,
33 `Test User ID: ${testUserId ?? 'not set'}`,
34 ].join('\n'),
35 'Global User Context'
@@ -45,7 +43,6 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
43 yield* ui.output(
44 JSON.stringify({
45 default_org_id: defaultOrgId ?? null,
48 - default_project_id: defaultProjectId ?? null,
46 test_user_id: testUserId ?? null,
47 })
48 );
ts/packages/cli/src/effects/create-tool-router-session.ts
+4 -7
@@ -1,6 +1,5 @@
1 import { Effect } from 'effect';
2 import type { Composio } from '@composio/client';
3 -import { ComposioClientSingleton } from 'src/services/composio-clients';
3
4 export interface CreateToolRouterSessionOptions {
5 /** Enable auto connection management. Default: false. */
@@ -39,12 +38,10 @@ export const createToolRouterSession = (
38 * (resolve singleton, get client, create session) repeated across commands.
39 */
40 export const resolveToolRouterSession = (
41 + client: Composio,
42 userId: string,
43 options?: CreateToolRouterSessionOptions
44 ) =>
45 - Effect.gen(function* () {
46 - const clientSingleton = yield* ComposioClientSingleton;
47 - const client = yield* clientSingleton.get();
48 - const sessionId = yield* createToolRouterSession(client, userId, options);
49 - return { client, sessionId };
50 - });
45 + createToolRouterSession(client, userId, options).pipe(
46 + Effect.map(sessionId => ({ client, sessionId }))
47 + );
ts/packages/cli/src/effects/select-org-project.ts
+5 -64
@@ -1,11 +1,6 @@
1 import { Effect } from 'effect';
2 import { TerminalUI } from 'src/services/terminal-ui';
3 -import {
4 - listOrganizationProjects,
5 - listOrganizations,
6 - type OrganizationProjectSummary,
7 - type OrganizationSummary,
8 -} from 'src/services/composio-clients';
3 +import { listOrganizations, type OrganizationSummary } from 'src/services/composio-clients';
4 import { clampLimit } from 'src/ui/clamp-limit';
5
6 const DEFAULT_LIMIT = 50;
@@ -21,49 +16,15 @@ const selectOrganization = (organizations: ReadonlyArray<OrganizationSummary>) =
16 ]);
17 });
18
24 -/**
25 - * Prompts user to select a project, or auto-selects if only one.
26 - * When explicitProjectId is provided (e.g. from `orgs switch --project-id`), finds and returns it without prompting.
27 - */
28 -const selectProject = (
29 - projects: ReadonlyArray<OrganizationProjectSummary>,
30 - explicitProjectId?: string
31 -) =>
32 - Effect.gen(function* () {
33 - const ui = yield* TerminalUI;
34 - if (projects.length === 0) return undefined;
35 - if (explicitProjectId) {
36 - const match = projects.find(p => p.id === explicitProjectId);
37 - if (match) return match;
38 - }
39 - if (projects.length === 1) return projects[0];
40 - return yield* ui.select('Select a default project (global scope):', [
41 - ...projects.map(project => ({ value: project, label: project.name, hint: project.id })),
42 - ]);
43 - });
44 -
45 -/**
46 - * Runs the org/project selection flow: lists orgs, prompts for org (or auto-selects if 1),
47 - * lists projects, prompts for project (or auto-selects if 1).
48 - *
49 - * Reused by `composio manage orgs switch` and `composio login -y`.
50 - *
51 - * @param params.apiKey - User API key for API calls
52 - * @param params.baseURL - API base URL
53 - * @param params.explicitOrgId - If provided, skip org picker and use this org
54 - * @param params.explicitProjectId - If provided (and org selected), skip project picker
55 - * @param params.limit - Max orgs/projects to fetch (default 50)
56 - */
57 -export const runOrgProjectSelection = (params: {
19 +export const runOrgSelection = (params: {
20 apiKey: string;
21 baseURL: string;
22 explicitOrgId?: string;
61 - explicitProjectId?: string;
23 limit?: number;
24 }) =>
25 Effect.gen(function* () {
26 const ui = yield* TerminalUI;
66 - const { apiKey, baseURL, explicitOrgId, explicitProjectId, limit = DEFAULT_LIMIT } = params;
27 + const { apiKey, baseURL, explicitOrgId, limit = DEFAULT_LIMIT } = params;
28 const clampedLimit = clampLimit(limit);
29
30 const selectedOrganization =
@@ -84,30 +45,10 @@ export const runOrgProjectSelection = (params: {
45 yield* ui.log.warn('No organizations found for this API key.');
46 return undefined;
47 }
48 +
49 yield* ui.log.info(
50 `Selected organization: "${selectedOrganization.name}" (${selectedOrganization.id})`
51 );
52
91 - const projects = yield* listOrganizationProjects({
92 - baseURL,
93 - apiKey,
94 - orgId: selectedOrganization.id,
95 - limit: clampedLimit,
96 - });
97 - yield* ui.log.info(`Loaded ${projects.data.length} projects`);
98 -
99 - if (projects.data.length === 0) {
100 - yield* ui.log.warn(`No projects found for org "${selectedOrganization.name}".`);
101 - return undefined;
102 - }
103 -
104 - const selectedProject = yield* selectProject(projects.data, explicitProjectId);
105 -
106 - if (!selectedProject) {
107 - yield* ui.log.warn('No project selected.');
108 - return undefined;
109 - }
110 - yield* ui.log.info(`Selected project: "${selectedProject.name}" (${selectedProject.id})`);
111 -
112 - return { org: selectedOrganization, project: selectedProject } as const;
53 + return selectedOrganization;
54 });
ts/packages/cli/src/models/project-keys.ts
+2 -2
@@ -3,9 +3,9 @@ import { OptionFromNullishOr } from 'effect/Schema';
3 import { JSONTransformSchema } from './utils/json-transform-schema';
4
5 /**
6 - * Organization and project identifiers for a CLI project profile.
6 + * Organization and developer-project identifiers for a CLI project profile.
7 * Stored in `~/.composio/_keys/<projectId>.json` (global registry)
8 - * and `<cwd>/.composio/project.json` (per-directory config).
8 + * and `<cwd>/.composio/project.json` (per-directory developer config).
9 */
10 export const ProjectKeys = Schema.Struct({
11 /**
ts/packages/cli/src/models/user-data.ts
+3 -2
@@ -32,7 +32,8 @@ export const UserData = Schema.Struct({
32 ),
33
34 /**
35 - * Project ID for the current user.
35 + * Legacy global project ID retained for backward-compatible reads.
36 + * New CLI versions no longer persist this field.
37 */
38 projectId: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
39 Schema.fromKey('project_id')
@@ -57,7 +58,7 @@ export const UserDataWithDefaults = Schema.Struct({
58 baseURL: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('base_url')),
59 webURL: Schema.propertySignature(Schema.String).pipe(Schema.fromKey('web_url')),
60
60 - // orgId and projectId remain as Option<string> — they may not be set.
61 + // orgId and legacy projectId remain as Option<string> — they may not be set.
62 }).annotations({
63 identifier: 'UserDataWithDefaults',
64 description: 'User data storage for the Composio CLI with defaults',
ts/packages/cli/src/services/command-project.ts new
+159
@@ -0,0 +1,159 @@
1 +import { Data, Effect, Option } from 'effect';
2 +import { ProjectContext } from './project-context';
3 +import { ComposioUserContext } from './user-context';
4 +import {
5 + resolveConsumerProject,
6 + findDeveloperProjectByName,
7 + DeveloperProjectNotFoundError,
8 + AmbiguousDeveloperProjectNameError,
9 + type HttpDecodingError,
10 + type HttpServerError,
11 +} from './composio-clients';
12 +
13 +export type ProjectMode = 'consumer' | 'developer';
14 +
15 +export type CliProjectType = 'CONSUMER' | 'DEVELOPER';
16 +
17 +export type CliProjectResolutionSource =
18 + | 'consumer-default'
19 + | 'developer-project-name'
20 + | 'developer-local-config'
21 + | 'developer-explicit';
22 +
23 +export interface ResolvedCommandProject {
24 + readonly orgId: string;
25 + readonly projectId: string;
26 + readonly projectName?: string;
27 + readonly projectType: CliProjectType;
28 + readonly consumerUserId?: string;
29 + readonly source: CliProjectResolutionSource;
30 +}
31 +
32 +export class MissingDefaultOrgError extends Data.TaggedError(
33 + 'services/MissingDefaultOrgError'
34 +)<{}> {}
35 +
36 +export class MissingDeveloperProjectError extends Data.TaggedError(
37 + 'services/MissingDeveloperProjectError'
38 +)<{}> {}
39 +
40 +const requireDefaultOrg = (orgId: Option.Option<string>) =>
41 + Option.match(orgId, {
42 + onNone: () => Effect.fail(new MissingDefaultOrgError()),
43 + onSome: value => Effect.succeed(value),
44 + });
45 +
46 +export const resolveCommandProject = (params: { mode: ProjectMode; projectName?: string }) =>
47 + Effect.gen(function* () {
48 + const ctx = yield* ComposioUserContext;
49 + const projectContext = yield* ProjectContext;
50 + const apiKey = Option.getOrUndefined(ctx.data.apiKey);
51 + const currentOrgId = yield* requireDefaultOrg(ctx.data.orgId);
52 +
53 + if (!apiKey) {
54 + return yield* Effect.fail(new MissingDefaultOrgError());
55 + }
56 +
57 + if (params.mode === 'consumer') {
58 + if (params.projectName) {
59 + const developerProject = yield* findDeveloperProjectByName({
60 + baseURL: ctx.data.baseURL,
61 + apiKey,
62 + orgId: currentOrgId,
63 + name: params.projectName,
64 + });
65 +
66 + return {
67 + orgId: currentOrgId,
68 + projectId: developerProject.id,
69 + projectName: developerProject.name,
70 + projectType: 'DEVELOPER',
71 + source: 'developer-project-name',
72 + } satisfies ResolvedCommandProject;
73 + }
74 +
75 + const consumerProject = yield* resolveConsumerProject({
76 + baseURL: ctx.data.baseURL,
77 + apiKey,
78 + orgId: currentOrgId,
79 + });
80 +
81 + return {
82 + orgId: consumerProject.org_id,
83 + projectId: consumerProject.project_nano_id,
84 + projectName: consumerProject.project_name,
85 + projectType: 'CONSUMER',
86 + consumerUserId: consumerProject.consumer_user_id,
87 + source: 'consumer-default',
88 + } satisfies ResolvedCommandProject;
89 + }
90 +
91 + if (params.projectName) {
92 + const developerProject = yield* findDeveloperProjectByName({
93 + baseURL: ctx.data.baseURL,
94 + apiKey,
95 + orgId: currentOrgId,
96 + name: params.projectName,
97 + });
98 +
99 + return {
100 + orgId: currentOrgId,
101 + projectId: developerProject.id,
102 + projectName: developerProject.name,
103 + projectType: 'DEVELOPER',
104 + source: 'developer-explicit',
105 + } satisfies ResolvedCommandProject;
106 + }
107 +
108 + const localProject = yield* projectContext.resolve;
109 + if (Option.isNone(localProject)) {
110 + return yield* Effect.fail(new MissingDeveloperProjectError());
111 + }
112 +
113 + return {
114 + orgId: localProject.value.orgId,
115 + projectId: localProject.value.projectId,
116 + projectName: Option.getOrUndefined(localProject.value.projectName),
117 + projectType: 'DEVELOPER',
118 + source: 'developer-local-config',
119 + } satisfies ResolvedCommandProject;
120 + }) as Effect.Effect<
121 + ResolvedCommandProject,
122 + | MissingDefaultOrgError
123 + | MissingDeveloperProjectError
124 + | DeveloperProjectNotFoundError
125 + | AmbiguousDeveloperProjectNameError
126 + | HttpServerError
127 + | HttpDecodingError
128 + >;
129 +
130 +export const formatResolveCommandProjectError = (error: unknown): Error => {
131 + if (error instanceof MissingDefaultOrgError) {
132 + return new Error(
133 + 'No default org configured. Run `composio login` or `composio manage orgs switch`.'
134 + );
135 + }
136 + if (error instanceof MissingDeveloperProjectError) {
137 + return new Error('No developer project configured for this directory. Run `composio init`.');
138 + }
139 + if (error instanceof DeveloperProjectNotFoundError) {
140 + return new Error(
141 + `Developer project "${error.projectName}" was not found in org "${error.orgId}". Run \`composio init\` or \`composio manage projects list\`.`
142 + );
143 + }
144 + if (error instanceof AmbiguousDeveloperProjectNameError) {
145 + return new Error(
146 + `Developer project name "${error.projectName}" is ambiguous in org "${error.orgId}". Use an exact unique project name.`
147 + );
148 + }
149 + if (typeof error === 'object' && error && 'details' in error) {
150 + const details = (error as { details?: { message?: string } }).details;
151 + if (details?.message) {
152 + return new Error(details.message);
153 + }
154 + }
155 + if (error instanceof Error) {
156 + return error;
157 + }
158 + return new Error(String(error));
159 +};
ts/packages/cli/src/services/composio-clients.ts
+184 -42
@@ -732,6 +732,18 @@ export interface OrganizationProjectListResponse {
732 readonly total_items: number;
733 }
734
735 +export const ConsumerProjectResolveResponse = Schema.Struct({
736 + project_id: Schema.String,
737 + project_nano_id: Schema.String,
738 + project_name: Schema.String,
739 + org_id: Schema.String,
740 + project_type: Schema.Literal('CONSUMER'),
741 + consumer_user_id: Schema.String,
742 +}).annotations({ identifier: 'ConsumerProjectResolveResponse' });
743 +export type ConsumerProjectResolveResponse = Schema.Schema.Type<
744 + typeof ConsumerProjectResolveResponse
745 +>;
746 +
747 const extractArrayPayload = (json: unknown): ReadonlyArray<unknown> => {
748 if (Array.isArray(json)) return json;
749 if (json && typeof json === 'object') {
@@ -1085,6 +1097,131 @@ export const createProjectApiKey = (params: {
1097 return createdApiKey;
1098 });
1099
1100 +export const resolveConsumerProject = (params: {
1101 + baseURL: string;
1102 + apiKey: string;
1103 + orgId: string;
1104 +}): Effect.Effect<ConsumerProjectResolveResponse, HttpServerError | HttpDecodingError> =>
1105 + Effect.gen(function* () {
1106 + const response = yield* Effect.tryPromise({
1107 + try: () =>
1108 + fetch(`${params.baseURL}/api/v3/org/consumer/project/resolve`, {
1109 + method: 'POST',
1110 + redirect: 'error',
1111 + headers: {
1112 + 'x-user-api-key': params.apiKey,
1113 + 'x-org-id': params.orgId,
1114 + 'User-Agent': '@composio/cli',
1115 + Accept: 'application/json',
1116 + 'Content-Type': 'application/json',
1117 + },
1118 + }),
1119 + catch: error => new HttpServerError({ cause: error }),
1120 + });
1121 +
1122 + if (!response.ok) {
1123 + return yield* handleHttpErrorResponse(response);
1124 + }
1125 +
1126 + const { json } = yield* streamResponseWithByteCount(response);
1127 +
1128 + return yield* pipe(
1129 + Schema.decodeUnknown(ConsumerProjectResolveResponse)(json),
1130 + Effect.catchTag('ParseError', e => {
1131 + const message = ParseResult.TreeFormatter.formatErrorSync(e);
1132 + return new HttpDecodingError({
1133 + cause: `ParseError\n ${message}`,
1134 + });
1135 + })
1136 + );
1137 + });
1138 +
1139 +export class DeveloperProjectNotFoundError extends Data.TaggedError(
1140 + 'services/DeveloperProjectNotFoundError'
1141 +)<{
1142 + readonly orgId: string;
1143 + readonly projectName: string;
1144 +}> {}
1145 +
1146 +export class AmbiguousDeveloperProjectNameError extends Data.TaggedError(
1147 + 'services/AmbiguousDeveloperProjectNameError'
1148 +)<{
1149 + readonly orgId: string;
1150 + readonly projectName: string;
1151 + readonly matches: ReadonlyArray<OrganizationProjectSummary>;
1152 +}> {}
1153 +
1154 +export const findDeveloperProjectByName = (params: {
1155 + baseURL: string;
1156 + apiKey: string;
1157 + orgId: string;
1158 + name: string;
1159 + limit?: number;
1160 +}): Effect.Effect<
1161 + OrganizationProjectSummary,
1162 + | DeveloperProjectNotFoundError
1163 + | AmbiguousDeveloperProjectNameError
1164 + | HttpServerError
1165 + | HttpDecodingError
1166 +> =>
1167 + Effect.gen(function* () {
1168 + const projects = yield* listOrgProjects({
1169 + baseURL: params.baseURL,
1170 + apiKey: params.apiKey,
1171 + orgId: params.orgId,
1172 + limit: params.limit,
1173 + });
1174 +
1175 + const normalizedName = String.toLowerCase(params.name.trim());
1176 + const matches = projects.data.filter(
1177 + project => String.toLowerCase(project.name) === normalizedName
1178 + );
1179 +
1180 + if (matches.length === 0) {
1181 + return yield* Effect.fail(
1182 + new DeveloperProjectNotFoundError({
1183 + orgId: params.orgId,
1184 + projectName: params.name,
1185 + })
1186 + );
1187 + }
1188 +
1189 + if (matches.length > 1) {
1190 + return yield* Effect.fail(
1191 + new AmbiguousDeveloperProjectNameError({
1192 + orgId: params.orgId,
1193 + projectName: params.name,
1194 + matches,
1195 + })
1196 + );
1197 + }
1198 +
1199 + return matches[0];
1200 + });
1201 +
1202 +const normalizeApiKey = (rawApiKey?: string): string | undefined =>
1203 + typeof rawApiKey === 'string' && rawApiKey.trim().length > 0 ? rawApiKey : undefined;
1204 +
1205 +const buildDefaultHeaders = (params: {
1206 + userApiKey?: string;
1207 + orgId?: string;
1208 + projectId?: string;
1209 +}): Record<string, string> | undefined => {
1210 + const defaultHeaders = {
1211 + ...(params.userApiKey
1212 + ? ({ 'x-user-api-key': params.userApiKey } satisfies Record<string, string>)
1213 + : {}),
1214 + ...(params.orgId && params.projectId
1215 + ? ({
1216 + 'x-org-id': params.orgId,
1217 + 'x-project-id': params.projectId,
1218 + } satisfies Record<string, string>)
1219 + : {}),
1220 + };
1221 +
1222 + return Object.keys(defaultHeaders).length > 0 ? defaultHeaders : undefined;
1223 +};
1224 +
1225 // Utility function for calling the Composio API and decoding its response.
1226 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1227 const callClient = <T, S extends Schema.Schema<any, any>>(
@@ -1243,59 +1380,64 @@ export class ComposioClientSingleton extends Effect.Service<ComposioClientSingle
1380 effect: Effect.gen(function* () {
1381 const ctx = yield* ComposioUserContext;
1382 const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
1246 - let ref = Option.none<_RawComposioClient>();
1383 + const cache = new Map<string, _RawComposioClient>();
1384
1248 - return {
1249 - get: Effect.fn(function* () {
1250 - if (Option.isSome(ref)) {
1251 - return ref.value;
1385 + const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
1386 + Effect.gen(function* () {
1387 + const apiKey = normalizeApiKey(
1388 + params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey)
1389 + );
1390 + const cacheKey = JSON.stringify({
1391 + apiKey: apiKey ?? null,
1392 + orgId: params?.orgId ?? null,
1393 + projectId: params?.projectId ?? null,
1394 + });
1395 + const cached = cache.get(cacheKey);
1396 + if (cached) {
1397 + return cached;
1398 }
1399
1254 - // Note: `api_key` is not required in every API request.
1255 - const rawApiKey = ctx.data.apiKey.pipe(Option.getOrUndefined);
1256 - const apiKey =
1257 - typeof rawApiKey === 'string' && rawApiKey.trim().length > 0 ? rawApiKey : undefined;
1258 - const baseURL = ctx.data.baseURL;
1259 - const globalOrgId = Option.getOrUndefined(ctx.data.orgId);
1260 - const globalProjectId = Option.getOrUndefined(ctx.data.projectId);
1400 + const client = new _RawComposioClient({
1401 + apiKey: null,
1402 + baseURL: ctx.data.baseURL,
1403 + defaultHeaders: buildDefaultHeaders({
1404 + userApiKey: apiKey,
1405 + orgId: params?.orgId,
1406 + projectId: params?.projectId,
1407 + }),
1408 + });
1409 +
1410 + cache.set(cacheKey, client);
1411 + return client;
1412 + });
1413 +
1414 + return {
1415 + get: Effect.fn(function* () {
1416 const resolvedProjectContext = yield* Option.match(projectContextOpt, {
1417 onNone: () => Effect.succeed(Option.none()),
1418 onSome: projectContext =>
1419 projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none()))),
1420 });
1266 - const projectContextHeaders = Option.match(resolvedProjectContext, {
1267 - onNone: () =>
1268 - globalOrgId && globalProjectId
1269 - ? ({
1270 - 'x-org-id': globalOrgId,
1271 - 'x-project-id': globalProjectId,
1272 - } satisfies Record<string, string>)
1273 - : undefined,
1421 + return yield* Option.match(resolvedProjectContext, {
1422 + onNone: () => getFor(),
1423 onSome: keys =>
1275 - ({
1276 - 'x-org-id': keys.orgId,
1277 - 'x-project-id': keys.projectId,
1278 - }) satisfies Record<string, string>,
1424 + getFor({
1425 + orgId: keys.orgId,
1426 + projectId: keys.projectId,
1427 + }),
1428 });
1280 - const defaultHeaders = {
1281 - ...(apiKey ? ({ 'x-user-api-key': apiKey } satisfies Record<string, string>) : {}),
1282 - ...(projectContextHeaders ?? {}),
1283 - };
1284 - const normalizedDefaultHeaders =
1285 - Object.keys(defaultHeaders).length > 0 ? defaultHeaders : undefined;
1286 -
1287 - yield* Effect.logDebug('Creating raw Composio client...');
1288 - const client = new _RawComposioClient({
1289 - // Disable @composio/client's built-in x-api-key auth header.
1290 - // CLI always authenticates with x-user-api-key instead.
1291 - apiKey: null,
1292 - baseURL,
1293 - defaultHeaders: normalizedDefaultHeaders,
1294 - });
1295 -
1296 - ref = Option.some(client);
1297 - return client;
1429 }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1430 + getFor: Effect.fn(function* (params: {
1431 + userApiKey?: string;
1432 + orgId?: string;
1433 + projectId?: string;
1434 + }) {
1435 + return yield* getFor(params);
1436 + }) satisfies (params: {
1437 + userApiKey?: string;
1438 + orgId?: string;
1439 + projectId?: string;
1440 + }) => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1441 };
1442 }),
1443 dependencies: [ComposioUserContextLive],
ts/packages/cli/src/services/project-context.ts
+2 -2
@@ -44,8 +44,8 @@ const parseEnvFile = (content: string): Map<string, string> => {
44 };
45
46 /**
47 - * Service that resolves the current project context using a precedence chain.
48 - * Read-only -- it does NOT write files.
47 + * Service that resolves the current developer project context using a precedence chain.
48 + * Read-only -- it does NOT write files and is never used for consumer-project routing.
49 *
50 * Precedence (highest first):
51 * 1. System env vars (COMPOSIO_ORG_ID, COMPOSIO_PROJECT_ID)
ts/packages/cli/src/services/tools-executor.ts
+6 -3
@@ -1,4 +1,5 @@
1 import { Context, Effect, Layer } from 'effect';
2 +import type { Composio } from '@composio/client';
3 import type {
4 SessionExecuteResponse,
5 SessionExecuteMetaResponse,
@@ -38,6 +39,7 @@ export class ActionExecuteConnectedAccountNotFoundError extends Error {
39 export interface ToolExecuteParams {
40 readonly userId: string;
41 readonly arguments: Record<string, unknown>;
42 + readonly client?: Composio;
43 }
44
45 /**
@@ -107,20 +109,21 @@ export const ToolsExecutorLive = Layer.effect(
109 execute: (slug, params) =>
110 Effect.gen(function* () {
111 const client = yield* clientSingleton.get();
112 + const resolvedClient = params.client ?? client;
113 // One session per invocation — CLI runs one tool per process.
111 - const sessionId = yield* createToolRouterSession(client, params.userId, {
114 + const sessionId = yield* createToolRouterSession(resolvedClient, params.userId, {
115 manageConnections: true,
116 });
117
118 const raw: SessionExecuteResponse | SessionExecuteMetaResponse = yield* Effect.tryPromise(
119 () => {
120 if (isMetaToolSlug(slug)) {
118 - return client.toolRouter.session.executeMeta(sessionId, {
121 + return resolvedClient.toolRouter.session.executeMeta(sessionId, {
122 slug,
123 arguments: params.arguments,
124 });
125 }
123 - return client.toolRouter.session.execute(sessionId, {
126 + return resolvedClient.toolRouter.session.execute(sessionId, {
127 tool_slug: slug,
128 arguments: params.arguments,
129 });
ts/packages/cli/src/services/user-context.ts
+17 -8
@@ -29,12 +29,11 @@ export class ComposioUserContext extends Context.Tag('ComposioUserData')<
29 logout: Effect.Effect<void, ParseError | PlatformError, never>;
30
31 /**
32 - * Logs in the user by setting the API key, and optionally org/project IDs.
32 + * Logs in the user by setting the API key, and optionally org ID.
33 */
34 login: (
35 apiKey: string,
36 orgId?: string,
37 - projectId?: string,
37 testUserId?: string
38 ) => Effect.Effect<void, ParseError | PlatformError, never>;
39
@@ -79,14 +78,14 @@ export const ComposioUserContextLive = Layer.effect(
78 });
79 });
80
82 - const login = (apiKey: string, orgId?: string, projectId?: string, testUserId?: string) =>
81 + const login = (apiKey: string, orgId?: string, testUserId?: string) =>
82 Effect.gen(function* () {
83 yield* update({
84 apiKey: Option.some(apiKey),
85 baseURL: Option.some(baseURL),
86 webURL: Option.some(webURL),
87 orgId: Option.fromNullable(orgId),
89 - projectId: Option.fromNullable(projectId),
88 + projectId: Option.none(),
89 testUserId: Option.fromNullable(testUserId),
90 });
91 });
@@ -96,10 +95,20 @@ export const ComposioUserContextLive = Layer.effect(
95 */
96 const update = (data: Partial<UserData>) =>
97 Effect.gen(function* () {
99 - const userDataAsJson = yield* userDataToJSON({ ...userData, ...data });
100 - yield* Effect.logDebug('Saving user data:', userDataAsJson);
101 - yield* fs.writeFileString(jsonUserConfigPath, userDataAsJson);
102 - userData = { ...userData, ...data } satisfies UserData;
98 + const nextUserData = { ...userData, ...data } satisfies UserData;
99 + const encodedUserData = yield* userDataToJSON(nextUserData);
100 + const normalizedUserDataJson = JSON.stringify(
101 + (() => {
102 + const parsed = JSON.parse(encodedUserData) as Record<string, unknown>;
103 + if (parsed.project_id === null) {
104 + delete parsed.project_id;
105 + }
106 + return parsed;
107 + })()
108 + );
109 + yield* Effect.logDebug('Saving user data:', normalizedUserDataJson);
110 + yield* fs.writeFileString(jsonUserConfigPath, normalizedUserDataJson);
111 + userData = nextUserData;
112 yield* Effect.logDebug('User data updated:', userData);
113 });
114
ts/packages/cli/test/__fixtures__/global-test-user-id/.composio/project.json new
+5
@@ -0,0 +1,5 @@
1 +{
2 + "org_id": "org_test",
3 + "project_id": "proj_test",
4 + "project_name": "Developer Project"
5 +}
ts/packages/cli/test/__fixtures__/global-test-user-id/.composio/user_data.json
+1 -1
@@ -2,7 +2,7 @@
2 "api_key": "test_api_key",
3 "base_url": "https://backend.composio.dev",
4 "web_url": "https://platform.composio.dev",
5 - "org_id": null,
5 + "org_id": "org_test",
6 "project_id": null,
7 "test_user_id": "global-default"
8 }
ts/packages/cli/test/__utils__/services/test-layer.ts
+67 -6
@@ -64,7 +64,6 @@ import { ProjectEnvironmentDetector } from 'src/services/project-environment-det
64 import { CommandRunner } from 'src/services/command-runner';
65 import { TerminalUI } from 'src/services/terminal-ui';
66 import { CommandExecutor } from '@effect/platform';
67 -import { Option } from 'effect';
67
68 export interface TestLiveInput {
69 /**
@@ -200,6 +199,54 @@ export interface TestLiveInput {
199
200 type RequiredLayer = Layer.Layer<any, any, never>;
201
202 +const ConsumerProjectResolveFetchMock = Layer.scopedDiscard(
203 + Effect.acquireRelease(
204 + Effect.sync(() => {
205 + const originalFetch = globalThis.fetch;
206 +
207 + globalThis.fetch = (async (requestInput: RequestInfo | URL, init?: RequestInit) => {
208 + const url =
209 + typeof requestInput === 'string'
210 + ? requestInput
211 + : requestInput instanceof URL
212 + ? requestInput.toString()
213 + : requestInput.url;
214 +
215 + if (url.includes('/api/v3/org/consumer/project/resolve')) {
216 + const headers = new Headers(
217 + requestInput instanceof Request ? requestInput.headers : undefined
218 + );
219 + new Headers(init?.headers).forEach((value, key) => headers.set(key, value));
220 +
221 + const orgId = headers.get('x-org-id') ?? 'org_test';
222 + return new Response(
223 + JSON.stringify({
224 + project_id: 'consumer_project_id_test',
225 + project_nano_id: 'consumer_project_test',
226 + project_name: 'Consumer Project',
227 + org_id: orgId,
228 + project_type: 'CONSUMER',
229 + consumer_user_id: `consumer-user-${orgId}`,
230 + }),
231 + {
232 + status: 200,
233 + headers: { 'Content-Type': 'application/json' },
234 + }
235 + );
236 + }
237 +
238 + return originalFetch(requestInput, init);
239 + }) as typeof globalThis.fetch;
240 +
241 + return originalFetch;
242 + }),
243 + originalFetch =>
244 + Effect.sync(() => {
245 + globalThis.fetch = originalFetch;
246 + })
247 + )
248 +);
249 +
250 /**
251 * Effect layer that injects all the services needed for tests, using mocks to avoid
252 * side-effects like unwanted HTTP requests to remote services.
@@ -866,6 +913,17 @@ export const TestLayer = (input?: TestLiveInput) =>
913 };
914
915 const mockComposioClient = {
916 + link: {
917 + create: async (params: { auth_config_id: string; user_id: string }) => {
918 + const response = connectedAccountsData.linkResponse ?? {
919 + connected_account_id: 'con_test_link',
920 + expires_at: '2026-12-31T23:59:59Z',
921 + link_token: 'lt_test_token',
922 + redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
923 + };
924 + return response;
925 + },
926 + },
927 toolkits: {
928 retrieve: async (slug: string) => {
929 const detailed = toolkitsData.detailedToolkits.find(
@@ -948,6 +1006,10 @@ export const TestLayer = (input?: TestLiveInput) =>
1006 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1007 return mockComposioClient as any;
1008 }),
1009 + getFor: Effect.fn(function* () {
1010 + // eslint-disable-next-line @typescript-eslint/no-explicit-any
1011 + return mockComposioClient as any;
1012 + }),
1013 })
1014 );
1015
@@ -1013,13 +1075,12 @@ export const TestLayer = (input?: TestLiveInput) =>
1075 BunContext.layer,
1076 MockTerminal.layer,
1077 BunPath.layer,
1078 + ConsumerProjectResolveFetchMock,
1079 StdinTest,
1080 TerminalUILayer,
1018 - Layer.succeed(
1019 - ProjectContext,
1020 - new ProjectContext({
1021 - resolve: Effect.succeed(Option.none()),
1022 - })
1081 + Layer.provide(
1082 + ProjectContext.Default,
1083 + Layer.mergeAll(BunFileSystem.layer, NodeOsTest, NodeProcessTest)
1084 )
1085 ) satisfies RequiredLayer;
1086
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+1 -1
@@ -15,7 +15,7 @@ describe('CLI: composio', () => {
15 expect(result).toEqual(
16 ValidationError.commandMismatch(
17 HelpDoc.p(
18 - "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'install', 'init', 'generate', 'manage'"
18 + "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'install', 'init', 'search', 'link', 'execute', 'listen', 'generate', 'manage'"
19 )
20 )
21 );
ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap
+8 -12
@@ -2,7 +2,7 @@
2
3 exports[`CLI: composio > [Given] --help flag [Then] prints help message 1`] = `
4 "
5 -Connect AI agents to external tools. Link accounts, discover tools, and execute them.
5 +Connect AI agents to external tools. \`search\`, \`link\`, and \`execute\` use your org consumer project by default. \`init\`, \`listen\`, and \`manage\` use developer project context.
6
7 USAGE
8 composio <command> [options]
@@ -27,43 +27,39 @@ BASIC COMMANDS
27 --no-browser Login without browser interaction
28 --no-wait Print login URL and session info, then exit (no browser, no waiting)
29 --key Complete login using session key from --no-wait
30 - -y, --yes Skip org/project picker; use session defaults
30 + -y, --yes Skip org picker; use session default org
31
32 logout
33 Log out from the Composio CLI session.
34 Usage: composio logout
35
36 init
37 - Initialize a Composio project in the current directory.
37 + Initialize this directory with a developer project.
38 Usage: composio init [--no-browser] [-y, --yes]
39 Options:
40 --no-browser Skip opening browser for auth
41 - -y, --yes Auto-select default org/project
41 + -y, --yes Auto-select the default developer project
42
43 search
44 Search tools by use case across toolkits/apps.
45 - Usage: composio search <query> [--toolkits text] [--user-id text] [--limit integer]
45 + Usage: composio search <query> [--toolkits text] [--limit integer]
46 Options:
47 <query> Semantic use-case query (e.g. "send emails")
48 --toolkits Filter by toolkit slugs, comma-separated
49 - --user-id User ID (falls back to project/global test_user_id)
49 --limit Number of results per page (1-1000)
50
51 execute
52 Execute a tool.
54 - Usage: composio execute <slug> [-d, --data text] [--user-id text]
53 + Usage: composio execute <slug> [-d, --data text]
54 Options:
55 <slug> Tool slug (e.g. "GITHUB_CREATE_ISSUE")
56 -d, --data JSON arguments, @file, or - for stdin
58 - --user-id User ID (falls back to project test_user_id)
57
58 link
59 Connect a user account for a toolkit/app.
62 - Usage: composio link [<toolkit>] [--auth-config text] [--user-id text] [--no-browser]
60 + Usage: composio link [<toolkit>] [--no-browser]
61 Options:
62 <toolkit> Toolkit slug to link (e.g. "github", "gmail")
65 - --auth-config Auth config ID (legacy flow)
66 - --user-id User ID for the connection
63 --no-browser Skip auto-opening the browser
64
65 listen
@@ -81,7 +77,7 @@ BASIC COMMANDS
77
78 ADVANCED COMMANDS
79 generate Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)
84 - manage Manage Composio resources — toolkits, tools, accounts, triggers, logs, orgs, and projects.
80 + manage Developer/admin workflows: orgs, toolkits, triggers, auth configs, logs, and deprecated project commands.
81
82 FLAGS
83 -h, --help Show help for command
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+152 -102
@@ -29,59 +29,75 @@ const connectedAccountsData = {
29 items: testConnectedAccounts,
30 } satisfies TestLiveInput['connectedAccountsData'];
31
32 +const incompleteConnectedAccountsData = {
33 + items: testConnectedAccounts,
34 + linkResponse: {
35 + connected_account_id: '',
36 + expires_at: '2026-12-31T23:59:59Z',
37 + link_token: 'lt_test_token',
38 + redirect_url: '',
39 + },
40 +} satisfies TestLiveInput['connectedAccountsData'];
41 +
42 const testConfigProvider = ConfigProvider.fromMap(
43 new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
44 ).pipe(extendConfigProvider);
45
46 describe('CLI: composio manage connected-accounts link', () => {
37 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
38 - '[Given] valid --auth-config and --user-id [Then] creates link and waits (default)',
39 - it => {
40 - it.scoped('creates link and waits for ACTIVE', () =>
41 - Effect.gen(function* () {
42 - yield* cli([
43 - 'manage',
44 - 'connected-accounts',
45 - 'link',
46 - '--auth-config',
47 - 'ac_gmail_oauth',
48 - '--user-id',
49 - 'default',
50 - '--no-browser',
51 - ]);
52 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
53 - const output = lines.join('\n');
47 + layer(
48 + TestLive({
49 + baseConfigProvider: testConfigProvider,
50 + connectedAccountsData,
51 + fixture: 'global-test-user-id',
52 + })
53 + )('[Given] valid --auth-config and --user-id [Then] creates link and waits (default)', it => {
54 + it.scoped('creates link and waits for ACTIVE', () =>
55 + Effect.gen(function* () {
56 + yield* cli([
57 + 'manage',
58 + 'connected-accounts',
59 + 'link',
60 + '--auth-config',
61 + 'ac_gmail_oauth',
62 + '--user-id',
63 + 'default',
64 + '--no-browser',
65 + ]);
66 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
67 + const output = lines.join('\n');
68
55 - expect(output).toContain('https://app.composio.dev/link?token=lt_test_token');
56 - expect(output).toContain('ACTIVE');
57 - })
58 - );
59 - }
60 - );
69 + expect(output).toContain('https://app.composio.dev/link?token=lt_test_token');
70 + expect(output).toContain('ACTIVE');
71 + })
72 + );
73 + });
74
62 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
63 - '[Given] valid --auth-config with explicit --user-id [Then] creates link',
64 - it => {
65 - it.scoped('uses explicit user-id', () =>
66 - Effect.gen(function* () {
67 - yield* cli([
68 - 'manage',
69 - 'connected-accounts',
70 - 'link',
71 - '--auth-config',
72 - 'ac_gmail_oauth',
73 - '--user-id',
74 - 'default',
75 - '--no-browser',
76 - ]);
77 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
78 - const output = lines.join('\n');
75 + layer(
76 + TestLive({
77 + baseConfigProvider: testConfigProvider,
78 + connectedAccountsData,
79 + fixture: 'global-test-user-id',
80 + })
81 + )('[Given] valid --auth-config with explicit --user-id [Then] creates link', it => {
82 + it.scoped('uses explicit user-id', () =>
83 + Effect.gen(function* () {
84 + yield* cli([
85 + 'manage',
86 + 'connected-accounts',
87 + 'link',
88 + '--auth-config',
89 + 'ac_gmail_oauth',
90 + '--user-id',
91 + 'default',
92 + '--no-browser',
93 + ]);
94 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
95 + const output = lines.join('\n');
96
80 - expect(output).toContain('https://app.composio.dev/link');
81 - })
82 - );
83 - }
84 - );
97 + expect(output).toContain('https://app.composio.dev/link');
98 + })
99 + );
100 + });
101
102 layer(
103 TestLive({
@@ -131,12 +147,81 @@ describe('CLI: composio manage connected-accounts link', () => {
147 );
148 });
149
134 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
135 - '[Given] composio link alias [Then] works like composio manage connected-accounts link',
150 + layer(
151 + TestLive({
152 + baseConfigProvider: testConfigProvider,
153 + connectedAccountsData,
154 + fixture: 'global-test-user-id',
155 + })
156 + )('[Given] composio link alias [Then] works like composio manage connected-accounts link', it => {
157 + it.scoped('root link works for consumer toolkit linking only', () =>
158 + Effect.gen(function* () {
159 + yield* cli(['link', 'gmail', '--no-browser']);
160 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
161 + const output = lines.join('\n');
162 +
163 + expect(output).toContain('https://app.composio.dev/link?token=lt_test_token');
164 + expect(output).toContain('ACTIVE');
165 + })
166 + );
167 + });
168 +
169 + layer(
170 + TestLive({
171 + baseConfigProvider: testConfigProvider,
172 + connectedAccountsData,
173 + fixture: 'global-test-user-id',
174 + })
175 + )('[Given] --no-wait [Then] outputs valid JSON parseable by jq', it => {
176 + it.scoped('prints JSON with status pending, connected_account_id, redirect_url', () =>
177 + Effect.gen(function* () {
178 + yield* cli([
179 + 'manage',
180 + 'connected-accounts',
181 + 'link',
182 + '--auth-config',
183 + 'ac_gmail_oauth',
184 + '--user-id',
185 + 'default',
186 + '--no-browser',
187 + '--no-wait',
188 + ]);
189 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
190 + const output = lines.join('\n');
191 +
192 + expect(output).toContain('"status"');
193 + expect(output).toContain('"pending"');
194 + expect(output).toContain('"message"');
195 + expect(output).toContain('"connected_account_id"');
196 + expect(output).toContain('con_test_link');
197 + expect(output).toContain('"redirect_url"');
198 + expect(output).toContain('https://app.composio.dev/link');
199 + // JSON is parseable
200 + const jsonMatch = output.match(/\{[\s\S]*"status"[\s\S]*\}/);
201 + expect(jsonMatch).toBeTruthy();
202 + if (jsonMatch) {
203 + const parsed = JSON.parse(jsonMatch[0]);
204 + expect(parsed.status).toBe('pending');
205 + expect(parsed.connected_account_id).toBe('con_test_link');
206 + }
207 + })
208 + );
209 + });
210 +
211 + layer(
212 + TestLive({
213 + baseConfigProvider: testConfigProvider,
214 + connectedAccountsData: incompleteConnectedAccountsData,
215 + fixture: 'global-test-user-id',
216 + })
217 + )(
218 + '[Given] auth-config link returns an incomplete response [Then] logs an error and exits early',
219 it => {
137 - it.scoped('alias expands to connected-accounts link', () =>
220 + it.scoped('reports the incomplete response instead of waiting with empty values', () =>
221 Effect.gen(function* () {
222 yield* cli([
223 + 'manage',
224 + 'connected-accounts',
225 'link',
226 '--auth-config',
227 'ac_gmail_oauth',
@@ -147,17 +232,24 @@ describe('CLI: composio manage connected-accounts link', () => {
232 const lines = yield* MockConsole.getLines({ stripAnsi: true });
233 const output = lines.join('\n');
234
150 - expect(output).toContain('https://app.composio.dev/link?token=lt_test_token');
151 - expect(output).toContain('ACTIVE');
235 + expect(output).toContain('The API returned an incomplete link response');
236 + expect(output).not.toContain('"status"');
237 + expect(output).not.toContain('Connection successful');
238 })
239 );
240 }
241 );
242
157 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
158 - '[Given] --no-wait [Then] outputs valid JSON parseable by jq',
159 - it => {
160 - it.scoped('prints JSON with status pending, connected_account_id, redirect_url', () =>
243 + layer(
244 + TestLive({
245 + baseConfigProvider: testConfigProvider,
246 + connectedAccountsData,
247 + fixture: 'global-test-user-id',
248 + })
249 + )('[Given] default (wait) [Then] waits for ACTIVE and outputs success JSON for jq', it => {
250 + it.scoped(
251 + 'prints JSON with status success, message, connected_account_id, toolkit, redirect_url',
252 + () =>
253 Effect.gen(function* () {
254 yield* cli([
255 'manage',
@@ -168,63 +260,21 @@ describe('CLI: composio manage connected-accounts link', () => {
260 '--user-id',
261 'default',
262 '--no-browser',
171 - '--no-wait',
263 ]);
264 const lines = yield* MockConsole.getLines({ stripAnsi: true });
265 const output = lines.join('\n');
266
267 expect(output).toContain('"status"');
177 - expect(output).toContain('"pending"');
268 + expect(output).toContain('"success"');
269 expect(output).toContain('"message"');
270 + expect(output).toContain('ACTIVE');
271 expect(output).toContain('"connected_account_id"');
272 expect(output).toContain('con_test_link');
273 + expect(output).toContain('"toolkit"');
274 + expect(output).toContain('"gmail"');
275 expect(output).toContain('"redirect_url"');
276 expect(output).toContain('https://app.composio.dev/link');
183 - // JSON is parseable
184 - const jsonMatch = output.match(/\{[\s\S]*"status"[\s\S]*\}/);
185 - expect(jsonMatch).toBeTruthy();
186 - if (jsonMatch) {
187 - const parsed = JSON.parse(jsonMatch[0]);
188 - expect(parsed.status).toBe('pending');
189 - expect(parsed.connected_account_id).toBe('con_test_link');
190 - }
277 })
192 - );
193 - }
194 - );
195 -
196 - layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
197 - '[Given] default (wait) [Then] waits for ACTIVE and outputs success JSON for jq',
198 - it => {
199 - it.scoped(
200 - 'prints JSON with status success, message, connected_account_id, toolkit, redirect_url',
201 - () =>
202 - Effect.gen(function* () {
203 - yield* cli([
204 - 'manage',
205 - 'connected-accounts',
206 - 'link',
207 - '--auth-config',
208 - 'ac_gmail_oauth',
209 - '--user-id',
210 - 'default',
211 - '--no-browser',
212 - ]);
213 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
214 - const output = lines.join('\n');
215 -
216 - expect(output).toContain('"status"');
217 - expect(output).toContain('"success"');
218 - expect(output).toContain('"message"');
219 - expect(output).toContain('ACTIVE');
220 - expect(output).toContain('"connected_account_id"');
221 - expect(output).toContain('con_test_link');
222 - expect(output).toContain('"toolkit"');
223 - expect(output).toContain('"gmail"');
224 - expect(output).toContain('"redirect_url"');
225 - expect(output).toContain('https://app.composio.dev/link');
226 - })
227 - );
228 - }
229 - );
278 + );
279 + });
280 });
ts/packages/cli/test/src/commands/orgs/orgs.switch.cmd.test.ts
+26 -51
@@ -26,72 +26,47 @@ describe('CLI: composio manage orgs switch', () => {
26 });
27
28 layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
29 - it.scoped('[When] no --org-id is provided [Then] lists orgs and projects with limit=50', () =>
30 - Effect.gen(function* () {
31 - const fetchSpy = vi
32 - .spyOn(globalThis, 'fetch')
33 - .mockResolvedValueOnce(
29 + it.scoped(
30 + '[When] no --org-id is provided [Then] lists orgs with limit=50 and stores org only',
31 + () =>
32 + Effect.gen(function* () {
33 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
34 mockFetchResponse({
35 organizations: [{ id: 'org_1', name: 'Org One' }],
36 })
37 - )
38 - .mockResolvedValueOnce(
39 - mockFetchResponse({
40 - data: [{ id: 'project_1', name: 'Project One' }],
41 - })
37 );
38
44 - yield* cli(['manage', 'orgs', 'switch']);
39 + yield* cli(['manage', 'orgs', 'switch']);
40
46 - expect(fetchSpy).toHaveBeenCalledTimes(2);
47 - const [orgUrl, orgRequest] = fetchSpy.mock.calls[0]!;
48 - expect(orgUrl).toContain('/api/v3/org/list?limit=50');
49 - expect((orgRequest as RequestInit).headers).toMatchObject({
50 - 'x-user-api-key': 'uak_test_key',
51 - });
41 + expect(fetchSpy).toHaveBeenCalledTimes(1);
42 + const [orgUrl, orgRequest] = fetchSpy.mock.calls[0]!;
43 + expect(orgUrl).toContain('/api/v3/org/list?limit=50');
44 + expect((orgRequest as RequestInit).headers).toMatchObject({
45 + 'x-user-api-key': 'uak_test_key',
46 + });
47
53 - const [projectUrl, projectRequest] = fetchSpy.mock.calls[1]!;
54 - expect(projectUrl).toContain('/api/v3/org/project/list?limit=50');
55 - expect((projectRequest as RequestInit).headers).toMatchObject({
56 - 'x-user-api-key': 'uak_test_key',
57 - 'x-org-id': 'org_1',
58 - });
59 -
60 - const fs = yield* FileSystem.FileSystem;
61 - const cacheDir = yield* setupCacheDir;
62 - const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
63 - const rawUserConfig = yield* fs.readFileString(userConfigPath, 'utf8');
64 - const userConfig = JSON.parse(rawUserConfig) as Record<string, unknown>;
65 - expect(userConfig.org_id).toBe('org_1');
66 - expect(userConfig.project_id).toBe('project_1');
48 + const fs = yield* FileSystem.FileSystem;
49 + const cacheDir = yield* setupCacheDir;
50 + const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
51 + const rawUserConfig = yield* fs.readFileString(userConfigPath, 'utf8');
52 + const userConfig = JSON.parse(rawUserConfig) as Record<string, unknown>;
53 + expect(userConfig.org_id).toBe('org_1');
54 + expect(userConfig.project_id).toBeUndefined();
55
68 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
69 - expect(output).toContain('Updated global defaults');
70 - })
56 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
57 + expect(output).toContain('Updated default org');
58 + })
59 );
60 });
61
62 layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
75 - it.scoped('[When] --org-id is provided [Then] skips org list and selects project', () =>
63 + it.scoped('[When] --org-id is provided [Then] skips org list and stores org only', () =>
64 Effect.gen(function* () {
77 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
78 - mockFetchResponse({
79 - data: [
80 - { id: 'project_1', name: 'Project One' },
81 - { id: 'project_2', name: 'Project Two' },
82 - ],
83 - })
84 - );
65 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
66
67 yield* cli(['manage', 'orgs', 'switch', '--org-id', 'org_manual']);
68
88 - expect(fetchSpy).toHaveBeenCalledTimes(1);
89 - const [projectUrl, projectRequest] = fetchSpy.mock.calls[0]!;
90 - expect(projectUrl).toContain('/api/v3/org/project/list?limit=50');
91 - expect((projectRequest as RequestInit).headers).toMatchObject({
92 - 'x-user-api-key': 'uak_test_key',
93 - 'x-org-id': 'org_manual',
94 - });
69 + expect(fetchSpy).toHaveBeenCalledTimes(0);
70
71 const fs = yield* FileSystem.FileSystem;
72 const cacheDir = yield* setupCacheDir;
@@ -99,7 +74,7 @@ describe('CLI: composio manage orgs switch', () => {
74 const rawUserConfig = yield* fs.readFileString(userConfigPath, 'utf8');
75 const userConfig = JSON.parse(rawUserConfig) as Record<string, unknown>;
76 expect(userConfig.org_id).toBe('org_manual');
102 - expect(userConfig.project_id).toBe('project_1');
77 + expect(userConfig.project_id).toBeUndefined();
78 })
79 );
80 });
ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts
+4 -6
@@ -15,7 +15,7 @@ describe('CLI: composio manage projects list', () => {
15 });
16
17 layer(TestLive({ fixture: 'user-config-with-global-context' }))(it => {
18 - it.scoped('[Then] lists projects, marks selected global project, and shows switch hints', () =>
18 + it.scoped('[Then] lists developer projects and shows init guidance', () =>
19 Effect.gen(function* () {
20 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
21 mockFetchResponse({
@@ -38,14 +38,12 @@ describe('CLI: composio manage projects list', () => {
38
39 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
40 expect(output).toContain('Loaded 2 projects');
41 - expect(output).toContain('✓ Project One (project_1)');
41 + expect(output).toContain(' Project One (project_1)');
42 expect(output).toContain(' Project Two (project_2)');
43 expect(output).toContain(
44 - 'Hint: run `composio manage projects switch` to switch the default global project.'
45 - );
46 - expect(output).toContain(
47 - 'Run `composio manage orgs switch` to switch org and project together.'
44 + 'Hint: run `composio init` in a directory to bind it to a developer project.'
45 );
46 + expect(output).toContain('Run `composio manage orgs switch` to change your default org.');
47 })
48 );
49 });
ts/packages/cli/test/src/commands/projects/projects.switch.cmd.test.ts
+9 -60
@@ -1,67 +1,16 @@
1 -import path from 'node:path';
2 -import { ConfigProvider, Effect } from 'effect';
1 +import { Effect } from 'effect';
2 import { describe, expect, layer } from '@effect/vitest';
4 -import { afterEach, vi } from 'vitest';
5 -import { FileSystem } from '@effect/platform';
3 import { cli, MockConsole, TestLive } from 'test/__utils__';
7 -import * as constants from 'src/constants';
8 -import { setupCacheDir } from 'src/effects/setup-cache-dir';
9 -
10 -const testConfigProvider = ConfigProvider.fromMap(
11 - new Map([
12 - ['COMPOSIO_USER_API_KEY', 'uak_test_key'],
13 - ['USER_API_KEY', 'uak_test_key'],
14 - ])
15 -);
16 -
17 -const mockFetchResponse = (body: unknown, status = 200) =>
18 - new Response(JSON.stringify(body), {
19 - status,
20 - headers: { 'Content-Type': 'application/json' },
21 - });
4
5 describe('CLI: composio manage projects switch', () => {
24 - afterEach(() => {
25 - vi.restoreAllMocks();
26 - });
27 -
28 - layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
29 - it.scoped(
30 - '[When] --org-id is provided [Then] it switches global project and shows org hint',
31 - () =>
32 - Effect.gen(function* () {
33 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
34 - mockFetchResponse({
35 - data: [
36 - { id: 'project_1', name: 'Project One' },
37 - { id: 'project_2', name: 'Project Two' },
38 - ],
39 - })
40 - );
41 -
42 - yield* cli(['manage', 'projects', 'switch', '--org-id', 'org_manual']);
43 -
44 - expect(fetchSpy).toHaveBeenCalledTimes(1);
45 - const [projectUrl, projectRequest] = fetchSpy.mock.calls[0]!;
46 - expect(projectUrl).toContain('/api/v3/org/project/list?limit=50');
47 - expect((projectRequest as RequestInit).headers).toMatchObject({
48 - 'x-user-api-key': 'uak_test_key',
49 - 'x-org-id': 'org_manual',
50 - });
51 -
52 - const fs = yield* FileSystem.FileSystem;
53 - const cacheDir = yield* setupCacheDir;
54 - const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
55 - const rawUserConfig = yield* fs.readFileString(userConfigPath, 'utf8');
56 - const userConfig = JSON.parse(rawUserConfig) as Record<string, unknown>;
57 - expect(userConfig.org_id).toBe('org_manual');
58 - expect(userConfig.project_id).toBe('project_1');
59 -
60 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
61 - expect(output).toContain(
62 - 'To switch organization as well, run `composio manage orgs switch`.'
63 - );
64 - })
6 + layer(TestLive())(it => {
7 + it.scoped('[Then] it reports global developer project switching is deprecated', () =>
8 + Effect.gen(function* () {
9 + yield* cli(['manage', 'projects', 'switch']).pipe(Effect.catchAll(() => Effect.void));
10 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
11 + expect(output).toContain('Global developer project switching is no longer supported');
12 + expect(output).toContain('composio init');
13 + })
14 );
15 });
16 });
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+25 -24
@@ -45,6 +45,7 @@ describe('CLI: composio manage tools execute', () => {
45 layer(
46 TestLive({
47 baseConfigProvider: testConfigProvider,
48 + fixture: 'global-test-user-id',
49 stdin: { isTTY: true, data: '' },
50 })
51 )('[Given] -d inline JSON [Then] executes via Tool Router with defaults', it => {
@@ -75,19 +76,13 @@ describe('CLI: composio manage tools execute', () => {
76 layer(
77 TestLive({
78 baseConfigProvider: testConfigProvider,
79 + fixture: 'global-test-user-id',
80 stdin: { isTTY: true, data: '' },
81 })
82 )('[Given] composio execute alias [Then] works like composio manage tools execute', it => {
81 - it.scoped('alias expands to tools execute', () =>
83 + it.scoped('root execute works for consumer flow without developer-only flags', () =>
84 Effect.gen(function* () {
83 - yield* cli([
84 - 'execute',
85 - 'GMAIL_SEND_EMAIL',
86 - '--user-id',
87 - 'default',
88 - '-d',
89 - '{"recipient":"a"}',
90 - ]);
85 + yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
86 const lines = yield* MockConsole.getLines({ stripAnsi: true });
87 const output = parseLastJson(lines);
88
@@ -107,7 +102,7 @@ describe('CLI: composio manage tools execute', () => {
102 )(
103 '[Given] no --user-id and no project test_user_id [Then] falls back to global test_user_id',
104 it => {
110 - it.scoped('uses global test user id from user_data.json', () =>
105 + it.scoped('executes without printing global test user diagnostics', () =>
106 Effect.gen(function* () {
107 yield* cli(['manage', 'tools', 'execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
108 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -116,7 +111,7 @@ describe('CLI: composio manage tools execute', () => {
111
112 expect(output.successful).toBe(true);
113 expect(output.data.tool_slug).toBe('GMAIL_SEND_EMAIL');
119 - expect(text).toContain('Using global test user id "global-default"');
114 + expect(text).not.toContain('Using global test user id');
115 })
116 );
117 }
@@ -198,24 +193,15 @@ describe('CLI: composio manage tools execute', () => {
193 stdin: { isTTY: true, data: '' },
194 })
195 )('[Given] execute-help with options before slug [Then] resolves correct slug', it => {
201 - it.scoped('does not treat --user-id value as slug', () =>
196 + it.scoped('resolves root execute help slug correctly', () =>
197 Effect.gen(function* () {
203 - yield* cli([
204 - 'manage',
205 - 'tools',
206 - 'execute',
207 - '--user-id',
208 - 'default',
209 - 'GMAIL_SEND_EMAIL',
210 - '--help',
211 - ]);
198 + yield* cli(['execute', 'GMAIL_SEND_EMAIL', '--help']);
199 const lines = yield* MockConsole.getLines({ stripAnsi: true });
200 const output = lines.join('\n');
201
202 expect(output).toContain('Slug: GMAIL_SEND_EMAIL');
203 expect(output).toContain('Data Parameters:');
204 expect(output).toContain('recipient');
218 - expect(output).not.toContain('default');
205 })
206 );
207 });
@@ -223,6 +209,7 @@ describe('CLI: composio manage tools execute', () => {
209 layer(
210 TestLive({
211 baseConfigProvider: testConfigProvider,
212 + fixture: 'global-test-user-id',
213 stdin: { isTTY: false, data: '{"owner":"composio"}' },
214 })
215 )('[Given] stdin is piped [Then] reads input from stdin', it => {
@@ -242,6 +229,7 @@ describe('CLI: composio manage tools execute', () => {
229 layer(
230 TestLive({
231 baseConfigProvider: testConfigProvider,
232 + fixture: 'global-test-user-id',
233 stdin: { isTTY: true, data: '' },
234 toolsExecutor: {
235 failWith: new ActionExecuteConnectedAccountNotFoundError({
@@ -268,7 +256,9 @@ describe('CLI: composio manage tools execute', () => {
256
257 expect(output).toContain('No connected account found');
258 expect(output).toContain('Tips');
271 - expect(output).toContain('composio manage connected-accounts link');
259 + expect(output).toContain(
260 + 'composio manage connected-accounts link gmail --user-id "<user-id>"'
261 + );
262 })
263 );
264 });
@@ -278,6 +268,7 @@ describe('CLI: composio manage tools execute', () => {
268 layer(
269 TestLive({
270 baseConfigProvider: testConfigProvider,
271 + fixture: 'global-test-user-id',
272 stdin: { isTTY: true, data: '' },
273 toolRouter: {
274 execute: async () => {
@@ -311,7 +302,9 @@ describe('CLI: composio manage tools execute', () => {
302
303 expect(output).toContain('No active connection');
304 expect(output).toContain('Tips');
314 - expect(output).toContain('composio manage connected-accounts link gmail');
305 + expect(output).toContain(
306 + 'composio manage connected-accounts link gmail --user-id "<user-id>"'
307 + );
308 })
309 );
310 });
@@ -319,6 +312,7 @@ describe('CLI: composio manage tools execute', () => {
312 layer(
313 TestLive({
314 baseConfigProvider: testConfigProvider,
315 + fixture: 'global-test-user-id',
316 stdin: { isTTY: true, data: '' },
317 toolRouter: {
318 execute: async (_sessionId, params) => ({
@@ -355,6 +349,7 @@ describe('CLI: composio manage tools execute', () => {
349 layer(
350 TestLive({
351 baseConfigProvider: testConfigProvider,
352 + fixture: 'global-test-user-id',
353 stdin: { isTTY: true, data: '' },
354 toolsExecutor: {
355 failWith: {
@@ -388,6 +383,7 @@ describe('CLI: composio manage tools execute', () => {
383 layer(
384 TestLive({
385 baseConfigProvider: testConfigProvider,
386 + fixture: 'global-test-user-id',
387 stdin: { isTTY: true, data: '' },
388 toolsExecutor: {
389 failWith: { error: { message: 'API error: invalid input' } },
@@ -420,6 +416,7 @@ describe('CLI: composio manage tools execute', () => {
416 layer(
417 TestLive({
418 baseConfigProvider: testConfigProvider,
419 + fixture: 'global-test-user-id',
420 stdin: { isTTY: true, data: '' },
421 toolsExecutor: {
422 respondWith: {
@@ -460,6 +457,7 @@ describe('CLI: composio manage tools execute', () => {
457 layer(
458 TestLive({
459 baseConfigProvider: testConfigProvider,
460 + fixture: 'global-test-user-id',
461 stdin: { isTTY: true, data: '' },
462 toolsExecutor: {
463 respondWith: {
@@ -501,6 +499,7 @@ describe('CLI: composio manage tools execute', () => {
499 layer(
500 TestLive({
501 baseConfigProvider: testConfigProvider,
502 + fixture: 'global-test-user-id',
503 stdin: { isTTY: true, data: '' },
504 toolsExecutor: {
505 failWith: new ActionExecuteConnectedAccountNotFoundError({
@@ -618,6 +617,7 @@ describe('CLI: composio manage tools execute', () => {
617 layer(
618 TestLive({
619 baseConfigProvider: testConfigProvider,
620 + fixture: 'global-test-user-id',
621 stdin: { isTTY: true, data: '' },
622 toolsExecutor: {
623 respondWith: {
@@ -671,6 +671,7 @@ describe('CLI: composio manage tools execute', () => {
671 layer(
672 TestLive({
673 baseConfigProvider: testConfigProvider,
674 + fixture: 'global-test-user-id',
675 stdin: { isTTY: true, data: '' },
676 toolsExecutor: {
677 respondWith: {
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+32 -23
@@ -119,8 +119,8 @@ describe('CLI: composio manage tools search', () => {
119 expect(output).toContain('"CTA"');
120 expect(output).toContain('"Execute a tool"');
121 expect(output).toContain('"Connect a user account"');
122 - expect(output).toContain('composio execute');
123 - expect(output).toContain('composio link gmail');
122 + expect(output).toContain('composio manage tools execute');
123 + expect(output).toContain('composio manage connected-accounts link gmail');
124 })
125 );
126 }
@@ -168,12 +168,16 @@ describe('CLI: composio manage tools search', () => {
168
169 const executeCta = cta.find(c => c.action === 'Execute a tool');
170 expect(executeCta).toBeTruthy();
171 - expect(executeCta!.command).toContain('composio execute "GMAIL_SEND_EMAIL"');
171 + expect(executeCta!.command).toContain(
172 + 'composio manage tools execute "GMAIL_SEND_EMAIL" --user-id "<user-id>"'
173 + );
174 expect(executeCta!.command).toMatch(/-d '\{"to":"","subject":"","body":""\}'/);
175
176 const linkCta = cta.find(c => c.action === 'Connect a user account');
177 expect(linkCta).toBeTruthy();
176 - expect(linkCta!.command).toBe('composio link gmail');
178 + expect(linkCta!.command).toBe(
179 + 'composio manage connected-accounts link gmail --user-id "<user-id>"'
180 + );
181 })
182 );
183 }
@@ -345,9 +349,11 @@ describe('CLI: composio manage tools search', () => {
349 expect(output).toContain('Plan:');
350 expect(output).toContain('1. Collect recipient details');
351 expect(output).toContain('Hints:');
348 - expect(output).toContain('composio manage tools info "GMAIL_SEND_EMAIL"');
352 expect(output).toContain(
350 - `composio manage tools execute "GMAIL_SEND_EMAIL" --user-id "<user-id>" --arguments '{}'`
353 + `composio manage tools execute "GMAIL_SEND_EMAIL" --user-id "<user-id>" -d "{}"`
354 + );
355 + expect(output).toContain(
356 + `composio manage connected-accounts link <toolkit> --user-id "<user-id>"`
357 );
358 })
359 );
@@ -367,9 +373,9 @@ describe('CLI: composio manage tools search', () => {
373 });
374
375 layer(TestLive(testLiveOptions))(
370 - '[Given] explicit --user-id [Then] uses that user id for session',
376 + '[Given] consumer search with explicit --user-id [Then] it still uses resolved consumer user id',
377 it => {
372 - it.scoped('passes user-id to session create', () =>
378 + it.scoped('uses consumer user id from the resolved project context', () =>
379 Effect.gen(function* () {
380 let createParams: SessionCreateParams | undefined;
381 const live = TestLive({
@@ -391,27 +397,30 @@ describe('CLI: composio manage tools search', () => {
397 Effect.provide(live)
398 );
399
394 - expect(createParams?.user_id).toBe('alice');
400 + expect(createParams?.user_id).toBe('consumer-user-org_test');
401 })
402 );
403 }
404 );
405
400 - layer(TestLive({ baseConfigProvider: testConfigProvider }))(
401 - '[Given] no test_user_id and no --user-id [Then] fails with missing user id message',
402 - it => {
403 - it.scoped('fails when user id cannot be resolved', () =>
404 - Effect.gen(function* () {
405 - const err = yield* cli(['manage', 'tools', 'search', 'send']).pipe(Effect.flip);
406 - const message = err instanceof Error ? err.message : String(err);
406 + layer(
407 + TestLive({
408 + baseConfigProvider: testConfigProvider,
409 + fixture: 'user-config-with-global-context',
410 + toolkitsData,
411 + })
412 + )('[Given] no explicit --user-id [Then] consumer search does not require one', it => {
413 + it.scoped('runs without printing global test user diagnostics', () =>
414 + Effect.gen(function* () {
415 + yield* cli(['manage', 'tools', 'search', 'send']);
416 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
417 + const output = lines.join('\n');
418
408 - expect(message).toContain('Missing user id');
409 - expect(message).toContain('--user-id');
410 - expect(message).toContain('composio init');
411 - })
412 - );
413 - }
414 - );
419 + expect(output).toContain('Found 2 tools');
420 + expect(output).not.toContain('Using global test user id');
421 + })
422 + );
423 + });
424
425 layer(TestLive(testLiveOptions))(
426 '[Given] composio search alias [Then] works like composio manage tools search',
ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts
+5
@@ -110,6 +110,7 @@ describe('CLI: composio manage triggers listen', () => {
110 layer(
111 TestLive({
112 baseConfigProvider: testConfigProvider,
113 + fixture: 'global-test-user-id',
114 realtimeData: {
115 events: [mockV3TriggerEvent],
116 },
@@ -133,6 +134,7 @@ describe('CLI: composio manage triggers listen', () => {
134 layer(
135 TestLive({
136 baseConfigProvider: testConfigProvider,
137 + fixture: 'global-test-user-id',
138 realtimeData: {
139 events: [mockV3TriggerEvent],
140 },
@@ -154,6 +156,7 @@ describe('CLI: composio manage triggers listen', () => {
156 layer(
157 TestLive({
158 baseConfigProvider: testConfigProvider,
159 + fixture: 'global-test-user-id',
160 realtimeData: {
161 events: [mockV3TriggerEvent],
162 },
@@ -196,6 +199,7 @@ describe('CLI: composio manage triggers listen', () => {
199 layer(
200 TestLive({
201 baseConfigProvider: testConfigProvider,
202 + fixture: 'global-test-user-id',
203 realtimeData: { events: [mockV3TriggerEvent] },
204 })
205 )(
@@ -226,6 +230,7 @@ describe('CLI: composio manage triggers listen', () => {
230 layer(
231 TestLive({
232 baseConfigProvider: testConfigProvider,
233 + fixture: 'global-test-user-id',
234 realtimeData: { events: [mockV3TriggerEvent] },
235 })
236 )('[Given] --forward [Then] sends signed webhook verifiable by composio/core', it => {
ts/packages/cli/test/src/commands/whoami.cmd.test.ts
-2
@@ -19,7 +19,6 @@ describe('CLI: composio whoami', () => {
19 expect(output).not.toContain(`api_key_from_test_config_provider`);
20 expect(output).not.toContain(`global_user_api_key`);
21 expect(output).toContain(`"default_org_id":null`);
22 - expect(output).toContain(`"default_project_id":null`);
22 expect(output).toContain(`"test_user_id":null`);
23 })
24 );
@@ -36,7 +35,6 @@ describe('CLI: composio whoami', () => {
35 expect(output).not.toContain(`api_key_from_test_fixture`);
36 expect(output).not.toContain(`global_user_api_key`);
37 expect(output).toContain(`"default_org_id":null`);
39 - expect(output).toContain(`"default_project_id":null`);
38 expect(output).toContain(`"test_user_id":null`);
39 })
40 );
ts/packages/cli/test/src/services/test-layer.test.ts new
+24
@@ -0,0 +1,24 @@
1 +import { describe, expect, it, vi } from 'vitest';
2 +import { Effect } from 'effect';
3 +import { TestLive } from 'test/__utils__';
4 +
5 +describe('TestLayer', () => {
6 + it('restores globalThis.fetch after the layer scope closes', async () => {
7 + const originalFetch = globalThis.fetch;
8 +
9 + await Effect.provide(Effect.void, TestLive()).pipe(Effect.scoped, Effect.runPromise);
10 +
11 + expect(globalThis.fetch).toBe(originalFetch);
12 + });
13 +
14 + it('does not leak the fetch mock into later spy restore cycles', async () => {
15 + const originalFetch = globalThis.fetch;
16 +
17 + await Effect.provide(Effect.void, TestLive()).pipe(Effect.scoped, Effect.runPromise);
18 +
19 + vi.spyOn(globalThis, 'fetch');
20 + vi.restoreAllMocks();
21 +
22 + expect(globalThis.fetch).toBe(originalFetch);
23 + });
24 +});
ts/packages/cli/vitest.config.ts
+5
@@ -3,6 +3,8 @@ import path from 'node:path';
3
4 const __dirname = path.resolve(path.dirname(new URL(import.meta.url).pathname));
5 const coreDir = path.resolve(__dirname, '../core');
6 +const tsBuildersDir = path.resolve(__dirname, '../ts-builders');
7 +const jsonSchemaToZodDir = path.resolve(__dirname, '../json-schema-to-zod');
8
9 export default defineConfig({
10 resolve: {
@@ -10,6 +12,9 @@ export default defineConfig({
12 '~': path.resolve(__dirname, './'),
13 src: path.resolve(__dirname, './src'),
14 test: path.resolve(__dirname, './test'),
15 + '@composio/core': path.join(coreDir, 'src/index.ts'),
16 + '@composio/ts-builders': path.join(tsBuildersDir, 'src/index.ts'),
17 + '@composio/json-schema-to-zod': path.join(jsonSchemaToZodDir, 'src/index.ts'),
18 'effect-errors/*': path.resolve(__dirname, './src/effect-errors'),
19 // @composio/core uses package.json "imports" (#config_defaults, #platform, etc.)
20 // Vitest/Vite does not resolve these for workspace deps, so alias them explicitly
ts/packages/core/package.json
+1 -1
@@ -131,7 +131,7 @@
131 ],
132 "scripts": {
133 "clean": "git clean -xdf node_modules",
134 - "build": "bun run --bun tsdown",
134 + "build": "pnpm exec tsdown",
135 "test": "vitest run",
136 "typecheck": "tsc --noEmit --skipLibCheck && tsc --noEmit --skipLibCheck -p tsconfig.type-tests.json",
137 "generate:docs": "tsx scripts/generate-docs.ts"
ts/packages/json-schema-to-zod/package.json
+1 -1
@@ -30,7 +30,7 @@
30 ],
31 "scripts": {
32 "clean": "git clean -xdf node_modules",
33 - "build": "bun run --bun tsdown",
33 + "build": "pnpm exec tsdown",
34 "test": "vitest run",
35 "typecheck:src": "tsc --noEmit -p ./tsconfig.src.json",
36 "typecheck:test": "tsc --noEmit -p ./tsconfig.test.json",
ts/packages/providers/anthropic/package.json
+1 -1
@@ -30,7 +30,7 @@
30 ],
31 "scripts": {
32 "clean": "git clean -xdf node_modules",
33 - "build": "bun run --bun tsdown",
33 + "build": "pnpm exec tsdown",
34 "test": "vitest run"
35 },
36 "keywords": [
ts/packages/providers/claude-agent-sdk/package.json
+1 -1
@@ -30,7 +30,7 @@
30 ],
31 "scripts": {
32 "clean": "git clean -xdf node_modules",
33 - "build": "bun run --bun tsdown",
33 + "build": "pnpm exec tsdown",
34 "test": "vitest run"
35 },
36 "keywords": [
ts/packages/providers/cloudflare/package.json
+1 -1
@@ -30,7 +30,7 @@
30 ],
31 "scripts": {
32 "clean": "git clean -xdf node_modules",
33 - "build": "bun run --bun tsdown",
33 + "build": "pnpm exec tsdown",
34 "test": "vitest run"
35 },
36 "keywords": [],
ts/packages/providers/google/package.json
+1 -1
@@ -30,7 +30,7 @@
30 ],
31 "scripts": {
32 "clean": "git clean -xdf node_modules",
33 - "build": "bun run --bun tsdown",
33 + "build": "pnpm exec tsdown",
34 "test": "vitest run"
35 },
36 "keywords": [
ts/packages/providers/langchain/package.json
+1 -1
@@ -30,7 +30,7 @@
30 ],
31 "scripts": {
32 "clean": "git clean -xdf node_modules",
33 - "build": "bun run --bun tsdown",
33 + "build": "pnpm exec tsdown",
34 "test": "vitest run"
35 },
36 "keywords": [],
ts/packages/providers/llamaindex/package.json
+1 -1
@@ -29,7 +29,7 @@
29 "dist"
30 ],
31 "scripts": {
32 - "build": "bun run --bun tsdown",
32 + "build": "pnpm exec tsdown",
33 "test": "vitest run"
34 },
35 "keywords": [
ts/packages/providers/mastra/package.json
+1 -1
@@ -30,7 +30,7 @@
30 ],
31 "scripts": {
32 "clean": "git clean -xdf node_modules",
33 - "build": "bun run --bun tsdown",
33 + "build": "pnpm exec tsdown",
34 "test": "vitest run",
35 "typecheck": "tsc --noEmit --skipLibCheck"
36 },
ts/packages/providers/openai-agents/package.json
+1 -1
@@ -30,7 +30,7 @@
30 ],
31 "scripts": {
32 "clean": "git clean -xdf node_modules",
33 - "build": "bun run --bun tsdown",
33 + "build": "pnpm exec tsdown",
34 "test": "vitest run"
35 },
36 "keywords": [],
ts/packages/providers/openai/package.json
+1 -1
@@ -30,7 +30,7 @@
30 ],
31 "scripts": {
32 "clean": "git clean -xdf node_modules",
33 - "build": "bun run --bun tsdown",
33 + "build": "pnpm exec tsdown",
34 "test": "vitest run"
35 },
36 "keywords": [],
ts/packages/providers/vercel/package.json
+1 -1
@@ -30,7 +30,7 @@
30 ],
31 "scripts": {
32 "clean": "git clean -xdf node_modules",
33 - "build": "bun run --bun tsdown",
33 + "build": "pnpm exec tsdown",
34 "test": "vitest run"
35 },
36 "keywords": [],
ts/packages/ts-builders/package.json
+1 -1
@@ -35,7 +35,7 @@
35 },
36 "scripts": {
37 "clean": "git clean -xdf node_modules",
38 - "build": "bun run --bun tsdown",
38 + "build": "pnpm exec tsdown",
39 "test": "vitest run"
40 },
41 "files": [
tsdown.config.base.ts
+5 -1
@@ -1,5 +1,9 @@
1 import type { UserConfig, OutExtensionContext } from 'tsdown';
2
3 +// Turbo task execution triggers a tsdown ATTW tarball path bug for scoped packages.
4 +// Keep ATTW for direct package builds, but disable it for workspace builds.
5 +const isTurboTask = Boolean(process.env.TURBO_HASH);
6 +
7 /**
8 * tsdown config with shared defaults.
9 * Package-specific options (e.g., entry, outDir, outExtensions) can be overridden by the caller.
@@ -77,7 +81,7 @@ export const baseConfig = {
81 */
82 attw: {
83 entrypoints: ['.'],
80 - enabled: true,
84 + enabled: !isTurboTask,
85 level: 'error',
86 profile: 'node16',
87 ignoreRules: [/* Node.js 10 only, attw doesn't automatically exclude it despite the selected profile */ 'internal-resolution-error'],