@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 303 lines 13.9 KB
Raw
1 /**
2 * One CLI invocation, from argv to a finished command: the command's lifecycle telemetry,
3 * `effect/cli`'s parser and the selected command, the hooks the selected command runs, and the one
4 * place a failure is put on screen. `runCli` (`src/cli-main.ts`) runs it for the binary over
5 * `InvocationLive`; tests run it through `cli()` over `TestLive`.
6 *
7 * Every failure leaves `runInvocation` on screen exactly once: printed by `Command.runWith` (help
8 * and parse errors, `CliError.ShowHelp`), by the command itself (`[Runtime.errorReported] = false`),
9 * or here (an expected failure's message, a 401 and how to recover, or the defect report). It
10 * leaves with its own cause, so a caller can still match its typed error; `forRunner` turns it
11 * into what the runner needs to print nothing more and exit with the right code.
12 */
13 import { Cause, Effect, Exit, Option, Ref, Runtime, type Layer } from 'effect';
14 import { CliError } from 'effect/cli';
15 import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
16 import {
17 configureCliAnalyticsReleaseVersion,
18 createCliCommandTelemetryContext,
19 } from 'src/analytics/events';
20 import type { CliCommandTelemetryContext } from 'src/analytics/types';
21 import { runWithConfig } from 'src/commands';
22 import * as constants from 'src/constants';
23 import { isExpectedFailure } from 'src/effects/expected-failure';
24 import { isUnauthorized, unauthorizedHint } from 'src/effects/rejected-user-api-key';
25 import { ReportedFailure } from 'src/effects/report-failure';
26 import { isSafeToRetry, retryHint } from 'src/effects/retry-advice';
27 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
28 import { getVersion } from 'src/effects/version';
29 import {
30 type CommandIdentity,
31 CommandInvocation,
32 type CommandInvocationShape,
33 INVOCATION_HOOKS,
34 type InvocationHookName,
35 ROOT_IDENTITY,
36 runsHook,
37 } from 'src/invocation/command-identity';
38 import { BackendMismatchWarning } from 'src/services/backend-mismatch-warning';
39 import { CommandLifecycleTelemetry } from 'src/services/command-lifecycle-telemetry';
40 import type { ComposioToolkitsRepository } from 'src/services/composio-clients';
41 import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
42 import type { InvocationHookShape } from 'src/services/invocation-hook';
43 import { PluginHint } from 'src/services/plugin-hint';
44 import { cliInvocationContext } from 'src/services/runtime-cli-context';
45 import type { ShutdownSignal } from 'src/services/shutdown-signal';
46 import { TerminalUI } from 'src/services/terminal-ui';
47 import type { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog';
48 import { BackgroundUpdateCheck, UpdateNotice } from 'src/services/update-check';
49 import { escapeTerminalLines, escapeTerminalText } from 'src/ui/escape-terminal-text';
50 import { extractMessage } from 'src/utils/api-error-extraction';
51 import type { InvocationLive } from './live';
52
53 /** The services an invocation runs with: `InvocationLive` in the binary, `TestLive` in tests. */
54 export type InvocationServices = Layer.Success<typeof InvocationLive> | ShutdownSignal;
55
56 // `runWithConfig`'s root command tree (built from every `.cmd.ts` subcommand in
57 // `src/commands`) is deep and wide enough that TypeScript's inference collapses its
58 // requirement (`R`) type to `any` rather than the precise union of service tags. That
59 // `any` is otherwise infectious through the rest of this pipeline, so it is pinned here to the
60 // services an invocation is given — this changes nothing at runtime, it only restores the
61 // precise static type that inference failed to produce on its own.
62 const runWithArgs = (argv: ReadonlyArray<string>) =>
63 Effect.flatMap(runWithConfig, run => run(argv)) as Effect.Effect<
64 void,
65 unknown,
66 InvocationServices
67 >;
68
69 /**
70 * Runs the command `effect/cli` selects for `argv` under its lifecycle telemetry. The command's
71 * identity is known only once the parser selected it: the selected registration calls
72 * `CommandInvocation.begin` (`src/commands/registration.ts`), and so do `--help`, `--version`,
73 * and a parse failure, for the command path `effect/cli` gives them. `begin` runs the selected
74 * command's invocation hooks, then reports the invoked event; the outcome is reported for the
75 * same command. A failure before any `begin` (a group-level check) is reported against the
76 * deepest registration whose dispatch started.
77 */
78 const runWithTelemetry = (argv: ReadonlyArray<string>) =>
79 Effect.gen(function* () {
80 const ui = yield* TerminalUI;
81 const terminal = yield* ui.capabilities;
82 const version = yield* getVersion;
83 configureCliAnalyticsReleaseVersion(version);
84 const invocationContext = yield* cliInvocationContext;
85 const telemetry = yield* CommandLifecycleTelemetry;
86 const toolkitLookup = yield* Effect.context<ComposioToolkitsRepository | ToolkitSlugCatalog>();
87 const startedAt = Date.now();
88
89 const contextFor = (identity: CommandIdentity, input: Option.Option<unknown>) =>
90 Effect.gen(function* () {
91 const context = createCliCommandTelemetryContext({
92 argv,
93 cliVersion: version,
94 terminal,
95 invocation: invocationContext,
96 identity,
97 input,
98 startedAt,
99 });
100 if (context.family !== 'execute' || context.argument === undefined) {
101 return context;
102 }
103 const toolkitSlug = yield* toolkitFromToolSlug(context.argument).pipe(
104 Effect.provideContext(toolkitLookup)
105 );
106 return { ...context, toolkitSlug };
107 });
108
109 const runHooks = yield* invocationHooks;
110 const started = yield* Ref.make(Option.none<CliCommandTelemetryContext>());
111 const entered = yield* Ref.make(ROOT_IDENTITY);
112 const start = (identity: CommandIdentity, input: Option.Option<unknown>) =>
113 contextFor(identity, input).pipe(
114 Effect.tap(context => Ref.set(started, Option.some(context))),
115 Effect.tap(context => telemetry.invoked(context))
116 );
117 const invocation: CommandInvocationShape = {
118 // Only the first command to begin counts: the bare group whose help ended in `ShowHelp`.
119 // A selected command (one with parsed input) runs its hooks first, so the backend mismatch
120 // warning precedes the toolkit lookup an `execute` invoked event makes; help (`--help`, a
121 // bare group), version, and parse failures run none.
122 begin: (identity, input) =>
123 Effect.flatMap(Ref.get(started), current =>
124 Option.match(current, {
125 onSome: () => Effect.void,
126 onNone: () =>
127 Option.match(input, {
128 onNone: () => Effect.void,
129 onSome: parsed => runHooks(identity, parsed),
130 }).pipe(Effect.andThen(start(identity, input))),
131 })
132 ),
133 enter: identity => Ref.set(entered, identity),
134 runId: Effect.map(
135 Ref.get(started),
136 Option.flatMap(context => Option.fromNullishOr(context.runId))
137 ),
138 };
139 // The command the outcome is reported for: the one that began, else the deepest registration
140 // entered, begun now so its invoked event still precedes the outcome.
141 const outcomeContext = Effect.flatMap(Ref.get(started), current =>
142 Option.match(current, {
143 onSome: Effect.succeed,
144 onNone: () => Effect.flatMap(Ref.get(entered), identity => start(identity, Option.none())),
145 })
146 );
147
148 return yield* runWithArgs(argv).pipe(
149 Effect.provideService(CommandInvocation, invocation),
150 Effect.scoped,
151 Effect.mapError(error =>
152 CliError.isCliError(error) ? error : mapOnlyComposioOverrideError({ error })
153 ),
154 Effect.tap(() => Effect.flatMap(outcomeContext, context => telemetry.succeeded(context))),
155 Effect.tapCause(cause =>
156 Effect.flatMap(outcomeContext, context => telemetry.failed(context, cause))
157 )
158 );
159 });
160
161 /**
162 * Runs, in order and on stderr, the invocation hooks the selected command's `CommandMeta` keeps,
163 * for the input `effect/cli` parsed for it. A group that only shows its help (the bare root
164 * included) begins with no input, like `--help`, so it never gets here.
165 */
166 const invocationHooks = Effect.gen(function* () {
167 const hooks: Readonly<Record<InvocationHookName, InvocationHookShape>> = {
168 backendMismatch: yield* BackendMismatchWarning,
169 updateNotice: yield* UpdateNotice,
170 pluginHint: yield* PluginHint,
171 backgroundUpdateCheck: yield* BackgroundUpdateCheck,
172 };
173 return (identity: CommandIdentity, input: unknown): Effect.Effect<void> =>
174 Effect.forEach(
175 INVOCATION_HOOKS.filter(hook => runsHook(identity.meta, hook, input)),
176 hook => hooks[hook].run({ identity }),
177 { discard: true }
178 );
179 });
180
181 /**
182 * Whether `reason` has nothing for this module to print: a failure already on screen, or an
183 * interruption, which must reach the runner untouched: 128 + n after a signal, else 130 from
184 * `Runtime.defaultTeardown`.
185 */
186 const hasNothingToPrint = (reason: Cause.Reason<unknown>): boolean =>
187 Cause.isInterruptReason(reason) ||
188 (Cause.isFailReason(reason) && !Runtime.getErrorReported(reason.error));
189
190 /** Puts the failure `cause` on screen unless it already is, or is an interruption alone. */
191 const report = (cause: Cause.Cause<unknown>) =>
192 Effect.gen(function* () {
193 const ui = yield* TerminalUI;
194 const error = Cause.findErrorOption(cause);
195 // A usage mistake, a missing setup or login, or a failure a remote service reported clearly
196 // (see `ExpectedFailure`) is not a broken invariant: its message alone, no defect report.
197 // A 401 behind the failure, from whichever command it escaped, adds the way to log in
198 // again when a login can fix it.
199 const printUnauthorizedHint = (failure: unknown) =>
200 isUnauthorized(failure)
201 ? Effect.flatMap(
202 unauthorizedHint(failure),
203 Option.match({ onNone: () => Effect.void, onSome: ui.error })
204 )
205 : Effect.void;
206 // A failed request that is safe to run again as it is says so after its message; the runner
207 // exits 75 for it (see `runnerCause`).
208 const printRetryHint = Option.exists(error, isSafeToRetry)
209 ? ui.error(retryHint('safe'))
210 : Effect.void;
211 // Both messages can quote a remote service, so their controls are escaped for display. An
212 // expected failure's message can have its own line breaks; a backend message is one line.
213 const expected = Option.filter(error, isExpectedFailure);
214 if (Option.isSome(expected)) {
215 yield* ui.error(escapeTerminalLines(expected.value.message));
216 yield* printUnauthorizedHint(expected.value);
217 yield* printRetryHint;
218 return;
219 }
220 // Any other 401 gets the backend's message in place of a defect report.
221 const rejected = Option.filter(error, isUnauthorized);
222 if (Option.isSome(rejected)) {
223 yield* ui.error(
224 escapeTerminalText(
225 extractMessage(rejected.value) ?? 'The Composio API rejected the request.'
226 )
227 );
228 yield* printUnauthorizedHint(rejected.value);
229 return;
230 }
231 // A failure already on screen — `ShowHelp` (`Command.runWith` printed help and any
232 // parse/validation errors before failing with it), or a command's own report — must not be
233 // printed again, or output doubles. An interruption is no failure to report.
234 const unreported = Cause.fromReasons(
235 cause.reasons.filter(reason => !hasNothingToPrint(reason))
236 );
237 if (unreported.reasons.length === 0) {
238 return;
239 }
240 const captured = yield* captureErrors(unreported, { stripCwd: true });
241 const message = prettyPrintFromCapturedErrors(captured, {
242 hideStackTrace: true,
243 stripCwd: true,
244 enabled: true,
245 }).trim();
246 if (message.length > 0) {
247 yield* ui.error(message);
248 yield* printRetryHint;
249 }
250 });
251
252 /**
253 * Puts the failure `cause` on screen once (see {@link report}), then fails with `cause`
254 * untouched: a caller can still match its typed error, and an interruption alone stays one, so
255 * the runner exits 130 (or 128 + n after a signal) instead of 1.
256 */
257 export const reportInvocationFailure = (cause: Cause.Cause<unknown>) =>
258 Effect.andThen(report(cause), Effect.failCause(cause));
259
260 /**
261 * Runs one invocation of the CLI for the full process `argv` (executable and script included):
262 * the command under lifecycle telemetry, with the invocation hooks when it begins.
263 *
264 * Fails with the command's own cause once it is on screen; an interruption alone is not printed.
265 */
266 export const runInvocation = (
267 argv: ReadonlyArray<string>
268 ): Effect.Effect<void, unknown, InvocationServices> =>
269 runWithTelemetry(argv).pipe(
270 Effect.withSpan('composio-cli', {
271 attributes: {
272 name: constants.APP_NAME,
273 filename: 'src/bin.ts',
274 },
275 }),
276 Effect.catchCause(reportInvocationFailure)
277 );
278
279 /**
280 * The cause the runner receives for a failed invocation. A failure `runInvocation` put on screen
281 * becomes a `ReportedFailure`: the runner logs nothing and exits 1, or 75 for a failed request
282 * that is safe to run again as it is. A failure that was on screen
283 * before (`ShowHelp`, a command's own report, `ChildProcessExited`) keeps its markers and its
284 * exit code, and an interruption stays one, so a signal still decides the exit.
285 */
286 export const runnerCause = (cause: Cause.Cause<unknown>): Cause.Cause<unknown> =>
287 cause.reasons.every(hasNothingToPrint)
288 ? cause
289 : Cause.fail(
290 new ReportedFailure(
291 Option.exists(Cause.findErrorOption(cause), isSafeToRetry)
292 ? { message: Cause.pretty(cause), retryable: true }
293 : { message: Cause.pretty(cause) }
294 )
295 );
296
297 /** `exit` as the runner receives it; see {@link runnerCause}. */
298 export const runnerExit = <A>(exit: Exit.Exit<A, unknown>): Exit.Exit<A, unknown> =>
299 Exit.isSuccess(exit) ? exit : Exit.failCause(runnerCause(exit.cause));
300
301 /** Hands `runInvocation`'s result to the runner; see {@link runnerCause}. */
302 export const forRunner = <A, R>(self: Effect.Effect<A, unknown, R>): Effect.Effect<A, unknown, R> =>
303 Effect.catchCause(self, cause => Effect.failCause(runnerCause(cause)));