1
+import type { SessionToolkitsResponse } from '@composio/client/resources/tool-router';
2
+import { Array as Arr, Effect, Option } from 'effect';
3
+import { CommandSurface, directoryTestUserId, namedProject } from 'src/commands/surface';
4
+import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
5
+import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
6
+import { idempotent } from 'src/services/composio-request';
7
+import { ProjectContext } from 'src/services/project-context';
8
+import { NodeProcess } from 'src/services/node-process';
9
+import { TerminalUI } from 'src/services/terminal-ui';
10
+import { ComposioUserContext } from 'src/services/user-context';
11
+import { clampLimit } from 'src/ui/clamp-limit';
12
+import { extractMessage } from 'src/utils/api-error-extraction';
13
+import {
14
+ formatToolkitsJson,
15
+ formatToolkitsTable,
16
+ mergeToolkitData,
17
+ type UnifiedToolkit,
18
+} from '../format';
19
+
20
+export type ToolkitsListParams = {
21
+ readonly query: Option.Option<string>;
22
+ readonly limit: number;
23
+ readonly connected: Option.Option<boolean>;
24
+};
25
+
26
+type SessionToolkitItem = SessionToolkitsResponse.Item;
27
+
28
+/** The user whose connection status the list shows, and the notice printed when it is a fallback. */
29
+export type ToolkitsListUser = {
30
+ readonly id: string;
31
+ readonly fallbackNotice: Option.Option<string>;
32
+};
33
+
34
+/**
35
+ * The `dev` group's `--user-id`, then the directory's test user id, then the global one.
36
+ */
37
+export const resolveToolkitsListUser = (candidates: {
38
+ readonly flag: Option.Option<string>;
39
+ readonly projectTestUserId: Option.Option<string>;
40
+ readonly globalTestUserId: Option.Option<string>;
41
+}): Option.Option<ToolkitsListUser> =>
42
+ Option.firstSomeOf([
43
+ Option.map(candidates.flag, id => ({ id, fallbackNotice: Option.none<string>() })),
44
+ Option.map(candidates.projectTestUserId, id => ({
45
+ id,
46
+ fallbackNotice: Option.some(`Using test user id "${id}"`),
47
+ })),
48
+ Option.map(candidates.globalTestUserId, id => ({
49
+ id,
50
+ fallbackNotice: Option.some(`Using global test user id "${id}"`),
51
+ })),
52
+ ]);
53
+
54
+/**
55
+ * Applies `--connected` to the merged rows. The filter needs the session's connection data; when a
56
+ * user was resolved but the session returned nothing, the rows are kept and the filter is reported
57
+ * as skipped.
58
+ */
59
+export const applyConnectedFilter = (
60
+ rows: ReadonlyArray<UnifiedToolkit>,
61
+ params: {
62
+ readonly connectedOnly: boolean;
63
+ readonly sessionLoaded: boolean;
64
+ readonly userResolved: boolean;
65
+ }
66
+): { readonly rows: ReadonlyArray<UnifiedToolkit>; readonly filterSkipped: boolean } => {
67
+ if (params.connectedOnly && params.sessionLoaded) {
68
+ return { rows: rows.filter(row => row.connected?.status === 'ACTIVE'), filterSkipped: false };
69
+ }
70
+ return { rows, filterSkipped: params.connectedOnly && params.userResolved };
71
+};
72
+
73
+/**
74
+ * Lists the toolkit catalog. When a user is known, the rows also carry that user's connection
75
+ * status, read from a tool router session; a failed session read only drops the status.
76
+ */
77
+export const runToolkitsList = ({ query, limit, connected }: ToolkitsListParams) =>
78
+ Effect.gen(function* () {
79
+ const { userId } = yield* CommandSurface;
80
+ const ui = yield* TerminalUI;
81
+ const repo = yield* ComposioToolkitsRepository;
82
+ const clientSingleton = yield* ComposioClientSingleton;
83
+ const projectContext = yield* ProjectContext;
84
+ const userContext = yield* ComposioUserContext;
85
+
86
+ const clampedLimit = clampLimit(limit);
87
+ // Resolved outside the session lookup, whose failures only drop the connection status.
88
+ const project = yield* namedProject;
89
+ const resolvedProjectContext = yield* projectContext.resolve;
90
+ const user = resolveToolkitsListUser({
91
+ flag: userId,
92
+ projectTestUserId: directoryTestUserId(
93
+ resolvedProjectContext,
94
+ Option.map(project, named => named.projectId)
95
+ ),
96
+ globalTestUserId: userContext.data.testUserId,
97
+ });
98
+
99
+ const fallbackNotice = Option.flatMap(user, resolved => resolved.fallbackNotice);
100
+ if (Option.isSome(fallbackNotice)) {
101
+ yield* ui.log.warn(fallbackNotice.value);
102
+ yield* ui.log.message('To show status for a specific user, use `--user-id`.');
103
+ }
104
+
105
+ if (Option.isSome(connected) && Option.isNone(user)) {
106
+ yield* ui.log.warn(
107
+ '`--connected` requires a user id. Use `--user-id` or run `composio dev init`.'
108
+ );
109
+ }
110
+
111
+ const catalogEffect = repo.searchToolkits({
112
+ search: Option.getOrUndefined(query),
113
+ limit: clampedLimit,
114
+ });
115
+
116
+ // The session is created alongside the catalog fetch (saves one round trip); its toolkits
117
+ // call needs the session id, so it runs after.
118
+ const sessionContextEffect = Option.match(user, {
119
+ onNone: () => Effect.succeedNone,
120
+ onSome: resolved =>
121
+ Effect.gen(function* () {
122
+ const client = yield* Option.match(project, {
123
+ onSome: named => Effect.succeed(named.client),
124
+ onNone: () => clientSingleton.get(),
125
+ });
126
+ const { sessionId } = yield* resolveToolRouterSession(client, resolved.id);
127
+ return Option.some({ client, sessionId });
128
+ }).pipe(
129
+ Effect.catch(error =>
130
+ Effect.logDebug('Failed to create session:', error).pipe(Effect.as(Option.none()))
131
+ )
132
+ ),
133
+ });
134
+
135
+ const [catalogResult, sessionContext] = yield* ui.withSpinner(
136
+ 'Fetching toolkits...',
137
+ Effect.all([catalogEffect, sessionContextEffect], { concurrency: 'unbounded' })
138
+ );
139
+
140
+ if (catalogResult.items.length === 0) {
141
+ yield* ui.log.warn('No toolkits found. Try broadening your search.');
142
+ yield* ui.output('[]');
143
+ return;
144
+ }
145
+
146
+ // The session items only add connection status to the catalog rows, and a failed or empty
147
+ // read is a silent fallback.
148
+ const sessionItems = yield* Option.match(sessionContext, {
149
+ onNone: () => Effect.succeedNone,
150
+ onSome: ({ client, sessionId }) =>
151
+ client.toolRouter.session
152
+ .toolkits(
153
+ sessionId,
154
+ {
155
+ search: Option.getOrUndefined(query),
156
+ limit: clampedLimit,
157
+ is_connected: Option.getOrUndefined(connected),
158
+ },
159
+ idempotent
160
+ )
161
+ .pipe(
162
+ Effect.map(response => response.items),
163
+ Effect.catch(error =>
164
+ Effect.logDebug('Failed to fetch session toolkits:', error).pipe(
165
+ Effect.as<ReadonlyArray<SessionToolkitItem>>([])
166
+ )
167
+ ),
168
+ Effect.map(Option.liftPredicate(Arr.isReadonlyArrayNonEmpty))
169
+ ),
170
+ });
171
+
172
+ const { rows, filterSkipped } = applyConnectedFilter(
173
+ mergeToolkitData(catalogResult.items, Option.getOrUndefined(sessionItems)),
174
+ {
175
+ connectedOnly: Option.getOrElse(connected, () => false),
176
+ sessionLoaded: Option.isSome(sessionItems),
177
+ userResolved: Option.isSome(user),
178
+ }
179
+ );
180
+ if (filterSkipped) {
181
+ yield* ui.log.warn('`--connected` filter could not be applied — session data unavailable.');
182
+ }
183
+
184
+ if (rows.length === 0) {
185
+ yield* ui.log.warn('No connected toolkits found. Try without --connected.');
186
+ yield* ui.output('[]');
187
+ return;
188
+ }
189
+
190
+ yield* ui.log.info(
191
+ `Listing ${rows.length} of ${catalogResult.total_items} toolkits\n\n${formatToolkitsTable(rows)}`
192
+ );
193
+
194
+ const firstSlug = rows[0]?.slug;
195
+ if (firstSlug) {
196
+ yield* ui.log.step(
197
+ `To view details of a toolkit:\n> composio dev toolkits info "${firstSlug}"`
198
+ );
199
+ }
200
+ yield* ui.output(formatToolkitsJson(rows));
201
+ }).pipe(
202
+ Effect.catch(error =>
203
+ Effect.gen(function* () {
204
+ const ui = yield* TerminalUI;
205
+ const proc = yield* NodeProcess;
206
+ yield* ui.log.error(extractMessage(error) ?? 'An error occurred while fetching toolkits.');
207
+ yield* ui.output('[]');
208
+ yield* proc.setExitCode(1);
209
+ })
210
+ )
211
+ );