Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 180 lines 7.9 KB
Raw
1 import { Array as Arr, Console, Effect, Schema } from 'effect';
2 import { CliError, CliOutput, Command } from 'effect/cli';
3 import type { TelemetryFamily } from 'src/analytics/types';
4 import {
5 beginAtCommandPath,
6 type CommandMetaShape,
7 withCommandMeta,
8 } from 'src/invocation/command-identity';
9 import { $defaultCmd, withRootLogLevel } from './$default.cmd';
10 import { getVersion } from 'src/effects/version';
11 import { versionCmd } from './version.cmd';
12 import { upgradeCmd } from './upgrade/upgrade.cmd';
13 import { whoamiCmd } from './whoami.cmd';
14 import { loginCmd } from './login/login.cmd';
15 import { signupCmd } from './signup/signup.cmd';
16 import { setupCmd } from './setup.cmd';
17 import { listenCmd } from './listen/listen.cmd';
18 import { logoutCmd } from './logout.cmd';
19 import { runCmd } from './run/run.cmd';
20 import { proxyCmd } from './proxy/proxy.cmd';
21 import { artifactsCmd } from './artifacts/artifacts.cmd';
22 import { installCmd } from './install/install.cmd';
23 import { generateCmd } from './generate/generate.cmd';
24 import { buildDevCommand } from './dev.cmd';
25 import { ExecuteInvocationArgs } from './tools/execute/tools.execute.parallel';
26 import {
27 buildHelpCommand,
28 RootHelpMarker,
29 helpFormatter,
30 RootHelpContext,
31 showCommandHelp,
32 } from './root-help';
33 import { toolsCmd$Search } from './tools/search/tools.search.cmd';
34 import { rootToolsCmd$Execute } from './tools/execute/tools.execute.cmd';
35 import { rootToolsCmd } from './tools/tools.cmd';
36 import { rootTriggersCmd } from './triggers/root-triggers.cmd';
37 import { connectedAccountsCmd$Link } from './connected-accounts/link/connected-accounts.link.cmd';
38 import { orgsCmd } from './orgs/orgs.cmd';
39 import { configCmd } from './config/config.cmd';
40 import { rootConnectionsCmd } from './connections/connections.cmd';
41 import { agentCmd } from './agent/agent.cmd';
42 import { cliDebugFlagsLayer, CLI_DEBUG_GLOBAL_FLAGS } from 'src/services/runtime-flags';
43 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
44 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
45 import { experimental, type CommandVisibility, tagged, visibleValues } from './feature-tags';
46 import { withRegisteredSubcommands } from './registration';
47 import { debugCmd } from './debug/debug.cmd';
48 import { normalizeListenStreamFlag, normalizeRunScriptArgs } from './argv-compat';
49 import { configureCliAnalyticsReleaseVersion } from 'src/analytics/events';
50 import { CommandSurface } from './surface';
51
52 // Lifecycle telemetry families are declared on root registrations only: every `dev` command,
53 // including `dev connected-accounts link` (the same `Command` value as the root `link`), reports the
54 // generic `CLI_COMMAND_*` events.
55 const family = (telemetryFamily: TelemetryFamily) => withCommandMeta({ telemetryFamily });
56
57 // Every invocation hook runs for every selected command (`src/invocation/invocation.ts`) except
58 // where a root registration below turns one off; its subcommands inherit that.
59 const hooks = (policies: NonNullable<CommandMetaShape['hooks']>) =>
60 withCommandMeta({ hooks: policies });
61
62 /** `composio version --check` resolves releases itself, like `composio upgrade`. */
63 const isExplicitVersionCheck = Schema.is(Schema.Struct({ check: Schema.Literal(true) }));
64
65 /** `composio help …` only prints help, like `--help`. */
66 const NO_HOOKS = {
67 backendMismatch: false,
68 updateNotice: false,
69 pluginHint: false,
70 backgroundUpdateCheck: false,
71 } as const;
72
73 const ROOT_COMMANDS = [
74 tagged(debugCmd),
75 tagged(
76 versionCmd.pipe(hooks({ backgroundUpdateCheck: input => !isExplicitVersionCheck(input) }))
77 ),
78 // `composio upgrade` resolves the latest release live and records it in the cache, so a cached
79 // notice could only repeat or contradict it.
80 tagged(upgradeCmd.pipe(hooks({ updateNotice: false, backgroundUpdateCheck: false }))),
81 tagged(whoamiCmd),
82 tagged(loginCmd.pipe(family('login'))),
83 tagged(signupCmd),
84 // `composio setup` installs the plugin the hint asks for.
85 tagged(setupCmd.pipe(family('setup'), hooks({ pluginHint: false }))),
86 tagged(agentCmd),
87 experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, listenCmd),
88 tagged(logoutCmd.pipe(family('logout'))),
89 tagged(runCmd.pipe(family('run'))),
90 tagged(proxyCmd.pipe(family('proxy'))),
91 tagged(artifactsCmd),
92 tagged(installCmd.pipe(family('install'))),
93 tagged(rootToolsCmd),
94 tagged(rootTriggersCmd),
95 tagged(toolsCmd$Search.pipe(family('search'))),
96 tagged(connectedAccountsCmd$Link.pipe(family('link'))),
97 tagged(rootToolsCmd$Execute.pipe(family('execute'))),
98 tagged(rootConnectionsCmd),
99 tagged(generateCmd),
100 tagged(orgsCmd),
101 tagged(configCmd),
102 ];
103
104 const getVisibleRootCommands = (visibility: CommandVisibility) => {
105 type RootCommand = (typeof ROOT_COMMANDS)[number]['value'];
106 return Arr.append(
107 visibleValues<RootCommand>(ROOT_COMMANDS, visibility),
108 buildDevCommand(visibility)
109 );
110 };
111
112 export const buildRootCommand = (visibility: CommandVisibility) => {
113 const commands = getVisibleRootCommands(visibility);
114 return $defaultCmd.pipe(
115 Command.withHandler(() => showCommandHelp()),
116 withRegisteredSubcommands([...commands, buildHelpCommand(commands).pipe(hooks(NO_HOOKS))]),
117 Command.annotate(RootHelpMarker, true),
118 Command.withGlobalFlags(CLI_DEBUG_GLOBAL_FLAGS),
119 withRootLogLevel,
120 // The `dev` group provides its own surface around its subcommands; everything else is root.
121 Command.provide(CommandSurface.root)
122 );
123 };
124
125 export const runWithConfig = Effect.gen(function* () {
126 const cliUserConfig = yield* ComposioCliUserConfig;
127 const visibility: CommandVisibility = {
128 isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
129 isExperimentalFeatureEnabled: feature => cliUserConfig.isExperimentalFeatureEnabled(feature),
130 };
131 const version = yield* getVersion;
132 configureCliAnalyticsReleaseVersion(version);
133 const rootCommand = buildRootCommand(visibility);
134 // v4's `Command.runWith` (unlike v3's `Command.run`) takes explicit arguments rather than
135 // pulling them from `Stdio`, and expects them *without* the node/bun executable + script path
136 // prefix — see `cli-main.ts` module docs for the full contract at this boundary.
137 const run = (args: ReadonlyArray<string>) => {
138 return Command.runWith(rootCommand, { version })(args).pipe(
139 // A parse failure selects no command: begin the one `effect/cli` names (canonical names,
140 // never the user's tokens). After a command began, this changes nothing.
141 Effect.tapError(error =>
142 error instanceof CliError.ShowHelp
143 ? beginAtCommandPath(rootCommand, error.commandPath)
144 : Effect.void
145 ),
146 Effect.provideService(RootHelpContext, { command: rootCommand, version }),
147 Effect.provideService(CliOutput.Formatter, helpFormatter())
148 );
149 };
150
151 // Effect renders help through Console.log. Route implicit help to stderr so stdout
152 // stays available for command data; explicit help and version requests use stdout.
153 const runWithDecorationOnStderr = (args: ReadonlyArray<string>) =>
154 Effect.gen(function* () {
155 const base = yield* Console.Console;
156 // Node/Bun consoles carry their methods as own (bound) properties and the
157 // test MockConsole is a plain object literal, so a spread copies every
158 // method; only `log` needs overriding.
159 return yield* Effect.provideService(run(args), Console.Console, {
160 ...base,
161 log: (...rest) => base.error(...rest),
162 });
163 });
164
165 const EXPLICIT_STDOUT_FLAGS: ReadonlySet<string> = new Set(['--help', '-h', '--version', '-v']);
166
167 const runCli = (args: ReadonlyArray<string>) =>
168 args.length === 0 ||
169 Arr.takeWhile(args, arg => arg !== '--').some(arg => EXPLICIT_STDOUT_FLAGS.has(arg))
170 ? run(args)
171 : runWithDecorationOnStderr(args);
172
173 return (argv: ReadonlyArray<string>) => {
174 const parsedArgv = normalizeRunScriptArgs(normalizeListenStreamFlag(argv));
175 return runCli(parsedArgv.slice(2)).pipe(
176 Effect.provideService(ExecuteInvocationArgs, parsedArgv.slice(2)),
177 Effect.provide(cliDebugFlagsLayer())
178 );
179 };
180 });