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 339 lines 14.3 KB
Raw
1 /**
2 * Shell startup files and the managed blocks `composio install` keeps in them: which shell is
3 * running, which rc files it reads, the exact PATH and completion blocks to write, and how a
4 * stale block is reconciled in place.
5 *
6 * install.sh carries an inline copy of the same contract for when the CLI cannot run. The
7 * shared fixtures under test/managed-block-fixtures pin both implementations to byte-identical
8 * output, so a behavioral edit here must land in install.sh too.
9 */
10 import * as FileSystem from 'effect/FileSystem';
11 import * as Path from 'effect/Path';
12 import type { PlatformError } from 'effect/PlatformError';
13 import { Array as Arr, Effect, Option } from 'effect';
14 import { atomicWriteFileString } from 'src/utils/atomic-write';
15
16 export const SHELLS = ['zsh', 'bash', 'fish'] as const;
17
18 export type Shell = (typeof SHELLS)[number];
19
20 export interface ShellConfig {
21 readonly shell: Shell;
22 readonly pathFiles: readonly string[];
23 readonly completionFile: string;
24 readonly pathBlock: string;
25 readonly completionBlock: Option.Option<string>;
26 }
27
28 export const MARKER = '# Composio CLI';
29 export const COMPLETIONS_MARKER = '# Composio CLI completions';
30
31 /**
32 * Reject bin-dir paths that cannot be embedded safely in a managed rc line.
33 *
34 * The resolved dir is only ever emitted inside double quotes — `export
35 * PATH="<dir>:$PATH"` for bash/zsh and `set --export PATH "<dir>" $PATH` for
36 * fish — so the set is deliberately narrow and mirrors `is_unsafe_path` in
37 * install.sh, keeping the inline fallback and this command on one contract:
38 *
39 * - `` ` ``, `$`, `\`, `"`: the only characters bash and zsh still expand
40 * inside double quotes (`!` history expansion does not apply to sourced
41 * files). fish expands a strict subset of those. Everything else — `;`, `|`,
42 * `&`, `(`, `)`, `'` — is literal there, so a path like
43 * `/Users/o'brien/.composio` is written verbatim rather than rejected.
44 * - `\n`, `\r`: structural, not a quoting concern — either would split the
45 * managed block into extra rc lines.
46 * - `:`: structural too, as the PATH separator: a dir containing one would
47 * silently prepend more than one entry.
48 */
49 const UNSAFE_PATH_CHARS = /[`$"\\\n\r:]/;
50 export const isUnsafePath = (p: string): boolean => UNSAFE_PATH_CHARS.test(p);
51
52 /** The supported shell named by `$SHELL`'s basename, if any. */
53 export const detectShellFromEnv = (path: Path.Path, shellEnv: string): Option.Option<Shell> => {
54 const base = path.basename(shellEnv);
55 return Arr.findFirst(SHELLS, shell => shell === base);
56 };
57
58 /**
59 * Render a path for embedding in a shell rc file. `~` never expands inside
60 * double quotes, so home-relative paths use a literal `$HOME` prefix instead.
61 * Must stay in lockstep with install.sh's render_bin_dir: the installer's
62 * delegated_setup_verified compares its own rendering against the line this
63 * command wrote byte for byte, so any disagreement makes every delegated
64 * install look stale and forces a needless inline rewrite.
65 */
66 export const renderWithHome = (dir: string, homedir: string): string => {
67 if (dir === homedir) return '$HOME';
68 if (dir.startsWith(`${homedir}/`)) return `$HOME/${dir.slice(homedir.length + 1)}`;
69 return dir;
70 };
71
72 export const pathBlockForShell = (shell: Shell, binDir: string, homedir: string): string => {
73 const rendered = renderWithHome(binDir, homedir);
74 return shell === 'fish'
75 ? [MARKER, `set --export PATH "${rendered}" $PATH`].join('\n')
76 : [MARKER, `export PATH="${rendered}:$PATH"`].join('\n');
77 };
78
79 /**
80 * The bash startup file a login shell reads the managed PATH block from, and
81 * whether creating it means taking over from an existing `~/.profile`.
82 */
83 export interface BashLoginFile {
84 readonly file: string;
85 readonly seedsProfilePassthrough: boolean;
86 }
87
88 /**
89 * Preamble for a `~/.bash_profile` this command creates. A login bash reads
90 * `/etc/profile` and then only the first existing of `.bash_profile`,
91 * `.bash_login`, `.profile`, so a newly created `.bash_profile` shadows a
92 * `.profile` the shell read until now. Sourcing it back keeps that content —
93 * including the Debian-style `.profile` that itself sources `.bashrc` — while
94 * leaving `.profile` (shared with every other POSIX shell) untouched.
95 */
96 export const BASH_PROFILE_PASSTHROUGH = [
97 '# Created by the Composio CLI installer.',
98 '# Bash reads this file instead of ~/.profile in login shells.',
99 'if [ -f "$HOME/.profile" ]; then',
100 ' . "$HOME/.profile"',
101 'fi',
102 ].join('\n');
103
104 /**
105 * Resolve the bash startup file that login-mode bash reads.
106 *
107 * Login bash never reads `.bashrc` — macOS Terminal.app starts exactly such a
108 * shell — so the PATH block has to reach a login-mode file too. An existing
109 * override (`.bash_profile`, then `.bash_login`) is reused; when neither
110 * exists, `.bash_profile` is created rather than writing the shared
111 * `.profile`, which a `.bash_profile` would shadow anyway.
112 */
113 export const resolveBashLoginFile = (
114 path: Path.Path,
115 homedir: string,
116 fs: FileSystem.FileSystem
117 ): Effect.Effect<BashLoginFile, PlatformError> =>
118 Effect.gen(function* () {
119 const bashProfile = path.join(homedir, '.bash_profile');
120 if (yield* fs.exists(bashProfile)) {
121 return { file: bashProfile, seedsProfilePassthrough: false };
122 }
123 const bashLogin = path.join(homedir, '.bash_login');
124 if (yield* fs.exists(bashLogin)) {
125 return { file: bashLogin, seedsProfilePassthrough: false };
126 }
127 const profileExists = yield* fs.exists(path.join(homedir, '.profile'));
128 return { file: bashProfile, seedsProfilePassthrough: profileExists };
129 });
130
131 /** Bash always configures both files: `.bashrc` for interactive shells, the login file for login shells. */
132 export const pathFilesForShell = (
133 path: Path.Path,
134 shell: Shell,
135 homedir: string,
136 bashLoginFile: string | undefined
137 ): string[] => {
138 switch (shell) {
139 case 'zsh':
140 return [path.join(homedir, '.zshrc')];
141 case 'fish':
142 return [path.join(homedir, '.config', 'fish', 'config.fish')];
143 case 'bash': {
144 // Bash is the only shell here that splits startup files by mode: an
145 // interactive non-login shell reads .bashrc, while a login shell (ssh,
146 // macOS Terminal.app) reads only its login files. Writing .bashrc alone
147 // would leave PATH unset in login shells whenever an override file
148 // shadows .profile, so the block lands in both. The override also stays
149 // a named value because the restart hint reports it separately.
150 const bashrc = path.join(homedir, '.bashrc');
151 return bashLoginFile ? [bashrc, bashLoginFile] : [bashrc];
152 }
153 }
154 };
155
156 export const buildShellConfig = (
157 path: Path.Path,
158 shell: Shell,
159 pathFiles: readonly string[],
160 binDir: string,
161 completionScript: Option.Option<string>,
162 homedir: string
163 ): ShellConfig => ({
164 shell,
165 pathFiles,
166 completionFile:
167 shell === 'fish'
168 ? path.join(homedir, '.config', 'fish', 'completions', 'composio.fish')
169 : pathFiles[0]!,
170 pathBlock: pathBlockForShell(shell, binDir, homedir),
171 completionBlock: Option.map(completionScript, script => `${COMPLETIONS_MARKER}\n${script}`),
172 });
173
174 /**
175 * Check whether a file already contains a given marker line. Byte-exact, like
176 * install.sh's awk `$0 == "# Composio CLI"` match: a marker mangled by CRLF
177 * endings or stray whitespace is not ours and is left alone on both sides.
178 */
179 export const fileContains = (contents: string, marker: string): boolean =>
180 contents.split('\n').some(line => line === marker);
181
182 /** Outcome of reconciling a startup file's managed PATH block against the resolved bin dir. */
183 export type ManagedPathBlockState =
184 | { readonly state: 'absent' }
185 | { readonly state: 'current' }
186 | { readonly state: 'stale'; readonly reconciled: string };
187
188 /**
189 * A line this installer could have written as the managed PATH assignment:
190 * POSIX `export PATH="<dir>:$PATH"` or fish `set --export PATH "<dir>" $PATH`.
191 * Matched structurally on the prefix/suffix (any bin dir) so stale blocks
192 * recording another directory are still recognized as ours.
193 */
194 const isManagedPathAssignment = (line: string): boolean => {
195 const trimmed = line.trim();
196 return (
197 (trimmed.startsWith('export PATH="') && trimmed.endsWith(':$PATH"')) ||
198 (trimmed.startsWith('set --export PATH "') && trimmed.endsWith('" $PATH'))
199 );
200 };
201
202 const LEGACY_POSIX_INSTALL_DIR_PREFIX = 'export COMPOSIO_INSTALL_DIR="';
203 const LEGACY_FISH_INSTALL_DIR_PREFIX = 'set --export COMPOSIO_INSTALL_DIR "';
204
205 /**
206 * The install-dir assignment the previously released installer wrote as the
207 * second line of its three-line managed block: POSIX
208 * `export COMPOSIO_INSTALL_DIR="<dir>"` or fish
209 * `set --export COMPOSIO_INSTALL_DIR "<dir>"`. Matched structurally on the
210 * prefix/quotes (any dir), like `isManagedPathAssignment`.
211 */
212 const isQuotedAssignment = (line: string, prefix: string): boolean =>
213 line.startsWith(prefix) && line.endsWith('"') && line.length > prefix.length;
214
215 const isLegacyInstallDirAssignment = (line: string): boolean => {
216 const trimmed = line.trim();
217 return (
218 isQuotedAssignment(trimmed, LEGACY_POSIX_INSTALL_DIR_PREFIX) ||
219 isQuotedAssignment(trimmed, LEGACY_FISH_INSTALL_DIR_PREFIX)
220 );
221 };
222
223 /**
224 * True when `first` and `second` are the two export lines of the legacy
225 * three-line block, in the same shell dialect. The closing PATH line is
226 * matched byte-for-byte (modulo surrounding whitespace) against the exact
227 * text the legacy installer emitted, so anything else after an install-dir
228 * assignment is user content and stays untouched.
229 */
230 const isLegacyManagedPair = (first: string, second: string): boolean => {
231 if (!isLegacyInstallDirAssignment(first)) return false;
232 const secondTrimmed = second.trim();
233 return first.trim().startsWith(LEGACY_POSIX_INSTALL_DIR_PREFIX)
234 ? secondTrimmed === 'export PATH="$COMPOSIO_INSTALL_DIR:$PATH"'
235 : secondTrimmed === 'set --export PATH $COMPOSIO_INSTALL_DIR $PATH';
236 };
237
238 /**
239 * Append managed blocks after existing content, separated by one blank line
240 * and ending with a newline. Content lacking a final newline gains one first,
241 * exactly as install.sh's line-based awk rewrite normalizes it.
242 */
243 export const appendManagedBlocks = (contents: string, blocks: readonly string[]): string => {
244 const base = contents === '' || contents.endsWith('\n') ? contents : `${contents}\n`;
245 return `${base}\n${blocks.join('\n\n')}\n`;
246 };
247
248 /**
249 * Reconcile the managed PATH block — the `MARKER` line plus the PATH
250 * assignment right below it — with the currently resolved bin directory.
251 *
252 * This mirrors install.sh's write_path_block awk program step for step, and
253 * the shared fixtures under test/managed-block-fixtures pin both
254 * implementations to byte-identical outputs — any behavioral edit here must
255 * land in install.sh too. A file whose single byte-exact marker is directly
256 * followed by the expected assignment is current and left untouched.
257 * Otherwise every managed line — each marker, plus the next line only when it
258 * is a recognizable managed PATH assignment, or the next two lines when they
259 * are the exact export pair of the legacy three-line block (marker,
260 * `export COMPOSIO_INSTALL_DIR=...`, PATH line, in POSIX or fish form);
261 * anything else (a user annotation, a blank line, another marker) is not
262 * ours to delete — is removed and one fresh block is appended after the
263 * remaining content. No
264 * user content is ever deleted, and because these prepend-style assignments
265 * make the last-sourced line win, the new bin dir takes PATH precedence over
266 * any orphaned stale assignment that had to be preserved.
267 */
268 export const reconcileManagedPathBlock = (
269 contents: string,
270 pathBlock: string
271 ): ManagedPathBlockState => {
272 const lines = contents.split('\n');
273 const markerIndexes = lines.flatMap((line, index) => (line === MARKER ? [index] : []));
274 const firstMarkerIndex = markerIndexes[0];
275 if (firstMarkerIndex === undefined) return { state: 'absent' };
276
277 const blockLines = pathBlock.split('\n');
278 if (markerIndexes.length === 1 && lines[firstMarkerIndex + 1] === blockLines[1]) {
279 return { state: 'current' };
280 }
281
282 // Managed lines: each marker line, plus the next line only when it is a
283 // recognizable managed PATH assignment, or the next two lines when they are
284 // the exact export pair of the legacy three-line block — anything else is
285 // not ours to delete.
286 const managedLineIndexes = new Set<number>(
287 markerIndexes.flatMap(markerIndex => {
288 const assignment = lines[markerIndex + 1];
289 if (assignment === undefined) return [markerIndex];
290 if (isManagedPathAssignment(assignment)) return [markerIndex, markerIndex + 1];
291 const legacyPathLine = lines[markerIndex + 2];
292 if (legacyPathLine !== undefined && isLegacyManagedPair(assignment, legacyPathLine)) {
293 return [markerIndex, markerIndex + 1, markerIndex + 2];
294 }
295 return [markerIndex];
296 })
297 );
298
299 // Like the awk rewrite, kept content is a sequence of newline-terminated
300 // lines: drop the split's trailing sentinel and re-terminate the last line.
301 const keptLines = lines.filter((_, index) => !managedLineIndexes.has(index));
302 const contentLines = keptLines[keptLines.length - 1] === '' ? keptLines.slice(0, -1) : keptLines;
303 const kept = contentLines.length === 0 ? '' : contentLines.join('\n') + '\n';
304 return { state: 'stale', reconciled: appendManagedBlocks(kept, [pathBlock]) };
305 };
306
307 /** The file's contents, or an empty string when it does not exist yet. */
308 export const readMaybeMissingFile = (
309 filePath: string,
310 fs: FileSystem.FileSystem
311 ): Effect.Effect<string, PlatformError> =>
312 fs
313 .readFileString(filePath)
314 .pipe(
315 Effect.catch(e =>
316 Effect.logDebug('File does not exist yet, will create:', e).pipe(Effect.as(''))
317 )
318 );
319
320 /** Resolve valid symlink chains so atomic writes update the target instead of replacing the link. */
321 export const resolveWriteTarget = (
322 filePath: string,
323 fs: FileSystem.FileSystem
324 ): Effect.Effect<string, PlatformError> =>
325 fs.readLink(filePath).pipe(
326 Effect.flatMap(() => fs.realPath(filePath)),
327 Effect.catch(() => Effect.succeed(filePath))
328 );
329
330 /**
331 * Replace an rc file's contents via the shared atomic-write helper, preserving
332 * the existing file's mode so a private rc stays private across the rewrite.
333 */
334 export const replaceFilePreservingMode = (
335 fs: FileSystem.FileSystem,
336 target: string,
337 contents: string
338 ): Effect.Effect<void, PlatformError> =>
339 atomicWriteFileString({ fs, target, contents, preserveMode: true });