3
import type { ConnectedAccountItem } from 'src/models/connected-accounts';
4
import { decodeConnectedAccountItems } from 'src/effects/decode-connected-account-list';
5
import type { TerminalUI } from 'src/services/terminal-ui';
6
+import { memoizeInProcess } from 'src/utils/memoize-in-process';
7
8
// `status` is an open enum, so this is shape-identical to
9
// `ConnectedAccountItem`; tool-router rows normalize statuses outside the
138
): ReadonlyArray<string> =>
139
items.filter(isUsableConnectedAccount).sort(compareNewestFirst).map(formatConnectedAccountChoice);
140
141
+export class ActiveConnectedAccountsListError extends Data.TaggedError(
142
+ 'services/ActiveConnectedAccountsListError'
143
+)<{
144
+ readonly message: string;
145
+ readonly cause: unknown;
146
+}> {}
147
+
148
+// `Composio` clients come from `ComposioClientSingleton`, one instance per
149
+// org/project, so identity is a sound cache key. Ids instead of the object
150
+// itself keep the memo key a string.
151
+const clientIds = new WeakMap<Composio, number>();
152
+let nextClientId = 0;
153
+const clientId = (client: Composio): number => {
154
+ let id = clientIds.get(client);
155
+ if (id === undefined) {
156
+ id = nextClientId++;
157
+ clientIds.set(client, id);
158
+ }
159
+ return id;
160
+};
161
+
162
+/**
163
+ * Every active connected account of `userId`, fetched once per client and
164
+ * user for the lifetime of the process.
165
+ *
166
+ * `composio execute` needs this list twice on every call, from two code paths
167
+ * that cannot see each other: `resolveConnectedAccountForToolkit` picks the
168
+ * account for the tool's toolkit, then `resolveToolRouterSessionConnections`
169
+ * builds the session's connection context from the full list. Both used to
170
+ * issue their own `GET /connected_accounts`, one toolkit-filtered and one not.
171
+ * The per-toolkit view is a subset of this list, so both read from here.
172
+ *
173
+ * `limit: 1000` is the session path's existing page size; a user with more
174
+ * active accounts than that was already truncated there.
175
+ */
176
+export const listActiveConnectedAccounts = memoizeInProcess({
177
+ keyOf: (input: { readonly client: Composio; readonly userId: string }) =>
178
+ `${clientId(input.client)}\u0000${input.userId}`,
179
+ make: ({ client, userId }) =>
180
+ Effect.tryPromise({
181
+ try: () =>
182
+ client.connectedAccounts.list({
183
+ user_ids: [userId],
184
+ statuses: ['ACTIVE'],
185
+ limit: 1000,
186
+ }),
187
+ catch: cause =>
188
+ new ActiveConnectedAccountsListError({
189
+ message: `Failed to list connected accounts for user "${userId}".`,
190
+ cause,
191
+ }),
192
+ }),
193
+});
194
+
195
+const TOOLKIT_ACCOUNTS_PAGE_SIZE = 100;
196
+
197
+// The account picker's own query: one toolkit, first 100 active accounts, in
198
+// server order. Kept verbatim as the fallback so results stay identical when
199
+// the shared list cannot stand in for it.
200
+const fetchConnectedAccountsForToolkit = (params: {
201
+ readonly client: Composio;
202
+ readonly userId: string;
203
+ readonly toolkitSlug: string;
204
+}) =>
205
+ Effect.tryPromise({
206
+ try: () =>
207
+ params.client.connectedAccounts.list({
208
+ toolkit_slugs: [params.toolkitSlug],
209
+ user_ids: [params.userId],
210
+ statuses: ['ACTIVE'],
211
+ limit: TOOLKIT_ACCOUNTS_PAGE_SIZE,
212
+ }),
213
+ // The raw rejection, so the caller's message reads as it always has.
214
+ catch: cause => cause,
215
+ }).pipe(Effect.map(response => response.items));
216
+
217
+/**
218
+ * The active accounts of one toolkit, derived from the shared per-user list
219
+ * when that list is complete, so `composio execute` does not issue a second,
220
+ * toolkit-filtered `GET /connected_accounts` next to the one session creation
221
+ * needs anyway.
222
+ *
223
+ * Derivation reproduces the server query exactly: same slug match, server
224
+ * order preserved, first 100. If the shared list was truncated (more active
225
+ * accounts than its page holds), the toolkit's accounts may sit past the cut,
226
+ * so the original filtered request runs instead.
227
+ */
228
+const listConnectedAccountsForToolkit = (params: {
229
+ readonly client: Composio;
230
+ readonly userId: string;
231
+ readonly toolkitSlug: string;
232
+}) =>
233
+ Effect.gen(function* () {
234
+ const shared = yield* listActiveConnectedAccounts({
235
+ client: params.client,
236
+ userId: params.userId,
237
+ }).pipe(Effect.mapError(error => error.cause));
238
+ const items = shared.items ?? [];
239
+ const complete = shared.next_cursor == null && shared.total_items <= items.length;
240
+ if (!complete) {
241
+ return yield* fetchConnectedAccountsForToolkit(params);
242
+ }
243
+
244
+ const wantedToolkit = params.toolkitSlug.toLowerCase();
245
+ return items
246
+ .filter(item => item.toolkit?.slug?.toLowerCase() === wantedToolkit)
247
+ .slice(0, TOOLKIT_ACCOUNTS_PAGE_SIZE);
248
+ });
249
+
250
export class ConnectedAccountResolutionError extends Data.TaggedError(
251
'services/ConnectedAccountResolutionError'
252
)<{
265
if (!params.toolkitSlug) return undefined;
266
const toolkitSlug = params.toolkitSlug;
267
158
- const accounts = yield* Effect.tryPromise({
159
- try: () =>
160
- params.client.connectedAccounts.list({
161
- toolkit_slugs: [toolkitSlug],
162
- user_ids: [params.userId],
163
- statuses: ['ACTIVE'],
164
- limit: 100,
165
- }),
166
- catch: cause =>
167
- new ConnectedAccountResolutionError({
168
- message: `Failed to load connected accounts for toolkit "${toolkitSlug}": ${String(cause)}`,
169
- toolkitSlug,
170
- cause,
171
- }),
172
- });
173
- const selectableAccounts = yield* decodeConnectedAccountItems(accounts.items).pipe(
268
+ const toolkitItems = yield* listConnectedAccountsForToolkit({
269
+ client: params.client,
270
+ userId: params.userId,
271
+ toolkitSlug,
272
+ }).pipe(
273
+ Effect.mapError(
274
+ cause =>
275
+ new ConnectedAccountResolutionError({
276
+ message: `Failed to load connected accounts for toolkit "${toolkitSlug}": ${String(cause)}`,
277
+ toolkitSlug,
278
+ cause,
279
+ })
280
+ )
281
+ );
282
+ const selectableAccounts = yield* decodeConnectedAccountItems(toolkitItems).pipe(
283
Effect.mapError(
284
cause =>
285
new ConnectedAccountResolutionError({