@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 367 lines 13.1 KB
Raw
1 import { telemetry, withCommandTelemetry } from 'src/analytics/command-input';
2 import { setupSkillCmd } from './setup-skill.cmd';
3 import { Command, Flag } from 'effect/cli';
4 import { Effect, Predicate } from 'effect';
5 import { trackCliEventEffect } from 'src/analytics/dispatch';
6 import {
7 getSetupCancelledEvent,
8 getSetupHostDetectedEvent,
9 getSetupSkippedEvent,
10 } from 'src/analytics/events';
11 import { APP_VERSION } from 'src/constants';
12 import { AGENT_HOST_LABELS } from 'src/services/agent-host';
13 import {
14 detectSetupTargets,
15 inspectSetupTargets,
16 installSetupTargets,
17 isSetupPluginReady,
18 isSetupReady,
19 SETUP_TARGETS,
20 uninstallSetupTargets,
21 type AgentHost,
22 type SetupTargetDetection,
23 type SetupUnsupportedReasonCode,
24 } from 'src/services/setup';
25 import { SetupCommandError, type SetupFailureReasonCode } from 'src/services/setup-command-error';
26 import { TerminalUI } from 'src/services/terminal-ui';
27 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
28 import { cliInvocationContext } from 'src/services/runtime-cli-context';
29 import { withRegisteredSubcommands } from 'src/commands/registration';
30
31 const target = Flag.Literals('target', SETUP_TARGETS).pipe(
32 Flag.withDefault('auto'),
33 Flag.withDescription('Agent host to configure: auto, claude, codex, or all')
34 );
35
36 const yes = Flag.Boolean('yes').pipe(
37 Flag.withAlias('y'),
38 Flag.withDefault(false),
39 Flag.withDescription('Accept setup changes without prompting')
40 );
41
42 const ifPresent = Flag.Boolean('if-present').pipe(
43 Flag.withDefault(false),
44 Flag.withDescription('Exit successfully when automatic detection finds no supported host')
45 );
46
47 const uninstall = Flag.Boolean('uninstall').pipe(
48 Flag.withDefault(false),
49 Flag.withDescription('Uninstall Composio plugins instead of installing them')
50 );
51
52 const formatTargets = (targets: ReadonlyArray<AgentHost>): string =>
53 targets.map(target => AGENT_HOST_LABELS[target]).join(' and ');
54
55 const errorMessage = (error: unknown): string =>
56 Predicate.isError(error) ? error.message : String(error);
57
58 const setupCommandError = (
59 message: string,
60 operation: 'setup' | 'uninstall',
61 reasonCode: SetupFailureReasonCode,
62 cause?: unknown
63 ) =>
64 new SetupCommandError({
65 message,
66 operation,
67 reasonCode,
68 ...(cause === undefined ? {} : { cause }),
69 });
70
71 /** Prints why setup failed and closes the session; the command then fails already reported. */
72 const renderSetupFailure = (error: SetupCommandError) =>
73 Effect.gen(function* () {
74 const ui = yield* TerminalUI;
75 const summary =
76 error.operation === 'uninstall'
77 ? 'Composio plugin uninstall was unsuccessful.'
78 : 'Composio setup was unsuccessful.';
79 if ((yield* ui.capabilities).canDecorate) {
80 yield* ui.log.error(error.message);
81 yield* ui.outro(summary);
82 } else {
83 yield* ui.error(`${summary} ${error.message}`);
84 }
85 });
86
87 // Only a host that is present but unsupported has a reason to report.
88 const unsupportedReasonCodeOf = (
89 detection: SetupTargetDetection
90 ): SetupUnsupportedReasonCode | undefined => {
91 if (!detection.available || detection.supported) return undefined;
92 return detection.unsupportedReasonCode ?? 'unknown';
93 };
94
95 const setupBaseCmd = Command.make(
96 'setup',
97 { target, yes, ifPresent, uninstall },
98 ({ target, yes, ifPresent, uninstall }) =>
99 Effect.gen(function* () {
100 const ui = yield* TerminalUI;
101 const terminal = yield* ui.capabilities;
102 const { invocationOrigin } = yield* cliInvocationContext;
103 const operation = uninstall ? 'uninstall' : 'setup';
104 yield* ui.intro(uninstall ? 'composio setup --uninstall' : 'composio setup');
105
106 const detections = yield* detectSetupTargets(target);
107 yield* Effect.forEach(detections, detection =>
108 trackCliEventEffect(
109 getSetupHostDetectedEvent({
110 operation,
111 requestedTarget: target,
112 target: detection.target,
113 available: detection.available,
114 supported: detection.supported,
115 hostVersion: detection.version,
116 unsupportedReasonCode: unsupportedReasonCodeOf(detection),
117 hostConfigDirPresent: detection.configDirPresent,
118 hostBinaryInKnownPaths: detection.binaryInKnownPaths,
119 invocationOrigin,
120 cliVersion: APP_VERSION,
121 })
122 )
123 );
124 const detected = detections.filter(result => result.available).map(result => result.target);
125 const supported = detections.filter(result => result.available && result.supported);
126 const unsupported = detections.filter(result => result.available && !result.supported);
127 const notDetected = detections
128 .filter(result => !result.available)
129 .map(result => result.target);
130
131 if (detected.length > 0) {
132 yield* ui.log.success(`${formatTargets(detected)} detected.`);
133 }
134 if (notDetected.length > 0) {
135 yield* ui.log.info(`${formatTargets(notDetected)} not detected.`);
136 }
137 if (target === 'all' && notDetected.length > 0) {
138 return yield* setupCommandError(
139 `\`--target all\` requires Claude Code and Codex. Missing: ${formatTargets(notDetected)}. Install the missing agent host, or use \`--target auto\` to operate on detected hosts only.`,
140 operation,
141 'all_requires_both_hosts'
142 );
143 }
144 if (unsupported.length > 0) {
145 const reason = unsupported
146 .map(result => result.unsupportedReason)
147 .filter((message): message is string => Boolean(message))
148 .join(' ');
149 if (target !== 'auto') {
150 return yield* setupCommandError(reason, operation, 'unsupported_host');
151 }
152 yield* ui.log.warn(
153 `${formatTargets(unsupported.map(result => result.target))} plugin setup skipped. ${reason}`
154 );
155 if (supported.length === 0) {
156 if (ifPresent) {
157 yield* trackCliEventEffect(
158 getSetupSkippedEvent({
159 operation,
160 requestedTarget: target,
161 invocationOrigin,
162 cliVersion: APP_VERSION,
163 })
164 );
165 yield* ui.outro(
166 `No supported agent host detected; plugin ${uninstall ? 'uninstall' : 'setup'} skipped.`
167 );
168 return;
169 }
170 return yield* setupCommandError(reason, operation, 'unsupported_host');
171 }
172 }
173 if (detected.length === 0) {
174 if (target === 'claude' || target === 'codex') {
175 return yield* setupCommandError(
176 `${target} is not installed or not available on PATH. Install it and rerun \`composio setup${uninstall ? ' --uninstall' : ''} --yes --target ${target}\`.`,
177 operation,
178 'target_not_installed'
179 );
180 }
181 if (!ifPresent || target !== 'auto') {
182 return yield* setupCommandError(
183 `No supported agent host was detected. Install Claude Code or Codex, then rerun \`composio setup${uninstall ? ' --uninstall' : ''} --yes\`.`,
184 operation,
185 'no_host_detected'
186 );
187 }
188 yield* trackCliEventEffect(
189 getSetupSkippedEvent({
190 operation,
191 requestedTarget: target,
192 invocationOrigin,
193 cliVersion: APP_VERSION,
194 })
195 );
196 yield* ui.outro(
197 `No supported agent host detected; plugin ${uninstall ? 'uninstall' : 'setup'} skipped.`
198 );
199 return;
200 }
201
202 const inspected = yield* inspectSetupTargets(detections, {
203 allowMarketplaceConflict: uninstall,
204 operation: uninstall ? 'uninstall' : 'setup',
205 });
206 if (uninstall) {
207 const installed = inspected.filter(status => status.plugin_installed);
208 const notInstalled = inspected.filter(status => !status.plugin_installed);
209 const skillInstaller = yield* SetupSkillInstaller;
210 const hasManagedClaudeSkill = inspected.some(status => status.target === 'claude')
211 ? yield* skillInstaller.hasManagedClaudeSkill
212 : false;
213 const removable = inspected.filter(
214 status => status.plugin_installed || (status.target === 'claude' && hasManagedClaudeSkill)
215 );
216
217 for (const status of installed) {
218 yield* ui.log.success(
219 `The Composio plugin for ${AGENT_HOST_LABELS[status.target]} is installed.`
220 );
221 }
222 for (const status of notInstalled) {
223 yield* ui.log.info(
224 `The Composio plugin for ${AGENT_HOST_LABELS[status.target]} is not installed.`
225 );
226 }
227
228 if (!yes && removable.length > 0) {
229 if (!terminal.canPrompt) {
230 return yield* setupCommandError(
231 'Non-interactive uninstall requires `--yes` to approve local changes.',
232 operation,
233 'non_interactive_requires_yes'
234 );
235 }
236 const confirmed = yield* ui.confirm(
237 `Remove Composio from ${formatTargets(removable.map(status => status.target))}?`,
238 { defaultValue: false }
239 );
240 if (!confirmed) {
241 yield* trackCliEventEffect(
242 getSetupCancelledEvent({
243 operation,
244 requestedTarget: target,
245 invocationOrigin,
246 cliVersion: APP_VERSION,
247 })
248 );
249 yield* ui.outro('Uninstall cancelled.');
250 return;
251 }
252 }
253
254 const results = yield* uninstallSetupTargets(inspected);
255 for (const result of results) {
256 if (!result.plugin_changed) continue;
257 yield* ui.log.success(
258 `Successfully uninstalled the Composio plugin for ${AGENT_HOST_LABELS[result.target]}.`
259 );
260 }
261 yield* ui.outro('Composio plugin uninstall complete.');
262 return;
263 }
264
265 for (const status of inspected.filter(isSetupPluginReady)) {
266 yield* ui.log.success(
267 `The Composio plugin for ${AGENT_HOST_LABELS[status.target]} is already installed and enabled.`
268 );
269 }
270
271 const pending = inspected.filter(status => !isSetupReady(status));
272 if (pending.length === 0) {
273 yield* ui.outro('Composio setup complete.');
274 return;
275 }
276
277 const pendingPlugins = pending.filter(status => !isSetupPluginReady(status));
278 if (!yes) {
279 if (!terminal.canPrompt) {
280 return yield* setupCommandError(
281 'Non-interactive setup requires `--yes` to approve local changes.',
282 operation,
283 'non_interactive_requires_yes'
284 );
285 }
286
287 const prompt =
288 pendingPlugins.length === pending.length
289 ? `Install the Composio plugin for ${formatTargets(pendingPlugins.map(status => status.target))}?`
290 : `Finish Composio setup for ${formatTargets(pending.map(status => status.target))}?`;
291 const confirmed = yield* ui.confirm(prompt, { defaultValue: true });
292 if (!confirmed) {
293 yield* trackCliEventEffect(
294 getSetupCancelledEvent({
295 operation,
296 requestedTarget: target,
297 invocationOrigin,
298 cliVersion: APP_VERSION,
299 })
300 );
301 yield* ui.outro('Setup cancelled.');
302 return;
303 }
304 }
305
306 const results = yield* installSetupTargets(pending);
307 for (const result of results) {
308 if (!result.plugin_changed) continue;
309
310 const initial = pending.find(status => status.target === result.target);
311 if (!initial) {
312 // v4 dropped `Effect.dieMessage`; `Effect.die` takes the defect directly.
313 return yield* Effect.die(
314 new Error(`Setup invariant violated: missing initial state for ${result.target}`)
315 );
316 }
317 let action = 'configured and enabled';
318 if (!initial.plugin_installed) action = 'installed and enabled';
319 else if (!initial.plugin_enabled) action = 'enabled';
320 yield* ui.log.success(
321 `Successfully ${action} the Composio plugin for ${AGENT_HOST_LABELS[result.target]}.`
322 );
323 }
324
325 yield* ui.outro('Composio setup complete.');
326 }).pipe(
327 Effect.mapError(error => {
328 if (error instanceof SetupCommandError) return error;
329 return setupCommandError(
330 errorMessage(error),
331 uninstall ? 'uninstall' : 'setup',
332 'unknown',
333 error
334 );
335 }),
336 Effect.tapError(renderSetupFailure)
337 )
338 );
339
340 export const setupCmd = withCommandTelemetry(setupBaseCmd, input =>
341 telemetry.fields({
342 operation: {
343 value: input.uninstall ? 'uninstall' : 'setup',
344 flags: input.uninstall ? ['--uninstall'] : [],
345 },
346 target: telemetry.value(input.target),
347 yes: telemetry.flag('--yes', input.yes),
348 if_present: telemetry.flag('--if-present', input.ifPresent),
349 })
350 ).pipe(
351 Command.withDescription('Install or uninstall Composio plugins for supported agent hosts.'),
352 Command.withExamples([
353 {
354 command: 'composio setup',
355 },
356 {
357 command: 'composio setup --target auto --yes',
358 },
359 {
360 command: 'composio setup --uninstall --target auto --yes',
361 },
362 {
363 command: 'composio setup --target all',
364 },
365 ]),
366 withRegisteredSubcommands([setupSkillCmd], { ownAction: true })
367 );