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 282 lines 11.3 KB
Raw
1 import type { ComposioClientShape } from '@composio/client/effect';
2 import { Data, Effect, Option, Schema } from 'effect';
3 import { ExpectedFailure } from 'src/effects/expected-failure';
4 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
5 import { decodeConnectedAccountItems } from 'src/effects/decode-connected-account-list';
6 import type { TerminalUI } from 'src/services/terminal-ui';
7 import { memoizeInProcess } from 'src/utils/memoize-in-process';
8 import { clientScopeKey } from 'src/services/composio-clients';
9 import { listAllConnectedAccounts } from 'src/services/list-all-connected-accounts';
10
11 // `status` is an open enum, so this is shape-identical to
12 // `ConnectedAccountItem`; tool-router rows normalize statuses outside the
13 // known set to an `'UNKNOWN'` sentinel. Selection only picks `'ACTIVE'`, so
14 // unknown rows still drop out — but without falsely labeling them
15 // `'INACTIVE'` (= user-disabled).
16 export type SelectableConnectedAccount = ConnectedAccountItem;
17
18 export const CachedConnectedAccountSummarySchema = Schema.Struct({
19 id: Schema.String,
20 alias: Schema.NullOr(Schema.String),
21 wordId: Schema.NullOr(Schema.String),
22 updatedAt: Schema.String,
23 createdAt: Schema.String,
24 });
25 export type CachedConnectedAccountSummary = typeof CachedConnectedAccountSummarySchema.Type;
26
27 const normalizeSelector = (value: string): string => value.trim().toLowerCase();
28
29 const parseTimestamp = (value: string | null | undefined): number => {
30 if (!value) return 0;
31 const parsed = Date.parse(value);
32 return Number.isFinite(parsed) ? parsed : 0;
33 };
34
35 export const compareNewestFirst = (
36 left: { readonly updated_at?: string | null; readonly created_at?: string | null },
37 right: { readonly updated_at?: string | null; readonly created_at?: string | null }
38 ): number =>
39 Math.max(parseTimestamp(right.updated_at), parseTimestamp(right.created_at)) -
40 Math.max(parseTimestamp(left.updated_at), parseTimestamp(left.created_at));
41
42 const compareSummaryNewestFirst = (
43 left: Pick<CachedConnectedAccountSummary, 'updatedAt' | 'createdAt'>,
44 right: Pick<CachedConnectedAccountSummary, 'updatedAt' | 'createdAt'>
45 ): number =>
46 Math.max(parseTimestamp(right.updatedAt), parseTimestamp(right.createdAt)) -
47 Math.max(parseTimestamp(left.updatedAt), parseTimestamp(left.createdAt));
48
49 export const isUsableConnectedAccount = (
50 item: Pick<SelectableConnectedAccount, 'status' | 'is_disabled'>
51 ): boolean => item.status === 'ACTIVE' && !item.is_disabled;
52
53 export const toCachedConnectedAccountSummary = (
54 item: Pick<ConnectedAccountItem, 'id' | 'alias' | 'word_id' | 'updated_at' | 'created_at'>
55 ): CachedConnectedAccountSummary => ({
56 id: item.id,
57 alias: item.alias ?? null,
58 wordId: item.word_id ?? null,
59 updatedAt: item.updated_at,
60 createdAt: item.created_at,
61 });
62
63 export const groupCachedConnectedAccountsByToolkit = (
64 items: ReadonlyArray<SelectableConnectedAccount>
65 ): Record<string, ReadonlyArray<CachedConnectedAccountSummary>> => {
66 const grouped = new Map<string, CachedConnectedAccountSummary[]>();
67
68 for (const item of items) {
69 if (!isUsableConnectedAccount(item)) continue;
70 const toolkit = item.toolkit.slug.trim().toLowerCase();
71 if (!toolkit) continue;
72
73 const next = grouped.get(toolkit) ?? [];
74 next.push(toCachedConnectedAccountSummary(item));
75 grouped.set(toolkit, next);
76 }
77
78 return Object.fromEntries(
79 [...grouped.entries()].map(([toolkit, summaries]) => [
80 toolkit,
81 [...summaries].sort(compareSummaryNewestFirst),
82 ])
83 );
84 };
85
86 export const resolveDefaultConnectedAccountsByToolkit = (
87 items: ReadonlyArray<SelectableConnectedAccount>
88 ): Record<string, string> => {
89 const grouped = new Map<string, SelectableConnectedAccount[]>();
90
91 for (const item of items) {
92 if (!isUsableConnectedAccount(item)) continue;
93 const toolkit = item.toolkit.slug.trim().toLowerCase();
94 if (!toolkit) continue;
95
96 const next = grouped.get(toolkit) ?? [];
97 next.push(item);
98 grouped.set(toolkit, next);
99 }
100
101 return Object.fromEntries(
102 [...grouped.entries()]
103 .map(([toolkit, toolkitItems]) => {
104 const selected = resolveConnectedAccountSelection(toolkitItems);
105 return selected ? ([toolkit, selected.id] as const) : null;
106 })
107 .filter((entry): entry is readonly [string, string] => entry !== null)
108 );
109 };
110
111 export const resolveConnectedAccountSelection = (
112 items: ReadonlyArray<SelectableConnectedAccount>,
113 selector?: string
114 ): SelectableConnectedAccount | undefined => {
115 const usable = items.filter(isUsableConnectedAccount).sort(compareNewestFirst);
116 if (usable.length === 0) return undefined;
117
118 if (!selector || selector.trim().length === 0) {
119 return usable.find(item => normalizeSelector(item.alias ?? '') === 'default') ?? usable[0];
120 }
121
122 const normalized = normalizeSelector(selector);
123 return (
124 usable.find(item => normalizeSelector(item.id) === normalized) ??
125 usable.find(item => normalizeSelector(item.alias ?? '') === normalized) ??
126 usable.find(item => normalizeSelector(item.word_id ?? '') === normalized)
127 );
128 };
129
130 export const formatConnectedAccountChoice = (
131 item: Pick<ConnectedAccountItem, 'id' | 'alias' | 'word_id'>
132 ): string => {
133 const labels = [item.alias, item.word_id].filter(
134 (value): value is string => typeof value === 'string' && value.trim().length > 0
135 );
136 return labels.length > 0 ? `${labels.join(' / ')} (${item.id})` : item.id;
137 };
138
139 export const formatConnectedAccountChoices = (
140 items: ReadonlyArray<ConnectedAccountItem>
141 ): ReadonlyArray<string> =>
142 items.filter(isUsableConnectedAccount).sort(compareNewestFirst).map(formatConnectedAccountChoice);
143
144 /**
145 * Every active connected account of `userId`, fetched once per credential,
146 * org, project, and user for the lifetime of the process. The client's
147 * credential, org, and project come from `clientScopeKey`: each `getFor`
148 * builds a new client, so two callers holding different instances for the
149 * same key and project still share one fetch.
150 *
151 * `composio execute` needs this list twice on every call, from two code paths
152 * that cannot see each other: `resolveConnectedAccountForToolkit` picks the
153 * account for the tool's toolkit, then `resolveToolRouterSessionConnections`
154 * builds the session's connection context from the full list. The per-toolkit
155 * view is a subset of this list, so both read from here instead of issuing
156 * their own `GET /connected_accounts`.
157 *
158 * Every page is fetched (`listAllConnectedAccounts`): the server serves at
159 * most 50 accounts per request, and a first page alone dropped connected
160 * toolkits from the session for users with more active accounts than that.
161 * Fails with the client's error; each caller wraps it in its own error.
162 */
163 export const listActiveConnectedAccounts = memoizeInProcess({
164 keyOf: (input: { readonly client: ComposioClientShape; readonly userId: string }) =>
165 `${clientScopeKey(input.client)}\u0000${input.userId}`,
166 make: ({ client, userId }) =>
167 listAllConnectedAccounts(client, { user_ids: [userId], statuses: ['ACTIVE'] }),
168 });
169
170 /**
171 * The active accounts of one toolkit, in server order, derived from the
172 * shared per-user list so `composio execute` does not issue a second,
173 * toolkit-filtered `GET /connected_accounts` next to the one session creation
174 * needs anyway. The slug is trimmed and lower-cased the way the grouping
175 * helpers above normalize toolkit slugs, so a padded `--toolkit` value still
176 * matches.
177 */
178 export const listConnectedAccountsForToolkit = (params: {
179 readonly client: ComposioClientShape;
180 readonly userId: string;
181 readonly toolkitSlug: string;
182 }) =>
183 Effect.gen(function* () {
184 const items = yield* listActiveConnectedAccounts({
185 client: params.client,
186 userId: params.userId,
187 });
188 const wantedToolkit = normalizeSelector(params.toolkitSlug);
189 return items.filter(item => normalizeSelector(item.toolkit.slug) === wantedToolkit);
190 });
191
192 export class ConnectedAccountResolutionError extends Data.TaggedError(
193 'services/ConnectedAccountResolutionError'
194 )<{
195 readonly message: string;
196 readonly toolkitSlug: string;
197 readonly cause?: unknown;
198 }> {
199 get [ExpectedFailure]() {
200 return true;
201 }
202 }
203
204 export const resolveConnectedAccountForToolkit = (params: {
205 readonly client: ComposioClientShape;
206 readonly toolkitSlug?: string;
207 readonly userId: string;
208 readonly selector: Option.Option<string>;
209 }): Effect.Effect<string | undefined, ConnectedAccountResolutionError, TerminalUI> =>
210 Effect.gen(function* () {
211 if (!params.toolkitSlug) return undefined;
212 const toolkitSlug = params.toolkitSlug;
213
214 const toolkitItems = yield* listConnectedAccountsForToolkit({
215 client: params.client,
216 userId: params.userId,
217 toolkitSlug,
218 }).pipe(
219 Effect.mapError(
220 cause =>
221 new ConnectedAccountResolutionError({
222 // "Error: " is how this message has always introduced the client's failure.
223 message: `Failed to load connected accounts for toolkit "${toolkitSlug}": Error: ${cause.message}`,
224 toolkitSlug,
225 cause,
226 })
227 )
228 );
229 const selectableAccounts = yield* decodeConnectedAccountItems(toolkitItems).pipe(
230 Effect.mapError(
231 cause =>
232 new ConnectedAccountResolutionError({
233 message: `Connected accounts for toolkit "${toolkitSlug}" did not match the expected response shape.`,
234 toolkitSlug,
235 cause,
236 })
237 )
238 );
239
240 // A selector that is empty or all-whitespace (e.g. `--account=`) is
241 // treated as "no selector" by resolveConnectedAccountSelection below; the
242 // ambiguity guard below it must agree, or an empty --account value would
243 // silently reach the "exactly one choice" fallback instead of failing.
244 const effectiveSelector = Option.filter(params.selector, value => value.trim().length > 0);
245
246 const selected = resolveConnectedAccountSelection(
247 selectableAccounts,
248 Option.getOrUndefined(effectiveSelector)
249 );
250
251 if (selected) {
252 // No --account given: if more than one usable account exists and none
253 // is the explicit alias=default, picking one silently is dangerous
254 // (e.g. an agent reading/writing the wrong mailbox). Fail the same way
255 // an unmatched selector already does, instead of guessing.
256 if (Option.isNone(effectiveSelector)) {
257 const usable = selectableAccounts.filter(isUsableConnectedAccount);
258 const hasExplicitDefault = usable.some(
259 item => normalizeSelector(item.alias ?? '') === 'default'
260 );
261 if (!hasExplicitDefault && usable.length > 1) {
262 const choices = formatConnectedAccountChoices(selectableAccounts);
263 return yield* new ConnectedAccountResolutionError({
264 message: `Multiple connected accounts exist for toolkit "${toolkitSlug}" and no --account was given. Available accounts: ${choices.join(', ')}. Pass --account <alias or id> to choose one.`,
265 toolkitSlug,
266 });
267 }
268 }
269 return selected.id;
270 }
271 if (Option.isNone(effectiveSelector)) return undefined;
272
273 const choices = formatConnectedAccountChoices(selectableAccounts);
274 const hint =
275 choices.length > 0
276 ? ` Available accounts: ${choices.join(', ')}.`
277 : ' No active connected accounts were found for that toolkit.';
278 return yield* new ConnectedAccountResolutionError({
279 message: `No connected account matched "${effectiveSelector.value}" for toolkit "${toolkitSlug}".${hint}`,
280 toolkitSlug,
281 });
282 });