@devries-cameron20 / composio Mirror · read-only / commits / 2d868cf88
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, 08:30 UTC

refactor(cli): split `install` into the command directory shape (#4968)

This PR: - moves shell detection, rc-file selection, and the managed PATH/completion blocks from `install.cmd.ts` into `src/services/shell-config.ts`; `install.sh` comments now point there - splits the 873-line `install.cmd.ts` into `install/install.{cmd,handler,format,errors}.ts`; `ShellSetupAbortError` keeps its tag and its exit-1 contract with `install.sh` - replaces loops and if-chains with `Effect.forEach`, `Option.match` and a tagged `CompletionPlan` - moves `install.cmd.test.ts` to `test/src/commands/install/` unchanged and adds `install.handler.test.ts` (13 exact-stderr cases) and `shell-config.test.ts` (33) - unit U7 of the CLI command-layout series; no user-visible change, so no CHANGELOG entry ## Context Verified: `pnpm --filter @composio/cli test` (1944 passed), root `pnpm typecheck`, `lint:effect`, oxlint. Binaries built from `origin/next` and this branch give identical stdout, stderr, exit codes and rc files across 44 install scenarios (TTY and piped, every shell, outdated/legacy blocks, abort paths). Hermetic install E2E passes locally on a linux-arm64 fixture for zsh, bash and fish; the x64 workflow runs here in CI.

Alberto Schiabel committed Oct 20, 2026 at 01:34 UTC 2d868cf88ce485db7076222aaa81045e524dddb7
13 files changed +1618 -883
install.sh
+2 -2
@@ -400,7 +400,7 @@ compute_inherited_resolution() {
400 # is only ever emitted inside double quotes -- `export PATH="<dir>:$PATH"` for
401 # bash/zsh and `set --export PATH "<dir>" $PATH` for fish -- so the set is
402 # deliberately narrow and mirrors UNSAFE_PATH_CHARS in
403 -# ts/packages/cli/src/commands/install.cmd.ts, keeping this inline fallback and
403 +# ts/packages/cli/src/services/shell-config.ts, keeping this inline fallback and
404 # `composio install` on one contract:
405 #
406 # ` $ " \ the only characters bash and zsh still expand inside double
@@ -424,7 +424,7 @@ is_unsafe_path() {
424 }
425
426 # Renders the home directory itself and paths under it with a literal $HOME
427 -# prefix. Must stay in lockstep with the CLI's renderWithHome (install.cmd.ts):
427 +# prefix. Must stay in lockstep with the CLI's renderWithHome (shell-config.ts):
428 # delegated_setup_verified compares the CLI-written line against this rendering
429 # byte for byte, so any disagreement makes every delegated install look stale
430 # and forces a needless inline rewrite.
ts/packages/cli/src/cli-main.ts
+1 -1
@@ -54,7 +54,7 @@ import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overri
54 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
55 import { PendingLoginSession } from 'src/services/pending-login-session';
56 import { SetupCommandError } from 'src/services/setup-command-error';
57 -import { ShellSetupAbortError } from 'src/commands/install.cmd';
57 +import { ShellSetupAbortError } from 'src/commands/install/install.errors';
58 import { isUsageFailure, type UsageFailure } from 'src/commands/errors';
59 import { cliInvocationContext } from 'src/services/runtime-cli-context';
60 import { readTelemetryDebugOverride, telemetryDebugModeLayer } from 'src/services/runtime-flags';
ts/packages/cli/src/commands/index.ts
+1 -1
@@ -13,7 +13,7 @@ import { logoutCmd } from './logout.cmd';
13 import { runCmd } from './run.cmd';
14 import { proxyCmd } from './proxy.cmd';
15 import { artifactsCmd } from './artifacts.cmd';
16 -import { installCmd } from './install.cmd';
16 +import { installCmd } from './install/install.cmd';
17 import { generateCmd } from './generate/generate.cmd';
18 import { buildDevCommand } from './dev.cmd';
19 import { ExecuteInvocationArgs } from './tools/commands/tools.execute.cmd';
ts/packages/cli/src/commands/install.cmd.ts deleted
-873
@@ -1,873 +0,0 @@
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 -);
ts/packages/cli/src/commands/install/install.cmd.ts new
+45
@@ -0,0 +1,45 @@
1 +import { Command, Flag } from 'effect/cli';
2 +import { SHELLS } from 'src/services/shell-config';
3 +import { runInstall } from './install.handler';
4 +
5 +const completionsOpt = Flag.Boolean('completions').pipe(
6 + Flag.withDescription('Install shell completions.'),
7 + Flag.withDefault(false)
8 +);
9 +
10 +const noCompletionsOpt = Flag.Boolean('no-completions').pipe(
11 + Flag.withDescription('Deprecated: shell completions are skipped by default.'),
12 + Flag.withDefault(false)
13 +);
14 +
15 +const shellOpt = Flag.Literals('shell', SHELLS).pipe(
16 + Flag.withDescription('Override automatic shell detection.'),
17 + Flag.optional
18 +);
19 +
20 +/**
21 + * CLI command to set up shell integration (PATH and completions).
22 + *
23 + * The directory added to `PATH` is `COMPOSIO_BIN_DIR` when set — the documented
24 + * override an installer hands to this command — then `~/.local/bin` when its
25 + * `composio` entry point is this executable, then the running binary's own
26 + * directory.
27 + *
28 + * @example
29 + * ```bash
30 + * composio install
31 + * composio install --completions
32 + * composio install --no-completions
33 + * composio install --shell zsh
34 + * COMPOSIO_BIN_DIR=~/.local/bin composio install
35 + * ```
36 + */
37 +export const installCmd = Command.make(
38 + 'install',
39 + { completions: completionsOpt, noCompletions: noCompletionsOpt, shell: shellOpt },
40 + runInstall
41 +).pipe(
42 + Command.withDescription(
43 + '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.'
44 + )
45 +);
ts/packages/cli/src/commands/install/install.errors.ts new
+12
@@ -0,0 +1,12 @@
1 +import { Data } from 'effect';
2 +
3 +/**
4 + * Aborted shell setup must fail the process: install.sh only runs its guarded
5 + * inline PATH fallback when `composio install` exits non-zero, so a successful
6 + * exit here would leave the user with no PATH setup and a green install. The
7 + * abort reason is already printed before this error is raised; cli-main.ts
8 + * maps it to exit code 1 without printing anything further.
9 + */
10 +export class ShellSetupAbortError extends Data.TaggedError('commands/ShellSetupAbortError')<{
11 + readonly message: string;
12 +}> {}
ts/packages/cli/src/commands/install/install.format.ts new
+148
@@ -0,0 +1,148 @@
1 +import { Data } from 'effect';
2 +import type { Effect } from 'effect';
3 +import type { Shell } from 'src/services/shell-config';
4 +import type { TerminalUI } from 'src/services/terminal-ui';
5 +
6 +// `composio install` writes nothing to stdout: every line is a report on stderr of what it
7 +// changed on disk.
8 +
9 +export const INSTALL_INTRO = 'composio install';
10 +export const DONE_OUTRO = 'Done';
11 +export const ABORTED_OUTRO = 'Aborted.';
12 +export const MANUAL_SETUP_OUTRO = 'Manual setup required.';
13 +
14 +export const BIN_DIR_NOT_ABSOLUTE_MESSAGE = 'Resolved bin directory must be an absolute path.';
15 +export const BIN_DIR_UNSAFE_MESSAGE =
16 + 'Resolved bin directory contains unsafe characters and cannot be written to shell config.';
17 +
18 +export const SHELL_NOT_DETECTED_MESSAGE =
19 + 'Could not detect your shell. Manually add the following to your shell config:';
20 +export const MANUAL_PATH_SETUP_TITLE = 'PATH setup';
21 +export const ALREADY_CONFIGURED_MESSAGE = 'Shell integration already configured — nothing to do.';
22 +export const RESTART_HINT_TITLE = 'Restart your shell to apply changes';
23 +
24 +export const tildify = (p: string, homedir: string): string =>
25 + p.startsWith(homedir + '/') ? `~/${p.slice(homedir.length + 1)}` : p;
26 +
27 +/**
28 + * With no shell there is no rc file to write, so the current process's `$PATH` is all the
29 + * evidence available. It says nothing about future shells, hence the deliberately hedged wording.
30 + */
31 +export const alreadyOnPathMessage = (binDir: string, homedir: string) =>
32 + `PATH: ${tildify(binDir, homedir)} is already on $PATH in this process, and no shell config file could be identified — nothing to update.`;
33 +
34 +/** The line a user without a detected shell adds by hand; `renderedBinDir` is `$HOME`-relative. */
35 +export const manualPathSetupLine = (renderedBinDir: string) =>
36 + `export PATH="${renderedBinDir}:$PATH"`;
37 +
38 +export const detectedShellMessage = (shell: Shell) => `Detected shell: ${shell}`;
39 +
40 +export const updatedFileMessage = (filePath: string, homedir: string) =>
41 + `Updated ${tildify(filePath, homedir)}`;
42 +
43 +/** Status lines summarizing the planned PATH work, in print order. */
44 +export const pathStatusLines = (params: {
45 + readonly pathWritten: boolean;
46 + readonly pathReplaced: boolean;
47 + readonly renderedBinDir: string;
48 +}): readonly string[] => {
49 + const lines = [
50 + ...(params.pathWritten ? [`PATH: will add ${params.renderedBinDir} to $PATH`] : []),
51 + ...(params.pathReplaced
52 + ? [`PATH: will update the managed block to ${params.renderedBinDir}`]
53 + : []),
54 + ];
55 + return lines.length > 0 ? lines : ['PATH: already configured'];
56 +};
57 +
58 +/** What happens to shell completions, decided before anything is written. */
59 +export type CompletionPlan = Data.TaggedEnum<{
60 + /** zsh never gets a completion block. */
61 + SkippedForZsh: Record<never, never>;
62 + /** `--completions` was not passed, or `--no-completions` was. */
63 + NotRequested: Record<never, never>;
64 + /** The completion generator produced nothing for this shell. */
65 + Unavailable: Record<never, never>;
66 + /** The completion file already carries the completions marker. */
67 + AlreadyConfigured: Record<never, never>;
68 + /** Append `block` to the completion file. */
69 + Install: { readonly block: string };
70 +}>;
71 +export const CompletionPlan = Data.taggedEnum<CompletionPlan>();
72 +
73 +/** The completions status line for `plan`. */
74 +export const completionStatusLine = (
75 + plan: CompletionPlan,
76 + params: { readonly shell: Shell; readonly completionFile: string; readonly homedir: string }
77 +): string =>
78 + CompletionPlan.$match(plan, {
79 + SkippedForZsh: () => 'Completions: skipped for zsh',
80 + NotRequested: () => 'Completions: skipped by default (pass --completions to enable)',
81 + Unavailable: () => 'Completions: not available for this shell',
82 + AlreadyConfigured: () => 'Completions: already configured',
83 + Install: () =>
84 + params.shell === 'fish'
85 + ? `Completions: will install fish completions to ${tildify(params.completionFile, params.homedir)}`
86 + : 'Completions: will install shell completions',
87 + });
88 +
89 +/** Shell-specific body of the restart hint printed after a change. */
90 +export const restartHintBody = (params: {
91 + readonly shell: Shell;
92 + readonly zshPathFile: string;
93 + readonly bashrc: string;
94 + readonly bashLoginOverride: string | undefined;
95 + readonly loginOverrideWritten: boolean;
96 + readonly homedir: string;
97 +}): string => {
98 + switch (params.shell) {
99 + case 'fish':
100 + return 'exec fish';
101 + case 'zsh':
102 + return `source ${tildify(params.zshPathFile, params.homedir)}`;
103 + case 'bash': {
104 + const sourceLine = `source ${tildify(params.bashrc, params.homedir)}`;
105 + return params.loginOverrideWritten && params.bashLoginOverride
106 + ? [
107 + sourceLine,
108 + `${tildify(params.bashLoginOverride, params.homedir)} was also updated — that entry applies to new login shells too.`,
109 + ].join('\n')
110 + : sourceLine;
111 + }
112 + }
113 +};
114 +
115 +/** The stderr writers `composio install` reports through. */
116 +export interface InstallReporter {
117 + readonly step: (message: string) => Effect.Effect<void>;
118 + readonly success: (message: string) => Effect.Effect<void>;
119 + readonly warn: (message: string) => Effect.Effect<void>;
120 + readonly failure: (message: string) => Effect.Effect<void>;
121 + readonly note: (body: string, title: string) => Effect.Effect<void>;
122 +}
123 +
124 +/**
125 + * Everything this command prints is a report of what it changed on disk, so
126 + * it has to reach the user even when stderr is not a terminal: install.sh
127 + * runs it as a subprocess, and container/CI installs pipe the whole session
128 + * to a build log. Decoration stays the interactive default; `ui.error`
129 + * writes the same text unformatted when there is nothing to decorate.
130 + */
131 +export const makeInstallReporter = (ui: TerminalUI, canDecorate: boolean): InstallReporter => {
132 + const plain = (prefix: string) => (message: string) => ui.error(`${prefix}${message}`);
133 + return canDecorate
134 + ? {
135 + step: ui.log.step,
136 + success: ui.log.success,
137 + warn: ui.log.warn,
138 + failure: ui.log.error,
139 + note: (body, title) => ui.note(body, title),
140 + }
141 + : {
142 + step: ui.error,
143 + success: ui.error,
144 + warn: plain('warning: '),
145 + failure: plain('error: '),
146 + note: (body, title) => ui.error(`${title}:\n${body}`),
147 + };
148 +};
ts/packages/cli/src/commands/install/install.handler.ts new
+531
@@ -0,0 +1,531 @@
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 + // Resolve the entry-point bin dir: explicit env, then a ~/.local/bin/composio
469 + // that is this executable, then the runtime executable's own directory.
470 + const envBinDir = yield* APP_CONFIG.BIN_DIR.pipe(Effect.orDie);
471 + const localBinDir = path.join(os.homedir, '.local', 'bin');
472 + const execPath = nodeProcess.execPath;
473 + const localBinComposioIsCurrentExecutable = yield* resolvesToCurrentExecutable(
474 + path.join(localBinDir, 'composio'),
475 + execPath,
476 + fs
477 + );
478 + const binDir = path.normalize(
479 + resolveBinDir({
480 + envBinDir,
481 + localBinDir,
482 + localBinComposioIsCurrentExecutable,
483 + execPath,
484 + path,
485 + })
486 + );
487 +
488 + yield* Option.match(unusableBinDirReason(path, binDir), {
489 + onNone: () => Effect.void,
490 + onSome: message => abortShellSetup(report, message),
491 + });
492 +
493 + // The installer owns the closing message: when install.sh delegates to
494 + // this command it passes COMPOSIO_CLI_INVOCATION_ORIGIN=installer and
495 + // prints the final action block itself. Keep the concise per-file status
496 + // lines but suppress the boxed restart hint so the CLI never prints a
497 + // competing instruction.
498 + const invocationOrigin = yield* APP_CONFIG.CLI_INVOCATION_ORIGIN.pipe(Effect.orDie);
499 + const installerOwnsFinalMessaging = invocationOrigin === 'installer';
500 +
501 + const host = yield* Effect.orDie(
502 + Config.all({ shell: HOST_CONFIG.SHELL, path: HOST_CONFIG.PATH })
503 + );
504 + const shell = Option.fromUndefinedOr(params.shell).pipe(
505 + Option.orElse(() => detectShellFromEnv(path, host.shell ?? ''))
506 + );
507 +
508 + yield* Option.match(shell, {
509 + onNone: () =>
510 + reportUndetectedShell({
511 + report,
512 + binDir,
513 + binDirOnPath: isDirOnPath(host.path ?? '', binDir),
514 + }),
515 + onSome: detected =>
516 + configureShell({
517 + shell: detected,
518 + binDir,
519 + completions: params.completions,
520 + installerOwnsFinalMessaging,
521 + report,
522 + }),
523 + });
524 + });
525 +
526 +/** `--no-completions` wins over `--completions`. */
527 +export const runInstall = ({ completions, noCompletions, shell }: InstallParams) =>
528 + installShellIntegration({
529 + completions: completions && !noCompletions,
530 + shell: Option.getOrUndefined(shell),
531 + });
ts/packages/cli/src/services/shell-config.ts new
+339
@@ -0,0 +1,339 @@
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 });
ts/packages/cli/test/src/commands/install/install.cmd.test.ts renamed
+3 -5
@@ -5,11 +5,9 @@ import { describe, expect, layer } from '@effect/vitest';
5 import { Effect, Exit } from 'effect';
6 import * as FileSystem from 'effect/FileSystem';
7 import { NodeOs } from 'src/services/node-os';
8 -import {
9 - installShellIntegration,
10 - ShellSetupAbortError,
11 - type Shell,
12 -} from 'src/commands/install.cmd';
8 +import { ShellSetupAbortError } from 'src/commands/install/install.errors';
9 +import { installShellIntegration } from 'src/commands/install/install.handler';
10 +import type { Shell } from 'src/services/shell-config';
11 import { makeTerminalUI } from 'src/services/terminal-ui';
12 import { cli, TestLive, MockConsole } from 'test/__utils__';
13 import { liveEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
ts/packages/cli/test/src/commands/install/install.handler.test.ts new
+389
@@ -0,0 +1,389 @@
1 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 +import * as BunPath from '@effect/platform-bun/BunPath';
3 +import { describe, expect, it } from '@effect/vitest';
4 +import { ConfigProvider, Effect, Layer, Option } from 'effect';
5 +import * as FileSystem from 'effect/FileSystem';
6 +import path from 'node:path';
7 +import { Writable } from 'node:stream';
8 +import * as tempy from 'tempy';
9 +import { ShellSetupAbortError } from 'src/commands/install/install.errors';
10 +import {
11 + BIN_DIR_NOT_ABSOLUTE_MESSAGE,
12 + BIN_DIR_UNSAFE_MESSAGE,
13 +} from 'src/commands/install/install.format';
14 +import { installShellIntegration, runInstall } from 'src/commands/install/install.handler';
15 +import { CliUserConfig } from 'src/models/cli-user-config';
16 +import { ComposioCliUserConfig } from 'src/services/cli-user-config';
17 +import { defaultNodeOs, NodeOs } from 'src/services/node-os';
18 +import { NodeProcess } from 'src/services/node-process';
19 +import { getTerminalCapabilities, makeTerminalUI, TerminalUI } from 'src/services/terminal-ui';
20 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
21 +
22 +const BIN_DIR = '/opt/composio/bin';
23 +
24 +const cliUserConfig = ComposioCliUserConfig.of({
25 + data: {
26 + channel: 'stable',
27 + developerModeEnabled: false,
28 + developerDangerousCommandsEnabled: false,
29 + experimentalFeatures: {},
30 + artifactDirectory: undefined,
31 + security: 'auto',
32 + },
33 + raw: CliUserConfig.make({
34 + developer: { enabled: false, destructiveActions: false },
35 + experimentalFeatures: {},
36 + artifactDirectory: Option.none(),
37 + security: 'auto',
38 + }),
39 + channel: 'stable',
40 + isDevModeEnabled: () => false,
41 + areDeveloperDangerousCommandsEnabled: () => false,
42 + isExperimentalFeatureEnabled: () => false,
43 + update: () => Effect.void,
44 +});
45 +
46 +const makeSink = () => {
47 + const chunks: string[] = [];
48 + const sink = new Writable({
49 + write(chunk, _encoding, callback) {
50 + chunks.push(String(chunk));
51 + callback();
52 + },
53 + });
54 + return Object.assign(sink, { isTTY: false, chunks });
55 +};
56 +
57 +/**
58 + * What the install handler needs and nothing more: the real filesystem over a fresh home
59 + * directory, the running executable at `execPath`, the given environment, and a terminal
60 + * whose stderr is a pipe, so every report line is written plain and can be compared exactly.
61 + * Pass `ui` to swap the terminal out — e.g. for a recording UI that pins the decorated
62 + * (`canDecorate=true`) report channel.
63 + */
64 +const installTest = (
65 + params: {
66 + readonly env?: Record<string, string>;
67 + readonly execPath?: string;
68 + readonly ui?: Layer.Layer<TerminalUI>;
69 + } = {}
70 +) => {
71 + const home = tempy.temporaryDirectory({ prefix: 'install-handler' });
72 + const stderr = makeSink();
73 + const uiLayer =
74 + params.ui ??
75 + Layer.succeed(
76 + TerminalUI,
77 + makeTerminalUI({ stdin: { isTTY: false }, stdout: makeSink(), stderr })
78 + );
79 + const layer = Layer.mergeAll(
80 + BunFileSystem.layer,
81 + BunPath.layer,
82 + Layer.succeed(NodeOs, defaultNodeOs({ homedir: home })),
83 + Layer.succeed(
84 + NodeProcess,
85 + NodeProcess.of({
86 + cwd: home,
87 + execPath: params.execPath ?? `${BIN_DIR}/composio`,
88 + platform: 'linux',
89 + arch: 'x64',
90 + setExitCode: () => Effect.void,
91 + })
92 + ),
93 + uiLayer,
94 + Layer.succeed(ComposioCliUserConfig, cliUserConfig),
95 + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { PATH: '/usr/bin:/bin', ...params.env } }))
96 + );
97 + return {
98 + home,
99 + layer,
100 + /** Every stderr line written so far. */
101 + stderrLines: () => stderr.chunks.join('').split('\n').slice(0, -1),
102 + };
103 +};
104 +
105 +const readHomeFile = (home: string, file: string) =>
106 + Effect.gen(function* () {
107 + const fs = yield* FileSystem.FileSystem;
108 + return yield* fs.readFileString(path.join(home, file));
109 + });
110 +
111 +/**
112 + * A stderr-TTY terminal (`canDecorate=true`, the interactive default) that records where
113 + * `makeInstallReporter`'s decorated arm sends each report: status lines to `log.step`,
114 + * per-file confirmations to `log.success`, aborts to `log.error`, boxed hints to `note`,
115 + * and the plain `error` fallback never touched.
116 + */
117 +const decoratedInstallUI = () => {
118 + const calls = {
119 + step: [] as string[],
120 + success: [] as string[],
121 + warn: [] as string[],
122 + error: [] as string[],
123 + note: [] as [message: string, title: string | undefined][],
124 + plainError: [] as string[],
125 + };
126 + const ui = TerminalUI.of({
127 + ...terminalUITestImpl,
128 + capabilities: Effect.succeed(
129 + getTerminalCapabilities({
130 + stdin: { isTTY: false },
131 + stdout: { isTTY: false },
132 + stderr: { isTTY: true },
133 + })
134 + ),
135 + error: data => Effect.sync(() => calls.plainError.push(data)),
136 + log: {
137 + ...terminalUITestImpl.log,
138 + success: message => Effect.sync(() => calls.success.push(message)),
139 + warn: message => Effect.sync(() => calls.warn.push(message)),
140 + error: message => Effect.sync(() => calls.error.push(message)),
141 + step: message => Effect.sync(() => calls.step.push(message)),
142 + },
143 + note: (message, title) => Effect.sync(() => calls.note.push([message, title])),
144 + });
145 + return { calls, layer: Layer.succeed(TerminalUI, ui) };
146 +};
147 +
148 +describe('installShellIntegration', () => {
149 + it.effect('zsh: writes ~/.zshrc and prints the restart hint', () => {
150 + const { home, layer, stderrLines } = installTest({ env: { SHELL: '/bin/zsh' } });
151 + return Effect.gen(function* () {
152 + yield* installShellIntegration({ completions: false });
153 +
154 + expect(stderrLines()).toEqual([
155 + 'Detected shell: zsh',
156 + `PATH: will add ${BIN_DIR} to $PATH`,
157 + 'Completions: skipped for zsh',
158 + 'Updated ~/.zshrc',
159 + 'Restart your shell to apply changes:',
160 + 'source ~/.zshrc',
161 + ]);
162 + expect(yield* readHomeFile(home, '.zshrc')).toBe(
163 + `\n# Composio CLI\nexport PATH="${BIN_DIR}:$PATH"\n`
164 + );
165 + }).pipe(Effect.provide(layer));
166 + });
167 +
168 + it.effect('zsh: a second run reports the current block and writes nothing', () => {
169 + const { layer, stderrLines } = installTest({ env: { SHELL: '/bin/zsh' } });
170 + return Effect.gen(function* () {
171 + yield* installShellIntegration({ completions: false });
172 + const firstRun = stderrLines().length;
173 + yield* installShellIntegration({ completions: false });
174 +
175 + expect(stderrLines().slice(firstRun)).toEqual([
176 + 'Detected shell: zsh',
177 + 'PATH: already configured',
178 + 'Completions: skipped for zsh',
179 + 'Shell integration already configured — nothing to do.',
180 + ]);
181 + }).pipe(Effect.provide(layer));
182 + });
183 +
184 + it.effect(
185 + 'bash with an existing ~/.profile: the created ~/.bash_profile sources it and is reported first',
186 + () => {
187 + const { home, layer, stderrLines } = installTest({ env: { SHELL: '/bin/bash' } });
188 + return Effect.gen(function* () {
189 + const fs = yield* FileSystem.FileSystem;
190 + yield* fs.writeFileString(path.join(home, '.profile'), 'export FOO=1\n');
191 +
192 + yield* installShellIntegration({ completions: false });
193 +
194 + expect(stderrLines()).toEqual([
195 + 'Detected shell: bash',
196 + `PATH: will add ${BIN_DIR} to $PATH`,
197 + 'Completions: skipped by default (pass --completions to enable)',
198 + 'Updated ~/.bash_profile',
199 + 'Updated ~/.bashrc',
200 + 'Restart your shell to apply changes:',
201 + 'source ~/.bashrc',
202 + '~/.bash_profile was also updated — that entry applies to new login shells too.',
203 + ]);
204 + expect(yield* readHomeFile(home, '.bash_profile')).toMatch(
205 + /^\n# Created by the Composio CLI installer\.\n[\s\S]*\nfi\n\n# Composio CLI\n/
206 + );
207 + expect(yield* readHomeFile(home, '.profile')).toBe('export FOO=1\n');
208 + }).pipe(Effect.provide(layer));
209 + }
210 + );
211 +
212 + it.effect('fish with completions: PATH and completions land in their own files', () => {
213 + const { home, layer, stderrLines } = installTest({ env: { SHELL: '/usr/bin/fish' } });
214 + return Effect.gen(function* () {
215 + yield* installShellIntegration({ completions: true });
216 +
217 + expect(stderrLines()).toEqual([
218 + 'Detected shell: fish',
219 + `PATH: will add ${BIN_DIR} to $PATH`,
220 + 'Completions: will install fish completions to ~/.config/fish/completions/composio.fish',
221 + 'Updated ~/.config/fish/config.fish',
222 + 'Updated ~/.config/fish/completions/composio.fish',
223 + 'Restart your shell to apply changes:',
224 + 'exec fish',
225 + ]);
226 + expect(yield* readHomeFile(home, '.config/fish/completions/composio.fish')).toMatch(
227 + /^\n# Composio CLI completions\n/
228 + );
229 + }).pipe(Effect.provide(layer));
230 + });
231 +
232 + it.effect('a stale managed block is replaced in place', () => {
233 + const { home, layer, stderrLines } = installTest({
234 + env: { SHELL: '/bin/zsh', COMPOSIO_BIN_DIR: '/custom/bin' },
235 + });
236 + return Effect.gen(function* () {
237 + const fs = yield* FileSystem.FileSystem;
238 + yield* fs.writeFileString(
239 + path.join(home, '.zshrc'),
240 + '# mine\n# Composio CLI\nexport PATH="/old/bin:$PATH"\n'
241 + );
242 +
243 + yield* installShellIntegration({ completions: false });
244 +
245 + expect(stderrLines().slice(0, 4)).toEqual([
246 + 'Detected shell: zsh',
247 + 'PATH: will update the managed block to /custom/bin',
248 + 'Completions: skipped for zsh',
249 + 'Updated ~/.zshrc',
250 + ]);
251 + expect(yield* readHomeFile(home, '.zshrc')).toBe(
252 + '# mine\n\n# Composio CLI\nexport PATH="/custom/bin:$PATH"\n'
253 + );
254 + }).pipe(Effect.provide(layer));
255 + });
256 +
257 + it.effect('the installer origin keeps the status lines and drops the restart hint', () => {
258 + const { layer, stderrLines } = installTest({
259 + env: { SHELL: '/bin/zsh', COMPOSIO_CLI_INVOCATION_ORIGIN: 'installer' },
260 + });
261 + return Effect.gen(function* () {
262 + yield* installShellIntegration({ completions: false });
263 +
264 + expect(stderrLines()).toEqual([
265 + 'Detected shell: zsh',
266 + `PATH: will add ${BIN_DIR} to $PATH`,
267 + 'Completions: skipped for zsh',
268 + 'Updated ~/.zshrc',
269 + ]);
270 + }).pipe(Effect.provide(layer));
271 + });
272 +
273 + it.effect('no detectable shell prints the line to add by hand', () => {
274 + const { layer, stderrLines } = installTest({ env: { SHELL: '/bin/sh' } });
275 + return Effect.gen(function* () {
276 + yield* installShellIntegration({ completions: false });
277 +
278 + expect(stderrLines()).toEqual([
279 + 'warning: Could not detect your shell. Manually add the following to your shell config:',
280 + 'PATH setup:',
281 + `export PATH="${BIN_DIR}:$PATH"`,
282 + ]);
283 + }).pipe(Effect.provide(layer));
284 + });
285 +
286 + it.effect('no detectable shell with the bin dir on $PATH has nothing to update', () => {
287 + const { layer, stderrLines } = installTest({ env: { PATH: `/usr/bin:${BIN_DIR}` } });
288 + return Effect.gen(function* () {
289 + yield* installShellIntegration({ completions: false });
290 +
291 + expect(stderrLines()).toEqual([
292 + `PATH: ${BIN_DIR} is already on $PATH in this process, and no shell config file could be identified — nothing to update.`,
293 + ]);
294 + }).pipe(Effect.provide(layer));
295 + });
296 +
297 + it.effect.each([
298 + ['a relative bin dir', './bin', BIN_DIR_NOT_ABSOLUTE_MESSAGE],
299 + ['a bin dir with a PATH delimiter', '/a:/b', BIN_DIR_UNSAFE_MESSAGE],
300 + ['a bin dir that expands in double quotes', '/tmp/x$(evil)', BIN_DIR_UNSAFE_MESSAGE],
301 + ])('%s aborts with ShellSetupAbortError before touching any file', ([, binDir, message]) => {
302 + const { home, layer, stderrLines } = installTest({
303 + env: { SHELL: '/bin/zsh', COMPOSIO_BIN_DIR: binDir },
304 + });
305 + return Effect.gen(function* () {
306 + const error = yield* Effect.flip(installShellIntegration({ completions: false }));
307 +
308 + expect(error).toEqual(new ShellSetupAbortError({ message }));
309 + expect(stderrLines()).toEqual([`error: ${message}`]);
310 + const fs = yield* FileSystem.FileSystem;
311 + expect(yield* fs.exists(path.join(home, '.zshrc'))).toBe(false);
312 + }).pipe(Effect.provide(layer));
313 + });
314 +});
315 +
316 +describe('runInstall', () => {
317 + it.effect('--shell overrides $SHELL and --no-completions wins over --completions', () => {
318 + const { home, layer, stderrLines } = installTest({ env: { SHELL: '/bin/zsh' } });
319 + return Effect.gen(function* () {
320 + yield* runInstall({ completions: true, noCompletions: true, shell: Option.some('fish') });
321 +
322 + expect(stderrLines().slice(0, 3)).toEqual([
323 + 'Detected shell: fish',
324 + `PATH: will add ${BIN_DIR} to $PATH`,
325 + 'Completions: skipped by default (pass --completions to enable)',
326 + ]);
327 + const fs = yield* FileSystem.FileSystem;
328 + expect(yield* fs.exists(path.join(home, '.zshrc'))).toBe(false);
329 + }).pipe(Effect.provide(layer));
330 + });
331 +
332 + it.effect('--completions without --no-completions installs them', () => {
333 + const { layer, stderrLines } = installTest({ env: { SHELL: '/bin/bash' } });
334 + return Effect.gen(function* () {
335 + yield* runInstall({ completions: true, noCompletions: false, shell: Option.none() });
336 +
337 + expect(stderrLines()[2]).toBe('Completions: will install shell completions');
338 + }).pipe(Effect.provide(layer));
339 + });
340 +});
341 +
342 +describe('decorated reporter (stderr TTY)', () => {
343 + it.effect(
344 + 'zsh: reports route to the log/note channels with the same content and no plain prefixes',
345 + () => {
346 + const { calls, layer: ui } = decoratedInstallUI();
347 + const { home, layer, stderrLines } = installTest({ env: { SHELL: '/bin/zsh' }, ui });
348 + return Effect.gen(function* () {
349 + yield* installShellIntegration({ completions: false });
350 +
351 + expect(calls.step).toEqual([
352 + 'Detected shell: zsh',
353 + `PATH: will add ${BIN_DIR} to $PATH`,
354 + 'Completions: skipped for zsh',
355 + ]);
356 + expect(calls.success).toEqual(['Updated ~/.zshrc']);
357 + expect(calls.note).toEqual([['source ~/.zshrc', 'Restart your shell to apply changes']]);
358 + expect(calls.warn).toEqual([]);
359 + expect(calls.error).toEqual([]);
360 + expect(calls.plainError).toEqual([]);
361 + expect(stderrLines()).toEqual([]);
362 + expect(yield* readHomeFile(home, '.zshrc')).toBe(
363 + `\n# Composio CLI\nexport PATH="${BIN_DIR}:$PATH"\n`
364 + );
365 + }).pipe(Effect.provide(layer));
366 + }
367 + );
368 +
369 + it.effect('abort: the failure line routes to log.error without the error: prefix', () => {
370 + const { calls, layer: ui } = decoratedInstallUI();
371 + const { home, layer } = installTest({
372 + env: { SHELL: '/bin/zsh', COMPOSIO_BIN_DIR: '/tmp/x$(evil)' },
373 + ui,
374 + });
375 + return Effect.gen(function* () {
376 + const error = yield* Effect.flip(installShellIntegration({ completions: false }));
377 +
378 + expect(error).toEqual(new ShellSetupAbortError({ message: BIN_DIR_UNSAFE_MESSAGE }));
379 + expect(calls.error).toEqual([BIN_DIR_UNSAFE_MESSAGE]);
380 + expect(calls.step).toEqual([]);
381 + expect(calls.success).toEqual([]);
382 + expect(calls.warn).toEqual([]);
383 + expect(calls.note).toEqual([]);
384 + expect(calls.plainError).toEqual([]);
385 + const fs = yield* FileSystem.FileSystem;
386 + expect(yield* fs.exists(path.join(home, '.zshrc'))).toBe(false);
387 + }).pipe(Effect.provide(layer));
388 + });
389 +});
ts/packages/cli/test/src/install-managed-block-conformance.test.ts
+1 -1
@@ -5,7 +5,7 @@ import {
5 pathBlockForShell,
6 reconcileManagedPathBlock,
7 type Shell,
8 -} from 'src/commands/install.cmd';
8 +} from 'src/services/shell-config';
9
10 /**
11 * Managed PATH block contract conformance.
ts/packages/cli/test/src/services/shell-config.test.ts new
+146
@@ -0,0 +1,146 @@
1 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 +import * as BunPath from '@effect/platform-bun/BunPath';
3 +import { describe, expect, it } from '@effect/vitest';
4 +import { Effect, Layer, Option } from 'effect';
5 +import * as FileSystem from 'effect/FileSystem';
6 +import * as Path from 'effect/Path';
7 +import path from 'node:path';
8 +import * as tempy from 'tempy';
9 +import {
10 + buildShellConfig,
11 + detectShellFromEnv,
12 + isUnsafePath,
13 + pathBlockForShell,
14 + pathFilesForShell,
15 + renderWithHome,
16 + resolveBashLoginFile,
17 + type Shell,
18 +} from 'src/services/shell-config';
19 +
20 +const HOME = '/home/user';
21 +const PlatformLive = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
22 +
23 +describe('detectShellFromEnv', () => {
24 + it.effect.each([
25 + ['/bin/zsh', Option.some('zsh')],
26 + ['/usr/local/bin/bash', Option.some('bash')],
27 + ['/opt/homebrew/bin/fish', Option.some('fish')],
28 + ['zsh', Option.some('zsh')],
29 + ['/bin/sh', Option.none()],
30 + ['/usr/bin/nu', Option.none()],
31 + ['', Option.none()],
32 + ] as const)('$SHELL=%j detects %s', ([shellEnv, expected]) =>
33 + Effect.gen(function* () {
34 + const p = yield* Path.Path;
35 + expect(detectShellFromEnv(p, shellEnv)).toEqual(expected);
36 + }).pipe(Effect.provide(PlatformLive))
37 + );
38 +});
39 +
40 +describe('isUnsafePath', () => {
41 + it.each([
42 + ['/home/user/.local/bin', false],
43 + ["/Users/o'brien/.local/bin", false],
44 + ['/opt/a;b|c&(d)', false],
45 + ['/tmp/x$(evil)', true],
46 + ['/tmp/`evil`', true],
47 + ['/tmp/"quoted"', true],
48 + ['/tmp/back\\slash', true],
49 + ['/tmp/a:/b', true],
50 + ['/tmp/new\nline', true],
51 + ['/tmp/carriage\rreturn', true],
52 + ])('%j is unsafe: %s', (dir, expected) => {
53 + expect(isUnsafePath(dir)).toBe(expected);
54 + });
55 +});
56 +
57 +describe('renderWithHome', () => {
58 + it.each([
59 + [HOME, '$HOME'],
60 + [`${HOME}/.local/bin`, '$HOME/.local/bin'],
61 + [`${HOME}2/bin`, `${HOME}2/bin`],
62 + ['/usr/local/bin', '/usr/local/bin'],
63 + ])('%j renders as %j', (dir, expected) => {
64 + expect(renderWithHome(dir, HOME)).toBe(expected);
65 + });
66 +});
67 +
68 +describe('pathBlockForShell', () => {
69 + it.each<[Shell, string]>([
70 + ['zsh', '# Composio CLI\nexport PATH="$HOME/.local/bin:$PATH"'],
71 + ['bash', '# Composio CLI\nexport PATH="$HOME/.local/bin:$PATH"'],
72 + ['fish', '# Composio CLI\nset --export PATH "$HOME/.local/bin" $PATH'],
73 + ])('%s writes the managed marker and its PATH assignment', (shell, expected) => {
74 + expect(pathBlockForShell(shell, `${HOME}/.local/bin`, HOME)).toBe(expected);
75 + });
76 +});
77 +
78 +describe('pathFilesForShell and buildShellConfig', () => {
79 + it.effect('zsh configures ~/.zshrc and puts completions in the same file', () =>
80 + Effect.gen(function* () {
81 + const p = yield* Path.Path;
82 + const pathFiles = pathFilesForShell(p, 'zsh', HOME, undefined);
83 + expect(pathFiles).toEqual([`${HOME}/.zshrc`]);
84 +
85 + const config = buildShellConfig(p, 'zsh', pathFiles, '/opt/bin', Option.none(), HOME);
86 + expect(config.completionFile).toBe(`${HOME}/.zshrc`);
87 + expect(config.completionBlock).toEqual(Option.none());
88 + }).pipe(Effect.provide(PlatformLive))
89 + );
90 +
91 + it.effect('bash configures ~/.bashrc and its login file', () =>
92 + Effect.gen(function* () {
93 + const p = yield* Path.Path;
94 + expect(pathFilesForShell(p, 'bash', HOME, `${HOME}/.bash_login`)).toEqual([
95 + `${HOME}/.bashrc`,
96 + `${HOME}/.bash_login`,
97 + ]);
98 + }).pipe(Effect.provide(PlatformLive))
99 + );
100 +
101 + it.effect('fish keeps completions in their own file under a marker', () =>
102 + Effect.gen(function* () {
103 + const p = yield* Path.Path;
104 + const pathFiles = pathFilesForShell(p, 'fish', HOME, undefined);
105 + expect(pathFiles).toEqual([`${HOME}/.config/fish/config.fish`]);
106 +
107 + const config = buildShellConfig(
108 + p,
109 + 'fish',
110 + pathFiles,
111 + '/opt/bin',
112 + Option.some('complete -c composio'),
113 + HOME
114 + );
115 + expect(config.completionFile).toBe(`${HOME}/.config/fish/completions/composio.fish`);
116 + expect(config.completionBlock).toEqual(
117 + Option.some('# Composio CLI completions\ncomplete -c composio')
118 + );
119 + }).pipe(Effect.provide(PlatformLive))
120 + );
121 +});
122 +
123 +describe('resolveBashLoginFile', () => {
124 + const resolveIn = (existing: ReadonlyArray<string>) =>
125 + Effect.gen(function* () {
126 + const fs = yield* FileSystem.FileSystem;
127 + const p = yield* Path.Path;
128 + const home = tempy.temporaryDirectory({ prefix: 'shell-config' });
129 + yield* Effect.forEach(existing, file => fs.writeFileString(path.join(home, file), ''));
130 + const resolved = yield* resolveBashLoginFile(p, home, fs);
131 + return { ...resolved, file: path.relative(home, resolved.file) };
132 + }).pipe(Effect.provide(PlatformLive));
133 +
134 + it.effect.each([
135 + [[], { file: '.bash_profile', seedsProfilePassthrough: false }],
136 + [['.profile'], { file: '.bash_profile', seedsProfilePassthrough: true }],
137 + [['.bash_login'], { file: '.bash_login', seedsProfilePassthrough: false }],
138 + [['.bash_login', '.profile'], { file: '.bash_login', seedsProfilePassthrough: false }],
139 + [['.bash_profile', '.bash_login'], { file: '.bash_profile', seedsProfilePassthrough: false }],
140 + [['.bash_profile', '.profile'], { file: '.bash_profile', seedsProfilePassthrough: false }],
141 + ] as const)('with %j present resolves %j', ([existing, expected]) =>
142 + Effect.gen(function* () {
143 + expect(yield* resolveIn(existing)).toEqual(expected);
144 + })
145 + );
146 +});