11
Stream,
12
Sink,
13
SynchronizedRef,
14
+ Context,
15
+ Layer,
16
} from 'effect';
17
import { Composio as _RawComposioClient, APIPromise } from '@composio/client';
18
import { FileSystem, Path } from '@effect/platform';
421
}
422
423
function buildTriggerInstancesNamespace(
422
- clientSingleton: ComposioClientSingleton,
424
+ clientSingleton: ComposioClientSingletonShape,
425
withMetrics: <A, E, R>(
426
effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
427
) => Effect.Effect<A, E, R>
475
};
476
}
477
476
-function buildTriggerInstanceRepositoryOperations(client: ComposioClientLive) {
478
+function buildTriggerInstanceRepositoryOperations(client: ComposioClientLiveShape) {
479
return {
480
listActiveTriggers: (params: TriggerInstancesListActiveParams) =>
481
client.triggerInstances.listActive(params),
1379
1380
// Utility function for calling the Composio API and decoding its response.
1381
const callClient = <T, S extends Schema.Schema.AnyNoContext>(
1380
- clientSingleton: ComposioClientSingleton,
1382
+ clientSingleton: ComposioClientSingletonShape,
1383
apiCall: (client: _RawComposioClient) => APIPromise<T>,
1384
responseSchema: S
1385
): Effect.Effect<
1439
// Utility function for calling paginated Composio API endpoints.
1440
// Automatically fetches all pages, using MAX_PAGE_SIZE per request.
1441
const callClientWithPagination = <T, S extends PaginatedSchema>(
1440
- clientSingleton: ComposioClientSingleton,
1442
+ clientSingleton: ComposioClientSingletonShape,
1443
apiCall: (client: _RawComposioClient, cursor?: string, limit?: number) => APIPromise<T>,
1444
responseSchema: S
1445
): Effect.Effect<
1526
* Singleton service that lazily accesses `Config` only when needed, which is used to build and provide
1527
* a raw (uneffectful, Promise-based) Composio client instance.
1528
*/
1527
-export class ComposioClientSingleton extends Effect.Service<ComposioClientSingleton>()(
1528
- 'services/ComposioClientSingleton',
1529
- {
1530
- accessors: true,
1531
- effect: Effect.gen(function* () {
1532
- const ctx = yield* ComposioUserContext;
1533
- const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
1534
- const fs = yield* FileSystem.FileSystem;
1535
- const path = yield* Path.Path;
1536
- const os = yield* NodeOs;
1537
- const cache = new Map<string, _RawComposioClient>();
1538
-
1539
- const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
1540
- Effect.gen(function* () {
1541
- const apiKey = normalizeApiKey(
1542
- params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey)
1543
- );
1544
- const cacheKey = JSON.stringify({
1545
- apiKey: apiKey ?? null,
1546
- orgId: params?.orgId ?? null,
1547
- projectId: params?.projectId ?? null,
1548
- });
1549
- const cached = cache.get(cacheKey);
1550
- if (cached) {
1551
- return cached;
1552
- }
1529
+const makeComposioClientSingleton = Effect.gen(function* () {
1530
+ const ctx = yield* ComposioUserContext;
1531
+ const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
1532
+ const fs = yield* FileSystem.FileSystem;
1533
+ const path = yield* Path.Path;
1534
+ const os = yield* NodeOs;
1535
+ const cache = new Map<string, _RawComposioClient>();
1536
+
1537
+ const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
1538
+ Effect.gen(function* () {
1539
+ const apiKey = normalizeApiKey(params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey));
1540
+ const cacheKey = JSON.stringify({
1541
+ apiKey: apiKey ?? null,
1542
+ orgId: params?.orgId ?? null,
1543
+ projectId: params?.projectId ?? null,
1544
+ });
1545
+ const cached = cache.get(cacheKey);
1546
+ if (cached) {
1547
+ return cached;
1548
+ }
1549
1554
- const cliSessionId = yield* getCurrentCwdSessionId().pipe(
1555
- Effect.provideService(FileSystem.FileSystem, fs),
1556
- Effect.provideService(Path.Path, path),
1557
- Effect.provideService(NodeOs, os)
1558
- );
1550
+ const cliSessionId = yield* getCurrentCwdSessionId().pipe(
1551
+ Effect.provideService(FileSystem.FileSystem, fs),
1552
+ Effect.provideService(Path.Path, path),
1553
+ Effect.provideService(NodeOs, os)
1554
+ );
1555
1560
- const client = new _RawComposioClient({
1561
- apiKey: null,
1562
- baseURL: ctx.data.baseURL,
1563
- defaultHeaders: buildDefaultHeaders({
1564
- userApiKey: apiKey,
1565
- orgId: params?.orgId,
1566
- projectId: params?.projectId,
1567
- cliSessionId,
1568
- }),
1569
- });
1556
+ const client = new _RawComposioClient({
1557
+ apiKey: null,
1558
+ baseURL: ctx.data.baseURL,
1559
+ defaultHeaders: buildDefaultHeaders({
1560
+ userApiKey: apiKey,
1561
+ orgId: params?.orgId,
1562
+ projectId: params?.projectId,
1563
+ cliSessionId,
1564
+ }),
1565
+ });
1566
1571
- cache.set(cacheKey, client);
1572
- return client;
1573
- });
1567
+ cache.set(cacheKey, client);
1568
+ return client;
1569
+ });
1570
1575
- return {
1576
- get: Effect.fn(function* () {
1577
- const resolvedProjectContext = yield* Option.match(projectContextOpt, {
1578
- onNone: () => Effect.succeed(Option.none()),
1579
- onSome: projectContext =>
1580
- projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none()))),
1581
- });
1582
- return yield* Option.match(resolvedProjectContext, {
1583
- onNone: () => getFor(),
1584
- onSome: keys =>
1585
- getFor({
1586
- orgId: keys.orgId,
1587
- projectId: keys.projectId,
1588
- }),
1589
- });
1590
- }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1591
- getFor: Effect.fn(function* (params: {
1592
- userApiKey?: string;
1593
- orgId?: string;
1594
- projectId?: string;
1595
- }) {
1596
- return yield* getFor(params);
1597
- }) satisfies (params: {
1598
- userApiKey?: string;
1599
- orgId?: string;
1600
- projectId?: string;
1601
- }) => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1602
- };
1603
- }),
1604
- dependencies: [ComposioUserContextLive],
1605
- }
1606
-) {}
1571
+ return {
1572
+ get: Effect.fn(function* () {
1573
+ const resolvedProjectContext = yield* Option.match(projectContextOpt, {
1574
+ onNone: () => Effect.succeed(Option.none()),
1575
+ onSome: projectContext =>
1576
+ projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none()))),
1577
+ });
1578
+ return yield* Option.match(resolvedProjectContext, {
1579
+ onNone: () => getFor(),
1580
+ onSome: keys =>
1581
+ getFor({
1582
+ orgId: keys.orgId,
1583
+ projectId: keys.projectId,
1584
+ }),
1585
+ });
1586
+ }) satisfies () => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1587
+ getFor: Effect.fn(function* (params: {
1588
+ userApiKey?: string;
1589
+ orgId?: string;
1590
+ projectId?: string;
1591
+ }) {
1592
+ return yield* getFor(params);
1593
+ }) satisfies (params: {
1594
+ userApiKey?: string;
1595
+ orgId?: string;
1596
+ projectId?: string;
1597
+ }) => Effect.Effect<_RawComposioClient, NoSuchElementException, never>,
1598
+ };
1599
+});
1600
+
1601
+export type ComposioClientSingletonShape = Effect.Effect.Success<
1602
+ typeof makeComposioClientSingleton
1603
+>;
1604
+
1605
+export class ComposioClientSingleton extends Context.Tag('services/ComposioClientSingleton')<
1606
+ ComposioClientSingleton,
1607
+ ComposioClientSingletonShape
1608
+>() {
1609
+ static readonly Default = Layer.effect(ComposioClientSingleton, makeComposioClientSingleton).pipe(
1610
+ Layer.provide(ComposioUserContextLive)
1611
+ );
1612
+}
1613
1614
/**
1615
* Build the `tools` namespace for ComposioClientLive.
1616
* Extracted to keep the main generator under the max-lines-per-function limit.
1617
*/
1618
function buildToolsNamespace(
1613
- clientSingleton: ComposioClientSingleton,
1619
+ clientSingleton: ComposioClientSingletonShape,
1620
withMetrics: <A, E, R>(
1621
effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1622
) => Effect.Effect<A, E, R>
1729
* Extracted to keep the main generator under the max-lines-per-function limit.
1730
*/
1731
function buildAuthConfigsNamespace(
1726
- clientSingleton: ComposioClientSingleton,
1732
+ clientSingleton: ComposioClientSingletonShape,
1733
withMetrics: <A, E, R>(
1734
effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1735
) => Effect.Effect<A, E, R>
1798
* Extracted to keep the main generator under the max-lines-per-function limit.
1799
*/
1800
function buildConnectedAccountsNamespace(
1795
- clientSingleton: ComposioClientSingleton,
1801
+ clientSingleton: ComposioClientSingletonShape,
1802
withMetrics: <A, E, R>(
1803
effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1804
) => Effect.Effect<A, E, R>
1865
}
1866
1867
// Service that wraps the raw Composio client, which is shared by all client services.
1862
-export class ComposioClientLive extends Effect.Service<ComposioClientLive>()(
1863
- 'services/ComposioClientLive',
1864
- {
1865
- effect: Effect.gen(function* () {
1866
- const clientSingleton = yield* ComposioClientSingleton;
1867
-
1868
- // Initialize metrics tracking via SynchronizedRef
1869
- const metricsRef = yield* SynchronizedRef.make<Metrics>({ byteSize: 0, requests: 0 });
1870
-
1871
- // Helper to update metrics and return just the data
1872
- const withMetrics = <A, E, R>(
1873
- effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1874
- ): Effect.Effect<A, E, R> =>
1875
- Effect.gen(function* () {
1876
- const { data, metrics } = yield* effect;
1877
- yield* SynchronizedRef.update(metricsRef, current => ({
1878
- byteSize: current.byteSize + metrics.byteSize,
1879
- requests: current.requests + metrics.requests,
1880
- }));
1881
- return data;
1882
- });
1883
-
1884
- return {
1885
- /**
1886
- * Returns a snapshot of the current accumulated metrics (total bytes received and request count).
1887
- */
1888
- getMetrics: () => SynchronizedRef.get(metricsRef),
1889
- toolkits: {
1890
- /**
1891
- * Retrieves a comprehensive list of toolkits that are available to the authenticated project.
1892
- * Automatically handles pagination to fetch all items.
1893
- */
1894
- list: () =>
1895
- withMetrics(
1896
- callClientWithPagination(
1897
- clientSingleton,
1898
- (client, cursor, limit) => client.toolkits.list({ cursor, limit }),
1899
- ToolkitsResponse
1900
- )
1901
- ),
1902
- /**
1903
- * Retrieves a single toolkit by its slug.
1904
- * Transforms the response to match the Toolkit schema.
1905
- */
1906
- retrieve: (slug: string) =>
1907
- withMetrics(
1908
- callClient(
1909
- clientSingleton,
1910
- client => client.toolkits.retrieve(slug),
1911
- ToolkitRetrieveResponse
1912
- )
1913
- ).pipe(
1914
- // Transform to Toolkit format by adding missing fields
1915
- Effect.map(
1916
- retrieved =>
1917
- ({
1918
- name: retrieved.name,
1919
- slug: retrieved.slug,
1920
- auth_schemes: [], // retrieve endpoint doesn't return auth_schemes
1921
- composio_managed_auth_schemes: retrieved.composio_managed_auth_schemes,
1922
- is_local_toolkit: retrieved.is_local_toolkit,
1923
- no_auth: retrieved.no_auth,
1924
- meta: retrieved.meta,
1925
- }) satisfies Toolkit
1926
- )
1927
- ),
1928
- /**
1929
- * Searches toolkits with optional filters. Returns a single page of results (no auto-pagination).
1930
- * @param params - Search/filter parameters
1931
- */
1932
- search: (params: {
1933
- search?: string;
1934
- category?: string;
1935
- limit?: number;
1936
- cursor?: string;
1937
- }) =>
1938
- withMetrics(
1939
- callClient(
1940
- clientSingleton,
1941
- client =>
1942
- client.toolkits.list({
1943
- search: params.search,
1944
- category: params.category,
1945
- limit: params.limit,
1946
- cursor: params.cursor,
1947
- }),
1948
- ToolkitSearchResponse
1949
- )
1950
- ).pipe(
1951
- Effect.map(
1952
- response =>
1953
- ({
1954
- items: response.items,
1955
- total_items: response.total_items,
1956
- total_pages: response.total_pages,
1957
- next_cursor: response.next_cursor,
1958
- }) satisfies ToolkitSearchResult
1959
- )
1960
- ),
1961
- /**
1962
- * Retrieves detailed toolkit info including auth_config_details.
1963
- * @param slug - Toolkit slug
1964
- */
1965
- retrieveDetailed: (slug: string) =>
1966
- withMetrics(
1967
- callClient(
1968
- clientSingleton,
1969
- client => client.toolkits.retrieve(slug),
1970
- ToolkitDetailedResponse
1971
- )
1972
- ),
1973
- },
1974
- tools: buildToolsNamespace(clientSingleton, withMetrics),
1975
- triggersTypes: {
1976
- /**
1977
- * Retrieves a list of all available trigger type enum values that can be used across the API.
1978
- */
1979
- retrieveEnum: () =>
1980
- withMetrics(
1981
- callClient(
1982
- clientSingleton,
1983
- client => client.triggersTypes.retrieveEnum(),
1984
- TriggerTypesAsEnumsResponse
1985
- )
1986
- ),
1987
- /**
1988
- * Retrieves detailed info about a single trigger type by slug.
1989
- * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
1990
- */
1991
- retrieve: (slug: string) =>
1992
- withMetrics(
1993
- callClient(
1994
- clientSingleton,
1995
- client => client.triggersTypes.retrieve(slug),
1996
- TriggerType
1997
- )
1998
- ),
1999
- /**
2000
- * Retrieve a list of trigger types, automatically handling pagination.
2001
- * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2002
- */
2003
- list: (toolkitSlugs?: ReadonlyArray<string>) =>
2004
- withMetrics(
2005
- callClientWithPagination(
2006
- clientSingleton,
2007
- (client, cursor, limit) =>
2008
- client.triggersTypes.list({
2009
- cursor,
2010
- limit,
2011
- toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,
2012
- }),
2013
- TriggerTypesResponse
2014
- )
2015
- ),
2016
- },
2017
- triggerInstances: buildTriggerInstancesNamespace(clientSingleton, withMetrics),
2018
- cli: {
2019
- /**
2020
- * Generates a new CLI session with a random 6-character code.
2021
- * @param params.scope - 'user' for login, 'project' for init (future)
2022
- *
2023
- * TODO: don't use `@composio/client`, wrap `fetch` directly.
2024
- */
2025
- createSession: (params?: { scope?: 'user' | 'project' }) =>
2026
- withMetrics(
2027
- callClient(
2028
- clientSingleton,
2029
- client =>
2030
- client.cli.createSession(
2031
- { scope: params?.scope ?? 'user' },
2032
- { headers: { 'Content-Type': 'application/json' } }
2033
- ),
2034
- CliCreateSessionResponse
2035
- )
2036
- ),
1868
+const makeComposioClientLive = Effect.gen(function* () {
1869
+ const clientSingleton = yield* ComposioClientSingleton;
1870
2038
- /**
2039
- * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.
2040
- */
2041
- getSession: (session: { id: string }) =>
2042
- withMetrics(
2043
- callClient(
2044
- clientSingleton,
2045
- client => client.cli.getSession(session),
2046
- CliGetSessionResponse
2047
- )
2048
- ),
2049
- getRealtimeCredentials: () =>
2050
- withMetrics(
2051
- callClient(
2052
- clientSingleton,
2053
- client => client.cli.realtime.credentials(),
2054
- CliRealtimeCredentialsResponse
2055
- )
2056
- ),
2057
- authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2058
- withMetrics(
2059
- callClient(
2060
- clientSingleton,
2061
- client => client.cli.realtime.auth(params),
2062
- CliRealtimeAuthResponse
2063
- )
2064
- ),
2065
- },
2066
- authConfigs: buildAuthConfigsNamespace(clientSingleton, withMetrics),
2067
- connectedAccounts: buildConnectedAccountsNamespace(clientSingleton, withMetrics),
2068
- };
2069
- }),
2070
- dependencies: [ComposioClientSingleton.Default],
2071
- }
2072
-) {}
1871
+ // Initialize metrics tracking via SynchronizedRef
1872
+ const metricsRef = yield* SynchronizedRef.make<Metrics>({ byteSize: 0, requests: 0 });
1873
2074
-export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsRepository>()(
2075
- 'services/ComposioToolkitsRepository',
2076
- {
2077
- effect: Effect.gen(function* () {
2078
- const client = yield* ComposioClientLive;
1874
+ // Helper to update metrics and return just the data
1875
+ const withMetrics = <A, E, R>(
1876
+ effect: Effect.Effect<{ data: A; metrics: Metrics }, E, R>
1877
+ ): Effect.Effect<A, E, R> =>
1878
+ Effect.gen(function* () {
1879
+ const { data, metrics } = yield* effect;
1880
+ yield* SynchronizedRef.update(metricsRef, current => ({
1881
+ byteSize: current.byteSize + metrics.byteSize,
1882
+ requests: current.requests + metrics.requests,
1883
+ }));
1884
+ return data;
1885
+ });
1886
2080
- const getToolkits = () =>
2081
- client.toolkits.list().pipe(
2082
- Effect.map(response => response.items),
2083
- Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>)
2084
- );
1887
+ return {
1888
+ /**
1889
+ * Returns a snapshot of the current accumulated metrics (total bytes received and request count).
1890
+ */
1891
+ getMetrics: () => SynchronizedRef.get(metricsRef),
1892
+ toolkits: {
1893
+ /**
1894
+ * Retrieves a comprehensive list of toolkits that are available to the authenticated project.
1895
+ * Automatically handles pagination to fetch all items.
1896
+ */
1897
+ list: () =>
1898
+ withMetrics(
1899
+ callClientWithPagination(
1900
+ clientSingleton,
1901
+ (client, cursor, limit) => client.toolkits.list({ cursor, limit }),
1902
+ ToolkitsResponse
1903
+ )
1904
+ ),
1905
+ /**
1906
+ * Retrieves a single toolkit by its slug.
1907
+ * Transforms the response to match the Toolkit schema.
1908
+ */
1909
+ retrieve: (slug: string) =>
1910
+ withMetrics(
1911
+ callClient(
1912
+ clientSingleton,
1913
+ client => client.toolkits.retrieve(slug),
1914
+ ToolkitRetrieveResponse
1915
+ )
1916
+ ).pipe(
1917
+ // Transform to Toolkit format by adding missing fields
1918
+ Effect.map(
1919
+ retrieved =>
1920
+ ({
1921
+ name: retrieved.name,
1922
+ slug: retrieved.slug,
1923
+ auth_schemes: [], // retrieve endpoint doesn't return auth_schemes
1924
+ composio_managed_auth_schemes: retrieved.composio_managed_auth_schemes,
1925
+ is_local_toolkit: retrieved.is_local_toolkit,
1926
+ no_auth: retrieved.no_auth,
1927
+ meta: retrieved.meta,
1928
+ }) satisfies Toolkit
1929
+ )
1930
+ ),
1931
+ /**
1932
+ * Searches toolkits with optional filters. Returns a single page of results (no auto-pagination).
1933
+ * @param params - Search/filter parameters
1934
+ */
1935
+ search: (params: { search?: string; category?: string; limit?: number; cursor?: string }) =>
1936
+ withMetrics(
1937
+ callClient(
1938
+ clientSingleton,
1939
+ client =>
1940
+ client.toolkits.list({
1941
+ search: params.search,
1942
+ category: params.category,
1943
+ limit: params.limit,
1944
+ cursor: params.cursor,
1945
+ }),
1946
+ ToolkitSearchResponse
1947
+ )
1948
+ ).pipe(
1949
+ Effect.map(
1950
+ response =>
1951
+ ({
1952
+ items: response.items,
1953
+ total_items: response.total_items,
1954
+ total_pages: response.total_pages,
1955
+ next_cursor: response.next_cursor,
1956
+ }) satisfies ToolkitSearchResult
1957
+ )
1958
+ ),
1959
+ /**
1960
+ * Retrieves detailed toolkit info including auth_config_details.
1961
+ * @param slug - Toolkit slug
1962
+ */
1963
+ retrieveDetailed: (slug: string) =>
1964
+ withMetrics(
1965
+ callClient(
1966
+ clientSingleton,
1967
+ client => client.toolkits.retrieve(slug),
1968
+ ToolkitDetailedResponse
1969
+ )
1970
+ ),
1971
+ },
1972
+ tools: buildToolsNamespace(clientSingleton, withMetrics),
1973
+ triggersTypes: {
1974
+ /**
1975
+ * Retrieves a list of all available trigger type enum values that can be used across the API.
1976
+ */
1977
+ retrieveEnum: () =>
1978
+ withMetrics(
1979
+ callClient(
1980
+ clientSingleton,
1981
+ client => client.triggersTypes.retrieveEnum(),
1982
+ TriggerTypesAsEnumsResponse
1983
+ )
1984
+ ),
1985
+ /**
1986
+ * Retrieves detailed info about a single trigger type by slug.
1987
+ * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
1988
+ */
1989
+ retrieve: (slug: string) =>
1990
+ withMetrics(
1991
+ callClient(clientSingleton, client => client.triggersTypes.retrieve(slug), TriggerType)
1992
+ ),
1993
+ /**
1994
+ * Retrieve a list of trigger types, automatically handling pagination.
1995
+ * @param toolkitSlugs - Optional array of toolkit slugs to filter by
1996
+ */
1997
+ list: (toolkitSlugs?: ReadonlyArray<string>) =>
1998
+ withMetrics(
1999
+ callClientWithPagination(
2000
+ clientSingleton,
2001
+ (client, cursor, limit) =>
2002
+ client.triggersTypes.list({
2003
+ cursor,
2004
+ limit,
2005
+ toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,
2006
+ }),
2007
+ TriggerTypesResponse
2008
+ )
2009
+ ),
2010
+ },
2011
+ triggerInstances: buildTriggerInstancesNamespace(clientSingleton, withMetrics),
2012
+ cli: {
2013
+ /**
2014
+ * Generates a new CLI session with a random 6-character code.
2015
+ * @param params.scope - 'user' for login, 'project' for init (future)
2016
+ *
2017
+ * TODO: don't use `@composio/client`, wrap `fetch` directly.
2018
+ */
2019
+ createSession: (params?: { scope?: 'user' | 'project' }) =>
2020
+ withMetrics(
2021
+ callClient(
2022
+ clientSingleton,
2023
+ client =>
2024
+ client.cli.createSession(
2025
+ { scope: params?.scope ?? 'user' },
2026
+ { headers: { 'Content-Type': 'application/json' } }
2027
+ ),
2028
+ CliCreateSessionResponse
2029
+ )
2030
+ ),
2031
2032
/**
2087
- * Fetches specific toolkits by their slugs.
2088
- * Makes parallel API calls to retrieve each toolkit.
2089
- * @param slugs - Array of toolkit slugs to fetch
2033
+ * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.
2034
*/
2091
- const getToolkitsBySlugs = (slugs: ReadonlyArray<string>) =>
2092
- Effect.all(
2093
- slugs.map(slug =>
2094
- client.toolkits.retrieve(slug).pipe(
2095
- // Only convert 404 errors to InvalidToolkitsError.
2096
- // Other HTTP errors (500, 401, network failures, etc.) should propagate as-is.
2097
- Effect.catchTag('services/HttpServerError', e =>
2098
- Effect.if(e.status === 404, {
2099
- onTrue: () =>
2100
- Effect.fail(
2101
- new InvalidToolkitsError({
2102
- invalidToolkits: [slug],
2103
- availableToolkits: [],
2104
- })
2105
- ),
2106
- onFalse: () => Effect.fail(e),
2107
- })
2108
- )
2109
- )
2110
- ),
2111
- { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
2112
- ).pipe(Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>));
2035
+ getSession: (session: { id: string }) =>
2036
+ withMetrics(
2037
+ callClient(
2038
+ clientSingleton,
2039
+ client => client.cli.getSession(session),
2040
+ CliGetSessionResponse
2041
+ )
2042
+ ),
2043
+ getRealtimeCredentials: () =>
2044
+ withMetrics(
2045
+ callClient(
2046
+ clientSingleton,
2047
+ client => client.cli.realtime.credentials(),
2048
+ CliRealtimeCredentialsResponse
2049
+ )
2050
+ ),
2051
+ authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2052
+ withMetrics(
2053
+ callClient(
2054
+ clientSingleton,
2055
+ client => client.cli.realtime.auth(params),
2056
+ CliRealtimeAuthResponse
2057
+ )
2058
+ ),
2059
+ },
2060
+ authConfigs: buildAuthConfigsNamespace(clientSingleton, withMetrics),
2061
+ connectedAccounts: buildConnectedAccountsNamespace(clientSingleton, withMetrics),
2062
+ };
2063
+});
2064
2114
- return {
2115
- getToolkits,
2116
- getToolkitsBySlugs,
2117
- getMetrics: () => client.getMetrics(),
2118
- getToolsAsEnums: () => client.tools.retrieveEnum(),
2119
- /**
2120
- * Fetches tools with optional toolkit filtering.
2121
- * When toolkitSlugs is provided, fetches all matching tools.
2122
- * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2123
- */
2124
- getTools: (toolkitSlugs?: ReadonlyArray<string>) =>
2125
- client.tools.list(toolkitSlugs ?? []).pipe(
2126
- Effect.map(response => response.items),
2127
- Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2128
- ),
2129
- /**
2130
- * Fetches tools with per-toolkit version support.
2131
- * Groups toolkits by version and makes separate API calls for each group.
2132
- * @param specs - Array of { toolkitSlug, toolkitVersion } specifications
2133
- */
2134
- getToolsByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>
2135
- client.tools.listByVersionSpecs(specs).pipe(
2136
- Effect.map(response => response.items),
2137
- Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2138
- ),
2139
- getTriggerTypesAsEnums: () => client.triggersTypes.retrieveEnum(),
2140
- /**
2141
- * Retrieves detailed info about a single trigger type by slug.
2142
- * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
2143
- */
2144
- getTriggerTypeDetailed: (slug: string) => client.triggersTypes.retrieve(slug),
2145
- /**
2146
- * Fetches trigger types with optional toolkit filtering.
2147
- * When toolkitSlugs is provided, fetches all matching trigger types.
2148
- * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2149
- */
2150
- getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>
2151
- client.triggersTypes.list(toolkitSlugs).pipe(
2152
- Effect.map(response => response.items),
2153
- Effect.map(items => sortBySlug(items) as ReadonlyArray<TriggerType>)
2154
- ),
2155
- /**
2156
- * Validates that the given toolkit slugs are valid by comparing them against the list
2157
- * of available toolkits. Returns the list of valid toolkit slugs (normalized to lowercase).
2158
- * @param toolkitSlugs - Array of toolkit slugs to validate (case-insensitive)
2159
- */
2160
- validateToolkits: (
2161
- toolkitSlugs: ReadonlyArray<string>
2162
- ): Effect.Effect<
2163
- ReadonlyArray<string>,
2164
- InvalidToolkitsError | HttpError | NoSuchElementException
2165
- > =>
2166
- Effect.gen(function* () {
2167
- // Normalize input slugs to lowercase for comparison
2168
- const normalizedInputSlugs = toolkitSlugs.map(slug => String.toLowerCase(slug));
2169
-
2170
- // Fetch all available toolkits
2171
- const allToolkits = yield* getToolkits();
2172
- const availableSlugs = allToolkits.map(toolkit => String.toLowerCase(toolkit.slug));
2173
-
2174
- // Find invalid slugs
2175
- const invalidSlugs = normalizedInputSlugs.filter(
2176
- slug => !availableSlugs.includes(slug)
2177
- );
2065
+export type ComposioClientLiveShape = Effect.Effect.Success<typeof makeComposioClientLive>;
2066
2179
- if (invalidSlugs.length > 0) {
2180
- return yield* Effect.fail(
2181
- new InvalidToolkitsError({
2182
- invalidToolkits: invalidSlugs,
2183
- availableToolkits: availableSlugs,
2184
- })
2185
- );
2186
- }
2067
+export class ComposioClientLive extends Context.Tag('services/ComposioClientLive')<
2068
+ ComposioClientLive,
2069
+ ComposioClientLiveShape
2070
+>() {
2071
+ static readonly Default = Layer.effect(ComposioClientLive, makeComposioClientLive).pipe(
2072
+ Layer.provide(ComposioClientSingleton.Default)
2073
+ );
2074
+}
2075
2188
- return normalizedInputSlugs;
2189
- }),
2190
- /**
2191
- * Filters the given list of toolkits to only include those with the specified slugs.
2192
- * @param toolkits - Array of toolkits to filter
2193
- * @param toolkitSlugs - Array of toolkit slugs to filter by (case-insensitive)
2194
- */
2195
- filterToolkitsBySlugs: (
2196
- toolkits: ReadonlyArray<Toolkit>,
2197
- toolkitSlugs: ReadonlyArray<string>
2198
- ): ReadonlyArray<Toolkit> => {
2199
- const normalizedSlugs = new Set(toolkitSlugs.map(slug => String.toLowerCase(slug)));
2200
- return toolkits.filter(toolkit => normalizedSlugs.has(String.toLowerCase(toolkit.slug)));
2201
- },
2202
- /**
2203
- * Validates that the requested toolkit versions exist in the API's available_versions.
2204
- * Makes parallel API calls to fetch toolkit metadata for validation.
2205
- *
2206
- * @param overrides - Map of toolkit slug to requested version
2207
- * @param relevantToolkits - Optional array of toolkit slugs to validate (if --toolkits filter is used)
2208
- * @returns Effect that succeeds with the validated overrides and warnings, or fails with InvalidToolkitVersionsError
2209
- */
2210
- validateToolkitVersions: (
2211
- overrides: ToolkitVersionOverrides,
2212
- relevantToolkits?: ReadonlyArray<string>
2213
- ): Effect.Effect<
2214
- {
2215
- validatedOverrides: ToolkitVersionOverrides;
2216
- warnings: ReadonlyArray<string>;
2217
- },
2218
- InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementException
2219
- > => validateToolkitVersionsImpl(client, overrides, relevantToolkits),
2220
- /**
2221
- * Searches toolkits with optional filters. Returns a single page of results.
2222
- * @param params - Search/filter parameters
2223
- */
2224
- searchToolkits: (params: {
2225
- search?: string;
2226
- category?: string;
2227
- limit?: number;
2228
- cursor?: string;
2229
- }) => client.toolkits.search(params),
2230
- /**
2231
- * Retrieves detailed toolkit info including auth_config_details.
2232
- * @param slug - Toolkit slug
2233
- */
2234
- getToolkitDetailed: (slug: string) => client.toolkits.retrieveDetailed(slug),
2235
- /**
2236
- * Searches tools with optional filters. Returns a single page of results.
2237
- * @param params - Search/filter parameters
2238
- */
2239
- searchTools: (params: {
2240
- search?: string;
2241
- toolkit_slug?: string;
2242
- tags?: string;
2243
- limit?: number;
2244
- cursor?: string;
2245
- }) => client.tools.search(params),
2246
- /**
2247
- * Retrieves detailed info about a single tool by slug.
2248
- * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")
2249
- */
2250
- getToolDetailed: (slug: string) => client.tools.retrieve(slug),
2251
- /**
2252
- * Lists auth configs with optional filters. Returns a single page of results.
2253
- * @param params - Search/filter parameters
2254
- */
2255
- listAuthConfigs: (params: {
2256
- search?: string;
2257
- toolkit_slug?: string;
2258
- limit?: number;
2259
- show_disabled?: boolean;
2260
- }) => client.authConfigs.list(params),
2261
- /**
2262
- * Retrieves detailed info about a single auth config by its nanoid.
2263
- * @param nanoid - Auth config ID
2264
- */
2265
- getAuthConfig: (nanoid: string) => client.authConfigs.retrieve(nanoid),
2266
- /**
2267
- * Creates a new auth config for a toolkit.
2268
- * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
2269
- */
2270
- createAuthConfig: (params: AuthConfigCreateParams) => client.authConfigs.create(params),
2271
- deleteAuthConfig: (nanoid: string) => client.authConfigs.delete(nanoid),
2272
- // Connected account operations (thin wrappers — see buildConnectedAccountsNamespace)
2273
- listConnectedAccounts: (params: {
2274
- toolkit_slugs?: string[];
2275
- user_ids?: string[];
2276
- statuses?: string[];
2277
- limit?: number;
2278
- }) => client.connectedAccounts.list(params),
2279
- getConnectedAccount: (nanoid: string) => client.connectedAccounts.retrieve(nanoid),
2280
- deleteConnectedAccount: (nanoid: string) => client.connectedAccounts.delete(nanoid),
2281
- createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>
2282
- client.connectedAccounts.createLink(params),
2283
- ...buildTriggerInstanceRepositoryOperations(client),
2284
- };
2285
- }),
2286
- dependencies: [ComposioClientLive.Default],
2287
- }
2288
-) {}
2076
+const makeComposioToolkitsRepository = Effect.gen(function* () {
2077
+ const client = yield* ComposioClientLive;
2078
2290
-export class ComposioSessionRepository extends Effect.Service<ComposioSessionRepository>()(
2291
- 'services/ComposioSessionRepository',
2292
- {
2293
- effect: Effect.gen(function* () {
2294
- const client = yield* ComposioClientLive;
2079
+ const getToolkits = () =>
2080
+ client.toolkits.list().pipe(
2081
+ Effect.map(response => response.items),
2082
+ Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>)
2083
+ );
2084
2296
- return {
2297
- createSession: (params?: { scope?: 'user' | 'project' }) =>
2298
- client.cli.createSession(params),
2299
- getSession: (session: { id: string }) => client.cli.getSession({ id: session.id }),
2300
- getRealtimeCredentials: () => client.cli.getRealtimeCredentials(),
2301
- authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2302
- client.cli.authRealtimeChannel(params),
2303
- };
2304
- }),
2305
- dependencies: [ComposioClientLive.Default],
2306
- }
2307
-) {}
2085
+ /**
2086
+ * Fetches specific toolkits by their slugs.
2087
+ * Makes parallel API calls to retrieve each toolkit.
2088
+ * @param slugs - Array of toolkit slugs to fetch
2089
+ */
2090
+ const getToolkitsBySlugs = (slugs: ReadonlyArray<string>) =>
2091
+ Effect.all(
2092
+ slugs.map(slug =>
2093
+ client.toolkits.retrieve(slug).pipe(
2094
+ // Only convert 404 errors to InvalidToolkitsError.
2095
+ // Other HTTP errors (500, 401, network failures, etc.) should propagate as-is.
2096
+ Effect.catchTag('services/HttpServerError', e =>
2097
+ Effect.if(e.status === 404, {
2098
+ onTrue: () =>
2099
+ Effect.fail(
2100
+ new InvalidToolkitsError({
2101
+ invalidToolkits: [slug],
2102
+ availableToolkits: [],
2103
+ })
2104
+ ),
2105
+ onFalse: () => Effect.fail(e),
2106
+ })
2107
+ )
2108
+ )
2109
+ ),
2110
+ { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
2111
+ ).pipe(Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>));
2112
+
2113
+ return {
2114
+ getToolkits,
2115
+ getToolkitsBySlugs,
2116
+ getMetrics: () => client.getMetrics(),
2117
+ getToolsAsEnums: () => client.tools.retrieveEnum(),
2118
+ /**
2119
+ * Fetches tools with optional toolkit filtering.
2120
+ * When toolkitSlugs is provided, fetches all matching tools.
2121
+ * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2122
+ */
2123
+ getTools: (toolkitSlugs?: ReadonlyArray<string>) =>
2124
+ client.tools.list(toolkitSlugs ?? []).pipe(
2125
+ Effect.map(response => response.items),
2126
+ Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2127
+ ),
2128
+ /**
2129
+ * Fetches tools with per-toolkit version support.
2130
+ * Groups toolkits by version and makes separate API calls for each group.
2131
+ * @param specs - Array of { toolkitSlug, toolkitVersion } specifications
2132
+ */
2133
+ getToolsByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>
2134
+ client.tools.listByVersionSpecs(specs).pipe(
2135
+ Effect.map(response => response.items),
2136
+ Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2137
+ ),
2138
+ getTriggerTypesAsEnums: () => client.triggersTypes.retrieveEnum(),
2139
+ /**
2140
+ * Retrieves detailed info about a single trigger type by slug.
2141
+ * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
2142
+ */
2143
+ getTriggerTypeDetailed: (slug: string) => client.triggersTypes.retrieve(slug),
2144
+ /**
2145
+ * Fetches trigger types with optional toolkit filtering.
2146
+ * When toolkitSlugs is provided, fetches all matching trigger types.
2147
+ * @param toolkitSlugs - Optional array of toolkit slugs to filter by
2148
+ */
2149
+ getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>
2150
+ client.triggersTypes.list(toolkitSlugs).pipe(
2151
+ Effect.map(response => response.items),
2152
+ Effect.map(items => sortBySlug(items) as ReadonlyArray<TriggerType>)
2153
+ ),
2154
+ /**
2155
+ * Validates that the given toolkit slugs are valid by comparing them against the list
2156
+ * of available toolkits. Returns the list of valid toolkit slugs (normalized to lowercase).
2157
+ * @param toolkitSlugs - Array of toolkit slugs to validate (case-insensitive)
2158
+ */
2159
+ validateToolkits: (
2160
+ toolkitSlugs: ReadonlyArray<string>
2161
+ ): Effect.Effect<
2162
+ ReadonlyArray<string>,
2163
+ InvalidToolkitsError | HttpError | NoSuchElementException
2164
+ > =>
2165
+ Effect.gen(function* () {
2166
+ // Normalize input slugs to lowercase for comparison
2167
+ const normalizedInputSlugs = toolkitSlugs.map(slug => String.toLowerCase(slug));
2168
+
2169
+ // Fetch all available toolkits
2170
+ const allToolkits = yield* getToolkits();
2171
+ const availableSlugs = allToolkits.map(toolkit => String.toLowerCase(toolkit.slug));
2172
+
2173
+ // Find invalid slugs
2174
+ const invalidSlugs = normalizedInputSlugs.filter(slug => !availableSlugs.includes(slug));
2175
+
2176
+ if (invalidSlugs.length > 0) {
2177
+ return yield* Effect.fail(
2178
+ new InvalidToolkitsError({
2179
+ invalidToolkits: invalidSlugs,
2180
+ availableToolkits: availableSlugs,
2181
+ })
2182
+ );
2183
+ }
2184
+
2185
+ return normalizedInputSlugs;
2186
+ }),
2187
+ /**
2188
+ * Filters the given list of toolkits to only include those with the specified slugs.
2189
+ * @param toolkits - Array of toolkits to filter
2190
+ * @param toolkitSlugs - Array of toolkit slugs to filter by (case-insensitive)
2191
+ */
2192
+ filterToolkitsBySlugs: (
2193
+ toolkits: ReadonlyArray<Toolkit>,
2194
+ toolkitSlugs: ReadonlyArray<string>
2195
+ ): ReadonlyArray<Toolkit> => {
2196
+ const normalizedSlugs = new Set(toolkitSlugs.map(slug => String.toLowerCase(slug)));
2197
+ return toolkits.filter(toolkit => normalizedSlugs.has(String.toLowerCase(toolkit.slug)));
2198
+ },
2199
+ /**
2200
+ * Validates that the requested toolkit versions exist in the API's available_versions.
2201
+ * Makes parallel API calls to fetch toolkit metadata for validation.
2202
+ *
2203
+ * @param overrides - Map of toolkit slug to requested version
2204
+ * @param relevantToolkits - Optional array of toolkit slugs to validate (if --toolkits filter is used)
2205
+ * @returns Effect that succeeds with the validated overrides and warnings, or fails with InvalidToolkitVersionsError
2206
+ */
2207
+ validateToolkitVersions: (
2208
+ overrides: ToolkitVersionOverrides,
2209
+ relevantToolkits?: ReadonlyArray<string>
2210
+ ): Effect.Effect<
2211
+ {
2212
+ validatedOverrides: ToolkitVersionOverrides;
2213
+ warnings: ReadonlyArray<string>;
2214
+ },
2215
+ InvalidToolkitVersionsError | InvalidToolkitsError | HttpError | NoSuchElementException
2216
+ > => validateToolkitVersionsImpl(client, overrides, relevantToolkits),
2217
+ /**
2218
+ * Searches toolkits with optional filters. Returns a single page of results.
2219
+ * @param params - Search/filter parameters
2220
+ */
2221
+ searchToolkits: (params: {
2222
+ search?: string;
2223
+ category?: string;
2224
+ limit?: number;
2225
+ cursor?: string;
2226
+ }) => client.toolkits.search(params),
2227
+ /**
2228
+ * Retrieves detailed toolkit info including auth_config_details.
2229
+ * @param slug - Toolkit slug
2230
+ */
2231
+ getToolkitDetailed: (slug: string) => client.toolkits.retrieveDetailed(slug),
2232
+ /**
2233
+ * Searches tools with optional filters. Returns a single page of results.
2234
+ * @param params - Search/filter parameters
2235
+ */
2236
+ searchTools: (params: {
2237
+ search?: string;
2238
+ toolkit_slug?: string;
2239
+ tags?: string;
2240
+ limit?: number;
2241
+ cursor?: string;
2242
+ }) => client.tools.search(params),
2243
+ /**
2244
+ * Retrieves detailed info about a single tool by slug.
2245
+ * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")
2246
+ */
2247
+ getToolDetailed: (slug: string) => client.tools.retrieve(slug),
2248
+ /**
2249
+ * Lists auth configs with optional filters. Returns a single page of results.
2250
+ * @param params - Search/filter parameters
2251
+ */
2252
+ listAuthConfigs: (params: {
2253
+ search?: string;
2254
+ toolkit_slug?: string;
2255
+ limit?: number;
2256
+ show_disabled?: boolean;
2257
+ }) => client.authConfigs.list(params),
2258
+ /**
2259
+ * Retrieves detailed info about a single auth config by its nanoid.
2260
+ * @param nanoid - Auth config ID
2261
+ */
2262
+ getAuthConfig: (nanoid: string) => client.authConfigs.retrieve(nanoid),
2263
+ /**
2264
+ * Creates a new auth config for a toolkit.
2265
+ * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
2266
+ */
2267
+ createAuthConfig: (params: AuthConfigCreateParams) => client.authConfigs.create(params),
2268
+ deleteAuthConfig: (nanoid: string) => client.authConfigs.delete(nanoid),
2269
+ // Connected account operations (thin wrappers — see buildConnectedAccountsNamespace)
2270
+ listConnectedAccounts: (params: {
2271
+ toolkit_slugs?: string[];
2272
+ user_ids?: string[];
2273
+ statuses?: string[];
2274
+ limit?: number;
2275
+ }) => client.connectedAccounts.list(params),
2276
+ getConnectedAccount: (nanoid: string) => client.connectedAccounts.retrieve(nanoid),
2277
+ deleteConnectedAccount: (nanoid: string) => client.connectedAccounts.delete(nanoid),
2278
+ createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>
2279
+ client.connectedAccounts.createLink(params),
2280
+ ...buildTriggerInstanceRepositoryOperations(client),
2281
+ };
2282
+});
2283
+
2284
+export type ComposioToolkitsRepositoryShape = Effect.Effect.Success<
2285
+ typeof makeComposioToolkitsRepository
2286
+>;
2287
+
2288
+export class ComposioToolkitsRepository extends Context.Tag('services/ComposioToolkitsRepository')<
2289
+ ComposioToolkitsRepository,
2290
+ ComposioToolkitsRepositoryShape
2291
+>() {
2292
+ static readonly Default = Layer.effect(
2293
+ ComposioToolkitsRepository,
2294
+ makeComposioToolkitsRepository
2295
+ ).pipe(Layer.provide(ComposioClientLive.Default));
2296
+}
2297
+
2298
+const makeComposioSessionRepository = Effect.gen(function* () {
2299
+ const client = yield* ComposioClientLive;
2300
+
2301
+ return {
2302
+ createSession: (params?: { scope?: 'user' | 'project' }) => client.cli.createSession(params),
2303
+ getSession: (session: { id: string }) => client.cli.getSession({ id: session.id }),
2304
+ getRealtimeCredentials: () => client.cli.getRealtimeCredentials(),
2305
+ authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
2306
+ client.cli.authRealtimeChannel(params),
2307
+ };
2308
+});
2309
+
2310
+export type ComposioSessionRepositoryShape = Effect.Effect.Success<
2311
+ typeof makeComposioSessionRepository
2312
+>;
2313
+
2314
+export class ComposioSessionRepository extends Context.Tag('services/ComposioSessionRepository')<
2315
+ ComposioSessionRepository,
2316
+ ComposioSessionRepositoryShape
2317
+>() {
2318
+ static readonly Default = Layer.effect(
2319
+ ComposioSessionRepository,
2320
+ makeComposioSessionRepository
2321
+ ).pipe(Layer.provide(ComposioClientLive.Default));
2322
+}