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

next
ts 168 lines 5.9 KB
Raw
1 import { Effect, Match } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 import {
4 CONNECTED_ACCOUNTS_SHAPE_MESSAGE,
5 decodeAllConnectedAccountPages,
6 } from 'src/effects/decode-connected-account-list';
7 import { failedWith } from 'src/effects/request-error';
8 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
9 import { ComposioClientSingleton } from 'src/services/composio-clients';
10 import { actingUser } from 'src/commands/surface';
11 import { TerminalUI } from 'src/services/terminal-ui';
12 import { bold } from 'src/ui/colors';
13 import { redact } from 'src/ui/redact';
14 import { listAllConnectedAccounts } from 'src/services/list-all-connected-accounts';
15 import { ConnectionsRemovalRequestError } from './connections.remove.errors';
16
17 /** The flags of `composio connections remove`. */
18 export type ConnectionsRemoveParams = {
19 readonly account: string;
20 readonly yes: boolean;
21 };
22
23 const invalidInput = commandInputError('connections remove');
24
25 /** Without a terminal to confirm on, removing needs `--yes`. */
26 const NEEDS_YES_MESSAGE =
27 '`composio connections remove` needs --yes when not running interactively.';
28
29 const normalizeSelector = (value: string): string => value.trim().toLowerCase();
30
31 const selectorMatches = (item: ConnectedAccountItem, selector: string): boolean => {
32 const normalized = normalizeSelector(selector);
33 return (
34 normalizeSelector(item.id) === normalized ||
35 normalizeSelector(item.alias ?? '') === normalized ||
36 normalizeSelector(item.word_id ?? '') === normalized ||
37 normalizeSelector(item.toolkit.slug) === normalized
38 );
39 };
40
41 const formatAccountSummary = (item: ConnectedAccountItem): string =>
42 [
43 `${bold('Toolkit:')} ${item.toolkit.slug}`,
44 `${bold('Alias:')} ${item.alias || '-'}`,
45 `${bold('Word Id:')} ${item.word_id || '-'}`,
46 `${bold('Connected Account:')} ${redact({ value: item.id, prefix: 'con_' })}`,
47 `${bold('Status:')} ${item.status}`,
48 ].join('\n');
49
50 const formatAccountChoice = (item: ConnectedAccountItem): string => {
51 const labels = [item.alias, item.word_id].filter(
52 (value): value is string => typeof value === 'string' && value.trim().length > 0
53 );
54 const selectors = labels.length > 0 ? ` (${labels.join(' / ')})` : '';
55 return `${item.toolkit.slug}${selectors}: ${redact({ value: item.id, prefix: 'con_' })}`;
56 };
57
58 const resolveAccount = (params: {
59 readonly accounts: ReadonlyArray<ConnectedAccountItem>;
60 readonly selector: string;
61 }): ConnectedAccountItem | { readonly error: string } => {
62 const matches = params.accounts.filter(item => selectorMatches(item, params.selector));
63
64 if (matches.length === 0) {
65 return {
66 error: `No connection matched "${params.selector}". Run \`composio connections list\` to inspect available connections.`,
67 };
68 }
69
70 const idMatches = matches.filter(
71 item => normalizeSelector(item.id) === normalizeSelector(params.selector)
72 );
73 const idMatch = idMatches[0];
74 if (idMatch && idMatches.length === 1) {
75 return idMatch;
76 }
77
78 const match = matches[0];
79 if (match && matches.length === 1) {
80 return match;
81 }
82
83 return {
84 error: [
85 `Multiple connections matched "${params.selector}". Use a unique alias, word_id, or connected account ID.`,
86 '',
87 ...matches.map(item => `- ${formatAccountChoice(item)}`),
88 ].join('\n'),
89 };
90 };
91
92 /**
93 * Removes one connection after a confirmation. Without a terminal to confirm on, it needs `--yes`
94 * and otherwise fails with a `CommandInputError` before any request; declining the prompt removes
95 * nothing and exits 0.
96 */
97 export const runConnectionsRemove = ({ account, yes }: ConnectionsRemoveParams) =>
98 Effect.gen(function* () {
99 const ui = yield* TerminalUI;
100 const { canPrompt } = yield* ui.capabilities;
101 if (!yes && !canPrompt) {
102 return yield* invalidInput(NEEDS_YES_MESSAGE, '--yes');
103 }
104 const clientSingleton = yield* ComposioClientSingleton;
105 const { userId: consumerUserId, project: resolvedProject } = yield* actingUser();
106
107 const client = yield* clientSingleton.getFor({
108 orgId: resolvedProject.orgId,
109 projectId: resolvedProject.projectId,
110 });
111 const rawItems = yield* ui.withSpinner(
112 'Fetching connections...',
113 listAllConnectedAccounts(client, { user_ids: [consumerUserId] }).pipe(
114 Effect.mapError(
115 cause =>
116 new ConnectionsRemovalRequestError({
117 message: Match.value(cause).pipe(
118 Match.tag(
119 'effects/ConnectedAccountListShapeError',
120 () => CONNECTED_ACCOUNTS_SHAPE_MESSAGE
121 ),
122 Match.orElse(() => 'Failed to list connections.')
123 ),
124 cause,
125 })
126 )
127 )
128 );
129 const accounts = yield* decodeAllConnectedAccountPages(rawItems).pipe(
130 failedWith(ConnectionsRemovalRequestError, CONNECTED_ACCOUNTS_SHAPE_MESSAGE)
131 );
132 const resolved = resolveAccount({ accounts, selector: account });
133
134 if ('error' in resolved) {
135 return yield* invalidInput(resolved.error, '<account>');
136 }
137
138 yield* ui.note(
139 `${formatAccountSummary(resolved)}\n\nThis will remove the connection from Composio and tools will no longer be able to use it.`,
140 'Remove Connection'
141 );
142
143 const confirmed =
144 yes ||
145 (yield* ui.confirm(`Remove ${resolved.toolkit.slug} connection?`, {
146 defaultValue: false,
147 }));
148 if (!confirmed) {
149 yield* ui.log.warn('No connection removed.');
150 return;
151 }
152
153 yield* ui.withSpinner(
154 `Removing ${resolved.toolkit.slug} connection...`,
155 client.connectedAccounts
156 .delete(resolved.id)
157 .pipe(
158 failedWith(
159 ConnectionsRemovalRequestError,
160 `Failed to remove connected account "${resolved.id}".`
161 )
162 ),
163 {
164 successMessage: `Removed ${resolved.toolkit.slug} connection.`,
165 errorMessage: `Failed to remove ${resolved.toolkit.slug} connection.`,
166 }
167 );
168 });