1
import {
2
- pipe,
2
Context,
3
Data,
4
Effect,
5
Layer,
6
Option,
7
+ Predicate,
8
Schema,
9
Array,
10
Order,
11
String,
12
- Stream,
13
- SynchronizedRef,
12
} from 'effect';
13
import * as FileSystem from 'effect/FileSystem';
14
import * as Path from 'effect/Path';
15
import type { Cause } from 'effect';
18
-import { Composio as _RawComposioClient, APIPromise } from '@composio/client';
16
+import { Composio as _RawComposioClient, APIError, type RequestOptions } from '@composio/client';
17
+import { paginate, type CursorPage } from '@composio/client/pagination';
18
import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
19
import type { ConnectedAccountListParams } from '@composio/client/resources/connected-accounts';
21
-import {
22
- Toolkit,
23
- Toolkits,
24
- ToolkitDetailed,
25
- ToolkitSlug,
26
- type ToolkitSearchResult,
27
-} from 'src/models/toolkits';
20
+import type { OrgListResponse, ProjectListResponse } from '@composio/client/resources/org';
21
+import type {
22
+ ConsumerListConnectedToolkitsResponse,
23
+ ProjectResolveResponse,
24
+} from '@composio/client/resources/org/consumer';
25
+import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
26
+import { Toolkit, Toolkits, ToolkitDetailed, type ToolkitSearchResult } from 'src/models/toolkits';
27
import { AuthConfigItem, AuthConfigItems } from 'src/models/auth-configs';
28
import { ConnectedAccountItem, ConnectedAccountItems } from 'src/models/connected-accounts';
29
import { TriggerInstanceItems } from 'src/models/triggers';
31
-import { ToolsAsEnums, Tools, Tool } from 'src/models/tools';
30
+import { ToolsAsEnums, Tools } from 'src/models/tools';
31
import {
32
groupByVersion,
33
type ToolkitVersionSpec,
34
type ToolkitVersionOverrides,
35
} from 'src/effects/toolkit-version-overrides';
37
-import { JsonRecordSchema } from 'src/effects/json';
36
import { Session, RetrievedSession } from 'src/models/session';
37
import { TriggerType, TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigger-types';
38
import * as constants from 'src/constants';
39
import { getCurrentCwdSessionId } from 'src/analytics/dispatch';
40
import { ComposioUserContext, ComposioUserContextLive } from './user-context';
41
import { ProjectContext } from './project-context';
44
-import { renderPrettyError } from './utils/pretty-error';
42
+import { makeClientMetricsCollector } from './composio-client-metrics';
43
import { NodeOs } from './node-os';
44
45
type NoSuchElementError = Cause.NoSuchElementError;
49
*/
50
51
/**
54
- * Structured error details from the Composio API.
52
+ * Structured error details from the Composio API error envelope.
53
*/
54
export interface HttpErrorDetails {
55
readonly message: string;
58
- readonly suggestedFix: string;
56
+ readonly suggestedFix?: string;
57
readonly code: number;
58
}
59
60
/**
61
* Error thrown when a HTTP request fails.
62
+ *
63
+ * `status`, `details`, and `requestId` are populated from the client's
64
+ * `APIError` when the failure is an API response; a connection failure or an
65
+ * unexpected rejection carries only `cause`.
66
*/
67
export class HttpServerError extends Data.TaggedError('services/HttpServerError')<{
68
readonly cause?: unknown;
69
readonly status?: number;
70
readonly details?: HttpErrorDetails;
71
+ readonly requestId?: string;
72
+}> {}
73
+
74
+/**
75
+ * Error thrown when a client cannot be constructed from the current configuration.
76
+ */
77
+export class ComposioClientConfigurationError extends Data.TaggedError(
78
+ 'services/ComposioClientConfigurationError'
79
+)<{
80
+ readonly message: string;
81
+ readonly cause: unknown;
82
}> {}
83
84
/**
116
117
export type HttpError = HttpServerError | HttpDecodingError;
118
119
+/**
120
+ * Every failure a client call can produce: the request itself, decoding a
121
+ * CLI-owned contract, or obtaining a client from the singleton.
122
+ */
123
+export type ClientError = HttpError | ComposioClientConfigurationError | NoSuchElementError;
124
+
125
+/**
126
+ * Request helpers
127
+ */
128
+
129
+// Maximum items per page allowed by the server
130
+const MAX_PAGE_SIZE = 1000;
131
+
132
+// Maximum concurrent requests per each endpoint
133
+const MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 4;
134
+
135
+const toHttpServerError = (cause: unknown): HttpServerError => {
136
+ if (cause instanceof APIError) {
137
+ const details = cause.details;
138
+ return new HttpServerError({
139
+ cause,
140
+ status: cause.status,
141
+ requestId: cause.requestId,
142
+ details: details
143
+ ? { message: details.message, code: details.code, suggestedFix: details.suggested_fix }
144
+ : undefined,
145
+ });
146
+ }
147
+ return new HttpServerError({ cause });
148
+};
149
+
150
+/**
151
+ * Runs one client call. The client parses JSON and rejects on non-2xx, so the
152
+ * only work left is mapping its rejection onto `HttpServerError`.
153
+ */
154
+const request = <A, E>(
155
+ client: Effect.Effect<_RawComposioClient, E>,
156
+ call: (client: _RawComposioClient, signal: AbortSignal) => PromiseLike<A>
157
+): Effect.Effect<A, E | HttpServerError> =>
158
+ client.pipe(
159
+ Effect.flatMap(resolved =>
160
+ Effect.tryPromise({ try: signal => call(resolved, signal), catch: toHttpServerError })
161
+ )
162
+ );
163
+
164
+/**
165
+ * Runs a paginated client call to exhaustion and returns every item, asking
166
+ * for `MAX_PAGE_SIZE` items per page.
167
+ */
168
+const requestAll = <Page extends CursorPage<unknown>, E>(
169
+ client: Effect.Effect<_RawComposioClient, E>,
170
+ fetchPage: (
171
+ client: _RawComposioClient,
172
+ page: { readonly cursor: string | undefined; readonly limit: number },
173
+ signal: AbortSignal
174
+ ) => PromiseLike<Page>
175
+) =>
176
+ request(client, (resolved, signal) =>
177
+ paginate<Page>(({ cursor }) =>
178
+ fetchPage(resolved, { cursor, limit: MAX_PAGE_SIZE }, signal)
179
+ ).toArray()
180
+ );
181
+
182
+/**
183
+ * Decodes a payload against a CLI-owned contract.
184
+ */
185
+const decode =
186
+ <S extends Schema.Top>(schema: S) =>
187
+ (input: unknown): Effect.Effect<S['Type'], HttpDecodingError, S['DecodingServices']> =>
188
+ Schema.decodeUnknownEffect(schema)(input).pipe(
189
+ Effect.catchTag(
190
+ 'SchemaError',
191
+ e =>
192
+ new HttpDecodingError({
193
+ cause: `SchemaError\n ${e.message}`,
194
+ })
195
+ )
196
+ );
197
+
198
// Sort items by slug.
199
// TODO: make sure this happens on the server-side.
200
const sortBySlug = <T extends { readonly slug: string }>(
205
Order.mapInput(Order.String, (item: T) => item.slug)
206
);
207
208
+/**
209
+ * Converts a 404 from a toolkit lookup into `InvalidToolkitsError` naming
210
+ * that slug; every other failure propagates unchanged.
211
+ */
212
+const invalidToolkitOn404 = <A>(slug: string, toolkit: Effect.Effect<A, ClientError>) =>
213
+ Effect.catchTag(
214
+ toolkit,
215
+ 'services/HttpServerError',
216
+ (e): Effect.Effect<never, InvalidToolkitsError | HttpServerError> =>
217
+ e.status === 404
218
+ ? Effect.fail(
219
+ new InvalidToolkitsError({
220
+ invalidToolkits: [slug],
221
+ availableToolkits: [],
222
+ })
223
+ )
224
+ : Effect.fail(e)
225
+ );
226
+
227
const validateToolkitVersionsImpl = (
117
- client: {
118
- toolkits: {
119
- retrieve: (slug: string) => Effect.Effect<Toolkit, HttpError | NoSuchElementError, never>;
120
- };
121
- },
228
+ retrieveToolkit: (slug: string) => Effect.Effect<Toolkit, ClientError, never>,
229
overrides: ToolkitVersionOverrides,
230
relevantToolkits?: ReadonlyArray<string>
231
): Effect.Effect<
233
validatedOverrides: ToolkitVersionOverrides;
234
warnings: ReadonlyArray<string>;
235
},
129
- InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementError
236
+ InvalidToolkitVersionsError | InvalidToolkitsError | ClientError
237
> =>
238
Effect.gen(function* () {
239
const determineOverridesToValidate = (
274
availableVersions: ReadonlyArray<string>;
275
isValid: boolean;
276
}>,
170
- InvalidToolkitsError | HttpError | NoSuchElementError
277
+ InvalidToolkitsError | ClientError
278
> =>
279
Effect.all(
280
overridesToValidate.map(([toolkit, requestedVersion]) =>
174
- client.toolkits.retrieve(toolkit).pipe(
175
- Effect.map(toolkitData => ({
176
- toolkit,
177
- requestedVersion,
178
- availableVersions: toolkitData.meta.available_versions,
179
- isValid: toolkitData.meta.available_versions.includes(requestedVersion),
180
- })),
181
- Effect.catchTag(
182
- 'services/HttpServerError',
183
- (e): Effect.Effect<never, InvalidToolkitsError | HttpServerError> =>
184
- e.status === 404
185
- ? Effect.fail(
186
- new InvalidToolkitsError({
187
- invalidToolkits: [toolkit],
188
- availableToolkits: [],
189
- })
190
- )
191
- : Effect.fail(e)
281
+ invalidToolkitOn404(
282
+ toolkit,
283
+ retrieveToolkit(toolkit).pipe(
284
+ Effect.map(toolkitData => ({
285
+ toolkit,
286
+ requestedVersion,
287
+ availableVersions: toolkitData.meta.available_versions,
288
+ isValid: toolkitData.meta.available_versions.includes(requestedVersion),
289
+ }))
290
)
291
)
292
),
337
});
338
339
/**
242
- * Response schemas
243
- */
244
-
245
-export const CliCreateSessionResponse = Session;
246
-export type CliCreateSessionResponse = Schema.Schema.Type<typeof CliCreateSessionResponse>;
247
-
248
-export const CliGetSessionResponse = RetrievedSession;
249
-export type CliRetrieveSessionResponse = Schema.Schema.Type<typeof CliGetSessionResponse>;
250
-
251
-export const CliRealtimeCredentialsResponse = Schema.Struct({
252
- project_id: Schema.String,
253
- pusher_key: Schema.String,
254
- pusher_cluster: Schema.String,
255
-}).annotate({ identifier: 'CliRealtimeCredentialsResponse' });
256
-export type CliRealtimeCredentialsResponse = Schema.Schema.Type<
257
- typeof CliRealtimeCredentialsResponse
258
->;
259
-
260
-export const CliRealtimeAuthResponse = Schema.Struct({
261
- auth: Schema.String,
262
- channel_data: Schema.optional(Schema.String),
263
-}).annotate({ identifier: 'CliRealtimeAuthResponse' });
264
-export type CliRealtimeAuthResponse = Schema.Schema.Type<typeof CliRealtimeAuthResponse>;
265
-
266
-export const ToolkitsResponse = Schema.Struct({
267
- items: Toolkits,
268
- total_pages: Schema.Int,
269
- next_cursor: Schema.NullOr(Schema.String),
270
-}).annotate({ identifier: 'ToolkitsResponse' });
271
-export type ToolkitsResponse = Schema.Schema.Type<typeof ToolkitsResponse>;
272
-
273
-// Similar to Toolkits, without auth_schemes, with auth_config_details instead
274
-export const ToolkitRetrieveResponse = Schema.Struct({
275
- name: Schema.String,
276
- slug: ToolkitSlug,
277
- is_local_toolkit: Schema.Boolean,
278
- composio_managed_auth_schemes: Schema.Array(Schema.String).pipe(
279
- Schema.withDecodingDefaultType(Effect.succeed([]))
280
- ),
281
- no_auth: Schema.Boolean.pipe(Schema.withDecodingDefaultType(Effect.succeed(false))),
282
- meta: Schema.Struct({
283
- description: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
284
- categories: Schema.Array(Schema.Unknown).pipe(
285
- Schema.withDecodingDefaultType(Effect.succeed([]))
286
- ),
287
- created_at: Schema.DateTimeUtcFromString,
288
- updated_at: Schema.DateTimeUtcFromString,
289
- available_versions: Schema.Array(Schema.String).pipe(
290
- Schema.withDecodingDefaultType(Effect.succeed([]))
291
- ),
292
- tools_count: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
293
- triggers_count: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
294
- }),
295
-}).annotate({ identifier: 'ToolkitRetrieveResponse' });
296
-export type ToolkitRetrieveResponse = Schema.Schema.Type<typeof ToolkitRetrieveResponse>;
297
-
298
-export const ToolsAsEnumsResponse = ToolsAsEnums;
299
-export type ToolsAsEnumsResponse = Schema.Schema.Type<typeof ToolsAsEnumsResponse>;
300
-
301
-export const ToolsResponse = Schema.Struct({
302
- items: Tools,
303
- total_pages: Schema.Int,
304
- next_cursor: Schema.NullOr(Schema.String),
305
-}).annotate({ identifier: 'ToolsResponse' });
306
-export type ToolsResponse = Schema.Schema.Type<typeof ToolsResponse>;
307
-
308
-export const ToolDetailedResponse = Schema.Struct({
309
- name: Schema.String,
310
- slug: Schema.String,
311
- description: Schema.String,
312
- tags: Schema.Array(Schema.String),
313
- available_versions: Schema.Array(Schema.String),
314
- input_parameters: JsonRecordSchema,
315
- output_parameters: JsonRecordSchema,
316
- no_auth: Schema.Boolean.pipe(Schema.withDecodingDefaultType(Effect.succeed(false))),
317
- toolkit: Schema.Struct({
318
- name: Schema.String,
319
- slug: Schema.String,
320
- }).pipe(Schema.withDecodingDefaultType(Effect.succeed({ name: '', slug: '' }))),
321
-}).annotate({ identifier: 'ToolDetailedResponse' });
322
-export type ToolDetailedResponse = Schema.Schema.Type<typeof ToolDetailedResponse>;
323
-
324
-export const TriggerTypesAsEnumsResponse = TriggerTypesAsEnums;
325
-export type TriggerTypesAsEnumsResponse = Schema.Schema.Type<typeof TriggerTypesAsEnumsResponse>;
326
-
327
-export const TriggerTypesResponse = Schema.Struct({
328
- items: TriggerTypes,
329
- total_pages: Schema.Int,
330
- next_cursor: Schema.NullOr(Schema.String),
331
-}).annotate({ identifier: 'TriggerTypesResponse' });
332
-export type TriggerTypesResponse = Schema.Schema.Type<typeof TriggerTypesResponse>;
333
-
334
-export const TriggerInstancesListActiveResponse = Schema.Struct({
335
- items: TriggerInstanceItems,
336
- total_items: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(0))),
337
- total_pages: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(1))),
338
- current_page: Schema.Int.pipe(Schema.withDecodingDefaultType(Effect.succeed(1))),
339
- next_cursor: Schema.NullOr(Schema.String).pipe(
340
- Schema.withDecodingDefaultType(Effect.succeed(null))
341
- ),
342
-}).annotate({ identifier: 'TriggerInstancesListActiveResponse' });
343
-export type TriggerInstancesListActiveResponse = Schema.Schema.Type<
344
- typeof TriggerInstancesListActiveResponse
345
->;
346
-
347
-export const TriggerInstanceUpsertResponse = Schema.Struct({
348
- trigger_id: Schema.String,
349
-}).annotate({ identifier: 'TriggerInstanceUpsertResponse' });
350
-export type TriggerInstanceUpsertResponse = Schema.Schema.Type<
351
- typeof TriggerInstanceUpsertResponse
352
->;
353
-
354
-export const TriggerInstanceManageUpdateResponse = Schema.Struct({
355
- status: Schema.Literal('success'),
356
-}).annotate({ identifier: 'TriggerInstanceManageUpdateResponse' });
357
-export type TriggerInstanceManageUpdateResponse = Schema.Schema.Type<
358
- typeof TriggerInstanceManageUpdateResponse
359
->;
360
-
361
-export const TriggerInstanceManageDeleteResponse = Schema.Struct({
362
- trigger_id: Schema.String,
363
-}).annotate({ identifier: 'TriggerInstanceManageDeleteResponse' });
364
-export type TriggerInstanceManageDeleteResponse = Schema.Schema.Type<
365
- typeof TriggerInstanceManageDeleteResponse
366
->;
367
-
368
-/**
369
- * Response from GET /api/v3/auth/session/info.
370
- * Contains project, org member, and API key details for the authenticated session.
371
- * Fields like webhook_url, webhook_secret, auto_id, deleted are intentionally omitted.
340
+ * CLI-owned response contracts
341
+ *
342
+ * Response types otherwise come from `@composio/client`. A schema stays here
343
+ * only where the CLI owns the contract: output allowlists that keep
344
+ * credential-bearing fields off stdout, and the single escape-hatch endpoint
345
+ * the client does not type.
346
*/
373
-export const SessionInfoResponse = Schema.Struct({
374
- project: Schema.Struct({
375
- name: Schema.String,
376
- id: Schema.String,
377
- org_id: Schema.String,
378
- nano_id: Schema.String,
379
- email: Schema.String,
380
- created_at: Schema.String,
381
- updated_at: Schema.String,
382
- org: Schema.Struct({
383
- name: Schema.String,
384
- id: Schema.String,
385
- plan: Schema.String,
386
- }),
387
- }),
388
- org_member: Schema.Struct({
389
- id: Schema.String,
390
- user_id: Schema.optional(Schema.String),
391
- email: Schema.String,
392
- name: Schema.String,
393
- role: Schema.String,
394
- }),
395
- api_key: Schema.NullOr(
396
- Schema.Struct({
397
- name: Schema.String,
398
- project_id: Schema.String,
399
- id: Schema.String,
400
- org_member_id: Schema.String,
401
- api_key: Schema.optional(Schema.String),
402
- key: Schema.optional(Schema.String),
403
- })
404
- ),
405
-}).annotate({ identifier: 'SessionInfoResponse' });
406
-export type SessionInfoResponse = Schema.Schema.Type<typeof SessionInfoResponse>;
407
-
408
-const authHeaderForApiKey = (apiKey: string): Record<string, string> => ({
409
- 'x-user-api-key': apiKey,
410
-});
411
-
412
-export interface TriggerInstancesListActiveParams {
413
- user_ids?: string[];
414
- connected_account_ids?: string[];
415
- auth_config_ids?: string[];
416
- trigger_ids?: string[];
417
- trigger_names?: string[];
418
- show_disabled?: boolean;
419
- limit?: number;
420
-}
421
-
422
-export interface TriggerInstanceUpsertParams {
423
- connected_account_id?: string;
424
- trigger_config?: Record<string, unknown>;
425
-}
426
-
427
-function buildTriggerInstancesNamespace(
428
- clientSingleton: ComposioClientSingletonShape,
429
- withMetrics: <A, E, R>(
430
- effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
431
- ) => Effect.Effect<A, E, R>
432
-) {
433
- return {
434
- /**
435
- * Lists active trigger instances with optional filters.
436
- * Returns a single page of results.
437
- */
438
- listActive: (params: TriggerInstancesListActiveParams) =>
439
- withMetrics(
440
- callClient(
441
- clientSingleton,
442
- client =>
443
- client.triggerInstances.listActive({
444
- user_ids: params.user_ids,
445
- connected_account_ids: params.connected_account_ids,
446
- auth_config_ids: params.auth_config_ids,
447
- trigger_ids: params.trigger_ids,
448
- trigger_names: params.trigger_names,
449
- show_disabled: params.show_disabled,
450
- limit: params.limit,
451
- }),
452
- TriggerInstancesListActiveResponse
453
- )
454
- ),
455
- upsert: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
456
- withMetrics(
457
- callClient(
458
- clientSingleton,
459
- client => client.triggerInstances.upsert(triggerSlug, params),
460
- TriggerInstanceUpsertResponse
461
- )
462
- ),
463
- manageUpdate: (triggerId: string, params: { status: 'enable' | 'disable' }) =>
464
- withMetrics(
465
- callClient(
466
- clientSingleton,
467
- client => client.triggerInstances.manage.update(triggerId, params),
468
- TriggerInstanceManageUpdateResponse
469
- )
470
- ),
471
- manageDelete: (triggerId: string) =>
472
- withMetrics(
473
- callClient(
474
- clientSingleton,
475
- client => client.triggerInstances.manage.delete(triggerId),
476
- TriggerInstanceManageDeleteResponse
477
- )
478
- ),
479
- };
480
-}
481
-
482
-function buildTriggerInstanceRepositoryOperations(client: ComposioClientLiveShape) {
483
- return {
484
- listActiveTriggers: (params: TriggerInstancesListActiveParams) =>
485
- client.triggerInstances.listActive(params),
486
- createTrigger: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
487
- client.triggerInstances.upsert(triggerSlug, params),
488
- enableTrigger: (triggerId: string) =>
489
- client.triggerInstances.manageUpdate(triggerId, { status: 'enable' }),
490
- disableTrigger: (triggerId: string) =>
491
- client.triggerInstances.manageUpdate(triggerId, { status: 'disable' }),
492
- deleteTrigger: (triggerId: string) => client.triggerInstances.manageDelete(triggerId),
493
- };
494
-}
495
-
496
-// Single-page search response (includes total_items for "Listing X of Y" display)
497
-export const ToolkitSearchResponse = Schema.Struct({
498
- items: Toolkits,
499
- total_items: Schema.Int,
500
- total_pages: Schema.Int,
501
- current_page: Schema.Int,
502
- next_cursor: Schema.NullOr(Schema.String),
503
-}).annotate({ identifier: 'ToolkitSearchResponse' });
504
-
505
-// Detailed retrieve response (includes auth_config_details)
506
-export const ToolkitDetailedResponse = ToolkitDetailed.annotate({
507
- identifier: 'ToolkitDetailedResponse',
508
-});
347
348
// Auth config list response (single page with total_items for "Listing X of Y" display)
349
export const AuthConfigListResponse = Schema.Struct({
357
}).annotate({ identifier: 'AuthConfigListResponse' });
358
export type AuthConfigListResponse = Schema.Schema.Type<typeof AuthConfigListResponse>;
359
522
-// Auth config retrieve response (same shape as a single list item)
523
-export const AuthConfigRetrieveResponse = AuthConfigItem.annotate({
524
- identifier: 'AuthConfigRetrieveResponse',
525
-});
526
-export type AuthConfigRetrieveResponse = Schema.Schema.Type<typeof AuthConfigRetrieveResponse>;
527
-
528
-// Auth config create response
529
-export const AuthConfigCreateResponse = Schema.Struct({
530
- auth_config: Schema.Struct({
531
- id: Schema.String,
532
- auth_scheme: Schema.String,
533
- is_composio_managed: Schema.Boolean,
534
- }),
535
- toolkit: Schema.Struct({
536
- slug: Schema.String,
537
- }),
538
-}).annotate({ identifier: 'AuthConfigCreateResponse' });
539
-export type AuthConfigCreateResponse = Schema.Schema.Type<typeof AuthConfigCreateResponse>;
540
-
360
// Connected account list response (single page with total_items for "Listing X of Y" display)
361
export const ConnectedAccountListResponse = Schema.Struct({
362
items: ConnectedAccountItems,
369
}).annotate({ identifier: 'ConnectedAccountListResponse' });
370
export type ConnectedAccountListResponse = Schema.Schema.Type<typeof ConnectedAccountListResponse>;
371
553
-// Connected account retrieve response (same shape as a single list item)
554
-export const ConnectedAccountRetrieveResponse = ConnectedAccountItem.annotate({
555
- identifier: 'ConnectedAccountRetrieveResponse',
556
-});
557
-
558
-// Link create response
559
-export const LinkCreateResponse = Schema.Struct({
560
- connected_account_id: Schema.String,
561
- expires_at: Schema.String,
562
- link_token: Schema.String,
563
- redirect_url: Schema.String,
564
-}).annotate({ identifier: 'LinkCreateResponse' });
565
-export type LinkCreateResponse = Schema.Schema.Type<typeof LinkCreateResponse>;
566
-export type ConnectedAccountRetrieveResponse = Schema.Schema.Type<
567
- typeof ConnectedAccountRetrieveResponse
568
->;
569
-
570
-/**
571
- * Error response schemas
572
- */
573
-export const HttpErrorResponse = Schema.Struct({
574
- status: Schema.Int,
575
- error: Schema.Struct({
576
- error: Schema.Struct({
577
- message: Schema.NonEmptyString,
578
- suggested_fix: Schema.String,
579
- code: Schema.Int,
580
- }),
372
+// `auth-configs create` prints this response to stdout, so it stays an
373
+// allowlist rather than the client's full type: a field the API adds later
374
+// must not reach a pipe without a decision here.
375
+export const AuthConfigCreateResponse = Schema.Struct({
376
+ auth_config: Schema.Struct({
377
+ id: Schema.String,
378
+ auth_scheme: Schema.String,
379
+ is_composio_managed: Schema.Boolean,
380
+ }),
381
+ toolkit: Schema.Struct({
382
+ slug: Schema.String,
383
}),
582
-}).annotate({ identifier: 'HttpErrorResponse' });
583
-export type HttpErrorResponse = Schema.Schema.Type<typeof HttpErrorResponse>;
384
+}).annotate({ identifier: 'AuthConfigCreateResponse' });
385
+export type AuthConfigCreateResponse = Schema.Schema.Type<typeof AuthConfigCreateResponse>;
386
+
387
+export const LatestToolVersionResponse = Schema.Struct({
388
+ tool_slug: Schema.String,
389
+ version: Schema.String,
390
+}).annotate({ identifier: 'LatestToolVersionResponse' });
391
+export type LatestToolVersionResponse = Schema.Schema.Type<typeof LatestToolVersionResponse>;
392
393
/**
586
- * Result of streaming a response with byte counting.
394
+ * Session info as the CLI consumes it: the client's response with `project`
395
+ * present. The endpoint answers `project: null` for org-level credentials,
396
+ * which every caller here treats as an unusable session.
397
*/
588
-interface StreamedResponse {
589
- /** The parsed JSON data from the response body */
590
- readonly json: unknown;
591
- /** The exact byte size of the response body */
592
- readonly byteSize: number;
593
-}
594
-
595
-type Metrics = {
596
- readonly byteSize: number;
597
- readonly requests: number;
398
+export type SessionInfoResponse = SessionRetrieveInfoResponse & {
399
+ readonly project: NonNullable<SessionRetrieveInfoResponse['project']>;
400
};
401
402
+const requireSessionProject = (
403
+ info: SessionRetrieveInfoResponse
404
+): Effect.Effect<SessionInfoResponse, HttpDecodingError> =>
405
+ info.project === null
406
+ ? Effect.fail(
407
+ new HttpDecodingError({
408
+ cause: 'Session info response has no project (org-level credentials)',
409
+ })
410
+ )
411
+ : Effect.succeed({ ...info, project: info.project });
412
+
413
/**
601
- * Handles HTTP error responses by reading the body and formatting a proper error message.
602
- * Attempts to decode the response as HttpErrorResponse for structured errors,
603
- * otherwise falls back to a generic error with status code.
604
- *
605
- * @param response - The Fetch API Response object with a non-OK status
606
- * @returns An Effect that always fails with HttpServerError containing formatted error details
414
+ * The org member's user id, falling back to the member id. The backend still
415
+ * sends `org_member.user_id` although the v3.1 spec omits it, and the persisted
416
+ * test user id derives from it, so it is read defensively.
417
*/
608
-const handleHttpErrorResponse = (response: Response): Effect.Effect<never, HttpServerError> =>
609
- Effect.gen(function* () {
610
- const status = response.status;
611
- const statusText = response.statusText;
612
-
613
- // Try to read the error body as JSON
614
- const errorBodyOpt = yield* Effect.tryPromise({
615
- try: () => response.json() as Promise<unknown>,
616
- catch: () => new HttpServerError({ cause: 'Failed to parse error response body' }),
617
- }).pipe(Effect.option);
618
-
619
- // Try to decode as structured error response
620
- if (Option.isSome(errorBodyOpt)) {
621
- const decodedOpt = Schema.decodeUnknownOption(HttpErrorResponse)(errorBodyOpt.value);
622
-
623
- if (Option.isSome(decodedOpt)) {
624
- const {
625
- error: { error },
626
- } = decodedOpt.value;
627
- const pretty = renderPrettyError([
628
- ['code', error.code],
629
- ['message', error.message],
630
- ['suggested fix', error.suggested_fix],
631
- ]);
632
-
633
- return yield* Effect.fail(
634
- new HttpServerError({
635
- cause: `HTTP ${status}\n${pretty}`,
636
- status,
637
- details: {
638
- message: error.message,
639
- suggestedFix: error.suggested_fix,
640
- code: error.code,
641
- },
642
- })
643
- );
644
- }
645
- }
646
-
647
- // Fallback to generic error message
648
- return yield* Effect.fail(
649
- new HttpServerError({
650
- cause: `HTTP ${status} ${statusText}`,
651
- status,
652
- })
653
- );
654
- });
418
+export const sessionUserIdOf = (info: SessionInfoResponse): string => {
419
+ const member: object = info.org_member;
420
+ return Predicate.hasProperty(member, 'user_id') && Predicate.isString(member.user_id)
421
+ ? member.user_id
422
+ : info.org_member.id;
423
+};
424
425
/**
657
- * Streams a Fetch Response body, counting bytes precisely and parsing JSON in a single pass.
658
- * Uses streaming to avoid loading the entire response into memory at once.
659
- *
660
- * @param response - The Fetch API Response object
661
- * @returns An Effect that yields the parsed JSON data and byte count
426
+ * The project API key carried by a session, or null. The v3.1 spec names the
427
+ * field `key`, and older responses spell it `api_key`; reading both keeps
428
+ * `composio dev init` from minting a second key when the backend sends the
429
+ * older spelling.
430
*/
663
-const streamResponseWithByteCount = (
664
- response: Response
665
-): Effect.Effect<StreamedResponse, HttpServerError> =>
666
- Effect.gen(function* () {
667
- const body = response.body;
668
- if (!body) {
669
- return yield* Effect.fail(
670
- new HttpServerError({
671
- cause: 'Response body is null',
672
- })
673
- );
674
- }
675
-
676
- // Convert the ReadableStream to an Effect Stream
677
- const byteStream = Stream.fromReadableStream({
678
- evaluate: () => body,
679
- onError: (error: unknown) =>
680
- new HttpServerError({
681
- cause: error,
682
- }),
683
- });
684
-
685
- // Collect all chunks while counting bytes (mutate array in-place for O(N) instead of O(N^2))
686
- const [chunks, byteSize] = yield* pipe(
687
- byteStream,
688
- Stream.runFold(
689
- (): [Uint8Array[], number] => [[], 0],
690
- ([chunks, size], chunk) => {
691
- chunks.push(chunk);
692
- return [chunks, size + chunk.byteLength] as [Uint8Array[], number];
693
- }
694
- )
695
- );
696
-
697
- // Merge chunks into a single Uint8Array
698
- const merged = new Uint8Array(byteSize);
699
- let offset = 0;
700
- for (const chunk of chunks) {
701
- merged.set(chunk, offset);
702
- offset += chunk.byteLength;
703
- }
704
-
705
- // Decode and parse JSON
706
- const text = new TextDecoder().decode(merged);
707
- const json = yield* Effect.try({
708
- try: () => JSON.parse(text) as unknown,
709
- catch: error =>
710
- new HttpServerError({
711
- cause: `Failed to parse JSON response: ${error}`,
712
- }),
713
- });
714
-
715
- return { json, byteSize };
716
- });
431
+export const sessionProjectApiKeyOf = (info: SessionInfoResponse): string | null => {
432
+ const apiKey: object | null = info.api_key;
433
+ if (apiKey === null) return null;
434
+ if (Predicate.hasProperty(apiKey, 'api_key') && Predicate.isString(apiKey.api_key)) {
435
+ return apiKey.api_key;
436
+ }
437
+ return info.api_key?.key ?? null;
438
+};
439
440
/**
719
- * A single project entry returned by GET /api/v3/org/project/list.
441
+ * A single project entry returned by GET /api/v3.1/org/project/list.
442
*/
721
-export const OrgProject = Schema.Struct({
722
- id: Schema.String,
723
- name: Schema.String,
724
- email: Schema.String,
725
- deleted: Schema.Boolean,
726
- org_id: Schema.String,
727
- created_at: Schema.String,
728
- updated_at: Schema.String,
729
-}).annotate({ identifier: 'OrgProject' });
730
-export type OrgProject = Schema.Schema.Type<typeof OrgProject>;
443
+export type OrgProject = ProjectListResponse.Data;
444
445
/**
733
- * Response from GET /api/v3/org/project/list.
446
+ * Response from GET /api/v3.1/org/project/list.
447
*/
735
-export const OrgProjectListResponse = Schema.Struct({
736
- data: Schema.Array(OrgProject),
737
- next_cursor: Schema.NullOr(Schema.String),
738
- total_pages: Schema.Int,
739
- current_page: Schema.Int,
740
- total_items: Schema.Int,
741
-}).annotate({ identifier: 'OrgProjectListResponse' });
742
-export type OrgProjectListResponse = Schema.Schema.Type<typeof OrgProjectListResponse>;
448
+export type OrgProjectListResponse = ProjectListResponse;
449
450
export interface OrganizationSummary {
451
readonly id: string;
467
readonly total_items: number;
468
}
469
764
-export const ConsumerProjectResolveResponse = Schema.Struct({
765
- project_id: Schema.String,
766
- project_nano_id: Schema.String,
767
- project_name: Schema.String,
768
- org_id: Schema.String,
769
- project_type: Schema.Literal('CONSUMER'),
770
- consumer_user_id: Schema.String,
771
-}).annotate({ identifier: 'ConsumerProjectResolveResponse' });
772
-export type ConsumerProjectResolveResponse = Schema.Schema.Type<
773
- typeof ConsumerProjectResolveResponse
774
->;
775
-
776
-export const LatestToolVersionResponse = Schema.Struct({
777
- tool_slug: Schema.String,
778
- version: Schema.String,
779
-}).annotate({ identifier: 'LatestToolVersionResponse' });
780
-export type LatestToolVersionResponse = Schema.Schema.Type<typeof LatestToolVersionResponse>;
781
-
782
-export const ConsumerConnectedToolkitsResponse = Schema.Struct({
783
- toolkits: Schema.Array(Schema.String),
784
-}).annotate({ identifier: 'ConsumerConnectedToolkitsResponse' });
785
-export type ConsumerConnectedToolkitsResponse = Schema.Schema.Type<
786
- typeof ConsumerConnectedToolkitsResponse
787
->;
788
-
789
-const extractArrayPayload = (json: unknown): ReadonlyArray<unknown> => {
790
- if (Array.isArray(json)) return json;
791
- if (json && typeof json === 'object') {
792
- const record = json as Record<string, unknown>;
793
- if (Array.isArray(record.organizations)) return record.organizations;
794
- if (Array.isArray(record.projects)) return record.projects;
795
- if (Array.isArray(record.data)) return record.data;
796
- if (Array.isArray(record.items)) return record.items;
797
- if (record.data && typeof record.data === 'object') {
798
- const nested = record.data as Record<string, unknown>;
799
- if (Array.isArray(nested.organizations)) return nested.organizations;
800
- if (Array.isArray(nested.projects)) return nested.projects;
801
- if (Array.isArray(nested.items)) return nested.items;
802
- if (Array.isArray(nested.data)) return nested.data;
803
- }
804
- }
805
- return [];
806
-};
807
-
808
-const readIdFromItem = (item: unknown): string | undefined => {
809
- if (!item || typeof item !== 'object') return undefined;
810
- const record = item as Record<string, unknown>;
811
- if (typeof record.id === 'string') return record.id;
812
- if (typeof record.nano_id === 'string') return record.nano_id;
813
- if (typeof record.org_id === 'string') return record.org_id;
814
- if (typeof record.project_id === 'string') return record.project_id;
815
- return undefined;
816
-};
817
-
818
-const readNameFromItem = (item: unknown): string | undefined => {
819
- if (!item || typeof item !== 'object') return undefined;
820
- const record = item as Record<string, unknown>;
821
- if (typeof record.name === 'string' && record.name.trim().length > 0) return record.name;
822
- if (typeof record.slug === 'string' && record.slug.trim().length > 0) return record.slug;
823
- return undefined;
824
-};
470
+export type ConsumerProjectResolveResponse = ProjectResolveResponse;
471
+export type ConsumerConnectedToolkitsResponse = ConsumerListConnectedToolkitsResponse;
472
826
-/**
827
- * Lists organizations available to the current user API key.
828
- * Uses plain fetch since this endpoint is not available in @composio/client.
829
- */
830
-export const listOrganizations = (params: {
831
- baseURL: string;
832
- apiKey: string;
473
+export interface TriggerInstancesListActiveParams {
474
+ user_ids?: string[];
475
+ connected_account_ids?: string[];
476
+ auth_config_ids?: string[];
477
+ trigger_ids?: string[];
478
+ trigger_names?: string[];
479
+ show_disabled?: boolean;
480
limit?: number;
834
-}): Effect.Effect<OrganizationListResponse, HttpServerError | HttpDecodingError> =>
835
- Effect.gen(function* () {
836
- const limit = params.limit ?? 50;
837
- const response = yield* Effect.tryPromise({
838
- try: () =>
839
- fetch(`${params.baseURL}/api/v3/org/list?limit=${limit}`, {
840
- method: 'GET',
841
- redirect: 'error',
842
- headers: {
843
- 'x-user-api-key': params.apiKey,
844
- 'User-Agent': '@composio/cli',
845
- Accept: 'application/json',
846
- 'Content-Type': 'application/json',
847
- },
848
- }),
849
- catch: error => new HttpServerError({ cause: error }),
850
- });
851
-
852
- if (!response.ok) {
853
- return yield* handleHttpErrorResponse(response);
854
- }
855
-
856
- const { json } = yield* streamResponseWithByteCount(response);
857
- const items = extractArrayPayload(json);
858
- const organizations = items
859
- .map(item => {
860
- const id = readIdFromItem(item);
861
- const name = readNameFromItem(item);
862
- if (!id || !name) return undefined;
863
- return { id, name } satisfies OrganizationSummary;
864
- })
865
- .filter((value): value is OrganizationSummary => value !== undefined);
481
+}
482
867
- return {
868
- data: organizations,
869
- total_items: organizations.length,
870
- };
871
- });
483
+export interface TriggerInstanceUpsertParams {
484
+ connected_account_id?: string;
485
+ trigger_config?: Record<string, unknown>;
486
+}
487
488
/**
874
- * Lists projects for a specific organization.
875
- * Uses plain fetch since this endpoint is not available in @composio/client.
489
+ * Client singleton
490
*/
877
-export const listOrganizationProjects = (params: {
878
- baseURL: string;
879
- apiKey: string;
880
- orgId: string;
881
- limit?: number;
882
-}): Effect.Effect<OrganizationProjectListResponse, HttpServerError | HttpDecodingError> =>
883
- Effect.gen(function* () {
884
- const limit = params.limit ?? 50;
885
- const response = yield* Effect.tryPromise({
886
- try: () =>
887
- fetch(`${params.baseURL}/api/v3/org/project/list?limit=${limit}`, {
888
- method: 'GET',
889
- redirect: 'error',
890
- headers: {
891
- 'x-user-api-key': params.apiKey,
892
- 'x-org-id': params.orgId,
893
- 'User-Agent': '@composio/cli',
894
- Accept: 'application/json',
895
- 'Content-Type': 'application/json',
896
- },
897
- }),
898
- catch: error => new HttpServerError({ cause: error }),
899
- });
491
901
- if (!response.ok) {
902
- return yield* handleHttpErrorResponse(response);
903
- }
492
+const normalizeApiKey = (rawApiKey?: string): string | undefined =>
493
+ typeof rawApiKey === 'string' && rawApiKey.trim().length > 0 ? rawApiKey : undefined;
494
905
- const { json } = yield* streamResponseWithByteCount(response);
906
- const items = extractArrayPayload(json);
907
- const projects = items
908
- .map(item => {
909
- const id = readIdFromItem(item);
910
- const name = readNameFromItem(item);
911
- if (!id || !name) return undefined;
912
- return { id, name } satisfies OrganizationProjectSummary;
913
- })
914
- .filter((value): value is OrganizationProjectSummary => value !== undefined);
915
-
916
- return {
917
- data: projects,
918
- total_items: projects.length,
919
- };
920
- });
921
-
922
-/**
923
- * Lists all projects for the logged-in user's organization.
924
- * Uses plain fetch since this endpoint is not available in @composio/client.
925
- *
926
- * @param params.baseURL - API base URL
927
- * @param params.apiKey - UAK (sent as `x-user-api-key`)
928
- * @param params.orgId - Organization ID (sent as `x-org-id`)
929
- * @param params.limit - Max projects to return (default 50)
930
- */
931
-export const listOrgProjects = (params: {
932
- baseURL: string;
933
- apiKey: string;
934
- orgId: string;
935
- limit?: number;
936
-}): Effect.Effect<OrgProjectListResponse, HttpServerError | HttpDecodingError> =>
937
- Effect.gen(function* () {
938
- const limit = params.limit ?? 50;
939
- const response = yield* Effect.tryPromise({
940
- try: () =>
941
- fetch(
942
- `${params.baseURL}/api/v3/org/project/list?list_all_org_projects=true&limit=${limit}`,
943
- {
944
- method: 'GET',
945
- redirect: 'error',
946
- headers: {
947
- 'x-user-api-key': params.apiKey,
948
- 'x-org-id': params.orgId,
949
- 'User-Agent': '@composio/cli',
950
- Accept: 'application/json',
951
- 'Content-Type': 'application/json',
952
- },
953
- }
954
- ),
955
- catch: error => new HttpServerError({ cause: error }),
956
- });
957
-
958
- if (!response.ok) {
959
- return yield* handleHttpErrorResponse(response);
960
- }
961
-
962
- const { json } = yield* streamResponseWithByteCount(response);
963
-
964
- return yield* pipe(
965
- Schema.decodeUnknownEffect(OrgProjectListResponse)(json),
966
- Effect.catchTag(
967
- 'SchemaError',
968
- e =>
969
- new HttpDecodingError({
970
- cause: `SchemaError\n ${e.message}`,
971
- })
972
- )
973
- );
974
- });
975
-
976
-/**
977
- * Calls GET /api/v3/auth/session/info with the full layered auth headers.
978
- * Uses plain fetch since this endpoint is not available in @composio/client.
979
- * This is a standalone function, NOT on ComposioSessionRepository, to keep
980
- * the repository as a pure facade over @composio/client.
981
- */
982
-export const getSessionInfo = (params: {
983
- baseURL: string;
984
- apiKey: string;
985
- orgId: string;
986
- projectId: string;
987
-}): Effect.Effect<SessionInfoResponse, HttpServerError | HttpDecodingError> =>
988
- Effect.gen(function* () {
989
- const response = yield* Effect.tryPromise({
990
- try: () =>
991
- fetch(`${params.baseURL}/api/v3/auth/session/info`, {
992
- method: 'GET',
993
- redirect: 'error',
994
- headers: {
995
- ...authHeaderForApiKey(params.apiKey),
996
- 'x-org-id': params.orgId,
997
- 'x-project-id': params.projectId,
998
- 'User-Agent': '@composio/cli',
999
- Accept: '*/*',
1000
- 'Content-Type': 'application/json',
1001
- },
1002
- }),
1003
- catch: error => new HttpServerError({ cause: error }),
1004
- });
1005
-
1006
- if (!response.ok) {
1007
- return yield* handleHttpErrorResponse(response);
1008
- }
1009
-
1010
- const { json } = yield* streamResponseWithByteCount(response);
1011
-
1012
- return yield* pipe(
1013
- Schema.decodeUnknownEffect(SessionInfoResponse)(json),
1014
- Effect.catchTag(
1015
- 'SchemaError',
1016
- e =>
1017
- new HttpDecodingError({
1018
- cause: `SchemaError\n ${e.message}`,
1019
- })
1020
- )
1021
- );
1022
- });
1023
-
1024
-/**
1025
- * Calls GET /api/v3/auth/session/info using the x-user-api-key header.
1026
- * Unlike getSessionInfo which requires both org AND project IDs, this variant
1027
- * resolves session metadata from the UAK alone — useful during login before
1028
- * org/project context is known.
1029
- *
1030
- * When `orgId` is provided, it is forwarded as `x-org-id` so the backend
1031
- * resolves the session against the caller's currently-selected global org
1032
- * (set via `composio orgs switch`). Without it, the backend falls back to the
1033
- * API key's home org, which makes the response ignore any org switch.
1034
- * Uses plain fetch since this endpoint is not available in @composio/client.
1035
- */
1036
-export const getSessionInfoByUserApiKey = (params: {
1037
- baseURL: string;
1038
- userApiKey: string;
1039
- orgId?: string;
1040
-}): Effect.Effect<SessionInfoResponse, HttpServerError | HttpDecodingError> =>
1041
- Effect.gen(function* () {
1042
- const response = yield* Effect.tryPromise({
1043
- try: () =>
1044
- fetch(`${params.baseURL}/api/v3/auth/session/info`, {
1045
- method: 'GET',
1046
- redirect: 'error',
1047
- headers: {
1048
- 'x-user-api-key': params.userApiKey,
1049
- ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
1050
- 'User-Agent': '@composio/cli',
1051
- Accept: '*/*',
1052
- 'Content-Type': 'application/json',
1053
- },
1054
- }),
1055
- catch: error => new HttpServerError({ cause: error }),
1056
- });
1057
-
1058
- if (!response.ok) {
1059
- return yield* handleHttpErrorResponse(response);
1060
- }
1061
-
1062
- const { json } = yield* streamResponseWithByteCount(response);
1063
-
1064
- return yield* pipe(
1065
- Schema.decodeUnknownEffect(SessionInfoResponse)(json),
1066
- Effect.catchTag(
1067
- 'SchemaError',
1068
- e =>
1069
- new HttpDecodingError({
1070
- cause: `SchemaError\n ${e.message}`,
1071
- })
1072
- )
1073
- );
1074
- });
1075
-
1076
-const getApiKeyFromPayload = (payload: unknown): string | undefined => {
1077
- const candidates = new Set<string>(['api_key', 'apiKey', 'key', 'token']);
1078
- const keyPrefixes = ['uak_', 'ak_'];
1079
- const queue: unknown[] = [payload];
1080
-
1081
- while (queue.length > 0) {
1082
- const current = queue.shift();
1083
- if (!current || typeof current !== 'object') continue;
1084
-
1085
- if (Array.isArray(current)) {
1086
- queue.push(...current);
1087
- continue;
1088
- }
1089
-
1090
- const entries = Object.entries(current as Record<string, unknown>);
1091
- for (const [key, value] of entries) {
1092
- if (
1093
- typeof value === 'string' &&
1094
- candidates.has(key) &&
1095
- keyPrefixes.some(prefix => value.startsWith(prefix))
1096
- ) {
1097
- return value;
1098
- }
1099
- if (value && typeof value === 'object') {
1100
- queue.push(value);
1101
- }
1102
- }
1103
- }
1104
-
1105
- return undefined;
1106
-};
1107
-
1108
-export const createProjectApiKey = (params: {
1109
- baseURL: string;
1110
- apiKey: string;
1111
- orgId: string;
1112
- projectId: string;
1113
- name: string;
1114
-}): Effect.Effect<string, HttpServerError | HttpDecodingError> =>
1115
- Effect.gen(function* () {
1116
- const response = yield* Effect.tryPromise({
1117
- try: () =>
1118
- fetch(`${params.baseURL}/api/v3/org/project/${params.projectId}/api_keys/create`, {
1119
- method: 'POST',
1120
- redirect: 'error',
1121
- headers: {
1122
- ...authHeaderForApiKey(params.apiKey),
1123
- 'x-org-id': params.orgId,
1124
- 'x-project-id': params.projectId,
1125
- 'User-Agent': '@composio/cli',
1126
- Accept: '*/*',
1127
- 'Content-Type': 'application/json',
1128
- },
1129
- body: JSON.stringify({ name: params.name }),
1130
- }),
1131
- catch: error => new HttpServerError({ cause: error }),
1132
- });
1133
-
1134
- if (!response.ok) {
1135
- return yield* handleHttpErrorResponse(response);
1136
- }
1137
-
1138
- const { json } = yield* streamResponseWithByteCount(response);
1139
- const createdApiKey = getApiKeyFromPayload(json);
1140
-
1141
- if (!createdApiKey) {
1142
- return yield* Effect.fail(
1143
- new HttpDecodingError({
1144
- cause: 'Create API key response did not contain an API key',
1145
- })
1146
- );
1147
- }
1148
-
1149
- return createdApiKey;
1150
- });
1151
-
1152
-export const resolveConsumerProject = (params: {
1153
- baseURL: string;
1154
- apiKey: string;
1155
- orgId: string;
1156
-}): Effect.Effect<ConsumerProjectResolveResponse, HttpServerError | HttpDecodingError> =>
1157
- Effect.gen(function* () {
1158
- const response = yield* Effect.tryPromise({
1159
- try: () =>
1160
- fetch(`${params.baseURL}/api/v3/org/consumer/project/resolve`, {
1161
- method: 'POST',
1162
- redirect: 'error',
1163
- headers: {
1164
- 'x-user-api-key': params.apiKey,
1165
- 'x-org-id': params.orgId,
1166
- 'User-Agent': '@composio/cli',
1167
- Accept: 'application/json',
1168
- 'Content-Type': 'application/json',
1169
- },
1170
- }),
1171
- catch: error => new HttpServerError({ cause: error }),
1172
- });
1173
-
1174
- if (!response.ok) {
1175
- return yield* handleHttpErrorResponse(response);
1176
- }
1177
-
1178
- const { json } = yield* streamResponseWithByteCount(response);
1179
-
1180
- return yield* pipe(
1181
- Schema.decodeUnknownEffect(ConsumerProjectResolveResponse)(json),
1182
- Effect.catchTag(
1183
- 'SchemaError',
1184
- e =>
1185
- new HttpDecodingError({
1186
- cause: `SchemaError\n ${e.message}`,
1187
- })
1188
- )
1189
- );
1190
- });
1191
-
1192
-export const getLatestToolVersion = (params: {
1193
- baseURL: string;
1194
- apiKey: string;
1195
- toolSlug: string;
1196
- orgId?: string;
1197
- projectId?: string;
1198
- projectApiKey?: string;
1199
-}): Effect.Effect<LatestToolVersionResponse, HttpServerError | HttpDecodingError> =>
1200
- Effect.gen(function* () {
1201
- const response = yield* Effect.tryPromise({
1202
- try: () =>
1203
- fetch(
1204
- `${params.baseURL}/api/v3/tools/${encodeURIComponent(params.toolSlug)}/get_latest_version`,
1205
- {
1206
- method: 'GET',
1207
- redirect: 'error',
1208
- headers: {
1209
- ...(params.projectApiKey
1210
- ? ({ 'x-api-key': params.projectApiKey } satisfies Record<string, string>)
1211
- : ({ 'x-user-api-key': params.apiKey } satisfies Record<string, string>)),
1212
- ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
1213
- ...(params.projectId ? { 'x-project-id': params.projectId } : {}),
1214
- 'User-Agent': '@composio/cli',
1215
- Accept: 'application/json',
1216
- 'Content-Type': 'application/json',
1217
- },
1218
- }
1219
- ),
1220
- catch: error => new HttpServerError({ cause: error }),
1221
- });
1222
-
1223
- if (!response.ok) {
1224
- return yield* handleHttpErrorResponse(response);
1225
- }
1226
-
1227
- const { json } = yield* streamResponseWithByteCount(response);
1228
-
1229
- return yield* pipe(
1230
- Schema.decodeUnknownEffect(LatestToolVersionResponse)(json),
1231
- Effect.catchTag(
1232
- 'SchemaError',
1233
- e =>
1234
- new HttpDecodingError({
1235
- cause: `SchemaError\n ${e.message}`,
1236
- })
1237
- )
1238
- );
1239
- });
1240
-
1241
-export const getConsumerConnectedToolkits = (params: {
1242
- baseURL: string;
1243
- apiKey: string;
1244
- orgId: string;
1245
- consumerUserId: string;
1246
-}): Effect.Effect<ConsumerConnectedToolkitsResponse, HttpServerError | HttpDecodingError> =>
1247
- Effect.gen(function* () {
1248
- const response = yield* Effect.tryPromise({
1249
- try: () =>
1250
- fetch(
1251
- `${params.baseURL}/api/v3/org/consumer/connected_toolkits?user_id=${encodeURIComponent(params.consumerUserId)}`,
1252
- {
1253
- method: 'GET',
1254
- redirect: 'error',
1255
- headers: {
1256
- 'x-user-api-key': params.apiKey,
1257
- 'x-org-id': params.orgId,
1258
- 'User-Agent': '@composio/cli',
1259
- Accept: 'application/json',
1260
- 'Content-Type': 'application/json',
1261
- },
1262
- }
1263
- ),
1264
- catch: error => new HttpServerError({ cause: error }),
1265
- });
1266
-
1267
- if (!response.ok) {
1268
- return yield* handleHttpErrorResponse(response);
1269
- }
1270
-
1271
- const { json } = yield* streamResponseWithByteCount(response);
1272
-
1273
- return yield* pipe(
1274
- Schema.decodeUnknownEffect(ConsumerConnectedToolkitsResponse)(json),
1275
- Effect.catchTag(
1276
- 'SchemaError',
1277
- e =>
1278
- new HttpDecodingError({
1279
- cause: `SchemaError\n ${e.message}`,
1280
- })
1281
- )
1282
- );
1283
- });
1284
-
1285
-export class DeveloperProjectNotFoundError extends Data.TaggedError(
1286
- 'services/DeveloperProjectNotFoundError'
1287
-)<{
1288
- readonly orgId: string;
1289
- readonly projectName: string;
1290
-}> {}
1291
-
1292
-export class AmbiguousDeveloperProjectNameError extends Data.TaggedError(
1293
- 'services/AmbiguousDeveloperProjectNameError'
1294
-)<{
1295
- readonly orgId: string;
1296
- readonly projectName: string;
1297
- readonly matches: ReadonlyArray<OrganizationProjectSummary>;
1298
-}> {}
1299
-
1300
-export const findDeveloperProjectByName = (params: {
1301
- baseURL: string;
1302
- apiKey: string;
1303
- orgId: string;
1304
- name: string;
1305
- limit?: number;
1306
-}): Effect.Effect<
1307
- OrganizationProjectSummary,
1308
- | DeveloperProjectNotFoundError
1309
- | AmbiguousDeveloperProjectNameError
1310
- | HttpServerError
1311
- | HttpDecodingError
1312
-> =>
1313
- Effect.gen(function* () {
1314
- const projects = yield* listOrgProjects({
1315
- baseURL: params.baseURL,
1316
- apiKey: params.apiKey,
1317
- orgId: params.orgId,
1318
- limit: params.limit,
1319
- });
1320
-
1321
- const normalizedName = String.toLowerCase(params.name.trim());
1322
- const matches = projects.data.filter(
1323
- project => String.toLowerCase(project.name) === normalizedName
1324
- );
1325
-
1326
- if (matches.length === 0) {
1327
- return yield* Effect.fail(
1328
- new DeveloperProjectNotFoundError({
1329
- orgId: params.orgId,
1330
- projectName: params.name,
1331
- })
1332
- );
1333
- }
1334
-
1335
- if (matches.length > 1) {
1336
- return yield* Effect.fail(
1337
- new AmbiguousDeveloperProjectNameError({
1338
- orgId: params.orgId,
1339
- projectName: params.name,
1340
- matches,
1341
- })
1342
- );
1343
- }
1344
-
1345
- return matches[0];
1346
- });
1347
-
1348
-const normalizeApiKey = (rawApiKey?: string): string | undefined =>
1349
- typeof rawApiKey === 'string' && rawApiKey.trim().length > 0 ? rawApiKey : undefined;
1350
-
1351
-const detectCliRuntime = (): string => {
1352
- if (typeof Bun !== 'undefined') {
1353
- return 'BUN';
1354
- }
495
+const detectCliRuntime = (): string => {
496
+ if (typeof Bun !== 'undefined') {
497
+ return 'BUN';
498
+ }
499
500
if (typeof process !== 'undefined' && process.versions?.node) {
501
return 'NODEJS';
529
: {}),
530
};
531
1388
- return Object.keys(defaultHeaders).length > 0 ? defaultHeaders : undefined;
1389
-};
1390
-
1391
-// Utility function for calling the Composio API and decoding its response.
1392
-const callClient = <T, S extends Schema.Top>(
1393
- clientSingleton: ComposioClientSingletonShape,
1394
- apiCall: (client: _RawComposioClient) => APIPromise<T>,
1395
- responseSchema: S
1396
-): Effect.Effect<
1397
- { data: S['Type']; metrics: Metrics },
1398
- HttpError | NoSuchElementError,
1399
- S['DecodingServices']
1400
-> =>
1401
- Effect.gen(function* () {
1402
- const client = yield* clientSingleton.get();
1403
- const response = yield* Effect.tryPromise({
1404
- try: () => apiCall(client).asResponse(),
1405
- catch: e =>
1406
- new HttpServerError({
1407
- cause: e,
1408
- }),
1409
- });
1410
-
1411
- // Check HTTP status before streaming - .asResponse() doesn't throw on HTTP errors
1412
- if (!response.ok) {
1413
- return yield* handleHttpErrorResponse(response);
1414
- }
1415
-
1416
- // Stream the response body with byte counting
1417
- const { json, byteSize } = yield* streamResponseWithByteCount(response);
1418
- const metrics = { byteSize, requests: 1 };
1419
-
1420
- const typedJson: S['Type'] = yield* pipe(
1421
- Schema.decodeUnknownEffect(responseSchema)(json),
1422
- Effect.catchTag(
1423
- 'SchemaError',
1424
- e =>
1425
- new HttpDecodingError({
1426
- cause: `SchemaError\n ${e.message}`,
1427
- })
1428
- )
1429
- );
1430
-
1431
- return { metrics, data: typedJson };
1432
- });
1433
-
1434
-// Schema constraint for paginated responses: the decoded page must expose the
1435
-// pagination envelope, expressed through the schema's `Type` phantom property so
1436
-// concrete item types stay free of `any`.
1437
-type PaginatedSchema = Schema.Top & {
1438
- readonly Type: {
1439
- readonly items: ReadonlyArray<unknown>;
1440
- readonly next_cursor: string | null;
1441
- readonly total_pages: number;
1442
- };
532
+ return defaultHeaders;
533
};
534
1445
-// Maximum items per page allowed by the server
1446
-const MAX_PAGE_SIZE = 1000;
1447
-
1448
-// Maximum concurrent requests per each endpoint
1449
-const MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 4;
1450
-
1451
-// Utility function for calling paginated Composio API endpoints.
1452
-// Automatically fetches all pages, using MAX_PAGE_SIZE per request.
1453
-const callClientWithPagination = <T, S extends PaginatedSchema>(
1454
- clientSingleton: ComposioClientSingletonShape,
1455
- apiCall: (client: _RawComposioClient, cursor?: string, limit?: number) => APIPromise<T>,
1456
- responseSchema: S
1457
-): Effect.Effect<
1458
- { data: S['Type']; metrics: Metrics },
1459
- HttpError | NoSuchElementError,
1460
- S['DecodingServices']
1461
-> =>
1462
- Effect.gen(function* () {
1463
- const client = yield* clientSingleton.get();
1464
- let totalByteSize = 0;
1465
- let totalRequests = 0;
1466
-
1467
- const fetchPage = (cursor?: string): Effect.Effect<StreamedResponse, HttpServerError> =>
1468
- Effect.gen(function* () {
1469
- const response = yield* Effect.tryPromise({
1470
- try: () => apiCall(client, cursor, MAX_PAGE_SIZE).asResponse(),
1471
- catch: e =>
1472
- new HttpServerError({
1473
- cause: e,
1474
- }),
1475
- });
1476
-
1477
- // Check HTTP status before streaming - .asResponse() doesn't throw on HTTP errors
1478
- if (!response.ok) {
1479
- return yield* handleHttpErrorResponse(response);
1480
- }
1481
-
1482
- // Stream the response body with byte counting
1483
- return yield* streamResponseWithByteCount(response);
1484
- });
1485
-
1486
- type DecodedPage = S['Type'];
1487
-
1488
- const decodeResponse = (json: unknown): Effect.Effect<DecodedPage, HttpDecodingError> =>
1489
- pipe(
1490
- Schema.decodeUnknownEffect(responseSchema)(json),
1491
- Effect.catchTag(
1492
- 'SchemaError',
1493
- e =>
1494
- new HttpDecodingError({
1495
- cause: `SchemaError\n ${e.message}`,
1496
- })
1497
- )
1498
- ) as Effect.Effect<DecodedPage, HttpDecodingError>;
1499
-
1500
- let allItems: ReadonlyArray<unknown> = [];
1501
- let currentCursor: string | null = null;
1502
- let totalPages = 0;
1503
-
1504
- // Fetch all pages using MAX_PAGE_SIZE per request
1505
- while (true) {
1506
- const { json, byteSize } = yield* fetchPage(currentCursor ?? undefined);
1507
- totalByteSize += byteSize;
1508
- totalRequests += 1;
1509
-
1510
- const decoded: DecodedPage = yield* decodeResponse(json);
1511
-
1512
- allItems = allItems.concat(decoded.items);
1513
- totalPages = decoded.total_pages;
1514
- currentCursor = decoded.next_cursor;
1515
-
1516
- // Stop if no more pages
1517
- if (currentCursor === null) {
1518
- break;
1519
- }
1520
- }
1521
-
1522
- const metrics = { byteSize: totalByteSize, requests: totalRequests };
1523
-
1524
- return {
1525
- data: {
1526
- items: allItems,
1527
- total_pages: totalPages,
1528
- next_cursor: currentCursor,
1529
- } as DecodedPage,
1530
- metrics,
1531
- };
1532
- });
1533
-
1534
-/**
1535
- * Services
1536
- */
1537
-
535
/**
536
* Shape exposed by {@link ComposioClientSingleton}.
537
*/
538
export interface ComposioClientSingletonShape {
1542
- readonly get: () => Effect.Effect<_RawComposioClient, NoSuchElementError>;
539
+ readonly get: () => Effect.Effect<
540
+ _RawComposioClient,
541
+ ComposioClientConfigurationError | NoSuchElementError
542
+ >;
543
readonly getFor: (params: {
544
userApiKey?: string;
545
orgId?: string;
546
projectId?: string;
1547
- }) => Effect.Effect<_RawComposioClient, NoSuchElementError>;
547
+ }) => Effect.Effect<_RawComposioClient, ComposioClientConfigurationError | NoSuchElementError>;
548
+ /**
549
+ * Returns a snapshot of the accumulated metrics (total bytes received and
550
+ * request count) across every client this singleton built.
551
+ */
552
+ readonly getMetrics: () => Effect.Effect<{
553
+ readonly byteSize: number;
554
+ readonly requests: number;
555
+ }>;
556
}
557
558
/**
559
* Singleton service that lazily accesses `Config` only when needed, which is used to build and provide
560
* a raw (uneffectful, Promise-based) Composio client instance.
561
+ *
562
+ * Clients are built with `Composio.fromEnv({}, ...)` so the ambient process
563
+ * environment is never consulted: every credential and the base URL come from
564
+ * the CLI's own configuration. Custom HTTP base URLs remain supported. The user key is
565
+ * placed in `defaultHeaders` as `x-user-api-key`, which keeps today's wire
566
+ * bytes on every operation; it is also passed as `userApiKey`, while the
567
+ * caller-placed header still wins at dispatch.
568
*/
569
const makeComposioClientSingleton = Effect.gen(function* () {
570
const ctx = yield* ComposioUserContext;
572
const fs = yield* FileSystem.FileSystem;
573
const path = yield* Path.Path;
574
const os = yield* NodeOs;
575
+ const metrics = makeClientMetricsCollector();
576
const cache = new Map<string, _RawComposioClient>();
577
578
const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
594
Effect.provideService(NodeOs, os)
595
);
596
1581
- const client = new _RawComposioClient({
1582
- apiKey: null,
1583
- baseURL: ctx.data.baseURL,
1584
- defaultHeaders: buildDefaultHeaders({
1585
- userApiKey: apiKey,
1586
- orgId: params?.orgId,
1587
- projectId: params?.projectId,
1588
- cliSessionId,
1589
- }),
597
+ const client = yield* Effect.try({
598
+ try: () =>
599
+ // An empty environment prevents implicit env reads, including COMPOSIO_CUSTOM_HEADERS.
600
+ _RawComposioClient.fromEnv(
601
+ {},
602
+ {
603
+ apiKey: null,
604
+ userApiKey: apiKey ?? null,
605
+ orgApiKey: null,
606
+ baseURL: ctx.data.baseURL,
607
+ // Preserve support for explicitly configured HTTP backends.
608
+ allowInsecureHTTP: true,
609
+ logLevel: 'off',
610
+ defaultHeaders: buildDefaultHeaders({
611
+ userApiKey: apiKey,
612
+ orgId: params?.orgId,
613
+ projectId: params?.projectId,
614
+ cliSessionId,
615
+ }),
616
+ fetch: metrics.fetch,
617
+ }
618
+ ),
619
+ catch: cause =>
620
+ new ComposioClientConfigurationError({
621
+ message: cause instanceof Error ? cause.message : global.String(cause),
622
+ cause,
623
+ }),
624
});
625
626
cache.set(cacheKey, client);
642
projectId: keys.projectId,
643
}),
644
});
1611
- }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementError, never>,
645
+ }),
646
getFor: Effect.fn(function* (params: {
647
userApiKey?: string;
648
orgId?: string;
649
projectId?: string;
650
}) {
651
return yield* getFor(params);
1618
- }) satisfies (params: {
1619
- userApiKey?: string;
1620
- orgId?: string;
1621
- projectId?: string;
1622
- }) => Effect.Effect<_RawComposioClient, NoSuchElementError, never>,
1623
- };
652
+ }),
653
+ getMetrics: metrics.getMetrics,
654
+ } satisfies ComposioClientSingletonShape;
655
});
656
657
/**
662
readonly projectId: string;
663
}
664
1634
-/**
1635
- * A view of `clientSingleton` whose `get()` builds the client for `scope`,
1636
- * so the shared call helpers can make a request for a project other than the
1637
- * one the project context resolves.
1638
- */
1639
-const scopedClientSingleton = (
1640
- clientSingleton: ComposioClientSingletonShape,
1641
- scope: ToolkitProjectScope
1642
-): ComposioClientSingletonShape => ({
1643
- ...clientSingleton,
1644
- get: () => clientSingleton.getFor({ orgId: scope.orgId, projectId: scope.projectId }),
1645
-});
1646
-
665
export class ComposioClientSingleton extends Context.Service<
666
ComposioClientSingleton,
667
ComposioClientSingletonShape
672
}
673
674
/**
1657
- * Build the `tools` namespace for ComposioClientLive.
1658
- * Extracted to keep the main generator under the max-lines-per-function limit.
675
+ * Account, session-info, and consumer helpers
676
+ *
677
+ * Standalone functions rather than repository methods: they take explicit
678
+ * credentials and scope, and callers already run inside layers that provide
679
+ * `ComposioClientSingleton`.
680
*/
1660
-function buildToolsNamespace(
1661
- clientSingleton: ComposioClientSingletonShape,
1662
- withMetrics: <A, E, R>(
1663
- effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1664
- ) => Effect.Effect<A, E, R>
1665
-) {
1666
- return {
1667
- /**
1668
- * Retrieve a list of all available tool enumeration values (tool slugs) for the project.
1669
- */
1670
- retrieveEnum: () =>
1671
- withMetrics(
1672
- callClient(clientSingleton, client => client.tools.retrieveEnum(), ToolsAsEnumsResponse)
1673
- ),
1674
- /**
1675
- * Retrieve a list of tools, automatically handling pagination.
1676
- * It always fetches the latest version of tools for each toolkit.
1677
- * For more granular toolkit version control, use `listByVersionSpecs`.
1678
- * @param toolkitSlugs - Array of toolkit slugs to filter by
1679
- */
1680
- list: (toolkitSlugs: ReadonlyArray<string>) =>
1681
- withMetrics(
1682
- callClientWithPagination(
1683
- clientSingleton,
1684
- (client, cursor, limit) =>
1685
- client.tools.list({
1686
- cursor,
1687
- toolkit_slug: toolkitSlugs.length > 0 ? toolkitSlugs.join(',') : undefined,
1688
- toolkit_versions: 'latest',
1689
- limit,
1690
- }),
1691
- ToolsResponse
1692
- )
1693
- ),
1694
- /**
1695
- * Retrieve tools for multiple toolkits, grouped by version.
1696
- * Makes parallel API calls for each version group, then merges results.
1697
- * @param specs - Array of toolkit version specifications
1698
- */
1699
- listByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>
1700
- Effect.gen(function* () {
1701
- const grouped = groupByVersion(specs);
1702
- const versionGroups = [...grouped.entries()];
1703
-
1704
- // Fetch all version groups in parallel with bounded concurrency
1705
- const responses = yield* Effect.all(
1706
- versionGroups.map(([version, slugs]) =>
1707
- withMetrics(
1708
- callClientWithPagination(
1709
- clientSingleton,
1710
- (client, cursor, limit) =>
1711
- client.tools.list({
1712
- cursor,
1713
- toolkit_slug: slugs.join(','),
1714
- toolkit_versions: version,
1715
- limit,
1716
- }),
1717
- ToolsResponse
1718
- )
1719
- )
1720
- ),
1721
- { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
1722
- );
681
1724
- // Merge all tools from all version groups
1725
- const allTools = responses.flatMap(response => response.items);
1726
- return { items: allTools };
682
+const orgScopedOptions = (orgId: string | undefined): RequestOptions | undefined =>
683
+ orgId ? { headers: { 'x-org-id': orgId } } : undefined;
684
+
685
+/**
686
+ * Lists organizations available to the current user API key.
687
+ */
688
+export const listOrganizations = (params: {
689
+ apiKey: string;
690
+ limit?: number;
691
+}): Effect.Effect<OrganizationListResponse, ClientError, ComposioClientSingleton> =>
692
+ Effect.gen(function* () {
693
+ const clientSingleton = yield* ComposioClientSingleton;
694
+ const response = yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
695
+ client.org.list({ limit: params.limit ?? 50 })
696
+ );
697
+ const organizations = response.organizations.map(
698
+ (organization: OrgListResponse.Organization) =>
699
+ ({ id: organization.id, name: organization.name }) satisfies OrganizationSummary
700
+ );
701
+
702
+ return {
703
+ data: organizations,
704
+ total_items: organizations.length,
705
+ };
706
+ });
707
+
708
+/**
709
+ * Lists projects for a specific organization.
710
+ */
711
+export const listOrganizationProjects = (params: {
712
+ apiKey: string;
713
+ orgId: string;
714
+ limit?: number;
715
+}): Effect.Effect<OrganizationProjectListResponse, ClientError, ComposioClientSingleton> =>
716
+ Effect.gen(function* () {
717
+ const clientSingleton = yield* ComposioClientSingleton;
718
+ const response = yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
719
+ client.org.project.list({ limit: params.limit ?? 50 }, orgScopedOptions(params.orgId))
720
+ );
721
+ const projects = response.data.map(
722
+ (project: OrgProject) =>
723
+ ({ id: project.id, name: project.name }) satisfies OrganizationProjectSummary
724
+ );
725
+
726
+ return {
727
+ data: projects,
728
+ total_items: projects.length,
729
+ };
730
+ });
731
+
732
+/**
733
+ * Lists all projects for the logged-in user's organization.
734
+ *
735
+ * @param params.apiKey - UAK (sent as `x-user-api-key`)
736
+ * @param params.orgId - Organization ID (sent as `x-org-id`)
737
+ * @param params.limit - Max projects to return (default 50)
738
+ */
739
+export const listOrgProjects = (params: {
740
+ apiKey: string;
741
+ orgId: string;
742
+ limit?: number;
743
+}): Effect.Effect<OrgProjectListResponse, ClientError, ComposioClientSingleton> =>
744
+ Effect.gen(function* () {
745
+ const clientSingleton = yield* ComposioClientSingleton;
746
+ return yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
747
+ client.org.project.list(
748
+ { list_all_org_projects: true, limit: params.limit ?? 50 },
749
+ orgScopedOptions(params.orgId)
750
+ )
751
+ );
752
+ });
753
+
754
+/**
755
+ * Calls GET /api/v3.1/auth/session/info with the full layered auth headers.
756
+ */
757
+export const getSessionInfo = (params: {
758
+ apiKey: string;
759
+ orgId: string;
760
+ projectId: string;
761
+}): Effect.Effect<SessionInfoResponse, ClientError, ComposioClientSingleton> =>
762
+ Effect.gen(function* () {
763
+ const clientSingleton = yield* ComposioClientSingleton;
764
+ const info = yield* request(
765
+ clientSingleton.getFor({
766
+ userApiKey: params.apiKey,
767
+ orgId: params.orgId,
768
+ projectId: params.projectId,
769
}),
1728
- /**
1729
- * Search tools with optional filters. Returns a single page of results (no auto-pagination).
1730
- * @param params - Search/filter parameters
1731
- */
1732
- search: (params: {
1733
- search?: string;
1734
- toolkit_slug?: string;
1735
- tags?: string;
1736
- limit?: number;
1737
- cursor?: string;
1738
- }) =>
1739
- withMetrics(
1740
- callClient(
1741
- clientSingleton,
1742
- client =>
1743
- client.tools.list({
1744
- search: params.search,
1745
- toolkit_slug: params.toolkit_slug,
1746
- tags: params.tags ? params.tags.split(',').map(t => t.trim()) : undefined,
1747
- limit: params.limit,
1748
- cursor: params.cursor,
1749
- toolkit_versions: 'latest',
1750
- }),
1751
- ToolsResponse
1752
- )
1753
- ),
1754
- /**
1755
- * Retrieves detailed info about a single tool by slug.
1756
- * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")
1757
- */
1758
- retrieve: (slug: string) =>
1759
- withMetrics(
1760
- callClient(
1761
- clientSingleton,
1762
- client => client.tools.retrieve(slug, { toolkit_versions: 'latest' }),
1763
- ToolDetailedResponse
1764
- )
1765
- ),
1766
- };
1767
-}
770
+ client => client.auth.session.retrieveInfo()
771
+ );
772
+ return yield* requireSessionProject(info);
773
+ });
774
+
775
+/**
776
+ * Calls GET /api/v3.1/auth/session/info using the x-user-api-key header.
777
+ * Unlike getSessionInfo which requires both org AND project IDs, this variant
778
+ * resolves session metadata from the UAK alone — useful during login before
779
+ * org/project context is known.
780
+ *
781
+ * When `orgId` is provided, it is forwarded as `x-org-id` so the backend
782
+ * resolves the session against the caller's currently-selected global org
783
+ * (set via `composio orgs switch`). Without it, the backend falls back to the
784
+ * API key's home org, which makes the response ignore any org switch.
785
+ */
786
+export const getSessionInfoByUserApiKey = (params: {
787
+ userApiKey: string;
788
+ orgId?: string;
789
+}): Effect.Effect<SessionInfoResponse, ClientError, ComposioClientSingleton> =>
790
+ Effect.gen(function* () {
791
+ const clientSingleton = yield* ComposioClientSingleton;
792
+ const info = yield* request(clientSingleton.getFor({ userApiKey: params.userApiKey }), client =>
793
+ client.auth.session.retrieveInfo(orgScopedOptions(params.orgId))
794
+ );
795
+ return yield* requireSessionProject(info);
796
+ });
797
+
798
+// The create-api-key response shape is not documented in the client. Walk the
799
+// body for the first `uak_`/`ak_`-prefixed string under a key-like name.
800
+const getApiKeyFromPayload = (payload: unknown): string | undefined => {
801
+ const candidates = new Set<string>(['api_key', 'apiKey', 'key', 'token']);
802
+ const keyPrefixes = ['uak_', 'ak_'];
803
+ const queue: unknown[] = [payload];
804
+
805
+ while (queue.length > 0) {
806
+ const current = queue.shift();
807
+ if (!current || typeof current !== 'object') continue;
808
+
809
+ if (Array.isArray(current)) {
810
+ queue.push(...current);
811
+ continue;
812
+ }
813
+
814
+ const entries = Object.entries(current as Record<string, unknown>);
815
+ for (const [key, value] of entries) {
816
+ if (
817
+ typeof value === 'string' &&
818
+ candidates.has(key) &&
819
+ keyPrefixes.some(prefix => value.startsWith(prefix))
820
+ ) {
821
+ return value;
822
+ }
823
+ if (value && typeof value === 'object') {
824
+ queue.push(value);
825
+ }
826
+ }
827
+ }
828
+
829
+ return undefined;
830
+};
831
+
832
+/**
833
+ * Mints a project API key. Never retried: a retry after a timed-out create
834
+ * would mint a second key the caller never sees.
835
+ */
836
+export const createProjectApiKey = (params: {
837
+ apiKey: string;
838
+ orgId: string;
839
+ projectId: string;
840
+ name: string;
841
+}): Effect.Effect<string, ClientError, ComposioClientSingleton> =>
842
+ Effect.gen(function* () {
843
+ const clientSingleton = yield* ComposioClientSingleton;
844
+ const payload = yield* request(
845
+ clientSingleton.getFor({
846
+ userApiKey: params.apiKey,
847
+ orgId: params.orgId,
848
+ projectId: params.projectId,
849
+ }),
850
+ client =>
851
+ client.post<unknown>(`/api/v3/org/project/${params.projectId}/api_keys/create`, {
852
+ body: { name: params.name },
853
+ maxRetries: 0,
854
+ })
855
+ );
856
+ const createdApiKey = getApiKeyFromPayload(payload);
857
1769
-/**
1770
- * Build the `authConfigs` namespace for ComposioClientLive.
1771
- * Extracted to keep the main generator under the max-lines-per-function limit.
1772
- */
1773
-function buildAuthConfigsNamespace(
1774
- clientSingleton: ComposioClientSingletonShape,
1775
- withMetrics: <A, E, R>(
1776
- effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1777
- ) => Effect.Effect<A, E, R>
1778
-) {
1779
- return {
1780
- /**
1781
- * List auth configs with optional filters. Returns a single page of results.
1782
- * @param params - Search/filter parameters
1783
- */
1784
- list: (params: {
1785
- search?: string;
1786
- toolkit_slug?: string;
1787
- limit?: number;
1788
- show_disabled?: boolean;
1789
- }) =>
1790
- withMetrics(
1791
- callClient(
1792
- clientSingleton,
1793
- client =>
1794
- client.authConfigs.list({
1795
- search: params.search,
1796
- toolkit_slug: params.toolkit_slug,
1797
- limit: params.limit,
1798
- show_disabled: params.show_disabled ?? true,
1799
- }),
1800
- AuthConfigListResponse
1801
- )
1802
- ),
1803
- /**
1804
- * Retrieves detailed info about a single auth config by its nanoid.
1805
- * @param nanoid - Auth config ID
1806
- */
1807
- retrieve: (nanoid: string) =>
1808
- withMetrics(
1809
- callClient(
1810
- clientSingleton,
1811
- client => client.authConfigs.retrieve(nanoid),
1812
- AuthConfigRetrieveResponse
1813
- )
1814
- ),
1815
- /**
1816
- * Creates a new auth config for a toolkit.
1817
- * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
1818
- */
1819
- create: (params: AuthConfigCreateParams) =>
1820
- withMetrics(
1821
- callClient(
1822
- clientSingleton,
1823
- client => client.authConfigs.create(params),
1824
- AuthConfigCreateResponse
1825
- )
1826
- ),
1827
- /**
1828
- * Soft-deletes an auth config by its nanoid.
1829
- * @param nanoid - Auth config ID
1830
- */
1831
- delete: (nanoid: string) =>
1832
- withMetrics(
1833
- callClient(clientSingleton, client => client.authConfigs.delete(nanoid), Schema.Unknown)
1834
- ),
1835
- };
1836
-}
858
+ if (!createdApiKey) {
859
+ return yield* Effect.fail(
860
+ new HttpDecodingError({
861
+ cause: 'Create API key response did not contain an API key',
862
+ })
863
+ );
864
+ }
865
+
866
+ return createdApiKey;
867
+ });
868
+
869
+export const resolveConsumerProject = (params: {
870
+ apiKey: string;
871
+ orgId: string;
872
+}): Effect.Effect<ConsumerProjectResolveResponse, ClientError, ComposioClientSingleton> =>
873
+ Effect.gen(function* () {
874
+ const clientSingleton = yield* ComposioClientSingleton;
875
+ return yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
876
+ client.org.consumer.project.resolve({
877
+ 'x-user-api-key': params.apiKey,
878
+ 'x-org-id': params.orgId,
879
+ })
880
+ );
881
+ });
882
883
/**
1839
- * Build the `connectedAccounts` namespace for ComposioClientLive.
1840
- * Extracted to keep the main generator under the max-lines-per-function limit.
884
+ * Resolves the latest version of a tool. When `projectApiKey` is given the
885
+ * request carries `x-api-key` instead of the user key, so exactly one
886
+ * credential is sent.
887
*/
1842
-function buildConnectedAccountsNamespace(
1843
- clientSingleton: ComposioClientSingletonShape,
1844
- withMetrics: <A, E, R>(
1845
- effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1846
- ) => Effect.Effect<A, E, R>
1847
-) {
1848
- return {
1849
- /**
1850
- * List connected accounts with optional filters. Returns a single page of results.
1851
- * @param params - Search/filter parameters
1852
- */
1853
- list: (params: {
1854
- toolkit_slugs?: string[];
1855
- user_ids?: string[];
1856
- statuses?: string[];
1857
- limit?: number;
1858
- }) =>
1859
- withMetrics(
1860
- callClient(
1861
- clientSingleton,
1862
- client =>
1863
- client.connectedAccounts.list({
1864
- toolkit_slugs: params.toolkit_slugs,
1865
- user_ids: params.user_ids,
1866
- // Bypass the stale Stainless union (still missing 'REVOKED')
1867
- // until @composio/client is regenerated.
1868
- statuses: params.statuses as ConnectedAccountListParams['statuses'],
1869
- limit: params.limit,
1870
- }),
1871
- ConnectedAccountListResponse
1872
- )
1873
- ),
1874
- /**
1875
- * Retrieves detailed info about a single connected account by its nanoid.
1876
- * @param nanoid - Connected account ID (e.g. "con_1a2b3c4d5e6f")
1877
- */
1878
- retrieve: (nanoid: string) =>
1879
- withMetrics(
1880
- callClient(
1881
- clientSingleton,
1882
- client => client.connectedAccounts.retrieve(nanoid),
1883
- ConnectedAccountRetrieveResponse
1884
- )
1885
- ),
1886
- /**
1887
- * Soft-deletes a connected account by its nanoid.
1888
- * @param nanoid - Connected account ID
1889
- */
1890
- delete: (nanoid: string) =>
1891
- withMetrics(
1892
- callClient(
1893
- clientSingleton,
1894
- client => client.connectedAccounts.delete(nanoid),
1895
- Schema.Unknown
888
+export const getLatestToolVersion = (params: {
889
+ apiKey: string;
890
+ toolSlug: string;
891
+ orgId?: string;
892
+ projectId?: string;
893
+ projectApiKey?: string;
894
+}): Effect.Effect<LatestToolVersionResponse, ClientError, ComposioClientSingleton> =>
895
+ Effect.gen(function* () {
896
+ const clientSingleton = yield* ComposioClientSingleton;
897
+ const headers = {
898
+ ...(params.projectApiKey
899
+ ? { 'x-api-key': params.projectApiKey, 'x-user-api-key': null }
900
+ : {}),
901
+ ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
902
+ ...(params.projectId ? { 'x-project-id': params.projectId } : {}),
903
+ };
904
+ const payload = yield* request(
905
+ clientSingleton.getFor({
906
+ userApiKey: params.apiKey,
907
+ orgId: params.orgId,
908
+ projectId: params.projectId,
909
+ }),
910
+ client =>
911
+ client.get<unknown>(
912
+ `/api/v3/tools/${encodeURIComponent(params.toolSlug)}/get_latest_version`,
913
+ { headers }
914
)
1897
- ),
1898
- /**
1899
- * Creates a new authentication link session for connecting an external account.
1900
- * @param params - auth_config_id and user_id
1901
- */
1902
- createLink: (params: { auth_config_id: string; user_id: string }) =>
1903
- withMetrics(
1904
- callClient(clientSingleton, client => client.link.create(params), LinkCreateResponse)
1905
- ),
1906
- };
1907
-}
915
+ );
916
+ return yield* decode(LatestToolVersionResponse)(payload);
917
+ });
918
1909
-// Service that wraps the raw Composio client, which is shared by all client services.
1910
-const makeComposioClientLive = Effect.gen(function* () {
1911
- const clientSingleton = yield* ComposioClientSingleton;
919
+export const getConsumerConnectedToolkits = (params: {
920
+ apiKey: string;
921
+ orgId: string;
922
+ consumerUserId: string;
923
+}): Effect.Effect<ConsumerConnectedToolkitsResponse, ClientError, ComposioClientSingleton> =>
924
+ Effect.gen(function* () {
925
+ const clientSingleton = yield* ComposioClientSingleton;
926
+ return yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
927
+ client.org.consumer.listConnectedToolkits({
928
+ user_id: params.consumerUserId,
929
+ 'x-user-api-key': params.apiKey,
930
+ 'x-org-id': params.orgId,
931
+ })
932
+ );
933
+ });
934
1913
- // Initialize metrics tracking via SynchronizedRef
1914
- const metricsRef = yield* SynchronizedRef.make<Metrics>({ byteSize: 0, requests: 0 });
935
+export class DeveloperProjectNotFoundError extends Data.TaggedError(
936
+ 'services/DeveloperProjectNotFoundError'
937
+)<{
938
+ readonly orgId: string;
939
+ readonly projectName: string;
940
+}> {}
941
1916
- // Helper to update metrics and return just the data
1917
- const withMetrics = <A, E, R>(
1918
- effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1919
- ): Effect.Effect<A, E, R> =>
1920
- Effect.gen(function* () {
1921
- const { data, metrics } = yield* effect;
1922
- yield* SynchronizedRef.update(metricsRef, current => ({
1923
- byteSize: current.byteSize + metrics.byteSize,
1924
- requests: current.requests + metrics.requests,
1925
- }));
1926
- return data;
942
+export class AmbiguousDeveloperProjectNameError extends Data.TaggedError(
943
+ 'services/AmbiguousDeveloperProjectNameError'
944
+)<{
945
+ readonly orgId: string;
946
+ readonly projectName: string;
947
+ readonly matches: ReadonlyArray<OrganizationProjectSummary>;
948
+}> {}
949
+
950
+export const findDeveloperProjectByName = (params: {
951
+ apiKey: string;
952
+ orgId: string;
953
+ name: string;
954
+ limit?: number;
955
+}): Effect.Effect<
956
+ OrganizationProjectSummary,
957
+ DeveloperProjectNotFoundError | AmbiguousDeveloperProjectNameError | ClientError,
958
+ ComposioClientSingleton
959
+> =>
960
+ Effect.gen(function* () {
961
+ const projects = yield* listOrgProjects({
962
+ apiKey: params.apiKey,
963
+ orgId: params.orgId,
964
+ limit: params.limit,
965
});
966
1929
- return {
1930
- /**
1931
- * Returns a snapshot of the current accumulated metrics (total bytes received and request count).
1932
- */
1933
- getMetrics: () => SynchronizedRef.get(metricsRef),
1934
- toolkits: {
1935
- /**
1936
- * Retrieves a comprehensive list of toolkits that are available to the authenticated project.
1937
- * Automatically handles pagination to fetch all items.
1938
- * @param managedBy - Which toolkits to list; the API defaults to Composio-managed ones
1939
- * @param scope - The org/project to list for, instead of the one the project context resolves
1940
- */
1941
- list: (managedBy?: 'composio' | 'project' | 'all', scope?: ToolkitProjectScope) =>
1942
- withMetrics(
1943
- callClientWithPagination(
1944
- scope ? scopedClientSingleton(clientSingleton, scope) : clientSingleton,
1945
- (client, cursor, limit) =>
1946
- client.toolkits.list({ cursor, limit, managed_by: managedBy }),
1947
- ToolkitsResponse
1948
- )
1949
- ),
1950
- /**
1951
- * Retrieves a single toolkit by its slug.
1952
- * Transforms the response to match the Toolkit schema.
1953
- */
1954
- retrieve: (slug: string) =>
1955
- withMetrics(
1956
- callClient(
1957
- clientSingleton,
1958
- client => client.toolkits.retrieve(slug),
1959
- ToolkitRetrieveResponse
1960
- )
1961
- ).pipe(
1962
- // Transform to Toolkit format by adding missing fields
1963
- Effect.map(
1964
- retrieved =>
1965
- ({
1966
- name: retrieved.name,
1967
- slug: retrieved.slug,
1968
- auth_schemes: [], // retrieve endpoint doesn't return auth_schemes
1969
- composio_managed_auth_schemes: retrieved.composio_managed_auth_schemes,
1970
- is_local_toolkit: retrieved.is_local_toolkit,
1971
- no_auth: retrieved.no_auth,
1972
- meta: retrieved.meta,
1973
- }) satisfies Toolkit
1974
- )
1975
- ),
1976
- /**
1977
- * Searches toolkits with optional filters. Returns a single page of results (no auto-pagination).
1978
- * @param params - Search/filter parameters
1979
- */
1980
- search: (params: { search?: string; category?: string; limit?: number; cursor?: string }) =>
1981
- withMetrics(
1982
- callClient(
1983
- clientSingleton,
1984
- client =>
1985
- client.toolkits.list({
1986
- search: params.search,
1987
- category: params.category,
1988
- limit: params.limit,
1989
- cursor: params.cursor,
1990
- }),
1991
- ToolkitSearchResponse
1992
- )
1993
- ).pipe(
1994
- Effect.map(
1995
- response =>
1996
- ({
1997
- items: response.items,
1998
- total_items: response.total_items,
1999
- total_pages: response.total_pages,
2000
- next_cursor: response.next_cursor,
2001
- }) satisfies ToolkitSearchResult
2002
- )
2003
- ),
2004
- /**
2005
- * Retrieves detailed toolkit info including auth_config_details.
2006
- * @param slug - Toolkit slug
2007
- */
2008
- retrieveDetailed: (slug: string) =>
2009
- withMetrics(
2010
- callClient(
2011
- clientSingleton,
2012
- client => client.toolkits.retrieve(slug),
2013
- ToolkitDetailedResponse
2014
- )
2015
- ),
2016
- },
2017
- tools: buildToolsNamespace(clientSingleton, withMetrics),
2018
- triggersTypes: {
2019
- /**
2020
- * Retrieves a list of all available trigger type enum values that can be used across the API.
2021
- */
2022
- retrieveEnum: () =>
2023
- withMetrics(
2024
- callClient(
2025
- clientSingleton,
2026
- client => client.triggersTypes.retrieveEnum(),
2027
- TriggerTypesAsEnumsResponse
2028
- )
2029
- ),
2030
- /**
2031
- * Retrieves detailed info about a single trigger type by slug.
2032
- * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
2033
- */
2034
- retrieve: (slug: string) =>
2035
- withMetrics(
2036
- callClient(clientSingleton, client => client.triggersTypes.retrieve(slug), TriggerType)
2037
- ),
2038
- /**
2039
- * Retrieve a list of trigger types, automatically handling pagination.
2040
- * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2041
- */
2042
- list: (toolkitSlugs?: ReadonlyArray<string>) =>
2043
- withMetrics(
2044
- callClientWithPagination(
2045
- clientSingleton,
2046
- (client, cursor, limit) =>
2047
- client.triggersTypes.list({
2048
- cursor,
2049
- limit,
2050
- toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,
2051
- }),
2052
- TriggerTypesResponse
2053
- )
2054
- ),
2055
- },
2056
- triggerInstances: buildTriggerInstancesNamespace(clientSingleton, withMetrics),
2057
- cli: {
2058
- /**
2059
- * Generates a new CLI session with a random 6-character code.
2060
- * @param params.scope - 'user' for login, 'project' for init (future)
2061
- *
2062
- * TODO: don't use `@composio/client`, wrap `fetch` directly.
2063
- */
2064
- createSession: (params?: { scope?: 'user' | 'project' }) =>
2065
- withMetrics(
2066
- callClient(
2067
- clientSingleton,
2068
- client =>
2069
- client.cli.createSession(
2070
- { scope: params?.scope ?? 'user' },
2071
- { headers: { 'Content-Type': 'application/json' } }
2072
- ),
2073
- CliCreateSessionResponse
2074
- )
2075
- ),
967
+ const normalizedName = String.toLowerCase(params.name.trim());
968
+ const matches = projects.data.filter(
969
+ project => String.toLowerCase(project.name) === normalizedName
970
+ );
971
2077
- /**
2078
- * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.
2079
- */
2080
- getSession: (session: { id: string }) =>
2081
- withMetrics(
2082
- callClient(
2083
- clientSingleton,
2084
- client => client.cli.getSession(session),
2085
- CliGetSessionResponse
2086
- )
2087
- ),
2088
- getRealtimeCredentials: () =>
2089
- withMetrics(
2090
- callClient(
2091
- clientSingleton,
2092
- client => client.cli.realtime.credentials(),
2093
- CliRealtimeCredentialsResponse
2094
- )
2095
- ),
2096
- authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2097
- withMetrics(
2098
- callClient(
2099
- clientSingleton,
2100
- client => client.cli.realtime.auth(params),
2101
- CliRealtimeAuthResponse
2102
- )
2103
- ),
2104
- },
2105
- authConfigs: buildAuthConfigsNamespace(clientSingleton, withMetrics),
2106
- connectedAccounts: buildConnectedAccountsNamespace(clientSingleton, withMetrics),
2107
- };
2108
-});
972
+ if (matches.length === 0) {
973
+ return yield* Effect.fail(
974
+ new DeveloperProjectNotFoundError({
975
+ orgId: params.orgId,
976
+ projectName: params.name,
977
+ })
978
+ );
979
+ }
980
+
981
+ if (matches.length > 1) {
982
+ return yield* Effect.fail(
983
+ new AmbiguousDeveloperProjectNameError({
984
+ orgId: params.orgId,
985
+ projectName: params.name,
986
+ matches,
987
+ })
988
+ );
989
+ }
990
2110
-export type ComposioClientLiveShape = Effect.Success<typeof makeComposioClientLive>;
991
+ return matches[0];
992
+ });
993
2112
-export class ComposioClientLive extends Context.Service<
2113
- ComposioClientLive,
2114
- ComposioClientLiveShape
2115
->()('services/ComposioClientLive') {
2116
- static readonly Default = Layer.effect(ComposioClientLive, makeComposioClientLive).pipe(
2117
- Layer.provide(ComposioClientSingleton.Default)
2118
- );
2119
-}
994
+/**
995
+ * Repositories
996
+ */
997
+
998
+/**
999
+ * Auth config, connected account, and trigger instance operations: single-page
1000
+ * CRUD with no catalog caching.
1001
+ */
1002
+const resourceOperations = (client: Effect.Effect<_RawComposioClient, ClientError>) => ({
1003
+ /**
1004
+ * Lists auth configs with optional filters. Returns a single page of results.
1005
+ * @param params - Search/filter parameters
1006
+ */
1007
+ listAuthConfigs: (params: {
1008
+ search?: string;
1009
+ toolkit_slug?: string;
1010
+ limit?: number;
1011
+ show_disabled?: boolean;
1012
+ }) =>
1013
+ request(client, c =>
1014
+ c.authConfigs.list({
1015
+ search: params.search,
1016
+ toolkit_slug: params.toolkit_slug,
1017
+ limit: params.limit,
1018
+ show_disabled: params.show_disabled ?? true,
1019
+ })
1020
+ ).pipe(Effect.flatMap(decode(AuthConfigListResponse))),
1021
+ /**
1022
+ * Retrieves detailed info about a single auth config by its nanoid.
1023
+ * @param nanoid - Auth config ID
1024
+ */
1025
+ getAuthConfig: (nanoid: string) =>
1026
+ request(client, c => c.authConfigs.retrieve(nanoid)).pipe(
1027
+ Effect.flatMap(decode(AuthConfigItem))
1028
+ ),
1029
+ /**
1030
+ * Creates a new auth config for a toolkit.
1031
+ * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
1032
+ */
1033
+ createAuthConfig: (params: AuthConfigCreateParams) =>
1034
+ request(client, c => c.authConfigs.create(params)).pipe(
1035
+ Effect.flatMap(decode(AuthConfigCreateResponse))
1036
+ ),
1037
+ /**
1038
+ * Soft-deletes an auth config by its nanoid.
1039
+ * @param nanoid - Auth config ID
1040
+ */
1041
+ deleteAuthConfig: (nanoid: string) => request(client, c => c.authConfigs.delete(nanoid)),
1042
+ /**
1043
+ * List connected accounts with optional filters. Returns a single page of results.
1044
+ * @param params - Search/filter parameters
1045
+ */
1046
+ listConnectedAccounts: (params: {
1047
+ toolkit_slugs?: string[];
1048
+ user_ids?: string[];
1049
+ statuses?: ConnectedAccountListParams['statuses'];
1050
+ limit?: number;
1051
+ }) =>
1052
+ request(client, c =>
1053
+ c.connectedAccounts.list({
1054
+ toolkit_slugs: params.toolkit_slugs,
1055
+ user_ids: params.user_ids,
1056
+ statuses: params.statuses,
1057
+ limit: params.limit,
1058
+ })
1059
+ ).pipe(Effect.flatMap(decode(ConnectedAccountListResponse))),
1060
+ /**
1061
+ * Retrieves detailed info about a single connected account by its nanoid.
1062
+ * @param nanoid - Connected account ID (e.g. "con_1a2b3c4d5e6f")
1063
+ */
1064
+ getConnectedAccount: (nanoid: string) =>
1065
+ request(client, c => c.connectedAccounts.retrieve(nanoid)).pipe(
1066
+ Effect.flatMap(decode(ConnectedAccountItem))
1067
+ ),
1068
+ /**
1069
+ * Soft-deletes a connected account by its nanoid.
1070
+ * @param nanoid - Connected account ID
1071
+ */
1072
+ deleteConnectedAccount: (nanoid: string) =>
1073
+ request(client, c => c.connectedAccounts.delete(nanoid)),
1074
+ /**
1075
+ * Creates a new authentication link session for connecting an external account.
1076
+ * @param params - auth_config_id and user_id
1077
+ */
1078
+ createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>
1079
+ request(client, c => c.link.create(params)),
1080
+ /**
1081
+ * Lists active trigger instances with optional filters.
1082
+ * Returns a single page of results.
1083
+ */
1084
+ listActiveTriggers: (params: TriggerInstancesListActiveParams) =>
1085
+ request(client, c =>
1086
+ c.triggerInstances.listActive({
1087
+ user_ids: params.user_ids,
1088
+ connected_account_ids: params.connected_account_ids,
1089
+ auth_config_ids: params.auth_config_ids,
1090
+ trigger_ids: params.trigger_ids,
1091
+ trigger_names: params.trigger_names,
1092
+ show_disabled: params.show_disabled,
1093
+ limit: params.limit,
1094
+ })
1095
+ ).pipe(
1096
+ Effect.flatMap(response =>
1097
+ decode(TriggerInstanceItems)(response.items).pipe(
1098
+ // `triggers status` prints `total_items` directly, so a response that
1099
+ // omits a count renders as a number rather than `undefined`.
1100
+ Effect.map(items => ({
1101
+ ...response,
1102
+ items,
1103
+ total_items: response.total_items ?? items.length,
1104
+ total_pages: response.total_pages ?? 1,
1105
+ current_page: response.current_page ?? 1,
1106
+ next_cursor: response.next_cursor ?? null,
1107
+ }))
1108
+ )
1109
+ )
1110
+ ),
1111
+ createTrigger: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
1112
+ request(client, c => c.triggerInstances.upsert(triggerSlug, params)),
1113
+ enableTrigger: (triggerId: string) =>
1114
+ request(client, c => c.triggerInstances.manage.update(triggerId, { status: 'enable' })),
1115
+ disableTrigger: (triggerId: string) =>
1116
+ request(client, c => c.triggerInstances.manage.update(triggerId, { status: 'disable' })),
1117
+ deleteTrigger: (triggerId: string) =>
1118
+ request(client, c => c.triggerInstances.manage.delete(triggerId)),
1119
+});
1120
1121
const makeComposioToolkitsRepository = Effect.gen(function* () {
2122
- const client = yield* ComposioClientLive;
1122
+ const clientSingleton = yield* ComposioClientSingleton;
1123
+ const client = clientSingleton.get();
1124
1125
const listToolkits = (managedBy?: 'project', scope?: ToolkitProjectScope) =>
2125
- client.toolkits.list(managedBy, scope).pipe(
2126
- Effect.map(response => response.items),
2127
- Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>)
1126
+ requestAll(scope ? clientSingleton.getFor(scope) : client, (c, { cursor, limit }, signal) =>
1127
+ c.toolkits.list({ cursor, limit, managed_by: managedBy }, { signal })
1128
+ ).pipe(Effect.flatMap(decode(Toolkits)), Effect.map(sortBySlug));
1129
+
1130
+ const getToolkitDetailed = (slug: string) =>
1131
+ request(client, c => c.toolkits.retrieve(slug)).pipe(Effect.flatMap(decode(ToolkitDetailed)));
1132
+
1133
+ // The retrieve endpoint omits `auth_schemes`; fill it so the result
1134
+ // satisfies the catalog `Toolkit` contract.
1135
+ const getToolkit = (slug: string): Effect.Effect<Toolkit, ClientError> =>
1136
+ getToolkitDetailed(slug).pipe(
1137
+ Effect.map(({ auth_config_details: _authConfigDetails, ...toolkit }) => ({
1138
+ ...toolkit,
1139
+ auth_schemes: [],
1140
+ }))
1141
);
1142
1143
const getToolkits = () => listToolkits();
1158
*/
1159
const getToolkitsBySlugs = (slugs: ReadonlyArray<string>) =>
1160
Effect.all(
2148
- slugs.map(slug =>
2149
- client.toolkits.retrieve(slug).pipe(
2150
- // Only convert 404 errors to InvalidToolkitsError.
2151
- // Other HTTP errors (500, 401, network failures, etc.) should propagate as-is.
2152
- Effect.catchTag(
2153
- 'services/HttpServerError',
2154
- (e): Effect.Effect<never, InvalidToolkitsError | HttpServerError> =>
2155
- e.status === 404
2156
- ? Effect.fail(
2157
- new InvalidToolkitsError({
2158
- invalidToolkits: [slug],
2159
- availableToolkits: [],
2160
- })
2161
- )
2162
- : Effect.fail(e)
2163
- )
2164
- )
2165
- ),
1161
+ slugs.map(slug => invalidToolkitOn404(slug, getToolkit(slug))),
1162
{ concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
2167
- ).pipe(Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>));
1163
+ ).pipe(Effect.map(sortBySlug));
1164
+
1165
+ const listTools = (query: { toolkit_slug?: string; toolkit_versions: string }) =>
1166
+ requestAll(client, (c, { cursor, limit }, signal) =>
1167
+ c.tools.list({ ...query, cursor, limit }, { signal })
1168
+ ).pipe(Effect.flatMap(decode(Tools)));
1169
1170
return {
1171
getToolkits,
1172
getProjectToolkits,
1173
getToolkitsBySlugs,
2173
- getMetrics: () => client.getMetrics(),
2174
- getToolsAsEnums: () => client.tools.retrieveEnum(),
1174
+ getMetrics: () => clientSingleton.getMetrics(),
1175
+ /**
1176
+ * Retrieve a list of all available tool enumeration values (tool slugs) for the project.
1177
+ */
1178
+ getToolsAsEnums: () =>
1179
+ request(client, c => c.tools.retrieveEnum()).pipe(Effect.flatMap(decode(ToolsAsEnums))),
1180
/**
2176
- * Fetches tools with optional toolkit filtering.
2177
- * When toolkitSlugs is provided, fetches all matching tools.
1181
+ * Fetches tools with optional toolkit filtering, always at the latest
1182
+ * toolkit version. For per-toolkit versions use `getToolsByVersionSpecs`.
1183
* @param toolkitSlugs - Optional array of toolkit slugs to filter by
1184
*/
1185
getTools: (toolkitSlugs?: ReadonlyArray<string>) =>
2181
- client.tools.list(toolkitSlugs ?? []).pipe(
2182
- Effect.map(response => response.items),
2183
- Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2184
- ),
1186
+ listTools({
1187
+ toolkit_slug: toolkitSlugs && toolkitSlugs.length > 0 ? toolkitSlugs.join(',') : undefined,
1188
+ toolkit_versions: 'latest',
1189
+ }).pipe(Effect.map(sortBySlug)),
1190
/**
1191
* Fetches tools with per-toolkit version support.
1192
* Groups toolkits by version and makes separate API calls for each group.
1193
* @param specs - Array of { toolkitSlug, toolkitVersion } specifications
1194
*/
1195
getToolsByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>
2191
- client.tools.listByVersionSpecs(specs).pipe(
2192
- Effect.map(response => response.items),
2193
- Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
1196
+ Effect.all(
1197
+ [...groupByVersion(specs).entries()].map(([version, slugs]) =>
1198
+ listTools({ toolkit_slug: slugs.join(','), toolkit_versions: version })
1199
+ ),
1200
+ { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
1201
+ ).pipe(Effect.map(groups => sortBySlug(groups.flat()))),
1202
+ /**
1203
+ * Retrieves a list of all available trigger type enum values that can be used across the API.
1204
+ */
1205
+ getTriggerTypesAsEnums: () =>
1206
+ request(client, c => c.triggersTypes.retrieveEnum()).pipe(
1207
+ Effect.flatMap(decode(TriggerTypesAsEnums))
1208
),
2195
- getTriggerTypesAsEnums: () => client.triggersTypes.retrieveEnum(),
1209
/**
1210
* Retrieves detailed info about a single trigger type by slug.
1211
* @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
1212
*/
2200
- getTriggerTypeDetailed: (slug: string) => client.triggersTypes.retrieve(slug),
1213
+ getTriggerTypeDetailed: (slug: string) =>
1214
+ request(client, c => c.triggersTypes.retrieve(slug)).pipe(
1215
+ Effect.flatMap(decode(TriggerType))
1216
+ ),
1217
/**
1218
* Fetches trigger types with optional toolkit filtering.
1219
* When toolkitSlugs is provided, fetches all matching trigger types.
1220
* @param toolkitSlugs - Optional array of toolkit slugs to filter by
1221
*/
1222
getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>
2207
- client.triggersTypes.list(toolkitSlugs).pipe(
2208
- Effect.map(response => response.items),
2209
- Effect.map(items => sortBySlug(items) as ReadonlyArray<TriggerType>)
2210
- ),
1223
+ requestAll(client, (c, { cursor, limit }, signal) =>
1224
+ c.triggersTypes.list(
1225
+ {
1226
+ cursor,
1227
+ limit,
1228
+ toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,
1229
+ },
1230
+ { signal }
1231
+ )
1232
+ ).pipe(Effect.flatMap(decode(TriggerTypes)), Effect.map(sortBySlug)),
1233
/**
1234
* Validates that the given toolkit slugs are valid by comparing them against the list
1235
* of available toolkits. Returns the list of valid toolkit slugs (normalized to lowercase).
1237
*/
1238
validateToolkits: (
1239
toolkitSlugs: ReadonlyArray<string>
2218
- ): Effect.Effect<
2219
- ReadonlyArray<string>,
2220
- InvalidToolkitsError | HttpError | NoSuchElementError
2221
- > =>
1240
+ ): Effect.Effect<ReadonlyArray<string>, InvalidToolkitsError | ClientError> =>
1241
Effect.gen(function* () {
1242
// Normalize input slugs to lowercase for comparison
1243
const normalizedInputSlugs = toolkitSlugs.map(slug => String.toLowerCase(slug));
1288
validatedOverrides: ToolkitVersionOverrides;
1289
warnings: ReadonlyArray<string>;
1290
},
2272
- InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementError
2273
- > => validateToolkitVersionsImpl(client, overrides, relevantToolkits),
1291
+ InvalidToolkitVersionsError | InvalidToolkitsError | ClientError
1292
+ > => validateToolkitVersionsImpl(getToolkit, overrides, relevantToolkits),
1293
/**
1294
* Searches toolkits with optional filters. Returns a single page of results.
1295
* @param params - Search/filter parameters
1299
category?: string;
1300
limit?: number;
1301
cursor?: string;
2283
- }) => client.toolkits.search(params),
1302
+ }): Effect.Effect<ToolkitSearchResult, ClientError> =>
1303
+ request(client, c =>
1304
+ c.toolkits.list({
1305
+ search: params.search,
1306
+ category: params.category,
1307
+ limit: params.limit,
1308
+ cursor: params.cursor,
1309
+ })
1310
+ ).pipe(
1311
+ Effect.flatMap(response =>
1312
+ decode(Toolkits)(response.items).pipe(
1313
+ Effect.map(
1314
+ items =>
1315
+ ({
1316
+ items,
1317
+ total_items: response.total_items,
1318
+ total_pages: response.total_pages,
1319
+ next_cursor: response.next_cursor ?? null,
1320
+ }) satisfies ToolkitSearchResult
1321
+ )
1322
+ )
1323
+ )
1324
+ ),
1325
/**
1326
* Retrieves detailed toolkit info including auth_config_details.
1327
* @param slug - Toolkit slug
1328
*/
2288
- getToolkitDetailed: (slug: string) => client.toolkits.retrieveDetailed(slug),
1329
+ getToolkitDetailed,
1330
/**
1331
* Searches tools with optional filters. Returns a single page of results.
1332
* @param params - Search/filter parameters
1337
tags?: string;
1338
limit?: number;
1339
cursor?: string;
2299
- }) => client.tools.search(params),
1340
+ }) =>
1341
+ request(client, c =>
1342
+ c.tools.list({
1343
+ search: params.search,
1344
+ toolkit_slug: params.toolkit_slug,
1345
+ tags: params.tags ? params.tags.split(',').map(t => t.trim()) : undefined,
1346
+ limit: params.limit,
1347
+ cursor: params.cursor,
1348
+ toolkit_versions: 'latest',
1349
+ })
1350
+ ),
1351
/**
1352
* Retrieves detailed info about a single tool by slug.
1353
* @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")
1354
*/
2304
- getToolDetailed: (slug: string) => client.tools.retrieve(slug),
2305
- /**
2306
- * Lists auth configs with optional filters. Returns a single page of results.
2307
- * @param params - Search/filter parameters
2308
- */
2309
- listAuthConfigs: (params: {
2310
- search?: string;
2311
- toolkit_slug?: string;
2312
- limit?: number;
2313
- show_disabled?: boolean;
2314
- }) => client.authConfigs.list(params),
2315
- /**
2316
- * Retrieves detailed info about a single auth config by its nanoid.
2317
- * @param nanoid - Auth config ID
2318
- */
2319
- getAuthConfig: (nanoid: string) => client.authConfigs.retrieve(nanoid),
2320
- /**
2321
- * Creates a new auth config for a toolkit.
2322
- * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
2323
- */
2324
- createAuthConfig: (params: AuthConfigCreateParams) => client.authConfigs.create(params),
2325
- deleteAuthConfig: (nanoid: string) => client.authConfigs.delete(nanoid),
2326
- // Connected account operations (thin wrappers — see buildConnectedAccountsNamespace)
2327
- listConnectedAccounts: (params: {
2328
- toolkit_slugs?: string[];
2329
- user_ids?: string[];
2330
- statuses?: string[];
2331
- limit?: number;
2332
- }) => client.connectedAccounts.list(params),
2333
- getConnectedAccount: (nanoid: string) => client.connectedAccounts.retrieve(nanoid),
2334
- deleteConnectedAccount: (nanoid: string) => client.connectedAccounts.delete(nanoid),
2335
- createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>
2336
- client.connectedAccounts.createLink(params),
2337
- ...buildTriggerInstanceRepositoryOperations(client),
1355
+ getToolDetailed: (slug: string) =>
1356
+ request(client, c => c.tools.retrieve(slug, { toolkit_versions: 'latest' })),
1357
+ ...resourceOperations(client),
1358
};
1359
});
1360
1367
static readonly Default = Layer.effect(
1368
ComposioToolkitsRepository,
1369
makeComposioToolkitsRepository
2350
- ).pipe(Layer.provide(ComposioClientLive.Default));
1370
+ ).pipe(Layer.provide(ComposioClientSingleton.Default));
1371
}
1372
1373
const makeComposioSessionRepository = Effect.gen(function* () {
2354
- const client = yield* ComposioClientLive;
1374
+ const clientSingleton = yield* ComposioClientSingleton;
1375
+ const client = clientSingleton.get();
1376
1377
return {
2357
- createSession: (params?: { scope?: 'user' | 'project' }) => client.cli.createSession(params),
2358
- getSession: (session: { id: string }) => client.cli.getSession({ id: session.id }),
2359
- getRealtimeCredentials: () => client.cli.getRealtimeCredentials(),
1378
+ /**
1379
+ * Generates a new CLI session with a random 6-character code.
1380
+ * @param params.scope - 'user' for login, 'project' for init (future)
1381
+ */
1382
+ createSession: (params?: { scope?: 'user' | 'project' }) =>
1383
+ request(client, c => c.cli.createSession({ scope: params?.scope ?? 'user' })).pipe(
1384
+ Effect.flatMap(decode(Session))
1385
+ ),
1386
+ /**
1387
+ * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.
1388
+ */
1389
+ getSession: (session: { id: string }) =>
1390
+ request(client, c => c.cli.getSession({ id: session.id })).pipe(
1391
+ Effect.flatMap(decode(RetrievedSession))
1392
+ ),
1393
+ getRealtimeCredentials: () => request(client, c => c.cli.realtime.credentials()),
1394
authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2361
- client.cli.authRealtimeChannel(params),
1395
+ request(client, c => c.cli.realtime.auth(params)),
1396
};
1397
});
1398
1405
static readonly Default = Layer.effect(
1406
ComposioSessionRepository,
1407
makeComposioSessionRepository
2374
- ).pipe(Layer.provide(ComposioClientLive.Default));
1408
+ ).pipe(Layer.provide(ComposioClientSingleton.Default));
1409
}