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
| 1 | import { Data, Effect, String } from 'effect'; |
| 2 | import type { RequestOptions } from '@composio/client/effect'; |
| 3 | import type { OrgListResponse, ProjectListResponse } from '@composio/client/resources/org'; |
| 4 | import type { |
| 5 | ConsumerListConnectedToolkitsResponse, |
| 6 | ProjectResolveResponse, |
| 7 | } from '@composio/client/resources/_internal/org/consumer'; |
| 8 | import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth'; |
| 9 | import { LatestToolVersionResponse } from 'src/models/tools'; |
| 10 | import { ComposioClientSingleton } from './composio-clients'; |
| 11 | import { HttpDecodingError, type ClientError } from './composio-errors'; |
| 12 | import { decode, idempotent, validated } from './composio-request'; |
| 13 | |
| 14 | /** |
| 15 | * Account, session-info, and consumer helpers |
| 16 | * |
| 17 | * Standalone functions rather than repository methods: they take explicit |
| 18 | * credentials and scope, and callers already run inside layers that provide |
| 19 | * `ComposioClientSingleton`. |
| 20 | */ |
| 21 | |
| 22 | /** |
| 23 | * Session info as the CLI consumes it: the client's response with `project` |
| 24 | * present. The endpoint answers `project: null` for org-level credentials, |
| 25 | * which every caller here treats as an unusable session. |
| 26 | */ |
| 27 | export type SessionInfoResponse = SessionRetrieveInfoResponse & { |
| 28 | readonly project: NonNullable<SessionRetrieveInfoResponse['project']>; |
| 29 | }; |
| 30 | |
| 31 | const requireSessionProject = ( |
| 32 | info: SessionRetrieveInfoResponse |
| 33 | ): Effect.Effect<SessionInfoResponse, HttpDecodingError> => |
| 34 | info.project === null |
| 35 | ? Effect.fail( |
| 36 | new HttpDecodingError({ |
| 37 | cause: 'Session info response has no project (org-level credentials)', |
| 38 | }) |
| 39 | ) |
| 40 | : Effect.succeed({ ...info, project: info.project }); |
| 41 | |
| 42 | /** The org member's id. The persisted playground test user id derives from it. */ |
| 43 | export const sessionUserIdOf = (info: SessionInfoResponse): string => info.org_member.id; |
| 44 | |
| 45 | /** The project API key carried by a session, or null. */ |
| 46 | export const sessionProjectApiKeyOf = (info: SessionInfoResponse): string | null => |
| 47 | info.api_key?.key ?? null; |
| 48 | |
| 49 | /** |
| 50 | * A single project entry returned by GET /api/v3.1/org/project/list. |
| 51 | */ |
| 52 | export type OrgProject = ProjectListResponse['data'][number]; |
| 53 | |
| 54 | export interface OrganizationSummary { |
| 55 | readonly id: string; |
| 56 | readonly name: string; |
| 57 | } |
| 58 | |
| 59 | interface OrganizationSummaryList { |
| 60 | readonly data: ReadonlyArray<OrganizationSummary>; |
| 61 | readonly total_items: number; |
| 62 | } |
| 63 | |
| 64 | const orgScopedOptions = (orgId: string | undefined): RequestOptions | undefined => |
| 65 | orgId ? { headers: { 'x-org-id': orgId } } : undefined; |
| 66 | |
| 67 | /** |
| 68 | * Lists organizations available to the current user API key. |
| 69 | */ |
| 70 | export const listOrganizations = (params: { |
| 71 | apiKey: string; |
| 72 | limit?: number; |
| 73 | }): Effect.Effect<OrganizationSummaryList, ClientError, ComposioClientSingleton> => |
| 74 | Effect.gen(function* () { |
| 75 | const clientSingleton = yield* ComposioClientSingleton; |
| 76 | const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey }); |
| 77 | const response = yield* client.org.list( |
| 78 | { limit: params.limit ?? 50 }, |
| 79 | { ...idempotent, ...validated } |
| 80 | ); |
| 81 | const organizations = response.organizations.map( |
| 82 | (organization: OrgListResponse['organizations'][number]) => |
| 83 | ({ id: organization.id, name: organization.name }) satisfies OrganizationSummary |
| 84 | ); |
| 85 | |
| 86 | return { |
| 87 | data: organizations, |
| 88 | total_items: organizations.length, |
| 89 | }; |
| 90 | }); |
| 91 | |
| 92 | /** |
| 93 | * Whether the user key belongs to `orgId`, reading every page of its org list. A missing org |
| 94 | * is only known after the last page. |
| 95 | */ |
| 96 | export const userKeyBelongsToOrg = (params: { |
| 97 | apiKey: string; |
| 98 | orgId: string; |
| 99 | }): Effect.Effect<boolean, ClientError, ComposioClientSingleton> => |
| 100 | Effect.gen(function* () { |
| 101 | const clientSingleton = yield* ComposioClientSingleton; |
| 102 | const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey }); |
| 103 | const fromPage = (cursor: string | undefined): Effect.Effect<boolean, ClientError> => |
| 104 | client.org |
| 105 | .list( |
| 106 | { limit: 100, ...(cursor === undefined ? {} : { cursor }) }, |
| 107 | { ...idempotent, ...validated } |
| 108 | ) |
| 109 | .pipe( |
| 110 | Effect.flatMap(page => |
| 111 | page.organizations.some(organization => organization.id === params.orgId) |
| 112 | ? Effect.succeed(true) |
| 113 | : page.next_cursor |
| 114 | ? fromPage(page.next_cursor) |
| 115 | : Effect.succeed(false) |
| 116 | ) |
| 117 | ); |
| 118 | return yield* fromPage(undefined); |
| 119 | }); |
| 120 | |
| 121 | /** |
| 122 | * Lists projects for a specific organization. |
| 123 | * |
| 124 | * Project lists are not client-decoded: the CLI reads a project's ids, name, |
| 125 | * and email, while the client schema also fixes `webhook_version` to the |
| 126 | * versions it knew at generation time. |
| 127 | */ |
| 128 | export const listOrganizationProjects = (params: { |
| 129 | apiKey: string; |
| 130 | orgId: string; |
| 131 | limit?: number; |
| 132 | }): Effect.Effect<OrganizationSummaryList, ClientError, ComposioClientSingleton> => |
| 133 | Effect.gen(function* () { |
| 134 | const clientSingleton = yield* ComposioClientSingleton; |
| 135 | const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey }); |
| 136 | const response = yield* client.org.project.list( |
| 137 | { limit: params.limit ?? 50 }, |
| 138 | { ...orgScopedOptions(params.orgId), ...idempotent } |
| 139 | ); |
| 140 | const projects = response.data.map( |
| 141 | (project: OrgProject) => |
| 142 | ({ id: project.id, name: project.name }) satisfies OrganizationSummary |
| 143 | ); |
| 144 | |
| 145 | return { |
| 146 | data: projects, |
| 147 | total_items: projects.length, |
| 148 | }; |
| 149 | }); |
| 150 | |
| 151 | /** |
| 152 | * Lists all projects for the logged-in user's organization. |
| 153 | * |
| 154 | * @param params.apiKey - UAK (sent as `x-user-api-key`) |
| 155 | * @param params.orgId - Organization ID (sent as `x-org-id`) |
| 156 | * @param params.limit - Max projects to return (default 50) |
| 157 | */ |
| 158 | export const listOrgProjects = (params: { |
| 159 | apiKey: string; |
| 160 | orgId: string; |
| 161 | limit?: number; |
| 162 | }): Effect.Effect<ProjectListResponse, ClientError, ComposioClientSingleton> => |
| 163 | Effect.gen(function* () { |
| 164 | const clientSingleton = yield* ComposioClientSingleton; |
| 165 | const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey }); |
| 166 | return yield* client.org.project.list( |
| 167 | { list_all_org_projects: true, limit: params.limit ?? 50 }, |
| 168 | { ...orgScopedOptions(params.orgId), ...idempotent } |
| 169 | ); |
| 170 | }); |
| 171 | |
| 172 | /** |
| 173 | * Calls GET /api/v3.1/auth/session/info with the full layered auth headers. |
| 174 | */ |
| 175 | export const getSessionInfo = (params: { |
| 176 | apiKey: string; |
| 177 | orgId: string; |
| 178 | projectId: string; |
| 179 | }): Effect.Effect<SessionInfoResponse, ClientError, ComposioClientSingleton> => |
| 180 | Effect.gen(function* () { |
| 181 | const clientSingleton = yield* ComposioClientSingleton; |
| 182 | const client = yield* clientSingleton.getFor({ |
| 183 | userApiKey: params.apiKey, |
| 184 | orgId: params.orgId, |
| 185 | projectId: params.projectId, |
| 186 | }); |
| 187 | // Read through a few fields only, and called after login has already |
| 188 | // linked the session: drift in a field the CLI never reads must not fail it. |
| 189 | const info = yield* client.auth.session.retrieveInfo(idempotent); |
| 190 | return yield* requireSessionProject(info); |
| 191 | }); |
| 192 | |
| 193 | /** |
| 194 | * Calls GET /api/v3.1/auth/session/info using the x-user-api-key header. |
| 195 | * Unlike getSessionInfo which requires both org AND project IDs, this variant |
| 196 | * resolves session metadata from the UAK alone — useful during login before |
| 197 | * org/project context is known. |
| 198 | * |
| 199 | * When `orgId` is provided, it is forwarded as `x-org-id` so the backend |
| 200 | * resolves the session against the caller's currently-selected global org |
| 201 | * (set via `composio orgs switch`). Without it, the backend falls back to the |
| 202 | * API key's home org, which makes the response ignore any org switch. |
| 203 | */ |
| 204 | export const getSessionInfoByUserApiKey = (params: { |
| 205 | userApiKey: string; |
| 206 | orgId?: string; |
| 207 | }): Effect.Effect<SessionInfoResponse, ClientError, ComposioClientSingleton> => |
| 208 | Effect.gen(function* () { |
| 209 | const clientSingleton = yield* ComposioClientSingleton; |
| 210 | const client = yield* clientSingleton.getFor({ userApiKey: params.userApiKey }); |
| 211 | const info = yield* client.auth.session.retrieveInfo({ |
| 212 | ...orgScopedOptions(params.orgId), |
| 213 | ...idempotent, |
| 214 | }); |
| 215 | return yield* requireSessionProject(info); |
| 216 | }); |
| 217 | |
| 218 | // The create-api-key response shape is not documented in the client. Walk the |
| 219 | // body for the first `uak_`/`ak_`-prefixed string under a key-like name. |
| 220 | const getApiKeyFromPayload = (payload: unknown): string | undefined => { |
| 221 | const candidates = new Set<string>(['api_key', 'apiKey', 'key', 'token']); |
| 222 | const keyPrefixes = ['uak_', 'ak_']; |
| 223 | const queue: unknown[] = [payload]; |
| 224 | |
| 225 | while (queue.length > 0) { |
| 226 | const current = queue.shift(); |
| 227 | if (!current || typeof current !== 'object') continue; |
| 228 | |
| 229 | if (Array.isArray(current)) { |
| 230 | queue.push(...current); |
| 231 | continue; |
| 232 | } |
| 233 | |
| 234 | const entries = Object.entries(current as Record<string, unknown>); |
| 235 | for (const [key, value] of entries) { |
| 236 | if ( |
| 237 | typeof value === 'string' && |
| 238 | candidates.has(key) && |
| 239 | keyPrefixes.some(prefix => value.startsWith(prefix)) |
| 240 | ) { |
| 241 | return value; |
| 242 | } |
| 243 | if (value && typeof value === 'object') { |
| 244 | queue.push(value); |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | return undefined; |
| 250 | }; |
| 251 | |
| 252 | /** |
| 253 | * Mints a project API key. Never retried: a retry after a timed-out create |
| 254 | * would mint a second key the caller never sees. |
| 255 | */ |
| 256 | export const createProjectApiKey = (params: { |
| 257 | apiKey: string; |
| 258 | orgId: string; |
| 259 | projectId: string; |
| 260 | name: string; |
| 261 | }): Effect.Effect<string, ClientError, ComposioClientSingleton> => |
| 262 | Effect.gen(function* () { |
| 263 | const clientSingleton = yield* ComposioClientSingleton; |
| 264 | const client = yield* clientSingleton.getFor({ |
| 265 | userApiKey: params.apiKey, |
| 266 | orgId: params.orgId, |
| 267 | projectId: params.projectId, |
| 268 | }); |
| 269 | const payload = yield* client.post(`/api/v3/org/project/${params.projectId}/api_keys/create`, { |
| 270 | body: { name: params.name }, |
| 271 | }); |
| 272 | const createdApiKey = getApiKeyFromPayload(payload); |
| 273 | |
| 274 | if (!createdApiKey) { |
| 275 | return yield* Effect.fail( |
| 276 | new HttpDecodingError({ |
| 277 | cause: 'Create API key response did not contain an API key', |
| 278 | }) |
| 279 | ); |
| 280 | } |
| 281 | |
| 282 | return createdApiKey; |
| 283 | }); |
| 284 | |
| 285 | export const resolveConsumerProject = (params: { |
| 286 | apiKey: string; |
| 287 | orgId: string; |
| 288 | }): Effect.Effect<ProjectResolveResponse, ClientError, ComposioClientSingleton> => |
| 289 | Effect.gen(function* () { |
| 290 | const clientSingleton = yield* ComposioClientSingleton; |
| 291 | const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey }); |
| 292 | return yield* client._internal.org.consumer.project.resolve( |
| 293 | { |
| 294 | 'x-user-api-key': params.apiKey, |
| 295 | 'x-org-id': params.orgId, |
| 296 | }, |
| 297 | idempotent |
| 298 | ); |
| 299 | }); |
| 300 | |
| 301 | /** |
| 302 | * Resolves the latest version of a tool. When `projectApiKey` is given the |
| 303 | * request is sent by a client that authenticates with it instead of the user |
| 304 | * key, so exactly one credential is sent. |
| 305 | */ |
| 306 | export const getLatestToolVersion = (params: { |
| 307 | apiKey: string; |
| 308 | toolSlug: string; |
| 309 | orgId?: string; |
| 310 | projectId?: string; |
| 311 | projectApiKey?: string; |
| 312 | }): Effect.Effect<LatestToolVersionResponse, ClientError, ComposioClientSingleton> => |
| 313 | Effect.gen(function* () { |
| 314 | const clientSingleton = yield* ComposioClientSingleton; |
| 315 | const credential = params.projectApiKey |
| 316 | ? { projectApiKey: params.projectApiKey } |
| 317 | : { userApiKey: params.apiKey }; |
| 318 | // A client's scope names the org and the project together; when only one |
| 319 | // of them is known it goes on the request, which an unscoped client allows. |
| 320 | const client = yield* clientSingleton.getFor( |
| 321 | params.orgId && params.projectId |
| 322 | ? { ...credential, orgId: params.orgId, projectId: params.projectId } |
| 323 | : credential |
| 324 | ); |
| 325 | const headers = |
| 326 | params.orgId && params.projectId |
| 327 | ? undefined |
| 328 | : { |
| 329 | ...(params.orgId ? { 'x-org-id': params.orgId } : {}), |
| 330 | ...(params.projectId ? { 'x-project-id': params.projectId } : {}), |
| 331 | }; |
| 332 | const payload = yield* client.get( |
| 333 | `/api/v3/tools/${encodeURIComponent(params.toolSlug)}/get_latest_version`, |
| 334 | { headers, ...idempotent } |
| 335 | ); |
| 336 | return yield* decode(LatestToolVersionResponse)(payload); |
| 337 | }); |
| 338 | |
| 339 | export const getConsumerConnectedToolkits = (params: { |
| 340 | apiKey: string; |
| 341 | orgId: string; |
| 342 | consumerUserId: string; |
| 343 | }): Effect.Effect<ConsumerListConnectedToolkitsResponse, ClientError, ComposioClientSingleton> => |
| 344 | Effect.gen(function* () { |
| 345 | const clientSingleton = yield* ComposioClientSingleton; |
| 346 | const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey }); |
| 347 | return yield* client._internal.org.consumer.listConnectedToolkits( |
| 348 | { |
| 349 | user_id: params.consumerUserId, |
| 350 | 'x-user-api-key': params.apiKey, |
| 351 | 'x-org-id': params.orgId, |
| 352 | }, |
| 353 | { ...idempotent, ...validated } |
| 354 | ); |
| 355 | }); |
| 356 | |
| 357 | export class DeveloperProjectNotFoundError extends Data.TaggedError( |
| 358 | 'services/DeveloperProjectNotFoundError' |
| 359 | )<{ |
| 360 | readonly orgId: string; |
| 361 | readonly projectName: string; |
| 362 | }> {} |
| 363 | |
| 364 | export class AmbiguousDeveloperProjectNameError extends Data.TaggedError( |
| 365 | 'services/AmbiguousDeveloperProjectNameError' |
| 366 | )<{ |
| 367 | readonly orgId: string; |
| 368 | readonly projectName: string; |
| 369 | readonly matches: ReadonlyArray<OrganizationSummary>; |
| 370 | }> {} |
| 371 | |
| 372 | export const findDeveloperProjectByName = (params: { |
| 373 | apiKey: string; |
| 374 | orgId: string; |
| 375 | name: string; |
| 376 | limit?: number; |
| 377 | }): Effect.Effect< |
| 378 | OrganizationSummary, |
| 379 | DeveloperProjectNotFoundError | AmbiguousDeveloperProjectNameError | ClientError, |
| 380 | ComposioClientSingleton |
| 381 | > => |
| 382 | Effect.gen(function* () { |
| 383 | const projects = yield* listOrgProjects({ |
| 384 | apiKey: params.apiKey, |
| 385 | orgId: params.orgId, |
| 386 | limit: params.limit, |
| 387 | }); |
| 388 | |
| 389 | const normalizedName = String.toLowerCase(params.name.trim()); |
| 390 | const matches = projects.data.filter( |
| 391 | project => String.toLowerCase(project.name) === normalizedName |
| 392 | ); |
| 393 | |
| 394 | if (matches.length === 0) { |
| 395 | return yield* Effect.fail( |
| 396 | new DeveloperProjectNotFoundError({ |
| 397 | orgId: params.orgId, |
| 398 | projectName: params.name, |
| 399 | }) |
| 400 | ); |
| 401 | } |
| 402 | |
| 403 | if (matches.length > 1) { |
| 404 | return yield* Effect.fail( |
| 405 | new AmbiguousDeveloperProjectNameError({ |
| 406 | orgId: params.orgId, |
| 407 | projectName: params.name, |
| 408 | matches, |
| 409 | }) |
| 410 | ); |
| 411 | } |
| 412 | |
| 413 | return matches[0]; |
| 414 | }); |