@devries-cameron20 / composio Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 241 lines 9.58 KB
Raw
1 import { Data, Effect, Option } from 'effect';
2 import type { ComposioClientShape } from '@composio/client/effect';
3 import type { SessionCreateParams } from '@composio/client/resources/tool-router';
4 import {
5 getFreshConsumerToolRouterAuthConfigsFromCache,
6 getFreshConsumerToolRouterConnectedAccountsFromCache,
7 writeConsumerConnectedToolkitsCache,
8 } from 'src/services/consumer-short-term-cache';
9 import {
10 resolveToolRouterSessionConnections,
11 type ToolRouterSessionConnectionContext,
12 } from 'src/services/tool-router-session-connections';
13 import {
14 ENHANCED_LINK_URL_OVERWRITE,
15 getConsumerPermissionSnapshot,
16 type ConsumerPermissionSnapshot,
17 } from 'src/services/tool-permissions';
18 import { nonEmptyOrUndefined } from 'src/utils/optional-params';
19
20 export interface CreateToolRouterSessionOptions {
21 /** Enable auto connection management. Default: false. */
22 readonly manageConnections?: boolean;
23 /** Restrict session to these toolkit slugs. */
24 readonly toolkits?: ReadonlyArray<string>;
25 /** Consumer-only cache scope for rolling auth-config reuse. */
26 readonly cacheScope?: {
27 readonly orgId: string;
28 readonly projectId: string;
29 readonly consumerUserId: string;
30 };
31 /** Explicit connected-account pins by toolkit slug. */
32 readonly connectedAccounts?: Record<string, string>;
33 /** Toolkits whose connected-account pins should be omitted from the session. */
34 readonly excludeConnectedAccountsForToolkits?: ReadonlyArray<string>;
35 /** Enable Tool Router multi-account mode for this session. */
36 readonly multiAccount?: {
37 readonly enable?: boolean;
38 readonly maxAccountsPerToolkit?: number;
39 readonly requireExplicitSelection?: boolean;
40 };
41 }
42
43 export interface CreatedToolRouterSession {
44 readonly sessionId: string;
45 readonly permissionSnapshot?: ConsumerPermissionSnapshot;
46 readonly connectedAccounts?: Record<string, string>;
47 readonly connectedAccountWordIds?: Record<string, string>;
48 }
49
50 export class ToolRouterSessionCreateError extends Data.TaggedError(
51 'effects/ToolRouterSessionCreateError'
52 )<{
53 readonly message: string;
54 readonly cause: unknown;
55 }> {}
56
57 /** Everything a Tool Router session is built from, resolved before the session exists. */
58 export interface ToolRouterSessionContext {
59 /** The session-create body, minus the user id. */
60 readonly sessionConfig: Omit<SessionCreateParams, 'user_id'>;
61 readonly permissionSnapshot?: ConsumerPermissionSnapshot;
62 readonly connectedAccounts?: Record<string, string>;
63 readonly connectedAccountWordIds?: Record<string, string>;
64 }
65
66 /**
67 * Resolve the connections, permission snapshot and session settings for the
68 * given user ID without creating a session. Callers that execute through the
69 * Dashboard use only the connection context; the Dashboard owns the session.
70 */
71 export const resolveToolRouterSessionContext = (
72 client: ComposioClientShape,
73 userId: string,
74 options?: CreateToolRouterSessionOptions
75 ) =>
76 Effect.gen(function* () {
77 const mergeConnectedAccounts = (...mappings: Array<Record<string, string> | undefined>) => {
78 const merged = Object.assign({}, ...mappings.filter(Boolean));
79 return Object.keys(merged).length > 0 ? merged : undefined;
80 };
81 const requestedToolkits = options?.toolkits ?? [];
82 const excludedToolkits = new Set(
83 (options?.excludeConnectedAccountsForToolkits ?? []).map(toolkit => toolkit.toLowerCase())
84 );
85 const filterConnectedAccounts = (mapping: Record<string, string> | undefined) => {
86 if (!mapping) return undefined;
87 const filtered = Object.fromEntries(
88 Object.entries(mapping).filter(([toolkit]) => !excludedToolkits.has(toolkit.toLowerCase()))
89 );
90 return Object.keys(filtered).length > 0 ? filtered : undefined;
91 };
92 const resolveConnectedAccountWordIds = (
93 selected: Record<string, string> | undefined,
94 available: ToolRouterSessionConnectionContext['availableConnectedAccounts']
95 ) => {
96 if (!selected || !available) return undefined;
97 const wordIds = Object.fromEntries(
98 Object.entries(selected).flatMap(([toolkit, connectedAccountId]) => {
99 const account = available[toolkit.toLowerCase()]?.find(
100 item => item.id === connectedAccountId
101 );
102 return account?.wordId ? [[toolkit, account.wordId]] : [];
103 })
104 );
105 return Object.keys(wordIds).length > 0 ? wordIds : undefined;
106 };
107
108 const cachedAuthConfigs = options?.cacheScope
109 ? yield* getFreshConsumerToolRouterAuthConfigsFromCache({
110 orgId: options.cacheScope.orgId,
111 consumerUserId: options.cacheScope.consumerUserId,
112 toolkits: nonEmptyOrUndefined(requestedToolkits),
113 })
114 : Option.none();
115 const cachedConnectedAccounts = options?.cacheScope
116 ? yield* getFreshConsumerToolRouterConnectedAccountsFromCache({
117 orgId: options.cacheScope.orgId,
118 consumerUserId: options.cacheScope.consumerUserId,
119 toolkits: nonEmptyOrUndefined(requestedToolkits),
120 })
121 : Option.none();
122
123 const connectionContext = Option.isSome(cachedAuthConfigs)
124 ? {
125 connectedToolkits: requestedToolkits,
126 authConfigs: cachedAuthConfigs.value.authConfigs,
127 connectedAccounts: mergeConnectedAccounts(
128 filterConnectedAccounts(
129 Option.isSome(cachedConnectedAccounts)
130 ? cachedConnectedAccounts.value.connectedAccounts
131 : undefined
132 ),
133 options?.connectedAccounts
134 ),
135 availableConnectedAccounts: Option.isSome(cachedConnectedAccounts)
136 ? cachedConnectedAccounts.value.availableConnectedAccounts
137 : undefined,
138 }
139 : yield* resolveToolRouterSessionConnections(client, userId, {
140 toolkits: nonEmptyOrUndefined(requestedToolkits),
141 }).pipe(
142 Effect.map(connectionContext => ({
143 ...connectionContext,
144 connectedAccounts: mergeConnectedAccounts(
145 filterConnectedAccounts(connectionContext.connectedAccounts),
146 options?.connectedAccounts
147 ),
148 }))
149 );
150
151 if (options?.cacheScope && Option.isNone(cachedAuthConfigs)) {
152 yield* writeConsumerConnectedToolkitsCache({
153 orgId: options.cacheScope.orgId,
154 consumerUserId: options.cacheScope.consumerUserId,
155 toolkits: connectionContext.connectedToolkits,
156 toolRouterAuthConfigs: {
157 authConfigs: connectionContext.authConfigs,
158 },
159 toolRouterConnectedAccounts: {
160 connectedAccounts: connectionContext.connectedAccounts,
161 availableConnectedAccounts: connectionContext.availableConnectedAccounts,
162 },
163 }).pipe(Effect.catch(() => Effect.void));
164 }
165
166 const connectedAccountIds = Object.values(connectionContext.connectedAccounts ?? {}).filter(
167 (value): value is string => typeof value === 'string'
168 );
169 const permissionSnapshot = options?.cacheScope
170 ? yield* getConsumerPermissionSnapshot({
171 orgId: options.cacheScope.orgId,
172 projectId: options.cacheScope.projectId,
173 consumerUserId: options.cacheScope.consumerUserId,
174 connectedAccountIds,
175 })
176 : undefined;
177 return {
178 sessionConfig: {
179 auth_configs: connectionContext.authConfigs,
180 connected_accounts: connectionContext.connectedAccounts,
181 manage_connections: { enable: options?.manageConnections ?? false },
182 multi_account: options?.multiAccount
183 ? {
184 enable: options.multiAccount.enable,
185 max_accounts_per_toolkit: options.multiAccount.maxAccountsPerToolkit,
186 require_explicit_selection: options.multiAccount.requireExplicitSelection,
187 }
188 : undefined,
189 toolkits: requestedToolkits.length > 0 ? { enable: [...requestedToolkits] } : undefined,
190 instant: { return_instant_charge: true },
191 experimental: permissionSnapshot?.enhancedControlsEnabled
192 ? { link_url_overwrite: ENHANCED_LINK_URL_OVERWRITE }
193 : undefined,
194 },
195 permissionSnapshot,
196 connectedAccounts: connectionContext.connectedAccounts,
197 connectedAccountWordIds: resolveConnectedAccountWordIds(
198 connectionContext.connectedAccounts,
199 connectionContext.availableConnectedAccounts
200 ),
201 } satisfies ToolRouterSessionContext;
202 });
203
204 /** Create an ephemeral Tool Router session from an already resolved context. */
205 export const createToolRouterSessionFromContext = (
206 client: ComposioClientShape,
207 userId: string,
208 { sessionConfig, ...context }: ToolRouterSessionContext
209 ) =>
210 client.toolRouter.session.create({ user_id: userId, ...sessionConfig }).pipe(
211 Effect.mapError(
212 cause =>
213 new ToolRouterSessionCreateError({
214 message: 'Failed to create a Tool Router session.',
215 cause,
216 })
217 ),
218 Effect.map((session): CreatedToolRouterSession => ({
219 sessionId: session.session_id,
220 ...context,
221 }))
222 );
223
224 /**
225 * Create an ephemeral Tool Router session for the given user ID.
226 * Returns the session id plus the permission and connected-account context bound to it.
227 *
228 * Accepts a pre-resolved client instance (from ComposioClientSingleton)
229 * so callers can resolve the dependency at layer construction time.
230 */
231 export const createToolRouterSessionContext = (
232 client: ComposioClientShape,
233 userId: string,
234 options?: CreateToolRouterSessionOptions
235 ) =>
236 resolveToolRouterSessionContext(client, userId, options).pipe(
237 Effect.flatMap(context => createToolRouterSessionFromContext(client, userId, context))
238 );
239
240 /** The name commands create their Tool Router session by. */
241 export const resolveToolRouterSession = createToolRouterSessionContext;