@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 125 lines 5.29 KB
Raw
1 import { Effect, FileSystem, Option, Path } from 'effect';
2 import { APP_CONFIG } from 'src/config';
3 import { withoutTrailingSlashes } from 'src/config/backend';
4 import * as constants from 'src/constants';
5 import { getCurrentLoggedInAgent } from 'src/services/agents';
6 import { NodeOs } from 'src/services/node-os';
7 import { ComposioUserContext } from 'src/services/user-context';
8 import { findApiError } from 'src/utils/api-error-extraction';
9
10 /** Whether `value` (or a failure it wraps) is the backend rejecting the user API key. */
11 const isRejectedUserApiKey = (value: unknown): boolean =>
12 findApiError(value)?.details?.slug === 'UserApiKey_Unauthorized';
13
14 /**
15 * Whether `value` (or a failure it wraps) is a 401 from the Composio API. Only
16 * {@link isRejectedUserApiKey} says the user API key itself was rejected; any other 401 may be
17 * about another credential.
18 */
19 export const isUnauthorized = (value: unknown): boolean => findApiError(value)?.status === 401;
20
21 /**
22 * The env vars that make `composio login` target the backend at `baseURL` and its Dashboard at
23 * `webURL`, as a command prefix. `COMPOSIO_WEB_URL` is named only when `webURL` is not the
24 * Dashboard the other variables already select, so the new login session opens where it can
25 * be completed.
26 */
27 /** `value` as one shell word: unchanged when it is plainly safe, else single-quoted. */
28 const shellWord = (value: string) =>
29 /^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
30
31 const loginTargetPrefix = (baseURL: string, webURL: string) => {
32 const base = withoutTrailingSlashes(baseURL);
33 const [backendVar, impliedWebURL] =
34 base === withoutTrailingSlashes(constants.DEFAULT_BASE_URL)
35 ? ['', constants.DEFAULT_WEB_URL]
36 : base === withoutTrailingSlashes(constants.STAGING_BASE_URL)
37 ? ['COMPOSIO_ENVIRONMENT=staging ', constants.STAGING_WEB_URL]
38 : [`COMPOSIO_BASE_URL=${shellWord(base)} `, constants.DEFAULT_WEB_URL];
39 const web = withoutTrailingSlashes(webURL);
40 const webVar =
41 web === withoutTrailingSlashes(impliedWebURL) ? '' : `COMPOSIO_WEB_URL=${shellWord(web)} `;
42 return `${backendVar}${webVar}`;
43 };
44
45 const keyFromEnv = APP_CONFIG.USER_API_KEY.pipe(
46 Effect.map(key => key !== undefined),
47 Effect.orElseSucceed(() => false)
48 );
49
50 /**
51 * Whether the stored login is the saved Composio agent identity's. False when it is not, or when
52 * the caller has none of the services that read it.
53 */
54 const loggedInAsAgent = Effect.gen(function* () {
55 const services = Option.all({
56 ctx: yield* Effect.serviceOption(ComposioUserContext),
57 fs: yield* Effect.serviceOption(FileSystem.FileSystem),
58 path: yield* Effect.serviceOption(Path.Path),
59 os: yield* Effect.serviceOption(NodeOs),
60 });
61 if (Option.isNone(services)) {
62 return false;
63 }
64 const { ctx, fs, path, os } = services.value;
65 return yield* getCurrentLoggedInAgent.pipe(
66 Effect.map(Option.isSome),
67 Effect.provideService(ComposioUserContext, ctx),
68 Effect.provideService(FileSystem.FileSystem, fs),
69 Effect.provideService(Path.Path, path),
70 Effect.provideService(NodeOs, os),
71 Effect.orElseSucceed(() => false)
72 );
73 });
74
75 /**
76 * The login command that replaces the stored login, on the backend that rejected its key. An
77 * agent identity's login uses the saved key through `agent login`, which never signs up a new
78 * agent. `composio logout` would delete that key; `login --agent` can replace the identity.
79 */
80 const loginAgainCommand = Effect.gen(function* () {
81 const ctx = yield* Effect.serviceOption(ComposioUserContext);
82 const prefix = Option.match(ctx, {
83 onNone: () => '',
84 onSome: c => loginTargetPrefix(c.data.baseURL, c.data.webURL),
85 });
86 return (yield* loggedInAsAgent)
87 ? `${prefix}composio agent login <composio_agent_key>\nUse the composio_agent_key from ~/.composio/agent.json.`
88 : `composio logout && ${prefix}composio login`;
89 });
90
91 /**
92 * How to recover from a rejected user API key. `composio logout` forgets the stored login's
93 * backend, so the login command names the backend that rejected the key, and its Dashboard,
94 * when they are not production's. Reads the user context when the caller has one, without requiring it.
95 */
96 export const rejectedUserApiKeyHint = Effect.gen(function* () {
97 if (yield* keyFromEnv) {
98 return 'Replace the key in COMPOSIO_USER_API_KEY, then retry.';
99 }
100 return `Log in again, then retry:\n> ${yield* loginAgainCommand}`;
101 });
102
103 /**
104 * How to recover from the 401 in `value`: {@link rejectedUserApiKeyHint} when the backend said
105 * the user API key was rejected. Any other 401 names the login only as the likely cause, and
106 * not at all without a user API key, which no login could have expired.
107 */
108 export const unauthorizedHint = (value: unknown): Effect.Effect<Option.Option<string>> =>
109 Effect.gen(function* () {
110 if (isRejectedUserApiKey(value)) {
111 return Option.some(yield* rejectedUserApiKeyHint);
112 }
113 if (yield* keyFromEnv) {
114 return Option.some(
115 'If the key in COMPOSIO_USER_API_KEY is no longer valid, replace it, then retry.'
116 );
117 }
118 const ctx = yield* Effect.serviceOption(ComposioUserContext);
119 const loggedIn = Option.exists(ctx, c => Option.isSome(c.data.apiKey));
120 return loggedIn
121 ? Option.some(
122 `If your login expired, log in again, then retry:\n> ${yield* loginAgainCommand}`
123 )
124 : Option.none();
125 });