Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 176 lines 6.33 KB
Raw
1 import { Effect } from 'effect';
2 import type { ComposioClientShape } from '@composio/client/effect';
3 import { isKnownConnectedAccountStatus } from 'src/models/connected-accounts';
4 import {
5 compareNewestFirst,
6 groupCachedConnectedAccountsByToolkit,
7 listActiveConnectedAccounts,
8 resolveDefaultConnectedAccountsByToolkit,
9 type SelectableConnectedAccount,
10 } from 'src/services/connected-account-selection';
11 import { listAllConnectedAccounts } from 'src/services/list-all-connected-accounts';
12
13 type RawConnectedAccount = {
14 readonly id: string;
15 readonly alias?: string | null;
16 readonly word_id?: string | null;
17 readonly is_disabled?: boolean | null;
18 readonly status?: string | null;
19 readonly user_id?: string | null;
20 readonly toolkit?: {
21 readonly slug?: string | null;
22 } | null;
23 readonly auth_config?: {
24 readonly id?: string | null;
25 readonly is_composio_managed?: boolean | null;
26 } | null;
27 readonly updated_at?: string | null;
28 readonly created_at?: string | null;
29 };
30
31 export type ToolRouterSessionConnectionContext = {
32 readonly connectedToolkits: ReadonlyArray<string>;
33 readonly authConfigs?: Record<string, string>;
34 readonly connectedAccounts?: Record<string, string>;
35 readonly availableConnectedAccounts?: Record<
36 string,
37 ReadonlyArray<{
38 readonly id: string;
39 readonly alias: string | null;
40 readonly wordId: string | null;
41 readonly updatedAt: string;
42 readonly createdAt: string;
43 }>
44 >;
45 };
46
47 const normalizeConnectedAccountStatus = (
48 status?: string | null
49 ): SelectableConnectedAccount['status'] =>
50 // Sentinel — `'INACTIVE'` would falsely tag the account as user-disabled.
51 status != null && isKnownConnectedAccountStatus(status) ? status : 'UNKNOWN';
52
53 const isNewerAccount = (candidate: RawConnectedAccount, current: RawConnectedAccount): boolean =>
54 compareNewestFirst(candidate, current) < 0;
55
56 const listConnectedAccountsForToolkits = (
57 client: ComposioClientShape,
58 userId: string,
59 toolkits: ReadonlyArray<string>
60 ) =>
61 listAllConnectedAccounts(client, {
62 user_ids: [userId],
63 statuses: ['ACTIVE'],
64 toolkit_slugs: [...toolkits],
65 });
66
67 export const resolveToolRouterSessionConnections = (
68 client: ComposioClientShape,
69 userId: string,
70 options?: {
71 readonly toolkits?: ReadonlyArray<string>;
72 }
73 ) =>
74 (options?.toolkits && options.toolkits.length > 0
75 ? listConnectedAccountsForToolkits(client, userId, options.toolkits)
76 : // The unfiltered list is the one `composio execute` also needs for its
77 // account picker, so it is fetched once per process and shared.
78 listActiveConnectedAccounts({ client, userId })
79 ).pipe(
80 Effect.map(accounts => {
81 const items = accounts as ReadonlyArray<RawConnectedAccount>;
82 const unknownStatuses = new Set<string>();
83 const normalizedItems: SelectableConnectedAccount[] = items.map(item => {
84 const normalizedStatus = normalizeConnectedAccountStatus(item.status);
85 if (normalizedStatus === 'UNKNOWN' && item.status) {
86 unknownStatuses.add(item.status);
87 }
88 return {
89 id: item.id,
90 alias: item.alias ?? null,
91 word_id: item.word_id ?? null,
92 status: normalizedStatus,
93 status_reason: null,
94 is_disabled: item.is_disabled ?? false,
95 user_id: item.user_id ?? '',
96 toolkit: {
97 slug: item.toolkit?.slug ?? '',
98 },
99 auth_config: {
100 id: item.auth_config?.id ?? '',
101 auth_scheme: '',
102 is_composio_managed: item.auth_config?.is_composio_managed ?? true,
103 is_disabled: false,
104 },
105 created_at: item.created_at ?? '',
106 updated_at: item.updated_at ?? '',
107 test_request_endpoint: '',
108 } satisfies SelectableConnectedAccount;
109 });
110
111 const connectedToolkits = new Set<string>();
112 const explicitAccountsByToolkit = new Map<string, RawConnectedAccount>();
113
114 // Second pass over raw items — needs `auth_config` / `is_disabled`
115 // dropped by the normalized projection.
116 for (const item of items) {
117 const toolkit = item.toolkit?.slug?.toLowerCase().trim();
118 if (!toolkit || item.is_disabled) continue;
119
120 connectedToolkits.add(toolkit);
121
122 // Tool Router already handles Composio-managed auth well.
123 // Explicitly pin non-managed auth configs/accounts so consumer sessions
124 // can execute against custom-auth toolkits like PostHog.
125 if (item.auth_config?.is_composio_managed !== false) {
126 continue;
127 }
128
129 const current = explicitAccountsByToolkit.get(toolkit);
130 if (!current || isNewerAccount(item, current)) {
131 explicitAccountsByToolkit.set(toolkit, item);
132 }
133 }
134
135 const authConfigs: Record<string, string> = {};
136 for (const [toolkit, item] of explicitAccountsByToolkit) {
137 const authConfigId = item.auth_config?.id?.trim();
138 if (!authConfigId) continue;
139 authConfigs[toolkit] = authConfigId;
140 }
141
142 return {
143 unknownStatuses,
144 context: {
145 connectedToolkits: [...connectedToolkits],
146 authConfigs: Object.keys(authConfigs).length > 0 ? authConfigs : undefined,
147 connectedAccounts: (() => {
148 const selected = resolveDefaultConnectedAccountsByToolkit(normalizedItems);
149 return Object.keys(selected).length > 0 ? selected : undefined;
150 })(),
151 availableConnectedAccounts: (() => {
152 const grouped = groupCachedConnectedAccountsByToolkit(normalizedItems);
153 return Object.keys(grouped).length > 0 ? grouped : undefined;
154 })(),
155 } satisfies ToolRouterSessionConnectionContext,
156 };
157 }),
158 Effect.tap(({ unknownStatuses }) =>
159 unknownStatuses.size > 0
160 ? Effect.logDebug(
161 `[ToolRouterSession] received unrecognized connected_account.status ` +
162 `value(s): ${[...unknownStatuses].join(', ')}. Treating as 'UNKNOWN' ` +
163 `(not selectable). Run "composio upgrade" to pick up the latest schema.`
164 )
165 : Effect.void
166 ),
167 Effect.map(({ context }) => context),
168 Effect.catch(() =>
169 Effect.succeed({
170 connectedToolkits: [],
171 authConfigs: undefined,
172 connectedAccounts: undefined,
173 availableConnectedAccounts: undefined,
174 } satisfies ToolRouterSessionConnectionContext)
175 )
176 );