@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 265 lines 10.9 KB
Raw
1 /**
2 * Which command an invocation runs, learned after `effect/cli` parsed argv (see
3 * `docs/adr/0001-command-identity-after-parse.md`).
4 *
5 * A command's identity is its command registration: the command path from the root plus the
6 * `CommandMeta` it declares and inherits. `withRegisteredSubcommands`
7 * (`src/commands/registration.ts`) gives every registration its identity while the parser's
8 * selection is dispatched, and only the selected command calls `CommandInvocation.begin`. `--help`,
9 * `--version`, and parse failures have no selected handler; they resolve the identity from the
10 * command path `effect/cli` hands them (`identityAt`).
11 */
12 import { Array as Arr, Context, Effect, Option, Predicate, Record as EffectRecord } from 'effect';
13 import { Command } from 'effect/cli';
14 import type { CommandTelemetryInput, TelemetryFamily } from 'src/analytics/types';
15
16 /**
17 * The hooks the invocation runs for the selected command (`src/invocation/invocation.ts`), in
18 * this order, when the command begins: before its invoked event and its login check.
19 */
20 export const INVOCATION_HOOKS = [
21 'backendMismatch',
22 'updateNotice',
23 'pluginHint',
24 'backgroundUpdateCheck',
25 ] as const;
26
27 export type InvocationHookName = (typeof INVOCATION_HOOKS)[number];
28
29 /**
30 * Whether a hook runs for a command: always (`true`), never (`false`), or as the input
31 * `effect/cli` parsed for the command decides (`composio version --check`). Subcommands inherit
32 * a boolean; a predicate applies only to the registration that declares it, since a
33 * subcommand's input has another shape, and its subcommands run the hook.
34 */
35 export type HookPolicy = boolean | ((input: unknown) => boolean);
36
37 /** The `dev` group's shared flags (`--user-id`, `--project-name`), by their `CommandSurface` field. */
38 export type SharedFlagName = 'userId' | 'projectName';
39
40 /**
41 * What a command declares about itself, under one annotation key (`Command.annotate`, or
42 * `withCommandMeta`). Every field is optional; what an absent field means is set once, in
43 * `resolveCommandMeta`.
44 */
45 export interface CommandMetaShape {
46 /**
47 * The family of lifecycle events the command reports (`CLI_EXECUTE_*`, `CLI_LINK_*`, …).
48 * Not inherited: a subcommand reports its own family, the generic `command` by default.
49 */
50 readonly telemetryFamily?: TelemetryFamily;
51 /** Command-specific privacy projection. Not inherited: child input has a different type. */
52 readonly telemetryInput?: (input: unknown) => CommandTelemetryInput;
53 /**
54 * Whether the command needs a logged-in user. Inherited: a group's subcommands need one too.
55 * The selected command checks it right after it began (`src/commands/registration.ts`), so
56 * `NotLoggedInError` names the command the user ran.
57 */
58 readonly requiresLogin?: boolean;
59 /**
60 * Which invocation hooks run for the command. Every hook runs unless the command, or a group
61 * above it, says otherwise; a boolean policy is inherited per hook, a predicate is not (see
62 * `HookPolicy`).
63 */
64 readonly hooks?: Partial<Readonly<Record<InvocationHookName, HookPolicy>>>;
65 /**
66 * Which of the `dev` group's shared flags the command can honor. Every one can unless the
67 * command, or a group above it, says `false`; inherited per flag. A flag the command cannot
68 * honor fails with `CommandInputError` right after the command began, naming the command that
69 * ran (`src/commands/registration.ts`), instead of being accepted and ignored.
70 */
71 readonly sharedFlags?: Partial<Readonly<Record<SharedFlagName, boolean>>>;
72 }
73
74 export const CommandMeta = Context.Reference<CommandMetaShape>('commands/CommandMeta', {
75 defaultValue: () => ({}),
76 });
77
78 /** `CommandMetaShape` with every field decided for one registration. */
79 export interface ResolvedCommandMeta {
80 readonly telemetryFamily: TelemetryFamily;
81 readonly telemetryInput?: (input: unknown) => CommandTelemetryInput;
82 readonly requiresLogin: boolean;
83 readonly hooks: Readonly<Record<InvocationHookName, HookPolicy>>;
84 /** The shared flags the command cannot honor, declared on itself or on a group above it. */
85 readonly unsupportedSharedFlags: ReadonlyArray<SharedFlagName>;
86 }
87
88 const EVERY_HOOK: ResolvedCommandMeta['hooks'] = {
89 backendMismatch: true,
90 updateNotice: true,
91 pluginHint: true,
92 backgroundUpdateCheck: true,
93 };
94
95 const SHARED_FLAG_NAMES: ReadonlyArray<SharedFlagName> = ['userId', 'projectName'];
96
97 /** The hook policies a subcommand inherits from `hooks`: the booleans; a predicate runs the hook. */
98 const inheritedHooks = (hooks: ResolvedCommandMeta['hooks']): ResolvedCommandMeta['hooks'] =>
99 EffectRecord.map(hooks, policy => (Predicate.isBoolean(policy) ? policy : true));
100
101 /** Resolves what a command declares (`own`) under a parent registration's resolved meta. */
102 export const resolveCommandMeta = (
103 parent: ResolvedCommandMeta | undefined,
104 own: CommandMetaShape
105 ): ResolvedCommandMeta => ({
106 telemetryFamily: own.telemetryFamily ?? 'command',
107 telemetryInput: own.telemetryInput,
108 requiresLogin: own.requiresLogin ?? parent?.requiresLogin ?? false,
109 hooks: { ...(parent === undefined ? EVERY_HOOK : inheritedHooks(parent.hooks)), ...own.hooks },
110 unsupportedSharedFlags: SHARED_FLAG_NAMES.filter(flag => {
111 const declared = own.sharedFlags?.[flag];
112 return declared === undefined
113 ? (parent?.unsupportedSharedFlags.includes(flag) ?? false)
114 : !declared;
115 }),
116 });
117
118 /** Whether `hook` runs for a command with `meta`, given the input `effect/cli` parsed for it. */
119 export const runsHook = (
120 meta: ResolvedCommandMeta,
121 hook: InvocationHookName,
122 input: unknown
123 ): boolean => {
124 const policy = meta.hooks[hook];
125 return Predicate.isBoolean(policy) ? policy : policy(input);
126 };
127
128 /** The meta `command` declares on itself. */
129 export const commandMetaOf = (command: Command.Command.Any): CommandMetaShape =>
130 Context.get(command.annotations, CommandMeta);
131
132 /**
133 * Adds `meta` to what `self` already declares in its `CommandMeta` annotation; a hook policy
134 * replaces only that hook's, and a shared-flag declaration only that flag's.
135 * `withCommandMeta({ requiresLogin: true })` makes a command, or a group entry and every
136 * subcommand under it, require a logged-in user.
137 */
138 export const withCommandMeta =
139 (meta: CommandMetaShape) =>
140 <const Name extends string, Input, ContextInput, E, R>(
141 self: Command.Command<Name, Input, ContextInput, E, R>
142 ): Command.Command<Name, Input, ContextInput, E, R> => {
143 const current = commandMetaOf(self);
144 return Command.annotate(self, CommandMeta, {
145 ...current,
146 ...meta,
147 hooks: { ...current.hooks, ...meta.hooks },
148 sharedFlags: { ...current.sharedFlags, ...meta.sharedFlags },
149 });
150 };
151
152 /** One command registration: where a command sits in the tree and what applies to it there. */
153 export interface CommandIdentity {
154 /** Canonical command names below `composio`; empty for the root command. */
155 readonly path: ReadonlyArray<string>;
156 readonly meta: ResolvedCommandMeta;
157 }
158
159 /** The root command's identity; the root declares no `CommandMeta`. */
160 export const ROOT_IDENTITY: CommandIdentity = {
161 path: [],
162 meta: resolveCommandMeta(undefined, {}),
163 };
164
165 /** The identity of `child` registered under `parent`. */
166 export const childIdentity = (
167 parent: CommandIdentity,
168 child: Command.Command.Any
169 ): CommandIdentity => {
170 const path = [...parent.path, child.name];
171 return { path, meta: resolveCommandMeta(parent.meta, commandMetaOf(child)) };
172 };
173
174 /** The command path as telemetry records it: the names joined by spaces, `composio` for the root. */
175 export const commandPathOf = (identity: CommandIdentity): string =>
176 identity.path.length === 0 ? 'composio' : identity.path.join(' ');
177
178 const subcommandNamed = (command: Command.Command.Any, name: string) =>
179 Arr.findFirst(
180 command.subcommands.flatMap(group => group.commands),
181 child => child.name === name
182 );
183
184 /**
185 * The identity of the registration `effect/cli` names by `commandPath` (canonical names, the root
186 * command's name first, as in `CliError.ShowHelp` and `GlobalFlag.HandlerContext`), found by
187 * walking `root`'s public subcommands. Stops at the deepest name the tree knows.
188 */
189 export const identityAt = (
190 root: Command.Command.Any,
191 commandPath: ReadonlyArray<string>
192 ): CommandIdentity => {
193 const walk = (
194 node: Command.Command.Any,
195 identity: CommandIdentity,
196 names: ReadonlyArray<string>
197 ): CommandIdentity =>
198 Arr.matchLeft(names, {
199 onEmpty: () => identity,
200 onNonEmpty: (name, rest) =>
201 Option.match(subcommandNamed(node, name), {
202 onNone: () => identity,
203 onSome: child => walk(child, childIdentity(identity, child), rest),
204 }),
205 });
206 return walk(root, ROOT_IDENTITY, commandPath.slice(1));
207 };
208
209 /**
210 * The identity of the registration whose dispatch is running: provided by every registration to
211 * everything below it (`src/commands/registration.ts`), the root's outside any.
212 */
213 export const CommandRegistration = Context.Reference<CommandIdentity>(
214 'commands/CommandRegistration',
215 { defaultValue: () => ROOT_IDENTITY }
216 );
217
218 /**
219 * The invocation's record of the command it runs. `runInvocation` provides it for one
220 * invocation; outside one (a test that drives a command directly) it records nothing.
221 */
222 export interface CommandInvocationShape {
223 /**
224 * Records `identity` as the command this invocation runs, with the input `effect/cli` parsed
225 * for it (none for help, version, parse failures, and a group that only shows its help), and
226 * reports that it started; with parsed input, first runs the invocation hooks its
227 * `CommandMeta` keeps. Only the first call counts. Never fails.
228 */
229 readonly begin: (identity: CommandIdentity, input: Option.Option<unknown>) => Effect.Effect<void>;
230 /**
231 * Notes that the dispatch of the registration `identity` started. Before `begin`, the deepest
232 * registration entered is what a failure is reported against: a group-level check that fails
233 * before the parser's selection is reached.
234 */
235 readonly enter: (identity: CommandIdentity) => Effect.Effect<void>;
236 /** The run id `begin` minted for `composio run`, shared with its telemetry events. */
237 readonly runId: Effect.Effect<Option.Option<string>>;
238 }
239
240 export const CommandInvocation = Context.Reference<CommandInvocationShape>(
241 'invocation/CommandInvocation',
242 {
243 defaultValue: () => ({
244 begin: () => Effect.void,
245 enter: () => Effect.void,
246 runId: Effect.succeedNone,
247 }),
248 }
249 );
250
251 /** Begins the command `commandPath` names, for an invocation `effect/cli` answers without one. */
252 export const beginAtCommandPath = (
253 root: Command.Command.Any,
254 commandPath: ReadonlyArray<string>
255 ): Effect.Effect<void> =>
256 Effect.gen(function* () {
257 const invocation = yield* CommandInvocation;
258 yield* invocation.begin(identityAt(root, commandPath), Option.none());
259 });
260
261 /** The run id of the running `composio run`, if this invocation is one. */
262 export const invocationRunId: Effect.Effect<Option.Option<string>> = Effect.gen(function* () {
263 const invocation = yield* CommandInvocation;
264 return yield* invocation.runId;
265 });