@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 136 lines 5.15 KB
Raw
1 import type { AuthConfigCreateParams as AuthConfigCreateRequest } from '@composio/client/resources/auth-configs';
2 import { Effect, Option, Result } from 'effect';
3 import { commandInputError } from 'src/commands/errors';
4 import { resolveDeveloperResourceProject } from 'src/commands/surface';
5 import { handleClientApiError } from 'src/effects/handle-http-error';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
8 import { TerminalUI } from 'src/services/terminal-ui';
9 import { redact } from 'src/ui/redact';
10 import { parseJsonRecord } from 'src/utils/parse-json';
11 import { formatAuthConfigCreated } from './auth-configs.create.format';
12
13 export type AuthConfigsCreateParams = {
14 readonly name: Option.Option<string>;
15 readonly toolkit: string;
16 readonly authScheme: Option.Option<string>;
17 readonly scopes: Option.Option<string>;
18 readonly customCredentials: Option.Option<string>;
19 };
20
21 /** `--custom-credentials` as a record, `undefined` when the flag is absent. */
22 const parseCustomCredentials = (customCredentials: Option.Option<string>) =>
23 Option.match(customCredentials, {
24 onNone: () => Result.succeed(undefined),
25 onSome: parseJsonRecord,
26 });
27
28 /** `--scopes` split on commas with blanks dropped, `undefined` when the flag is absent. */
29 export const parseScopes = (scopes: Option.Option<string>): Array<string> | undefined =>
30 Option.getOrUndefined(
31 Option.map(scopes, value =>
32 value
33 .split(',')
34 .map(s => s.trim())
35 .filter(Boolean)
36 )
37 );
38
39 /**
40 * The create request: Composio-managed auth without `--auth-scheme`, custom auth with it. Custom
41 * credentials and scopes go under `credentials`, the only place the API accepts them; managed
42 * auth carries only the scopes.
43 */
44 export const buildAuthConfigCreateRequest = (input: {
45 readonly name: string | undefined;
46 readonly toolkit: string;
47 readonly authScheme: Option.Option<string>;
48 readonly scopes: Array<string> | undefined;
49 readonly customCredentials: Record<string, unknown> | undefined;
50 }): AuthConfigCreateRequest =>
51 Option.match(input.authScheme, {
52 onNone: () => ({
53 toolkit: { slug: input.toolkit },
54 auth_config: {
55 type: 'use_composio_managed_auth' as const,
56 name: input.name,
57 credentials: input.scopes ? { scopes: input.scopes } : undefined,
58 },
59 }),
60 onSome: authScheme => ({
61 toolkit: { slug: input.toolkit },
62 auth_config: {
63 type: 'use_custom_auth' as const,
64 // The API validates the scheme and answers an unknown one with its own error and hint.
65 authScheme: authScheme as Extract<
66 NonNullable<AuthConfigCreateRequest['auth_config']>,
67 { authScheme: unknown }
68 >['authScheme'],
69 name: input.name,
70 credentials:
71 input.customCredentials || input.scopes
72 ? {
73 ...(input.customCredentials ?? {}),
74 ...(input.scopes ? { scopes: input.scopes } : {}),
75 }
76 : undefined,
77 },
78 }),
79 });
80
81 const invalidInput = commandInputError('dev auth-configs create');
82
83 /**
84 * Create an auth config in the developer project: the summary on stderr, the API response as JSON
85 * on stdout. Invalid `--custom-credentials` JSON fails with a `CommandInputError` before any
86 * request, and a developer project that cannot be found with `ProjectResolutionError`; an API failure is
87 * reported with a hint and exits 1.
88 */
89 export const runAuthConfigsCreate = ({
90 name,
91 toolkit,
92 authScheme,
93 scopes,
94 customCredentials,
95 }: AuthConfigsCreateParams) =>
96 Effect.gen(function* () {
97 const ui = yield* TerminalUI;
98 const repo = yield* ComposioToolkitsRepository;
99
100 const parsedCustomCredentials = parseCustomCredentials(customCredentials);
101 if (Result.isFailure(parsedCustomCredentials)) {
102 return yield* invalidInput(
103 'Invalid JSON in --custom-credentials. Please provide valid JSON.\nExample:\n> composio dev auth-configs create "name" --toolkit "gmail" --custom-credentials \'{"client_id":"...","client_secret":"..."}\'',
104 '--custom-credentials'
105 );
106 }
107
108 const request = buildAuthConfigCreateRequest({
109 name: Option.getOrUndefined(name),
110 toolkit,
111 authScheme,
112 scopes: parseScopes(scopes),
113 customCredentials: parsedCustomCredentials.success,
114 });
115 const project = yield* resolveDeveloperResourceProject;
116
117 const result = yield* ui
118 .withSpinner('Creating auth config...', repo.createAuthConfig(project, request))
119 .pipe(
120 Effect.catchTag(
121 CLIENT_API_ERROR_TAGS,
122 handleClientApiError(ui, {
123 fallbackMessage: 'Failed to create auth config.',
124 hint: `Check available auth schemes for "${toolkit}":\n> composio dev toolkits info "${toolkit}"`,
125 })
126 )
127 );
128
129 yield* ui.log.success('Auth config created.');
130 yield* ui.note(formatAuthConfigCreated(result), 'New Auth Config');
131
132 const redactedId = redact({ value: result.auth_config.id, prefix: 'ac_' });
133 yield* ui.log.step(`To view details:\n> composio dev auth-configs info "${redactedId}"`);
134
135 yield* ui.output(JSON.stringify(result, null, 2));
136 });