@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 360 lines 14.8 KB
Raw
1 import { Array as Arr, Context, Data, Effect, Layer, Option, pipe } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 import { ExpectedFailure } from 'src/effects/expected-failure';
4 import type { CommandIdentity, SharedFlagName } from 'src/invocation/command-identity';
5 import {
6 resolveCommandProject,
7 resolveDeveloperProjectOrDefault,
8 type ProjectMode,
9 type ResolvedCommandProject,
10 } from 'src/services/command-project';
11 import { ComposioClientSingleton } from 'src/services/composio-clients';
12 import { ProjectContext } from 'src/services/project-context';
13 import { TerminalUI } from 'src/services/terminal-ui';
14 import { ComposioUserContext } from 'src/services/user-context';
15
16 /** The command tree a command was invoked from. */
17 export type CommandTree = 'root' | 'dev';
18
19 export interface CommandSurfaceShape {
20 readonly tree: CommandTree;
21 /** `--user-id` of the `dev` group; always none on the root tree. */
22 readonly userId: Option.Option<string>;
23 /** `--project-name` of the `dev` group; always none on the root tree. */
24 readonly projectName: Option.Option<string>;
25 }
26
27 /**
28 * What differs between the root tree and the `dev` tree for a command that
29 * exists in both: each group provides this service around its subcommands, so
30 * one `Command` value serves both and its handler reads the surface instead of
31 * taking a `rootOnly` parameter.
32 */
33 export class CommandSurface extends Context.Service<CommandSurface, CommandSurfaceShape>()(
34 'commands/CommandSurface'
35 ) {
36 static readonly root: Layer.Layer<CommandSurface> = Layer.succeed(
37 CommandSurface,
38 CommandSurface.of({ tree: 'root', userId: Option.none(), projectName: Option.none() })
39 );
40
41 static readonly dev = (flags: {
42 readonly userId: Option.Option<string>;
43 readonly projectName: Option.Option<string>;
44 }): Layer.Layer<CommandSurface> =>
45 Layer.succeed(CommandSurface, CommandSurface.of({ tree: 'dev', ...flags }));
46 }
47
48 /**
49 * Resolves the command's project for the surface it runs in: the `dev` group's
50 * `--project-name` picks the developer project, the root tree never has one.
51 */
52 export const resolveSurfaceProject = (mode: ProjectMode) =>
53 Effect.gen(function* () {
54 const surface = yield* CommandSurface;
55 return yield* resolveCommandProject({
56 mode,
57 projectName: Option.getOrUndefined(surface.projectName),
58 });
59 });
60
61 /**
62 * A warning that reaches stderr even off a terminal, where `ui.log.*` decoration is dropped: a
63 * script or agent reading stderr must see a fallback that affects the result.
64 */
65 export const warnOnStderr = (message: string) =>
66 Effect.gen(function* () {
67 const ui = yield* TerminalUI;
68 if ((yield* ui.capabilities).canDecorate) {
69 yield* ui.log.warn(message);
70 } else {
71 yield* ui.error(`Warning: ${message}`);
72 }
73 });
74
75 /**
76 * The developer project of a dev command that reads or writes the project's resources (auth
77 * configs, connected accounts, trigger instances, logs): `--project-name`'s, else the
78 * directory's, else the backend's default developer project, named on stderr every time
79 * (`resolveDeveloperProjectOrDefault`). These commands once sent no project and let the backend
80 * pick that default, so a directory without a usable project of its own keeps working; a command
81 * that always required one uses `resolveSurfaceProject('developer')`. Resolved once, so every
82 * request of the command names the same project.
83 */
84 export const resolveDeveloperResourceProject = Effect.gen(function* () {
85 const { projectName } = yield* CommandSurface;
86 const { project, notice } = yield* resolveDeveloperProjectOrDefault({
87 projectName: Option.getOrUndefined(projectName),
88 });
89 yield* Effect.transposeOption(Option.map(notice, warnOnStderr));
90 return project;
91 });
92
93 /**
94 * The client for the developer project a dev command acts on (`resolveDeveloperResourceProject`),
95 * for a command whose requests all read or write that project's resources: they name it rather
96 * than leaving the backend to pick the key's default project.
97 */
98 export const developerProjectClient = Effect.gen(function* () {
99 const project = yield* resolveDeveloperResourceProject;
100 const clientSingleton = yield* ComposioClientSingleton;
101 return yield* clientSingleton.getFor({ orgId: project.orgId, projectId: project.projectId });
102 });
103
104 // --- acting user ------------------------------------------------------------------------------
105
106 /** Which step of the acting-user rule picked the user. */
107 export type ActingUserSource = 'consumer' | 'flag' | 'directory-test-user' | 'global-test-user';
108
109 /**
110 * The user a command acts as (glossary "Acting user"), with the project it was resolved
111 * against.
112 */
113 export interface ActingUser {
114 readonly userId: string;
115 readonly source: ActingUserSource;
116 readonly project: ResolvedCommandProject;
117 }
118
119 /** No step of the acting-user rule found a user for the command. */
120 export class MissingActingUserError extends Data.TaggedError('commands/MissingActingUserError')<{
121 readonly tree: CommandTree;
122 readonly projectName: Option.Option<string>;
123 readonly message: string;
124 }> {
125 get [ExpectedFailure]() {
126 return true;
127 }
128 }
129
130 /**
131 * The missing-user message for the tree. On the dev tree with `--project-name` the directory's
132 * test user does not carry over to another project, so it points at `--user-id` and
133 * `composio login` instead of `composio dev init`.
134 */
135 const missingUserMessage = (tree: CommandTree, projectName: Option.Option<string>): string =>
136 tree === 'root'
137 ? 'Missing consumer user id. Run `composio login` and try again.'
138 : Option.match(projectName, {
139 onNone: () =>
140 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.',
141 onSome: () =>
142 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
143 });
144
145 /**
146 * The test user the directory configures (`.composio/project.json`), for a command that runs
147 * against the directory's project (`projectId`, the project the command resolved). Another
148 * project, one `--project-name` names or the default developer project standing in for the
149 * directory's, does not borrow it, so the command falls back to the global test user.
150 */
151 const directoryTestUserId = (
152 directoryProject: Option.Option<{
153 readonly projectId: string;
154 readonly testUserId: Option.Option<string>;
155 }>,
156 projectId: string
157 ): Option.Option<string> =>
158 pipe(
159 directoryProject,
160 Option.filter(keys => keys.projectId === projectId),
161 Option.flatMap(keys => keys.testUserId)
162 );
163
164 /** The dev tree's rule over its candidates: `--user-id`, the directory test user, the global one. */
165 const devActingUser = (candidates: {
166 readonly flag: Option.Option<string>;
167 readonly directoryTestUserId: Option.Option<string>;
168 readonly globalTestUserId: Option.Option<string>;
169 }): Option.Option<Omit<ActingUser, 'project'>> =>
170 Option.firstSomeOf([
171 Option.map(candidates.flag, userId => ({ userId, source: 'flag' as const })),
172 Option.map(candidates.directoryTestUserId, userId => ({
173 userId,
174 source: 'directory-test-user' as const,
175 })),
176 Option.map(candidates.globalTestUserId, userId => ({
177 userId,
178 source: 'global-test-user' as const,
179 })),
180 ]);
181
182 const noticeBySource: Record<ActingUserSource, (userId: string) => Option.Option<string>> = {
183 consumer: () => Option.none(),
184 flag: () => Option.none(),
185 'directory-test-user': userId => Option.some(`Using test user id "${userId}"`),
186 'global-test-user': userId => Option.some(`Using global test user id "${userId}"`),
187 };
188
189 /** The stderr notice for a test user standing in; none for the consumer user or `--user-id`. */
190 export const fallbackNotice = (user: Omit<ActingUser, 'project'>): Option.Option<string> =>
191 noticeBySource[user.source](user.userId);
192
193 /** Prints `fallbackNotice` on stderr when a test user stands in. */
194 const announceFallback = (user: Option.Option<Omit<ActingUser, 'project'>>) =>
195 Effect.gen(function* () {
196 const ui = yield* TerminalUI;
197 yield* Effect.transposeOption(
198 Option.map(Option.flatMap(user, fallbackNotice), notice => ui.log.warn(notice))
199 );
200 });
201
202 /** The consumer user of a consumer project; an empty id counts as none. */
203 const consumerUser = (project: ResolvedCommandProject) =>
204 pipe(
205 Option.fromNullishOr(project.consumerUserId),
206 Option.filter(userId => userId.length > 0),
207 Option.map(userId => ({ userId, source: 'consumer' as const }))
208 );
209
210 /** The dev tree's user for the developer project `projectId` the command resolved. */
211 const devUser = (projectId: string) =>
212 Effect.gen(function* () {
213 const surface = yield* CommandSurface;
214 const userContext = yield* ComposioUserContext;
215 const projectContext = yield* ProjectContext;
216 const directoryProject = yield* projectContext.resolve.pipe(
217 Effect.option,
218 Effect.map(Option.flatten)
219 );
220 return devActingUser({
221 flag: surface.userId,
222 directoryTestUserId: directoryTestUserId(directoryProject, projectId),
223 globalTestUserId: userContext.data.testUserId,
224 });
225 });
226
227 /**
228 * The acting user, resolved against the project the command runs in. On the root tree, the
229 * consumer user of the consumer project. On the dev tree, against the developer project
230 * (`--project-name`, else the directory's): `--user-id`, then the directory test user (only
231 * for the directory's own project), then the global test user; a test user standing in is
232 * named on stderr (`fallbackNotice`). Fails with
233 * `ProjectResolutionError` when the project cannot be resolved and `MissingActingUserError`
234 * when no step finds a user.
235 */
236 export const actingUser = () =>
237 Effect.gen(function* () {
238 const { tree, projectName } = yield* CommandSurface;
239 const project = yield* resolveCommandProject(
240 tree === 'root'
241 ? { mode: 'consumer' }
242 : { mode: 'developer', projectName: Option.getOrUndefined(projectName) }
243 );
244 const user = tree === 'root' ? consumerUser(project) : yield* devUser(project.projectId);
245 yield* announceFallback(user);
246 if (Option.isNone(user)) {
247 return yield* new MissingActingUserError({
248 tree,
249 projectName,
250 message: missingUserMessage(tree, projectName),
251 });
252 }
253 return { ...user.value, project } satisfies ActingUser;
254 });
255
256 /**
257 * The dev tree's acting user for a command that also runs without one, against the developer
258 * project the command resolved (`resolveSurfaceProject('developer')`), by the same rule as
259 * `actingUser`: `--user-id`, then the directory test user (only for the directory's own project),
260 * then the global test user. Names a test user standing in on stderr, as `actingUser` does; none
261 * when no step finds a user.
262 */
263 export const devActingUserOption = (project: ResolvedCommandProject) =>
264 Effect.gen(function* () {
265 const user = yield* devUser(project.projectId);
266 yield* announceFallback(user);
267 return Option.map(user, (found): ActingUser => ({ ...found, project }));
268 });
269
270 /**
271 * The developer project and acting user of a dev command whose main work needs neither (it only
272 * adds a user's connection status): the user is none when the project is. The backend's default
273 * developer project stands in for the directory's (`resolveDeveloperResourceProject`, named on
274 * stderr) only when it can serve a user: `--user-id` or the global test user, since the
275 * directory's test user belongs to the directory's own project. Without `--project-name`, a
276 * project that cannot be resolved, for whatever reason, is none; a `--project-name` that cannot
277 * be resolved still fails.
278 */
279 export const resolveSurfaceProjectAndUserOption = Effect.gen(function* () {
280 const surface = yield* CommandSurface;
281 const userContext = yield* ComposioUserContext;
282 const userBeyondDirectory = Option.orElse(surface.userId, () => userContext.data.testUserId);
283 const resolved = (
284 Option.isSome(userBeyondDirectory)
285 ? resolveDeveloperResourceProject
286 : resolveSurfaceProject('developer')
287 ).pipe(Effect.map(Option.some));
288 const project = yield* Option.isSome(surface.projectName)
289 ? resolved
290 : resolved.pipe(
291 Effect.catch(error =>
292 Effect.logDebug('No developer project for connection status:', error).pipe(
293 Effect.as(Option.none<ResolvedCommandProject>())
294 )
295 )
296 );
297 const user = yield* Effect.map(
298 Effect.transposeOption(Option.map(project, devActingUserOption)),
299 Option.flatten
300 );
301 return { project, user };
302 });
303
304 /** A shared flag of the `dev` group. */
305 export type SharedFlag = '--user-id' | '--project-name';
306
307 /**
308 * `CommandMeta.sharedFlags` for a `dev` command, or a group, that honors neither shared flag:
309 * it cannot target another project and does not act as a user.
310 */
311 export const NO_SHARED_FLAGS = { userId: false, projectName: false } as const;
312
313 /** The shared flags, in the order a rejection reports them when several are given. */
314 const SHARED_FLAGS: ReadonlyArray<{ readonly name: SharedFlagName; readonly flag: SharedFlag }> = [
315 { name: 'projectName', flag: '--project-name' },
316 { name: 'userId', flag: '--user-id' },
317 ];
318
319 const unsupportedSharedFlag = (command: string): Record<SharedFlag, string> => ({
320 '--project-name': `\`composio ${command}\` cannot target another project yet. Remove --project-name, or run it from that project's directory.`,
321 '--user-id': `\`composio ${command}\` does not act as a user. Remove --user-id.`,
322 });
323
324 /** The first shared flag the surface carries among those `rejects` picks, if any. */
325 const givenSharedFlag = (rejects: (name: SharedFlagName) => boolean) =>
326 Effect.gen(function* () {
327 const surface = yield* CommandSurface;
328 return Arr.findFirst(SHARED_FLAGS, ({ name }) => rejects(name) && Option.isSome(surface[name]));
329 });
330
331 /**
332 * Fails with a `CommandInputError` when the surface carries either shared flag, with `messages`
333 * for its wording: the `dev` group's own `--mode` toggle, which changes a global setting.
334 */
335 export const rejectSharedFlags = (command: string, messages: Record<SharedFlag, string>) =>
336 Effect.flatMap(
337 givenSharedFlag(() => true),
338 Option.match({
339 onNone: () => Effect.void,
340 onSome: ({ flag }) => Effect.fail(commandInputError(command)(messages[flag], flag)),
341 })
342 );
343
344 /**
345 * Fails with a `CommandInputError` when the surface carries a shared flag the selected command
346 * cannot honor (`CommandMeta.sharedFlags`), naming the command that ran even when a group above
347 * it declared so. Without it the flag would be accepted and ignored. The registration runs it
348 * right after the command began (`src/commands/registration.ts`).
349 */
350 export const rejectUnsupportedSharedFlags = (identity: CommandIdentity) =>
351 Effect.flatMap(
352 givenSharedFlag(name => identity.meta.unsupportedSharedFlags.includes(name)),
353 Option.match({
354 onNone: () => Effect.void,
355 onSome: ({ flag }) => {
356 const command = identity.path.join(' ');
357 return Effect.fail(commandInputError(command)(unsupportedSharedFlag(command)[flag], flag));
358 },
359 })
360 );