1
-import { Command, Flag } from 'effect/cli';
2
-import * as FileSystem from 'effect/FileSystem';
3
-import * as Path from 'effect/Path';
4
-import type { PlatformError } from 'effect/PlatformError';
5
-import { Array as Arr, Config, Data, Effect, Option } from 'effect';
6
-import { APP_CONFIG, HOST_CONFIG } from 'src/config';
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 { TerminalUI } from 'src/services/terminal-ui';
11
-import { getCompletionScript } from 'src/effects/shell-completions';
12
-import { atomicWriteFileString } from 'src/utils/atomic-write';
13
-
14
-// ---------------------------------------------------------------------------
15
-// Options
16
-// ---------------------------------------------------------------------------
17
-
18
-const completionsOpt = Flag.Boolean('completions').pipe(
19
- Flag.withDescription('Install shell completions.'),
20
- Flag.withDefault(false)
21
-);
22
-
23
-const noCompletionsOpt = Flag.Boolean('no-completions').pipe(
24
- Flag.withDescription('Deprecated: shell completions are skipped by default.'),
25
- Flag.withDefault(false)
26
-);
27
-
28
-const SHELLS = ['zsh', 'bash', 'fish'] as const;
29
-
30
-const shellOpt = Flag.Literals('shell', SHELLS).pipe(
31
- Flag.withDescription('Override automatic shell detection.'),
32
- Flag.optional
33
-);
34
-
35
-// ---------------------------------------------------------------------------
36
-// Types
37
-// ---------------------------------------------------------------------------
38
-
39
-export type Shell = (typeof SHELLS)[number];
40
-
41
-/**
42
- * Aborted shell setup must fail the process: install.sh only runs its guarded
43
- * inline PATH fallback when `composio install` exits non-zero, so a successful
44
- * exit here would leave the user with no PATH setup and a green install. The
45
- * abort reason is already printed before this error is raised; cli-main.ts
46
- * maps it to exit code 1 without printing anything further.
47
- */
48
-export class ShellSetupAbortError extends Data.TaggedError('commands/ShellSetupAbortError')<{
49
- readonly message: string;
50
-}> {}
51
-
52
-interface ShellConfig {
53
- readonly shell: Shell;
54
- readonly pathFiles: readonly string[];
55
- readonly completionFile: string;
56
- readonly pathBlock: string;
57
- readonly completionBlock: string | undefined;
58
-}
59
-
60
-// ---------------------------------------------------------------------------
61
-// Helpers
62
-// ---------------------------------------------------------------------------
63
-
64
-const MARKER = '# Composio CLI';
65
-const COMPLETIONS_MARKER = '# Composio CLI completions';
66
-
67
-/**
68
- * Reject bin-dir paths that cannot be embedded safely in a managed rc line.
69
- *
70
- * The resolved dir is only ever emitted inside double quotes — `export
71
- * PATH="<dir>:$PATH"` for bash/zsh and `set --export PATH "<dir>" $PATH` for
72
- * fish — so the set is deliberately narrow and mirrors `is_unsafe_path` in
73
- * install.sh, keeping the inline fallback and this command on one contract:
74
- *
75
- * - `` ` ``, `$`, `\`, `"`: the only characters bash and zsh still expand
76
- * inside double quotes (`!` history expansion does not apply to sourced
77
- * files). fish expands a strict subset of those. Everything else — `;`, `|`,
78
- * `&`, `(`, `)`, `'` — is literal there, so a path like
79
- * `/Users/o'brien/.composio` is written verbatim rather than rejected.
80
- * - `\n`, `\r`: structural, not a quoting concern — either would split the
81
- * managed block into extra rc lines.
82
- * - `:`: structural too, as the PATH separator: a dir containing one would
83
- * silently prepend more than one entry.
84
- */
85
-const UNSAFE_PATH_CHARS = /[`$"\\\n\r:]/;
86
-const isUnsafePath = (p: string): boolean => UNSAFE_PATH_CHARS.test(p);
87
-
88
-const detectShellFromEnv = (path: Path.Path, shellEnv: string): Shell | undefined => {
89
- const base = path.basename(shellEnv);
90
- if (base === 'zsh') return 'zsh';
91
- if (base === 'bash') return 'bash';
92
- if (base === 'fish') return 'fish';
93
- return undefined;
94
-};
95
-
96
-const isDirOnPath = (pathEnv: string, dir: string): boolean =>
97
- pathEnv.split(':').some(entry => entry === dir);
98
-
99
-/**
100
- * True when `candidate` resolves (following symlinks) to the running
101
- * executable. A bare exists-check is not enough for bin-dir resolution: a
102
- * leftover `composio` from another installer (e.g. pip) would win, and the
103
- * PATH line would point shells at the wrong program.
104
- */
105
-const resolvesToCurrentExecutable = (
106
- candidate: string,
107
- execPath: string,
108
- fs: FileSystem.FileSystem
109
-): Effect.Effect<boolean> =>
110
- Effect.zipWith(
111
- fs.realPath(candidate),
112
- fs.realPath(execPath).pipe(Effect.orElseSucceed(() => execPath)),
113
- (candidateReal, execReal) => candidateReal === execReal
114
- ).pipe(Effect.orElseSucceed(() => false));
115
-
116
-/**
117
- * Bin-dir resolution order: explicit env, then `~/.local/bin` when its
118
- * `composio` entry point is the running executable, then the real binary's
119
- * own directory.
120
- */
121
-const resolveBinDir = (params: {
122
- readonly envBinDir: string | undefined;
123
- readonly localBinDir: string;
124
- readonly localBinComposioIsCurrentExecutable: boolean;
125
- readonly execPath: string;
126
- readonly path: Path.Path;
127
-}): string => {
128
- const trimmedEnvBinDir = params.envBinDir?.trim();
129
- if (trimmedEnvBinDir && trimmedEnvBinDir.length > 0) {
130
- return trimmedEnvBinDir;
131
- }
132
- if (params.localBinComposioIsCurrentExecutable) {
133
- return params.localBinDir;
134
- }
135
- return params.path.dirname(params.execPath);
136
-};
137
-
138
-/**
139
- * Render a path for embedding in a shell rc file. `~` never expands inside
140
- * double quotes, so home-relative paths use a literal `$HOME` prefix instead.
141
- * Must stay in lockstep with install.sh's render_bin_dir: the installer's
142
- * delegated_setup_verified compares its own rendering against the line this
143
- * command wrote byte for byte, so any disagreement makes every delegated
144
- * install look stale and forces a needless inline rewrite.
145
- */
146
-export const renderWithHome = (dir: string, homedir: string): string => {
147
- if (dir === homedir) return '$HOME';
148
- if (dir.startsWith(`${homedir}/`)) return `$HOME/${dir.slice(homedir.length + 1)}`;
149
- return dir;
150
-};
151
-
152
-export const pathBlockForShell = (shell: Shell, binDir: string, homedir: string): string => {
153
- const rendered = renderWithHome(binDir, homedir);
154
- return shell === 'fish'
155
- ? [MARKER, `set --export PATH "${rendered}" $PATH`].join('\n')
156
- : [MARKER, `export PATH="${rendered}:$PATH"`].join('\n');
157
-};
158
-
159
-/**
160
- * The bash startup file a login shell reads the managed PATH block from, and
161
- * whether creating it means taking over from an existing `~/.profile`.
162
- */
163
-interface BashLoginFile {
164
- readonly file: string;
165
- readonly seedsProfilePassthrough: boolean;
166
-}
167
-
168
-/**
169
- * Preamble for a `~/.bash_profile` this command creates. A login bash reads
170
- * `/etc/profile` and then only the first existing of `.bash_profile`,
171
- * `.bash_login`, `.profile`, so a newly created `.bash_profile` shadows a
172
- * `.profile` the shell read until now. Sourcing it back keeps that content —
173
- * including the Debian-style `.profile` that itself sources `.bashrc` — while
174
- * leaving `.profile` (shared with every other POSIX shell) untouched.
175
- */
176
-const BASH_PROFILE_PASSTHROUGH = [
177
- '# Created by the Composio CLI installer.',
178
- '# Bash reads this file instead of ~/.profile in login shells.',
179
- 'if [ -f "$HOME/.profile" ]; then',
180
- ' . "$HOME/.profile"',
181
- 'fi',
182
-].join('\n');
183
-
184
-/**
185
- * Resolve the bash startup file that login-mode bash reads.
186
- *
187
- * Login bash never reads `.bashrc` — macOS Terminal.app starts exactly such a
188
- * shell — so the PATH block has to reach a login-mode file too. An existing
189
- * override (`.bash_profile`, then `.bash_login`) is reused; when neither
190
- * exists, `.bash_profile` is created rather than writing the shared
191
- * `.profile`, which a `.bash_profile` would shadow anyway.
192
- */
193
-const resolveBashLoginFile = (
194
- path: Path.Path,
195
- homedir: string,
196
- fs: FileSystem.FileSystem
197
-): Effect.Effect<BashLoginFile, PlatformError> =>
198
- Effect.gen(function* () {
199
- const bashProfile = path.join(homedir, '.bash_profile');
200
- if (yield* fs.exists(bashProfile)) {
201
- return { file: bashProfile, seedsProfilePassthrough: false };
202
- }
203
- const bashLogin = path.join(homedir, '.bash_login');
204
- if (yield* fs.exists(bashLogin)) {
205
- return { file: bashLogin, seedsProfilePassthrough: false };
206
- }
207
- const profileExists = yield* fs.exists(path.join(homedir, '.profile'));
208
- return { file: bashProfile, seedsProfilePassthrough: profileExists };
209
- });
210
-
211
-/** Bash always configures both files: `.bashrc` for interactive shells, the login file for login shells. */
212
-const pathFilesForShell = (
213
- path: Path.Path,
214
- shell: Shell,
215
- homedir: string,
216
- bashLoginFile: string | undefined
217
-): string[] => {
218
- switch (shell) {
219
- case 'zsh':
220
- return [path.join(homedir, '.zshrc')];
221
- case 'fish':
222
- return [path.join(homedir, '.config', 'fish', 'config.fish')];
223
- case 'bash': {
224
- // Bash is the only shell here that splits startup files by mode: an
225
- // interactive non-login shell reads .bashrc, while a login shell (ssh,
226
- // macOS Terminal.app) reads only its login files. Writing .bashrc alone
227
- // would leave PATH unset in login shells whenever an override file
228
- // shadows .profile, so the block lands in both. The override also stays
229
- // a named value because the restart hint reports it separately.
230
- const bashrc = path.join(homedir, '.bashrc');
231
- return bashLoginFile ? [bashrc, bashLoginFile] : [bashrc];
232
- }
233
- }
234
-};
235
-
236
-const buildShellConfig = (
237
- path: Path.Path,
238
- shell: Shell,
239
- pathFiles: readonly string[],
240
- binDir: string,
241
- completionScript: string | undefined,
242
- homedir: string
243
-): ShellConfig => ({
244
- shell,
245
- pathFiles,
246
- completionFile:
247
- shell === 'fish'
248
- ? path.join(homedir, '.config', 'fish', 'completions', 'composio.fish')
249
- : pathFiles[0]!,
250
- pathBlock: pathBlockForShell(shell, binDir, homedir),
251
- completionBlock: completionScript ? `${COMPLETIONS_MARKER}\n${completionScript}` : undefined,
252
-});
253
-
254
-/**
255
- * Check whether a file already contains a given marker line. Byte-exact, like
256
- * install.sh's awk `$0 == "# Composio CLI"` match: a marker mangled by CRLF
257
- * endings or stray whitespace is not ours and is left alone on both sides.
258
- */
259
-const fileContains = (contents: string, marker: string): boolean =>
260
- contents.split('\n').some(line => line === marker);
261
-
262
-/** Outcome of reconciling a startup file's managed PATH block against the resolved bin dir. */
263
-type ManagedPathBlockState =
264
- | { readonly state: 'absent' }
265
- | { readonly state: 'current' }
266
- | { readonly state: 'stale'; readonly reconciled: string };
267
-
268
-/**
269
- * A line this installer could have written as the managed PATH assignment:
270
- * POSIX `export PATH="<dir>:$PATH"` or fish `set --export PATH "<dir>" $PATH`.
271
- * Matched structurally on the prefix/suffix (any bin dir) so stale blocks
272
- * recording another directory are still recognized as ours.
273
- */
274
-const isManagedPathAssignment = (line: string): boolean => {
275
- const trimmed = line.trim();
276
- return (
277
- (trimmed.startsWith('export PATH="') && trimmed.endsWith(':$PATH"')) ||
278
- (trimmed.startsWith('set --export PATH "') && trimmed.endsWith('" $PATH'))
279
- );
280
-};
281
-
282
-const LEGACY_POSIX_INSTALL_DIR_PREFIX = 'export COMPOSIO_INSTALL_DIR="';
283
-const LEGACY_FISH_INSTALL_DIR_PREFIX = 'set --export COMPOSIO_INSTALL_DIR "';
284
-
285
-/**
286
- * The install-dir assignment the previously released installer wrote as the
287
- * second line of its three-line managed block: POSIX
288
- * `export COMPOSIO_INSTALL_DIR="<dir>"` or fish
289
- * `set --export COMPOSIO_INSTALL_DIR "<dir>"`. Matched structurally on the
290
- * prefix/quotes (any dir), like `isManagedPathAssignment`.
291
- */
292
-const isQuotedAssignment = (line: string, prefix: string): boolean =>
293
- line.startsWith(prefix) && line.endsWith('"') && line.length > prefix.length;
294
-
295
-const isLegacyInstallDirAssignment = (line: string): boolean => {
296
- const trimmed = line.trim();
297
- return (
298
- isQuotedAssignment(trimmed, LEGACY_POSIX_INSTALL_DIR_PREFIX) ||
299
- isQuotedAssignment(trimmed, LEGACY_FISH_INSTALL_DIR_PREFIX)
300
- );
301
-};
302
-
303
-/**
304
- * True when `first` and `second` are the two export lines of the legacy
305
- * three-line block, in the same shell dialect. The closing PATH line is
306
- * matched byte-for-byte (modulo surrounding whitespace) against the exact
307
- * text the legacy installer emitted, so anything else after an install-dir
308
- * assignment is user content and stays untouched.
309
- */
310
-const isLegacyManagedPair = (first: string, second: string): boolean => {
311
- if (!isLegacyInstallDirAssignment(first)) return false;
312
- const secondTrimmed = second.trim();
313
- return first.trim().startsWith(LEGACY_POSIX_INSTALL_DIR_PREFIX)
314
- ? secondTrimmed === 'export PATH="$COMPOSIO_INSTALL_DIR:$PATH"'
315
- : secondTrimmed === 'set --export PATH $COMPOSIO_INSTALL_DIR $PATH';
316
-};
317
-
318
-/**
319
- * Append managed blocks after existing content, separated by one blank line
320
- * and ending with a newline. Content lacking a final newline gains one first,
321
- * exactly as install.sh's line-based awk rewrite normalizes it.
322
- */
323
-export const appendManagedBlocks = (contents: string, blocks: readonly string[]): string => {
324
- const base = contents === '' || contents.endsWith('\n') ? contents : `${contents}\n`;
325
- return `${base}\n${blocks.join('\n\n')}\n`;
326
-};
327
-
328
-/**
329
- * Reconcile the managed PATH block — the `MARKER` line plus the PATH
330
- * assignment right below it — with the currently resolved bin directory.
331
- *
332
- * This mirrors install.sh's write_path_block awk program step for step, and
333
- * the shared fixtures under test/managed-block-fixtures pin both
334
- * implementations to byte-identical outputs — any behavioral edit here must
335
- * land in install.sh too. A file whose single byte-exact marker is directly
336
- * followed by the expected assignment is current and left untouched.
337
- * Otherwise every managed line — each marker, plus the next line only when it
338
- * is a recognizable managed PATH assignment, or the next two lines when they
339
- * are the exact export pair of the legacy three-line block (marker,
340
- * `export COMPOSIO_INSTALL_DIR=...`, PATH line, in POSIX or fish form);
341
- * anything else (a user annotation, a blank line, another marker) is not
342
- * ours to delete — is removed and one fresh block is appended after the
343
- * remaining content. No
344
- * user content is ever deleted, and because these prepend-style assignments
345
- * make the last-sourced line win, the new bin dir takes PATH precedence over
346
- * any orphaned stale assignment that had to be preserved.
347
- */
348
-export const reconcileManagedPathBlock = (
349
- contents: string,
350
- pathBlock: string
351
-): ManagedPathBlockState => {
352
- const lines = contents.split('\n');
353
- const markerIndexes = lines.flatMap((line, index) => (line === MARKER ? [index] : []));
354
- const firstMarkerIndex = markerIndexes[0];
355
- if (firstMarkerIndex === undefined) return { state: 'absent' };
356
-
357
- const blockLines = pathBlock.split('\n');
358
- if (markerIndexes.length === 1 && lines[firstMarkerIndex + 1] === blockLines[1]) {
359
- return { state: 'current' };
360
- }
361
-
362
- // Managed lines: each marker line, plus the next line only when it is a
363
- // recognizable managed PATH assignment, or the next two lines when they are
364
- // the exact export pair of the legacy three-line block — anything else is
365
- // not ours to delete.
366
- const managedLineIndexes = new Set<number>(
367
- markerIndexes.flatMap(markerIndex => {
368
- const assignment = lines[markerIndex + 1];
369
- if (assignment === undefined) return [markerIndex];
370
- if (isManagedPathAssignment(assignment)) return [markerIndex, markerIndex + 1];
371
- const legacyPathLine = lines[markerIndex + 2];
372
- if (legacyPathLine !== undefined && isLegacyManagedPair(assignment, legacyPathLine)) {
373
- return [markerIndex, markerIndex + 1, markerIndex + 2];
374
- }
375
- return [markerIndex];
376
- })
377
- );
378
-
379
- // Like the awk rewrite, kept content is a sequence of newline-terminated
380
- // lines: drop the split's trailing sentinel and re-terminate the last line.
381
- const keptLines = lines.filter((_, index) => !managedLineIndexes.has(index));
382
- const contentLines = keptLines[keptLines.length - 1] === '' ? keptLines.slice(0, -1) : keptLines;
383
- const kept = contentLines.length === 0 ? '' : contentLines.join('\n') + '\n';
384
- return { state: 'stale', reconciled: appendManagedBlocks(kept, [pathBlock]) };
385
-};
386
-
387
-interface ManagedBlockReplacement {
388
- readonly contents: string;
389
- readonly displayPath: string;
390
-}
391
-
392
-interface PathBlockWritePlan {
393
- readonly appendPathFiles: readonly string[];
394
- readonly replacementsByTarget: ReadonlyMap<string, ManagedBlockReplacement>;
395
- readonly loginOverrideWritten: boolean;
396
-}
397
-
398
-/**
399
- * Decide, per configured PATH file, whether the managed block must be appended
400
- * (absent), replaced in place (stale bin dir), or left alone (already
401
- * current). Both appends and replacements are deduplicated by physical write
402
- * target so two logical paths aliasing the same file (a dotfiles symlink
403
- * setup) keep exactly one managed block.
404
- */
405
-const planPathBlockWrites = (params: {
406
- readonly pathFiles: readonly string[];
407
- readonly existingByFile: ReadonlyMap<string, string>;
408
- readonly pathFileTargets: ReadonlyMap<string, string>;
409
- readonly pathBlock: string;
410
- readonly bashLoginOverride: string | undefined;
411
-}): PathBlockWritePlan => {
412
- const appendPathFiles: string[] = [];
413
- const replacementsByTarget = new Map<string, ManagedBlockReplacement>();
414
- const queuedPathTargets = new Set<string>();
415
- let loginOverrideWritten = false;
416
- for (const filePath of params.pathFiles) {
417
- const existing = params.existingByFile.get(filePath) ?? '';
418
- const target = params.pathFileTargets.get(filePath)!;
419
- const reconciliation = reconcileManagedPathBlock(existing, params.pathBlock);
420
- if (reconciliation.state === 'stale') {
421
- if (!replacementsByTarget.has(target)) {
422
- replacementsByTarget.set(target, {
423
- contents: reconciliation.reconciled,
424
- displayPath: filePath,
425
- });
426
- if (filePath === params.bashLoginOverride) loginOverrideWritten = true;
427
- }
428
- continue;
429
- }
430
- // Only a byte-exact current block is a no-op. A `$PATH` that already
431
- // resolves in the invoking process is deliberately not a reason to skip:
432
- // it is transient evidence that says nothing about future shells.
433
- if (reconciliation.state === 'current' || queuedPathTargets.has(target)) {
434
- continue;
435
- }
436
- appendPathFiles.push(filePath);
437
- queuedPathTargets.add(target);
438
- if (filePath === params.bashLoginOverride) loginOverrideWritten = true;
439
- }
440
- return { appendPathFiles, replacementsByTarget, loginOverrideWritten };
441
-};
442
-
443
-/**
444
- * Replace an rc file's contents via the shared atomic-write helper, preserving
445
- * the existing file's mode so a private rc stays private across the rewrite.
446
- */
447
-const replaceFilePreservingMode = (
448
- fs: FileSystem.FileSystem,
449
- target: string,
450
- contents: string
451
-): Effect.Effect<void, PlatformError> =>
452
- atomicWriteFileString({ fs, target, contents, preserveMode: true });
453
-
454
-/** Append each file's queued blocks in one atomic, mode-preserving rewrite per file. */
455
-const appendQueuedBlocks = (params: {
456
- readonly blocksByFile: ReadonlyMap<string, ReadonlyArray<string>>;
457
- readonly pathFileTargets: ReadonlyMap<string, string>;
458
- readonly fs: FileSystem.FileSystem;
459
- readonly path: Path.Path;
460
- readonly homedir: string;
461
- readonly report: (message: string) => Effect.Effect<void>;
462
-}): Effect.Effect<void, PlatformError> =>
463
- Effect.gen(function* () {
464
- const { fs, path } = params;
465
- for (const [filePath, blocks] of params.blocksByFile.entries()) {
466
- // Re-read instead of reusing the pre-check snapshot: two configured paths
467
- // can alias the same physical file through symlinks, and this write must
468
- // not discard a previous iteration's append.
469
- const existingContents = yield* readMaybeMissingFile(filePath, fs);
470
- // PATH files were already resolved by the caller; only the completion
471
- // file needs a fresh resolve.
472
- const writeTarget =
473
- params.pathFileTargets.get(filePath) ?? (yield* resolveWriteTarget(filePath, fs));
474
-
475
- yield* fs
476
- .makeDirectory(path.dirname(writeTarget), { recursive: true })
477
- .pipe(
478
- Effect.catch(e =>
479
- Effect.logDebug('Could not create parent directory (may already exist):', e)
480
- )
481
- );
482
-
483
- yield* replaceFilePreservingMode(
484
- fs,
485
- writeTarget,
486
- appendManagedBlocks(existingContents, blocks)
487
- );
488
- yield* params.report(`Updated ${tildify(filePath, params.homedir)}`);
489
- }
490
- });
491
-
492
-/** Atomically rewrite each reconciled physical target, preserving its file mode. */
493
-const writeReconciledTargets = (params: {
494
- readonly replacementsByTarget: ReadonlyMap<string, ManagedBlockReplacement>;
495
- readonly fs: FileSystem.FileSystem;
496
- readonly homedir: string;
497
- readonly report: (message: string) => Effect.Effect<void>;
498
-}): Effect.Effect<void, PlatformError> =>
499
- Effect.gen(function* () {
500
- for (const [writeTarget, replacement] of params.replacementsByTarget.entries()) {
501
- yield* replaceFilePreservingMode(params.fs, writeTarget, replacement.contents);
502
- yield* params.report(`Updated ${tildify(replacement.displayPath, params.homedir)}`);
503
- }
504
- });
505
-
506
-/** Completion status line, plus whether the completion block still needs appending. */
507
-const planCompletionWrite = (params: {
508
- readonly shell: Shell;
509
- readonly completionsRequested: boolean;
510
- readonly completionBlock: string | undefined;
511
- readonly completionFile: string;
512
- readonly existingCompletionFile: string;
513
- readonly homedir: string;
514
-}): { readonly statusLine: string; readonly append: boolean } => {
515
- if (params.shell === 'zsh') {
516
- return { statusLine: 'Completions: skipped for zsh', append: false };
517
- }
518
- if (!params.completionsRequested) {
519
- return {
520
- statusLine: 'Completions: skipped by default (pass --completions to enable)',
521
- append: false,
522
- };
523
- }
524
- if (!params.completionBlock) {
525
- return { statusLine: 'Completions: not available for this shell', append: false };
526
- }
527
- if (fileContains(params.existingCompletionFile, COMPLETIONS_MARKER)) {
528
- return { statusLine: 'Completions: already configured', append: false };
529
- }
530
- return {
531
- statusLine:
532
- params.shell === 'fish'
533
- ? `Completions: will install fish completions to ${tildify(params.completionFile, params.homedir)}`
534
- : 'Completions: will install shell completions',
535
- append: true,
536
- };
537
-};
538
-
539
-/** Status lines summarizing the planned PATH work, in print order. */
540
-const pathStatusLines = (params: {
541
- readonly pathWritten: boolean;
542
- readonly pathReplaced: boolean;
543
- readonly renderedBinDir: string;
544
-}): readonly string[] => {
545
- const lines: string[] = [];
546
- if (params.pathWritten) lines.push(`PATH: will add ${params.renderedBinDir} to $PATH`);
547
- if (params.pathReplaced) {
548
- lines.push(`PATH: will update the managed block to ${params.renderedBinDir}`);
549
- }
550
- if (lines.length === 0) lines.push('PATH: already configured');
551
- return lines;
552
-};
553
-
554
-/** Shell-specific body of the restart hint printed after a change. */
555
-const restartHintBody = (params: {
556
- readonly shell: Shell;
557
- readonly zshPathFile: string;
558
- readonly bashrc: string;
559
- readonly bashLoginOverride: string | undefined;
560
- readonly loginOverrideWritten: boolean;
561
- readonly homedir: string;
562
-}): string => {
563
- switch (params.shell) {
564
- case 'fish':
565
- return 'exec fish';
566
- case 'zsh':
567
- return `source ${tildify(params.zshPathFile, params.homedir)}`;
568
- case 'bash': {
569
- const hintLines = [`source ${tildify(params.bashrc, params.homedir)}`];
570
- if (params.loginOverrideWritten && params.bashLoginOverride) {
571
- hintLines.push(
572
- `${tildify(params.bashLoginOverride, params.homedir)} was also updated — that entry applies to new login shells too.`
573
- );
574
- }
575
- return hintLines.join('\n');
576
- }
577
- }
578
-};
579
-
580
-const tildify = (p: string, homedir: string): string =>
581
- p.startsWith(homedir + '/') ? `~/${p.slice(homedir.length + 1)}` : p;
582
-
583
-const readMaybeMissingFile = (
584
- filePath: string,
585
- fs: FileSystem.FileSystem
586
-): Effect.Effect<string, PlatformError> =>
587
- fs
588
- .readFileString(filePath)
589
- .pipe(
590
- Effect.catch(e =>
591
- Effect.logDebug('File does not exist yet, will create:', e).pipe(Effect.as(''))
592
- )
593
- );
594
-
595
-/** Resolve valid symlink chains so atomic writes update the target instead of replacing the link. */
596
-const resolveWriteTarget = (
597
- filePath: string,
598
- fs: FileSystem.FileSystem
599
-): Effect.Effect<string, PlatformError> =>
600
- fs.readLink(filePath).pipe(
601
- Effect.flatMap(() => fs.realPath(filePath)),
602
- Effect.catch(() => Effect.succeed(filePath))
603
- );
604
-
605
-// ---------------------------------------------------------------------------
606
-// Exported logic (reusable from install.sh post-install delegation)
607
-// ---------------------------------------------------------------------------
608
-
609
-export const installShellIntegration = (params: {
610
- readonly completions: boolean;
611
- readonly shell?: Shell;
612
-}): Effect.Effect<
613
- void,
614
- PlatformError | ShellSetupAbortError,
615
- TerminalUI | NodeOs | NodeProcess | FileSystem.FileSystem | Path.Path | ComposioCliUserConfig
616
-> =>
617
- Effect.gen(function* () {
618
- const ui = yield* TerminalUI;
619
- const os = yield* NodeOs;
620
- const nodeProcess = yield* NodeProcess;
621
- const fs = yield* FileSystem.FileSystem;
622
- const path = yield* Path.Path;
623
-
624
- // Everything this command prints is a report of what it changed on disk, so
625
- // it has to reach the user even when stderr is not a terminal: install.sh
626
- // runs it as a subprocess, and container/CI installs pipe the whole session
627
- // to a build log. Decoration stays the interactive default; `ui.error`
628
- // writes the same text unformatted when there is nothing to decorate.
629
- const { canDecorate } = yield* ui.capabilities;
630
- const plain = (prefix: string) => (message: string) => ui.error(`${prefix}${message}`);
631
- const step = canDecorate ? ui.log.step : ui.error;
632
- const success = canDecorate ? ui.log.success : ui.error;
633
- const warn = canDecorate ? ui.log.warn : plain('warning: ');
634
- const failure = canDecorate ? ui.log.error : plain('error: ');
635
- const note = (body: string, title: string) =>
636
- canDecorate ? ui.note(body, title) : ui.error(`${title}:\n${body}`);
637
-
638
- yield* ui.intro('composio install');
639
-
640
- // Resolve the entry-point bin dir: explicit env, then a ~/.local/bin/composio
641
- // that is this executable, then the runtime executable's own directory.
642
- const envBinDir = yield* APP_CONFIG.BIN_DIR.pipe(Effect.orDie);
643
- const localBinDir = path.join(os.homedir, '.local', 'bin');
644
- const execPath = nodeProcess.execPath;
645
- const localBinComposioIsCurrentExecutable = yield* resolvesToCurrentExecutable(
646
- path.join(localBinDir, 'composio'),
647
- execPath,
648
- fs
649
- );
650
- const binDir = path.normalize(
651
- resolveBinDir({
652
- envBinDir,
653
- localBinDir,
654
- localBinComposioIsCurrentExecutable,
655
- execPath,
656
- path,
657
- })
658
- );
659
-
660
- if (!path.isAbsolute(binDir)) {
661
- const message = 'Resolved bin directory must be an absolute path.';
662
- yield* failure(message);
663
- yield* ui.outro('Aborted.');
664
- return yield* new ShellSetupAbortError({ message });
665
- }
666
-
667
- if (isUnsafePath(binDir)) {
668
- const message =
669
- 'Resolved bin directory contains unsafe characters and cannot be written to shell config.';
670
- yield* failure(message);
671
- yield* ui.outro('Aborted.');
672
- return yield* new ShellSetupAbortError({ message });
673
- }
674
-
675
- // The installer owns the closing message: when install.sh delegates to
676
- // this command it passes COMPOSIO_CLI_INVOCATION_ORIGIN=installer and
677
- // prints the final action block itself. Keep the concise per-file status
678
- // lines but suppress the boxed restart hint so the CLI never prints a
679
- // competing instruction.
680
- const invocationOrigin = yield* APP_CONFIG.CLI_INVOCATION_ORIGIN.pipe(Effect.orDie);
681
- const installerOwnsFinalMessaging = invocationOrigin === 'installer';
682
-
683
- const host = yield* Effect.orDie(
684
- Config.all({ shell: HOST_CONFIG.SHELL, path: HOST_CONFIG.PATH })
685
- );
686
- const shell = params.shell ?? detectShellFromEnv(path, host.shell ?? '');
687
- const binDirOnPath = isDirOnPath(host.path ?? '', binDir);
688
-
689
- if (!shell) {
690
- // With no shell there is no rc file to write, so the current process's
691
- // $PATH is all the evidence available. It says nothing about future
692
- // shells, hence the deliberately hedged wording.
693
- if (binDirOnPath) {
694
- yield* success(
695
- `PATH: ${tildify(binDir, os.homedir)} is already on $PATH in this process, and no shell config file could be identified — nothing to update.`
696
- );
697
- yield* ui.outro('Done');
698
- return;
699
- }
700
- yield* warn('Could not detect your shell. Manually add the following to your shell config:');
701
- yield* note(`export PATH="${renderWithHome(binDir, os.homedir)}:$PATH"`, 'PATH setup');
702
- yield* ui.outro('Manual setup required.');
703
- return;
704
- }
705
-
706
- yield* step(`Detected shell: ${shell}`);
707
-
708
- // Generate completions script if requested.
709
- // Lazy-import the root command to avoid a circular dependency
710
- // (index.ts → install.cmd.ts → index.ts).
711
- let completionScript: string | undefined;
712
- if (params.completions && shell !== 'zsh') {
713
- const cliUserConfig = yield* ComposioCliUserConfig;
714
- const mod = yield* Effect.promise(() => import('src/commands'));
715
- const lines = yield* getCompletionScript(
716
- mod.buildRootCommand({
717
- isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
718
- isExperimentalFeatureEnabled: feature =>
719
- cliUserConfig.isExperimentalFeatureEnabled(feature),
720
- }),
721
- shell
722
- );
723
- completionScript = lines.length > 0 ? Arr.join(lines, '\n') : undefined;
724
- }
725
-
726
- const bashLoginFile =
727
- shell === 'bash' ? yield* resolveBashLoginFile(path, os.homedir, fs) : undefined;
728
- const bashLoginOverride = bashLoginFile?.file;
729
- const pathFiles = pathFilesForShell(path, shell, os.homedir, bashLoginOverride);
730
- const config = buildShellConfig(path, shell, pathFiles, binDir, completionScript, os.homedir);
731
-
732
- const uniqueTargetFiles = [...new Set([...config.pathFiles, config.completionFile])];
733
- const existingByFile = new Map<string, string>();
734
- for (const filePath of uniqueTargetFiles) {
735
- existingByFile.set(filePath, yield* readMaybeMissingFile(filePath, fs));
736
- }
737
-
738
- // Resolve each configured PATH file's real write target up front so two
739
- // logical paths that alias the same physical file (a dotfiles setup
740
- // symlinking .bash_profile -> .bashrc) get the PATH block appended once,
741
- // not once per alias.
742
- const pathFileTargets = new Map<string, string>();
743
- for (const filePath of config.pathFiles) {
744
- pathFileTargets.set(filePath, yield* resolveWriteTarget(filePath, fs));
745
- }
746
-
747
- const blocksByFile = new Map<string, Array<string>>();
748
- const pushBlock = (filePath: string, block: string) => {
749
- const blocks = blocksByFile.get(filePath);
750
- if (blocks) {
751
- blocks.push(block);
752
- } else {
753
- blocksByFile.set(filePath, [block]);
754
- }
755
- };
756
-
757
- const writePlan = planPathBlockWrites({
758
- pathFiles: config.pathFiles,
759
- existingByFile,
760
- pathFileTargets,
761
- pathBlock: config.pathBlock,
762
- bashLoginOverride,
763
- });
764
- const { replacementsByTarget, loginOverrideWritten } = writePlan;
765
- // A `.bash_profile` created here takes over from an existing `~/.profile`,
766
- // so it leads with the passthrough that keeps sourcing it.
767
- if (
768
- bashLoginFile?.seedsProfilePassthrough === true &&
769
- writePlan.appendPathFiles.includes(bashLoginFile.file)
770
- ) {
771
- pushBlock(bashLoginFile.file, BASH_PROFILE_PASSTHROUGH);
772
- }
773
- for (const filePath of writePlan.appendPathFiles) {
774
- pushBlock(filePath, config.pathBlock);
775
- }
776
- const pathWritten = writePlan.appendPathFiles.length > 0;
777
-
778
- yield* Effect.forEach(
779
- pathStatusLines({
780
- pathWritten,
781
- pathReplaced: replacementsByTarget.size > 0,
782
- renderedBinDir: tildify(binDir, os.homedir),
783
- }),
784
- step
785
- );
786
-
787
- const completionWrite = planCompletionWrite({
788
- shell,
789
- completionsRequested: params.completions,
790
- completionBlock: config.completionBlock,
791
- completionFile: config.completionFile,
792
- existingCompletionFile: existingByFile.get(config.completionFile) ?? '',
793
- homedir: os.homedir,
794
- });
795
- if (completionWrite.append && config.completionBlock) {
796
- pushBlock(config.completionFile, config.completionBlock);
797
- }
798
- yield* step(completionWrite.statusLine);
799
-
800
- // Reconcile stale managed blocks first so any completion append below
801
- // (which re-reads from disk) lands on top of the replaced contents.
802
- yield* writeReconciledTargets({
803
- replacementsByTarget,
804
- fs,
805
- homedir: os.homedir,
806
- report: success,
807
- });
808
-
809
- yield* appendQueuedBlocks({
810
- blocksByFile,
811
- pathFileTargets,
812
- fs,
813
- path,
814
- homedir: os.homedir,
815
- report: success,
816
- });
817
-
818
- const changesWritten = blocksByFile.size > 0 || replacementsByTarget.size > 0;
819
- if (!changesWritten) {
820
- yield* success('Shell integration already configured — nothing to do.');
821
- }
822
-
823
- if (changesWritten && !installerOwnsFinalMessaging) {
824
- yield* note(
825
- restartHintBody({
826
- shell,
827
- zshPathFile: config.pathFiles[0]!,
828
- bashrc: path.join(os.homedir, '.bashrc'),
829
- bashLoginOverride,
830
- loginOverrideWritten,
831
- homedir: os.homedir,
832
- }),
833
- 'Restart your shell to apply changes'
834
- );
835
- }
836
-
837
- yield* ui.outro('Done');
838
- });
839
-
840
-// ---------------------------------------------------------------------------
841
-// Command
842
-// ---------------------------------------------------------------------------
843
-
844
-/**
845
- * CLI command to set up shell integration (PATH and completions).
846
- *
847
- * The directory added to `PATH` is `COMPOSIO_BIN_DIR` when set — the documented
848
- * override an installer hands to this command — then `~/.local/bin` when its
849
- * `composio` entry point is this executable, then the running binary's own
850
- * directory.
851
- *
852
- * @example
853
- * ```bash
854
- * composio install
855
- * composio install --completions
856
- * composio install --no-completions
857
- * composio install --shell zsh
858
- * COMPOSIO_BIN_DIR=~/.local/bin composio install
859
- * ```
860
- */
861
-export const installCmd = Command.make(
862
- 'install',
863
- { completions: completionsOpt, noCompletions: noCompletionsOpt, shell: shellOpt },
864
- ({ completions, noCompletions, shell }) =>
865
- installShellIntegration({
866
- completions: completions && !noCompletions,
867
- shell: Option.getOrUndefined(shell),
868
- })
869
-).pipe(
870
- Command.withDescription(
871
- 'Set up shell integration (PATH and completions). Set COMPOSIO_BIN_DIR to choose the directory added to PATH; it otherwise defaults to ~/.local/bin when that holds this executable, and to the directory of the running binary.'
872
- )
873
-);