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 538 lines 19.2 KB
Raw
1 import * as FileSystem from 'effect/FileSystem';
2 import * as Path from 'effect/Path';
3 import type { PlatformError } from 'effect/PlatformError';
4 import { Array as Arr, Config, Effect, Option } from 'effect';
5 import { APP_CONFIG, HOST_CONFIG } from 'src/config';
6 import { getCompletionScript } from 'src/effects/shell-completions';
7 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
8 import { NodeOs } from 'src/services/node-os';
9 import { NodeProcess } from 'src/services/node-process';
10 import {
11 BASH_PROFILE_PASSTHROUGH,
12 COMPLETIONS_MARKER,
13 appendManagedBlocks,
14 buildShellConfig,
15 detectShellFromEnv,
16 fileContains,
17 isUnsafePath,
18 pathFilesForShell,
19 readMaybeMissingFile,
20 reconcileManagedPathBlock,
21 renderWithHome,
22 replaceFilePreservingMode,
23 resolveBashLoginFile,
24 resolveWriteTarget,
25 type Shell,
26 } from 'src/services/shell-config';
27 import { TerminalUI } from 'src/services/terminal-ui';
28 import { ShellSetupAbortError } from './install.errors';
29 import {
30 ABORTED_OUTRO,
31 ALREADY_CONFIGURED_MESSAGE,
32 BIN_DIR_NOT_ABSOLUTE_MESSAGE,
33 BIN_DIR_UNSAFE_MESSAGE,
34 CompletionPlan,
35 DONE_OUTRO,
36 INSTALL_INTRO,
37 MANUAL_PATH_SETUP_TITLE,
38 MANUAL_SETUP_OUTRO,
39 RESTART_HINT_TITLE,
40 SHELL_NOT_DETECTED_MESSAGE,
41 alreadyOnPathMessage,
42 completionStatusLine,
43 detectedShellMessage,
44 makeInstallReporter,
45 manualPathSetupLine,
46 pathStatusLines,
47 restartHintBody,
48 tildify,
49 updatedFileMessage,
50 type InstallReporter,
51 } from './install.format';
52
53 /** The flags of `composio install`. */
54 export type InstallParams = {
55 readonly completions: boolean;
56 readonly noCompletions: boolean;
57 readonly shell: Option.Option<Shell>;
58 };
59
60 type InstallRequirements =
61 TerminalUI | NodeOs | NodeProcess | FileSystem.FileSystem | Path.Path | ComposioCliUserConfig;
62
63 const isDirOnPath = (pathEnv: string, dir: string): boolean =>
64 pathEnv.split(':').some(entry => entry === dir);
65
66 /**
67 * True when `candidate` resolves (following symlinks) to the running
68 * executable. A bare exists-check is not enough for bin-dir resolution: a
69 * leftover `composio` from another installer (e.g. pip) would win, and the
70 * PATH line would point shells at the wrong program.
71 */
72 const resolvesToCurrentExecutable = (
73 candidate: string,
74 execPath: string,
75 fs: FileSystem.FileSystem
76 ): Effect.Effect<boolean> =>
77 Effect.zipWith(
78 fs.realPath(candidate),
79 fs.realPath(execPath).pipe(Effect.orElseSucceed(() => execPath)),
80 (candidateReal, execReal) => candidateReal === execReal
81 ).pipe(Effect.orElseSucceed(() => false));
82
83 /**
84 * Bin-dir resolution order: explicit env, then `~/.local/bin` when its
85 * `composio` entry point is the running executable, then the real binary's
86 * own directory.
87 */
88 const resolveBinDir = (params: {
89 readonly envBinDir: string | undefined;
90 readonly localBinDir: string;
91 readonly localBinComposioIsCurrentExecutable: boolean;
92 readonly execPath: string;
93 readonly path: Path.Path;
94 }): string =>
95 Option.fromUndefinedOr(params.envBinDir).pipe(
96 Option.map(dir => dir.trim()),
97 Option.filter(dir => dir.length > 0),
98 Option.getOrElse(() =>
99 params.localBinComposioIsCurrentExecutable
100 ? params.localBinDir
101 : params.path.dirname(params.execPath)
102 )
103 );
104
105 /** A bin dir that cannot go into an rc file, and why; checked in this order. */
106 const UNUSABLE_BIN_DIR_CHECKS: ReadonlyArray<{
107 readonly rejects: (path: Path.Path, binDir: string) => boolean;
108 readonly message: string;
109 }> = [
110 { rejects: (path, binDir) => !path.isAbsolute(binDir), message: BIN_DIR_NOT_ABSOLUTE_MESSAGE },
111 { rejects: (_, binDir) => isUnsafePath(binDir), message: BIN_DIR_UNSAFE_MESSAGE },
112 ];
113
114 const unusableBinDirReason = (path: Path.Path, binDir: string): Option.Option<string> =>
115 Arr.findFirst(UNUSABLE_BIN_DIR_CHECKS, check => check.rejects(path, binDir)).pipe(
116 Option.map(check => check.message)
117 );
118
119 interface ManagedBlockReplacement {
120 readonly contents: string;
121 readonly displayPath: string;
122 }
123
124 interface PathBlockWritePlan {
125 readonly appendPathFiles: readonly string[];
126 readonly replacementsByTarget: ReadonlyMap<string, ManagedBlockReplacement>;
127 readonly loginOverrideWritten: boolean;
128 }
129
130 /**
131 * Decide, per configured PATH file, whether the managed block must be appended
132 * (absent), replaced in place (stale bin dir), or left alone (already
133 * current). Both appends and replacements are deduplicated by physical write
134 * target so two logical paths aliasing the same file (a dotfiles symlink
135 * setup) keep exactly one managed block.
136 */
137 const planPathBlockWrites = (params: {
138 readonly pathFiles: readonly string[];
139 readonly existingByFile: ReadonlyMap<string, string>;
140 readonly pathFileTargets: ReadonlyMap<string, string>;
141 readonly pathBlock: string;
142 readonly bashLoginOverride: string | undefined;
143 }): PathBlockWritePlan => {
144 const appendPathFiles: string[] = [];
145 const replacementsByTarget = new Map<string, ManagedBlockReplacement>();
146 const queuedPathTargets = new Set<string>();
147 let loginOverrideWritten = false;
148 for (const filePath of params.pathFiles) {
149 const existing = params.existingByFile.get(filePath) ?? '';
150 const target = params.pathFileTargets.get(filePath)!;
151 const reconciliation = reconcileManagedPathBlock(existing, params.pathBlock);
152 if (reconciliation.state === 'stale') {
153 if (!replacementsByTarget.has(target)) {
154 replacementsByTarget.set(target, {
155 contents: reconciliation.reconciled,
156 displayPath: filePath,
157 });
158 if (filePath === params.bashLoginOverride) loginOverrideWritten = true;
159 }
160 continue;
161 }
162 // Only a byte-exact current block is a no-op. A `$PATH` that already
163 // resolves in the invoking process is deliberately not a reason to skip:
164 // it is transient evidence that says nothing about future shells.
165 if (reconciliation.state === 'current' || queuedPathTargets.has(target)) {
166 continue;
167 }
168 appendPathFiles.push(filePath);
169 queuedPathTargets.add(target);
170 if (filePath === params.bashLoginOverride) loginOverrideWritten = true;
171 }
172 return { appendPathFiles, replacementsByTarget, loginOverrideWritten };
173 };
174
175 /** Whether the completion block is appended, and if not, why. */
176 const planCompletionWrite = (params: {
177 readonly shell: Shell;
178 readonly completionsRequested: boolean;
179 readonly completionBlock: Option.Option<string>;
180 readonly existingCompletionFile: string;
181 }): CompletionPlan => {
182 if (params.shell === 'zsh') return CompletionPlan.SkippedForZsh();
183 if (!params.completionsRequested) return CompletionPlan.NotRequested();
184 return Option.match(params.completionBlock, {
185 onNone: () => CompletionPlan.Unavailable(),
186 onSome: block =>
187 fileContains(params.existingCompletionFile, COMPLETIONS_MARKER)
188 ? CompletionPlan.AlreadyConfigured()
189 : CompletionPlan.Install({ block }),
190 });
191 };
192
193 /** Blocks to append, grouped by file in first-queued order. */
194 const groupBlocksByFile = (
195 queued: ReadonlyArray<readonly [file: string, block: string]>
196 ): ReadonlyMap<string, ReadonlyArray<string>> =>
197 Arr.reduce(queued, new Map<string, ReadonlyArray<string>>(), (byFile, [file, block]) =>
198 byFile.set(file, [...(byFile.get(file) ?? []), block])
199 );
200
201 /** Each file mapped to what `f` resolves for it, read one file at a time. */
202 const mapFiles = <A>(
203 files: ReadonlyArray<string>,
204 f: (file: string) => Effect.Effect<A, PlatformError>
205 ): Effect.Effect<ReadonlyMap<string, A>, PlatformError> =>
206 Effect.forEach(files, file => Effect.map(f(file), value => [file, value] as const)).pipe(
207 Effect.map(entries => new Map(entries))
208 );
209
210 /** Append each file's queued blocks in one atomic, mode-preserving rewrite per file. */
211 const appendQueuedBlocks = (params: {
212 readonly blocksByFile: ReadonlyMap<string, ReadonlyArray<string>>;
213 readonly pathFileTargets: ReadonlyMap<string, string>;
214 readonly fs: FileSystem.FileSystem;
215 readonly path: Path.Path;
216 readonly report: (filePath: string) => Effect.Effect<void>;
217 }): Effect.Effect<void, PlatformError> =>
218 Effect.forEach(
219 params.blocksByFile,
220 ([filePath, blocks]) =>
221 Effect.gen(function* () {
222 const { fs, path } = params;
223 // Re-read instead of reusing the pre-check snapshot: two configured paths
224 // can alias the same physical file through symlinks, and this write must
225 // not discard a previous iteration's append.
226 const existingContents = yield* readMaybeMissingFile(filePath, fs);
227 // PATH files were already resolved by the caller; only the completion
228 // file needs a fresh resolve.
229 const writeTarget =
230 params.pathFileTargets.get(filePath) ?? (yield* resolveWriteTarget(filePath, fs));
231
232 yield* fs
233 .makeDirectory(path.dirname(writeTarget), { recursive: true })
234 .pipe(
235 Effect.catch(e =>
236 Effect.logDebug('Could not create parent directory (may already exist):', e)
237 )
238 );
239
240 yield* replaceFilePreservingMode(
241 fs,
242 writeTarget,
243 appendManagedBlocks(existingContents, blocks)
244 );
245 yield* params.report(filePath);
246 }),
247 { discard: true }
248 );
249
250 /** Atomically rewrite each reconciled physical target, preserving its file mode. */
251 const writeReconciledTargets = (params: {
252 readonly replacementsByTarget: ReadonlyMap<string, ManagedBlockReplacement>;
253 readonly fs: FileSystem.FileSystem;
254 readonly report: (filePath: string) => Effect.Effect<void>;
255 }): Effect.Effect<void, PlatformError> =>
256 Effect.forEach(
257 params.replacementsByTarget,
258 ([writeTarget, replacement]) =>
259 replaceFilePreservingMode(params.fs, writeTarget, replacement.contents).pipe(
260 Effect.andThen(params.report(replacement.displayPath))
261 ),
262 { discard: true }
263 );
264
265 /**
266 * The completion script for `shell`, when the generator produces one. The root
267 * command is imported lazily to avoid a circular dependency
268 * (index.ts → install.cmd.ts → install.handler.ts → index.ts).
269 */
270 const generateCompletionScript = (shell: Shell) =>
271 Effect.gen(function* () {
272 const cliUserConfig = yield* ComposioCliUserConfig;
273 const mod = yield* Effect.promise(() => import('src/commands'));
274 const lines = yield* getCompletionScript(
275 mod.buildRootCommand({
276 isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
277 isExperimentalFeatureEnabled: feature =>
278 cliUserConfig.isExperimentalFeatureEnabled(feature),
279 }),
280 shell
281 );
282 return Arr.match(lines, {
283 onEmpty: () => Option.none<string>(),
284 onNonEmpty: nonEmpty => Option.some(Arr.join(nonEmpty, '\n')),
285 });
286 });
287
288 /** Prints the abort reason, then fails so the process exits 1 and install.sh falls back. */
289 const abortShellSetup = (report: InstallReporter, message: string) =>
290 Effect.gen(function* () {
291 const ui = yield* TerminalUI;
292 yield* report.failure(message);
293 yield* ui.outro(ABORTED_OUTRO);
294 return yield* new ShellSetupAbortError({ message });
295 });
296
297 /** No shell, so no rc file: either the bin dir is already on `$PATH`, or the user adds it. */
298 const reportUndetectedShell = (params: {
299 readonly report: InstallReporter;
300 readonly binDir: string;
301 readonly binDirOnPath: boolean;
302 }) =>
303 Effect.gen(function* () {
304 const ui = yield* TerminalUI;
305 const os = yield* NodeOs;
306 if (params.binDirOnPath) {
307 yield* params.report.success(alreadyOnPathMessage(params.binDir, os.homedir));
308 yield* ui.outro(DONE_OUTRO);
309 return;
310 }
311 yield* params.report.warn(SHELL_NOT_DETECTED_MESSAGE);
312 yield* params.report.note(
313 manualPathSetupLine(renderWithHome(params.binDir, os.homedir)),
314 MANUAL_PATH_SETUP_TITLE
315 );
316 yield* ui.outro(MANUAL_SETUP_OUTRO);
317 });
318
319 /** Writes the PATH block (and completions, when asked) into `shell`'s startup files. */
320 const configureShell = (params: {
321 readonly shell: Shell;
322 readonly binDir: string;
323 readonly completions: boolean;
324 readonly installerOwnsFinalMessaging: boolean;
325 readonly report: InstallReporter;
326 }) =>
327 Effect.gen(function* () {
328 const ui = yield* TerminalUI;
329 const os = yield* NodeOs;
330 const fs = yield* FileSystem.FileSystem;
331 const path = yield* Path.Path;
332 const { shell, binDir, report } = params;
333 const homedir = os.homedir;
334
335 yield* report.step(detectedShellMessage(shell));
336
337 const completionScript = yield* generateCompletionScript(shell).pipe(
338 Effect.when(Effect.succeed(params.completions && shell !== 'zsh')),
339 Effect.map(Option.flatten)
340 );
341
342 const bashLoginFile = yield* Effect.when(
343 resolveBashLoginFile(path, homedir, fs),
344 Effect.succeed(shell === 'bash')
345 );
346 const bashLoginOverride = Option.getOrUndefined(Option.map(bashLoginFile, f => f.file));
347 const pathFiles = pathFilesForShell(path, shell, homedir, bashLoginOverride);
348 const config = buildShellConfig(path, shell, pathFiles, binDir, completionScript, homedir);
349
350 const existingByFile = yield* mapFiles(
351 Arr.dedupe([...config.pathFiles, config.completionFile]),
352 filePath => readMaybeMissingFile(filePath, fs)
353 );
354
355 // Resolve each configured PATH file's real write target up front so two
356 // logical paths that alias the same physical file (a dotfiles setup
357 // symlinking .bash_profile -> .bashrc) get the PATH block appended once,
358 // not once per alias.
359 const pathFileTargets = yield* mapFiles(config.pathFiles, filePath =>
360 resolveWriteTarget(filePath, fs)
361 );
362
363 const writePlan = planPathBlockWrites({
364 pathFiles: config.pathFiles,
365 existingByFile,
366 pathFileTargets,
367 pathBlock: config.pathBlock,
368 bashLoginOverride,
369 });
370 const completionPlan = planCompletionWrite({
371 shell,
372 completionsRequested: params.completions,
373 completionBlock: config.completionBlock,
374 existingCompletionFile: existingByFile.get(config.completionFile) ?? '',
375 });
376
377 const blocksByFile = groupBlocksByFile([
378 // A `.bash_profile` created here takes over from an existing `~/.profile`,
379 // so it leads with the passthrough that keeps sourcing it.
380 ...Arr.fromOption(
381 bashLoginFile.pipe(
382 Option.filter(
383 loginFile =>
384 loginFile.seedsProfilePassthrough &&
385 writePlan.appendPathFiles.includes(loginFile.file)
386 ),
387 Option.map(loginFile => [loginFile.file, BASH_PROFILE_PASSTHROUGH] as const)
388 )
389 ),
390 ...writePlan.appendPathFiles.map(filePath => [filePath, config.pathBlock] as const),
391 ...Arr.fromOption(
392 Option.liftPredicate(completionPlan, CompletionPlan.$is('Install')).pipe(
393 Option.map(({ block }) => [config.completionFile, block] as const)
394 )
395 ),
396 ]);
397
398 yield* Effect.forEach(
399 pathStatusLines({
400 pathWritten: writePlan.appendPathFiles.length > 0,
401 pathReplaced: writePlan.replacementsByTarget.size > 0,
402 renderedBinDir: tildify(binDir, homedir),
403 }),
404 report.step,
405 { discard: true }
406 );
407 yield* report.step(
408 completionStatusLine(completionPlan, {
409 shell,
410 completionFile: config.completionFile,
411 homedir,
412 })
413 );
414
415 const reportUpdated = (filePath: string) =>
416 report.success(updatedFileMessage(filePath, homedir));
417
418 // Reconcile stale managed blocks first so any completion append below
419 // (which re-reads from disk) lands on top of the replaced contents.
420 yield* writeReconciledTargets({
421 replacementsByTarget: writePlan.replacementsByTarget,
422 fs,
423 report: reportUpdated,
424 });
425 yield* appendQueuedBlocks({ blocksByFile, pathFileTargets, fs, path, report: reportUpdated });
426
427 const changesWritten = blocksByFile.size > 0 || writePlan.replacementsByTarget.size > 0;
428 yield* Effect.when(report.success(ALREADY_CONFIGURED_MESSAGE), Effect.succeed(!changesWritten));
429 yield* Effect.when(
430 report.note(
431 restartHintBody({
432 shell,
433 zshPathFile: config.pathFiles[0]!,
434 bashrc: path.join(homedir, '.bashrc'),
435 bashLoginOverride,
436 loginOverrideWritten: writePlan.loginOverrideWritten,
437 homedir,
438 }),
439 RESTART_HINT_TITLE
440 ),
441 Effect.succeed(changesWritten && !params.installerOwnsFinalMessaging)
442 );
443
444 yield* ui.outro(DONE_OUTRO);
445 });
446
447 /**
448 * Sets up shell integration: adds the resolved bin dir to `PATH` in the
449 * detected (or given) shell's startup files and, when asked, installs
450 * completions. install.sh runs it after installing the binary.
451 */
452 export const installShellIntegration = (params: {
453 readonly completions: boolean;
454 readonly shell?: Shell;
455 }): Effect.Effect<void, PlatformError | ShellSetupAbortError, InstallRequirements> =>
456 Effect.gen(function* () {
457 const ui = yield* TerminalUI;
458 const os = yield* NodeOs;
459 const nodeProcess = yield* NodeProcess;
460 const fs = yield* FileSystem.FileSystem;
461 const path = yield* Path.Path;
462
463 const { canDecorate } = yield* ui.capabilities;
464 const report = makeInstallReporter(ui, canDecorate);
465
466 yield* ui.intro(INSTALL_INTRO);
467
468 if (os.platform === 'win32') {
469 return yield* abortShellSetup(
470 report,
471 'Shell setup is not available on Windows. The PowerShell installer already adds the CLI to your PATH.'
472 );
473 }
474
475 // Resolve the entry-point bin dir: explicit env, then a ~/.local/bin/composio
476 // that is this executable, then the runtime executable's own directory.
477 const envBinDir = yield* APP_CONFIG.BIN_DIR.pipe(Effect.orDie);
478 const localBinDir = path.join(os.homedir, '.local', 'bin');
479 const execPath = nodeProcess.execPath;
480 const localBinComposioIsCurrentExecutable = yield* resolvesToCurrentExecutable(
481 path.join(localBinDir, 'composio'),
482 execPath,
483 fs
484 );
485 const binDir = path.normalize(
486 resolveBinDir({
487 envBinDir,
488 localBinDir,
489 localBinComposioIsCurrentExecutable,
490 execPath,
491 path,
492 })
493 );
494
495 yield* Option.match(unusableBinDirReason(path, binDir), {
496 onNone: () => Effect.void,
497 onSome: message => abortShellSetup(report, message),
498 });
499
500 // The installer owns the closing message: when install.sh delegates to
501 // this command it passes COMPOSIO_CLI_INVOCATION_ORIGIN=installer and
502 // prints the final action block itself. Keep the concise per-file status
503 // lines but suppress the boxed restart hint so the CLI never prints a
504 // competing instruction.
505 const invocationOrigin = yield* APP_CONFIG.CLI_INVOCATION_ORIGIN.pipe(Effect.orDie);
506 const installerOwnsFinalMessaging = invocationOrigin === 'installer';
507
508 const host = yield* Effect.orDie(
509 Config.all({ shell: HOST_CONFIG.SHELL, path: HOST_CONFIG.PATH })
510 );
511 const shell = Option.fromUndefinedOr(params.shell).pipe(
512 Option.orElse(() => detectShellFromEnv(path, host.shell ?? ''))
513 );
514
515 yield* Option.match(shell, {
516 onNone: () =>
517 reportUndetectedShell({
518 report,
519 binDir,
520 binDirOnPath: isDirOnPath(host.path ?? '', binDir),
521 }),
522 onSome: detected =>
523 configureShell({
524 shell: detected,
525 binDir,
526 completions: params.completions,
527 installerOwnsFinalMessaging,
528 report,
529 }),
530 });
531 });
532
533 /** `--no-completions` wins over `--completions`. */
534 export const runInstall = ({ completions, noCompletions, shell }: InstallParams) =>
535 installShellIntegration({
536 completions: completions && !noCompletions,
537 shell: Option.getOrUndefined(shell),
538 });