Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Merge branch 'next' into feat/installer-auto-shell-default

jkomyno9a6d59326f0d
diff --cc .github/workflows/cli.test-installation.yml
index 15cc46181,70564a552..c64c72d8a
--- a/.github/workflows/cli.test-installation.yml
+++ b/.github/workflows/cli.test-installation.yml
@@@ -39,6 -45,6 +48,7 @@@ jobs
- name: Test documented uninstall snippet
run: bash test/install-sh-uninstall-snippet.test.sh
++
- name: Lint POSIX install scripts
run: shellcheck -s sh install.sh install/*.sh
diff --cc install.sh
index 06e082a24,c63287bed..8b1328e45
--- a/install.sh
+++ b/install.sh
@@@ -339,76 -297,39 +339,99 @@@ inherited_path_contains_bin_dir()
esac
}
+# Renders a value as one POSIX-safe shell word so recovery commands stay
+# copy-paste safe even when the installed path contains whitespace.
+shell_quote() {
+ case $1 in
+ '') printf "''\n" ;;
+ *[!A-Za-z0-9_./-]*) printf '%s\n' "$1" | sed "s/'/'\\\\''/g; s/^/'/; s/\$/'/" ;;
+ *) printf '%s\n' "$1" ;;
+ esac
+}
+
+# Follows symlinks and resolves the parent directory physically, so two paths
+# compare equal exactly when they name the same executable: the final block's
+# installed-vs-shadowed verdict must not change just because one side reaches
+# the binary through a symlink alias.
+resolve_physical_path() {
+ resolve_physical_target=$1
+ resolve_physical_steps=0
+ while [ -L "$resolve_physical_target" ] && [ "$resolve_physical_steps" -lt 40 ]; do
+ resolve_physical_link=$(readlink "$resolve_physical_target") || break
+ case $resolve_physical_link in
+ /*) resolve_physical_target=$resolve_physical_link ;;
+ *) resolve_physical_target=$(dirname "$resolve_physical_target")/$resolve_physical_link ;;
+ esac
+ resolve_physical_steps=$((resolve_physical_steps + 1))
+ done
+ resolve_physical_base=$(basename "$resolve_physical_target")
+ if resolve_physical_dir=$(cd "$(dirname "$resolve_physical_target")" 2>/dev/null && pwd -P); then
+ printf '%s/%s\n' "$resolve_physical_dir" "$resolve_physical_base"
+ else
+ printf '%s\n' "$resolve_physical_target"
+ fi
+}
+
+# Resolves the composio command against the PATH snapshot taken before any
+# installer code could modify PATH: what the invoking terminal can run.
+resolve_inherited_command() {
+ PATH=$inherited_path command -v composio 2>/dev/null
+}
+
+compute_inherited_resolution() {
+ inherited_command=$(resolve_inherited_command) || inherited_command=
+ inherited_resolution=unresolved
+ if [ -n "$inherited_command" ]; then
+ if [ "$(resolve_physical_path "$inherited_command")" = "$(resolve_physical_path "$exe")" ]; then
+ inherited_resolution=installed
+ else
+ inherited_resolution=shadowed
+ fi
+ fi
+}
+
+ # Reject bin dirs that cannot be embedded safely in a managed rc line. The dir
+ # is only ever emitted inside double quotes -- `export PATH="<dir>:$PATH"` for
+ # bash/zsh and `set --export PATH "<dir>" $PATH` for fish -- so the set is
+ # deliberately narrow and mirrors UNSAFE_PATH_CHARS in
+ # ts/packages/cli/src/commands/install.cmd.ts, keeping this inline fallback and
+ # `composio install` on one contract:
+ #
+ # ` $ " \ the only characters bash and zsh still expand inside double
+ # quotes (fish expands a strict subset). Everything else -- `;`,
+ # `|`, `&`, `(`, `)`, `'` -- is literal there, so a bin dir like
+ # /Users/o'brien/.local/bin is written verbatim, not rejected.
+ # CR LF structural: either would split the managed block into extra lines.
+ # : structural: the PATH separator would silently prepend two entries.
+ #
+ # Aborting rather than escaping is what keeps the two branches equivalent: a dir
+ # the CLI refuses must not slip into an rc file just because the CLI could not
+ # run. It also means the value reaching append_path_block can no longer carry a
+ # character that double quotes would interpret, so no escaping pass is needed
+ # (and `${var//x/y}` is a bashism this POSIX script cannot use anyway).
is_unsafe_path() {
- case $1 in *':'* | *';'* | *'`'* | *'$'* | *'|'* | *'&'* | *'"'* | *"'"* | *'('* | *')'* | *\\*) return 0 ;; esac
+ case $1 in *':'* | *'`'* | *'$'* | *'"'* | *\\*) return 0 ;; esac
unsafe_path_cr=$(printf '\r')
case $1 in *"$unsafe_path_cr"* | *'
'*) return 0 ;; esac
return 1
}
+# Renders the home directory itself and paths under it with a literal $HOME
+# prefix. Must stay in lockstep with the CLI's renderWithHome (install.cmd.ts):
+# delegated_setup_verified compares the CLI-written line against this rendering
+# byte for byte, so any disagreement makes every delegated install look stale
+# and forces a needless inline rewrite.
++#
+ # Callers must run is_unsafe_path first, so the only `$` in the result is the
+ # `$HOME` this function introduces -- it survives as a live variable reference
+ # in the rc line without any user-supplied `$` riding along with it.
render_bin_dir() {
render_bin_dir_value=$1
- case $render_bin_dir_value in "$HOME"/*) render_bin_dir_value=\$HOME/${render_bin_dir_value#"$HOME"/} ;; esac
+ case $render_bin_dir_value in
+ "$HOME") render_bin_dir_value=\$HOME ;;
+ "$HOME"/*) render_bin_dir_value=\$HOME/${render_bin_dir_value#"$HOME"/} ;;
+ esac
printf '%s\n' "$render_bin_dir_value"
}
diff --cc test/install-sh-release-resolution.test.sh
index e20c41533,0a1cb4991..9b44520da
--- a/test/install-sh-release-resolution.test.sh
+++ b/test/install-sh-release-resolution.test.sh
@@@ -796,9 -554,10 +796,10 @@@ EO
variant_install="$case_root/variant-$shell_name-install"
variant_bin="$case_root/variant-$shell_name-bin"
variant_output=$(run_variant "$shell_name" "$variant_home" "$variant_install" "$variant_bin" "$stable_tag" --no-plugins 2>&1)
- grep -Fq "|installer|$variant_bin|install --shell $shell_name" "$composio_log" ||
+ expected_variant_bin=$(cd "$variant_bin" && pwd -P)
+ grep -Fq "|installer|$expected_variant_bin|install --shell $shell_name" "$composio_log" ||
fail "$interpreter_name $shell_name variant delegation"
- assert_contains "$variant_output" "Configured $shell_name shell setup (cli)." "$interpreter_name $shell_name variant confirmation"
+ assert_contains "$variant_output" "$(configured_line "$shell_name")" "$interpreter_name $shell_name variant confirmation"
assert_not_contains "$variant_output" 'Required next step' "$interpreter_name $shell_name variant must not print setup guidance"
assert_not_contains "$variant_output" 'Optional shell setup' "$interpreter_name $shell_name variant must not print setup guidance"
done
@@@ -808,13 -567,35 +809,37 @@@
direct_home="$case_root/direct-shell-home"
direct_bin="$case_root/direct-shell-bin"
direct_output=$(run_installer "$direct_home" "$case_root/direct-shell-install" "$direct_bin" "$stable_tag" 2>&1)
- grep -Fq "|installer|$direct_bin|install --shell zsh" "$composio_log" || fail "$interpreter_name COMPOSIO_INSTALL_SHELL delegation"
+ expected_direct_bin=$(cd "$direct_bin" && pwd -P)
+ grep -Fq "|installer|$expected_direct_bin|install --shell zsh" "$composio_log" || fail "$interpreter_name COMPOSIO_INSTALL_SHELL delegation"
- assert_contains "$direct_output" 'Configured zsh shell setup (cli).' "$interpreter_name COMPOSIO_INSTALL_SHELL confirmation"
+ assert_contains "$direct_output" "$(configured_line zsh)" "$interpreter_name COMPOSIO_INSTALL_SHELL confirmation"
assert_not_contains "$direct_output" 'Required next step' "$interpreter_name COMPOSIO_INSTALL_SHELL must not print setup guidance"
- [[ ! -e "$direct_home/.zshrc" ]] || fail "$interpreter_name COMPOSIO_INSTALL_SHELL CLI path must not write rc files"
+ assert_tail "$direct_output" "$case_b_tail" "$interpreter_name COMPOSIO_INSTALL_SHELL Case B tail"
+ grep -Fq "export PATH=\"$direct_bin:\$PATH\"" "$direct_home/.zshrc" || fail "$interpreter_name COMPOSIO_INSTALL_SHELL CLI-written block"
+ assert_not_contains "$direct_output" 'Updated ~/.zshrc' "$interpreter_name COMPOSIO_INSTALL_SHELL CLI path must not rewrite rc files inline"
+ reset_case
+ CASE_INSTALL_SHELL=zsh
+ relative_work="$case_root/relative-shell-work"
+ relative_home="$case_root/relative-shell-home"
+ relative_install="$case_root/relative-shell-install"
+ mkdir -p "$relative_work"
+ (cd "$relative_work" && run_installer "$relative_home" "$relative_install" relative-bin "$stable_tag" >/dev/null 2>&1)
+ expected_relative_bin=$(cd "$relative_work/relative-bin" && pwd -P)
+ grep -Fq "|installer|$expected_relative_bin|install --shell zsh" "$composio_log" ||
+ fail "$interpreter_name relative COMPOSIO_BIN_DIR delegation must receive the resolved absolute path"
+
+ reset_case
+ CASE_INSTALL_SHELL=zsh
+ CASE_SHELL_CAPABILITY=unsupported
+ relative_fallback_work="$case_root/relative-fallback-work"
+ relative_fallback_home="$case_root/relative-fallback-home"
+ relative_fallback_install="$case_root/relative-fallback-install"
+ mkdir -p "$relative_fallback_work"
+ (cd "$relative_fallback_work" && run_installer "$relative_fallback_home" "$relative_fallback_install" relative-bin "$stable_tag" >/dev/null 2>&1)
+ expected_relative_fallback_bin=$(cd "$relative_fallback_work/relative-bin" && pwd -P)
+ grep -Fq "export PATH=\"$expected_relative_fallback_bin:\$PATH\"" "$relative_fallback_home/.zshrc" ||
+ fail "$interpreter_name relative COMPOSIO_BIN_DIR fallback must persist the resolved absolute path"
+
reset_case
CASE_INSTALL_SHELL=zsh
CASE_SHELL_CAPABILITY=unsupported
@@@ -859,21 -640,35 +884,40 @@@
grep -Fqx '# Composio CLI' "$bash_fallback_home/.bashrc" || fail "$interpreter_name bash fallback bashrc"
grep -Fqx '# Composio CLI' "$bash_fallback_home/.bash_profile" || fail "$interpreter_name bash fallback login override"
- for unsafe_character in ';' ':'; do
+ # The inline fallback embeds the resolved bin dir in an rc line, so a dir
+ # holding a character double quotes still expand -- `$`, a backtick, `"`, `\`
+ # -- or a structural `:` is refused outright, on the same set
+ # `composio install` refuses. A dir the CLI rejects must not slip into an rc
+ # file just because the CLI could not run.
+ injection_marker="$case_root/injection-marker"
+ unsafe_case=0
+ for unsafe_bin in "inject-\$(touch $injection_marker)" 'inject-`id`' 'inject-"quote"' 'inject\backslash' 'inject:colon'; do
reset_case
CASE_SHELL_CAPABILITY=unsupported
- unsafe_slug=${unsafe_character//[^[:alnum:]]/delimiter}
- unsafe_home="$case_root/unsafe-$unsafe_slug-variant-home"
- unsafe_install="$case_root/unsafe-$unsafe_slug-variant-install"
- unsafe_bin="$case_root/unsafe${unsafe_character}variant-bin"
- unsafe_variant_output=$(run_variant zsh "$unsafe_home" "$unsafe_install" "$unsafe_bin" "$stable_tag" 2>&1) ||
- fail "$interpreter_name unsafe variant bin dir with $unsafe_character must keep the install successful"
- [[ ! -e "$unsafe_home/.zshrc" ]] || fail "$interpreter_name unsafe variant must not write rc file"
- [[ -x "$unsafe_install/composio" ]] || fail "$interpreter_name unsafe variant must retain the binary"
- assert_contains "$unsafe_variant_output" 'warning:' "$interpreter_name unsafe variant warning"
- assert_contains "$unsafe_variant_output" "$unsafe_bin" "$interpreter_name unsafe variant warning names the rejected path"
- assert_tail "$unsafe_variant_output" "$(recovery_tail later "$unsafe_install/composio")" "$interpreter_name unsafe variant recovery tail"
+ unsafe_case=$((unsafe_case + 1))
+ unsafe_home="$case_root/unsafe-$unsafe_case-variant-home"
- if run_variant zsh "$unsafe_home" "$case_root/unsafe-variant-install" "$case_root/$unsafe_bin" "$stable_tag" >/dev/null 2>&1; then
- fail "$interpreter_name unsafe variant bin dir must fail: $unsafe_bin"
- fi
++ unsafe_install="$case_root/unsafe-$unsafe_case-variant-install"
++ unsafe_bin_dir="$case_root/$unsafe_bin"
++ unsafe_variant_output=$(run_variant zsh "$unsafe_home" "$unsafe_install" "$unsafe_bin_dir" "$stable_tag" 2>&1) ||
++ fail "$interpreter_name unsafe variant bin dir must keep the install successful: $unsafe_bin"
+ [[ ! -e "$unsafe_home/.zshrc" ]] || fail "$interpreter_name unsafe variant must not write rc file: $unsafe_bin"
++ [[ -x "$unsafe_install/composio" ]] || fail "$interpreter_name unsafe variant must retain the binary: $unsafe_bin"
++ assert_contains "$unsafe_variant_output" 'warning:' "$interpreter_name unsafe variant warning: $unsafe_bin"
++ assert_contains "$unsafe_variant_output" "$unsafe_bin_dir" "$interpreter_name unsafe variant warning names the rejected path: $unsafe_bin"
++ assert_tail "$unsafe_variant_output" "$(recovery_tail later "$unsafe_install/composio")" "$interpreter_name unsafe variant recovery tail: $unsafe_bin"
done
+ [[ ! -e "$injection_marker" ]] || fail "$interpreter_name command substitution in the bin dir must never run"
+
+ # The denylist stops at what double quotes actually expand: characters that
+ # are literal there stay legal and are written verbatim.
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ literal_home="$case_root/literal-variant-home"
+ literal_bin="$case_root/o'brien;bin"
+ run_variant zsh "$literal_home" "$case_root/literal-variant-install" "$literal_bin" "$stable_tag" >/dev/null 2>&1
+ expected_literal_bin=$(cd "$literal_bin" && pwd -P)
+ grep -Fq "export PATH=\"$expected_literal_bin:\$PATH\"" "$literal_home/.zshrc" ||
+ fail "$interpreter_name apostrophe bin dir must be written verbatim"
for base_mode in fail empty; do
reset_case
@@@ -885,428 -680,6 +929,430 @@@
[[ ! -e "$base_failure_home/.zshrc" ]] || fail "$interpreter_name $base_mode download must not write rc"
done
+ # --- Auto shell setup default: $SHELL picks the shell, setup delegates to the CLI ---
+
+ # Every recognized default-flow shell delegates through the setup chain.
+ for auto_shell in zsh bash fish; do
+ reset_case
+ CASE_SHELL_VALUE="/bin/$auto_shell"
+ auto_home="$case_root/auto-$auto_shell-home"
+ auto_install="$case_root/auto-$auto_shell-install"
+ auto_bin="$case_root/auto-$auto_shell-bin"
+ auto_output=$(run_installer "$auto_home" "$auto_install" "$auto_bin" "$stable_tag" 2>&1)
+ grep -Fq "|installer|$auto_bin|install --shell $auto_shell" "$composio_log" ||
+ fail "$interpreter_name auto $auto_shell delegation"
+ assert_contains "$auto_output" "$(configured_line "$auto_shell")" "$interpreter_name auto $auto_shell confirmation"
+ assert_tail "$auto_output" "$case_b_tail" "$interpreter_name auto $auto_shell Case B tail"
+ done
+
+ # Repeated default-flow installs keep taking the idempotent setup chain.
+ reset_case
+ idempotent_home="$case_root/idempotent-home"
+ idempotent_install="$case_root/idempotent-install"
+ idempotent_bin="$case_root/idempotent-bin"
+ run_installer "$idempotent_home" "$idempotent_install" "$idempotent_bin" "$stable_tag" >/dev/null 2>&1
+ run_installer "$idempotent_home" "$idempotent_install" "$idempotent_bin" "$stable_tag" >/dev/null 2>&1
+ [[ $(grep -c 'install --shell bash' "$composio_log") -eq 2 ]] ||
+ fail "$interpreter_name repeated auto installs must re-run idempotent setup"
+
+ # COMPOSIO_INSTALL_SHELL=none preserves install-only behavior.
+ reset_case
+ CASE_INSTALL_SHELL=none
+ none_home="$case_root/none-home"
+ none_install="$case_root/none-install"
+ none_output=$(run_installer "$none_home" "$none_install" "$case_root/none-bin" "$stable_tag" 2>&1)
+ if grep -Fq 'install --shell' "$composio_log"; then
+ fail "$interpreter_name none must not run shell setup"
+ fi
+ [[ ! -e "$none_home/.bashrc" && ! -e "$none_home/.bash_profile" ]] || fail "$interpreter_name none must not write rc files"
+ assert_contains "$none_output" 'COMPOSIO_INSTALL_SHELL=none' "$interpreter_name none skip disclosure"
+ assert_tail "$none_output" "$(recovery_tail now "$none_install/composio")" "$interpreter_name none install-only tail"
+
+ # none + already-resolving installed command uses the bare Case A ending.
+ reset_case
+ CASE_INSTALL_SHELL=none
+ none_ready_bin="$case_root/none-ready-bin"
+ CASE_PATH_PREFIX="$none_ready_bin:"
+ none_ready_output=$(run_installer "$case_root/none-ready-home" "$case_root/none-ready-install" "$none_ready_bin" "$stable_tag" 2>&1)
+ assert_tail "$none_ready_output" "$case_a_tail" "$interpreter_name none Case A tail"
+
+ # Case A: recognized shell, setup succeeds, and the inherited PATH already
+ # resolves the installed entry point. Setup still runs (idempotent).
+ reset_case
+ ready_bin="$case_root/ready-bin"
+ CASE_PATH_PREFIX="$ready_bin:"
+ ready_output=$(run_installer "$case_root/ready-home" "$case_root/ready-install" "$ready_bin" "$stable_tag" 2>&1)
+ grep -Fq 'install --shell bash' "$composio_log" || fail "$interpreter_name Case A still runs idempotent setup"
+ assert_tail "$ready_output" "$case_a_tail" "$interpreter_name Case A tail"
+
+ # Explicit shell + resolving command also ends in Case A.
+ reset_case
+ CASE_INSTALL_SHELL=zsh
+ explicit_ready_bin="$case_root/explicit-ready-bin"
+ CASE_PATH_PREFIX="$explicit_ready_bin:"
+ explicit_ready_output=$(run_installer "$case_root/explicit-ready-home" "$case_root/explicit-ready-install" "$explicit_ready_bin" "$stable_tag" 2>&1)
+ assert_tail "$explicit_ready_output" "$case_a_tail" "$interpreter_name explicit shell Case A tail"
+
+ # Physical-path identity: a pre-existing symlink on PATH that resolves to the
+ # installed executable still counts as Case A.
+ reset_case
+ alias_dir="$case_root/alias-dir"
+ alias_install="$case_root/alias-install"
+ mkdir -p "$alias_dir" "$alias_install"
+ ln -sf "$alias_install/composio" "$alias_dir/composio"
+ CASE_PATH_PREFIX="$alias_dir:"
+ alias_output=$(run_installer "$case_root/alias-home" "$alias_install" "$case_root/alias-bin" "$stable_tag" 2>&1)
+ assert_tail "$alias_output" "$case_a_tail" "$interpreter_name symlink-alias Case A tail"
+
+ # Unknown $SHELL degrades to install-only guidance plus the trusted absolute command.
+ reset_case
+ CASE_SHELL_VALUE=/bin/tcsh
+ unknown_home="$case_root/unknown-shell-home"
+ unknown_install="$case_root/unknown-shell-install"
+ unknown_output=$(run_installer "$unknown_home" "$unknown_install" "$case_root/unknown-shell-bin" "$stable_tag" 2>&1)
+ if grep -Fq 'install --shell' "$composio_log"; then
+ fail "$interpreter_name unknown shell must not run shell setup"
+ fi
+ [[ ! -e "$unknown_home/.bashrc" ]] || fail "$interpreter_name unknown shell must not write rc files"
+ assert_tail "$unknown_output" "$(recovery_tail now "$unknown_install/composio")" "$interpreter_name unknown shell install-only tail"
+
+ # Shadowing: bin dir on the inherited PATH, but another composio resolves
+ # first. The ending must never run the shadowed bare command.
+ reset_case
+ shadow_dir="$case_root/shadow-dir"
+ mkdir -p "$shadow_dir"
+ printf '#!/bin/sh\nexit 0\n' >"$shadow_dir/composio"
+ chmod +x "$shadow_dir/composio"
+ shadow_bin="$case_root/shadow-bin"
+ shadow_install="$case_root/shadow-install"
+ CASE_PATH_PREFIX="$shadow_dir:$shadow_bin:"
+ shadow_output=$(run_installer "$case_root/shadow-home" "$shadow_install" "$shadow_bin" "$stable_tag" 2>&1)
+ assert_contains "$shadow_output" "$shadow_dir/composio" "$interpreter_name shadow ending names the shadowing command"
+ assert_tail "$shadow_output" $'To use the newly installed CLI, run:\n\n '"$shadow_install/composio login" "$interpreter_name shadow tail avoids the shadowed bare command"
+
+ # Pinned old CLI: supports --shell but ignores the invocation-origin hint,
+ # prints its own boxed restart hint, and exits 0 without reconciling. A
+ # relative COMPOSIO_BIN_DIR must never reach setup raw; the installer must
+ # detect the unreconciled startup file and repair it inline. The delegated
+ # command's own presentation never reaches the user: the installer owns its
+ # output and its plain final block is the only ending.
+ reset_case
+ CASE_INSTALL_HINT=1
+ CASE_INSTALL_RECONCILE=0
+ oldcli_home="$case_root/oldcli-home"
+ oldcli_work="$case_root/oldcli-work"
+ oldcli_install="$case_root/oldcli-install"
+ mkdir -p "$oldcli_work"
+ oldcli_output=$(cd "$oldcli_work" && run_installer "$oldcli_home" "$oldcli_install" "rel-bin" "$stable_tag" 2>&1)
+ grep -Fq "|installer|$oldcli_work/rel-bin|install --shell bash" "$composio_log" ||
+ fail "$interpreter_name old-CLI setup must receive the resolved absolute bin dir"
+ grep -Fq "export PATH=\"$oldcli_work/rel-bin:\$PATH\"" "$oldcli_home/.bashrc" ||
+ fail "$interpreter_name old-CLI delegation must be reconciled inline with the absolute bin dir"
+ assert_contains "$oldcli_output" "$(configured_line bash)" "$interpreter_name old-CLI reconciliation disclosure"
+ assert_not_contains "$oldcli_output" '│ Restart your shell so composio is on PATH │' "$interpreter_name delegated CLI output must not leak"
+ assert_tail "$oldcli_output" "$case_b_tail" "$interpreter_name old-CLI hint superseded by the installer tail"
+
+ # The suppressed delegated output stays available for troubleshooting.
+ reset_case
+ CASE_INSTALL_HINT=1
+ CASE_DEBUG=1
+ delegated_debug_output=$(run_installer "$case_root/delegated-debug-home" "$case_root/delegated-debug-install" "$case_root/delegated-debug-bin" "$stable_tag" 2>&1)
+ assert_contains "$delegated_debug_output" 'delegated shell setup exited 0' "$interpreter_name debug reports the delegated exit status"
+ assert_contains "$delegated_debug_output" '│ Restart your shell so composio is on PATH │' "$interpreter_name debug replays the captured delegated output"
+ assert_contains "$delegated_debug_output" '+ shell setup source: cli' "$interpreter_name debug keeps the setup-source distinction"
+
+ # --- Login-shell reachability for bash (macOS Terminal.app) ---
+
+ # Inline path, virgin home: ~/.bashrc alone is unreachable from a login bash,
+ # so the installer must also create a login-mode startup file.
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ CASE_SHELL_VALUE=/bin/bash
+ bash_login_home="$case_root/bash-login-home"
+ bash_login_bin="$case_root/bash-login-bin"
+ bash_login_output=$(run_installer "$bash_login_home" "$case_root/bash-login-install" "$bash_login_bin" "$stable_tag" 2>&1)
+ grep -Fq "export PATH=\"$bash_login_bin:\$PATH\"" "$bash_login_home/.bashrc" ||
+ fail "$interpreter_name inline bash setup must configure .bashrc"
+ grep -Fq "export PATH=\"$bash_login_bin:\$PATH\"" "$bash_login_home/.bash_profile" ||
+ fail "$interpreter_name inline bash setup must configure a login-mode startup file"
+ assert_login_bash_path "$bash_login_home" "$bash_login_bin" "$interpreter_name inline bash login shell"
+ assert_contains "$bash_login_output" "$(configured_line bash)" "$interpreter_name inline bash names both startup files"
+ [[ ! -e "$bash_login_home/.profile" ]] || fail "$interpreter_name inline bash setup must not create ~/.profile"
+
+ # A created ~/.bash_profile shadows an existing ~/.profile, so it must keep
+ # sourcing it — and must never rewrite ~/.profile itself.
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ CASE_SHELL_VALUE=/bin/bash
+ bash_profile_home="$case_root/bash-profile-home"
+ bash_profile_bin="$case_root/bash-profile-bin"
+ mkdir -p "$bash_profile_home"
+ printf '%s\n' 'export DISTRO_PROFILE=1' >"$bash_profile_home/.profile"
+ run_installer "$bash_profile_home" "$case_root/bash-profile-install" "$bash_profile_bin" "$stable_tag" >/dev/null 2>&1
+ grep -Fq '. "$HOME/.profile"' "$bash_profile_home/.bash_profile" ||
+ fail "$interpreter_name a created .bash_profile must keep sourcing ~/.profile"
+ [[ $(<"$bash_profile_home/.profile") == 'export DISTRO_PROFILE=1' ]] ||
+ fail "$interpreter_name ~/.profile must not be modified"
+ assert_login_bash_path "$bash_profile_home" "$bash_profile_bin" "$interpreter_name shadowed profile login shell"
+ shadowed_profile_value=$(env -i HOME="$bash_profile_home" PATH=/usr/bin:/bin bash -lc 'printf %s "${DISTRO_PROFILE:-}"')
+ [[ $shadowed_profile_value == 1 ]] ||
+ fail "$interpreter_name a created .bash_profile must not shadow ~/.profile content"
+
+ # An existing ~/.bash_login is the login file bash reads, so it is reused and
+ # no ~/.bash_profile is invented in front of it.
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ CASE_SHELL_VALUE=/bin/bash
+ bash_login_only_home="$case_root/bash-login-only-home"
+ bash_login_only_bin="$case_root/bash-login-only-bin"
+ mkdir -p "$bash_login_only_home"
+ printf '%s\n' 'export LOGIN_OVERRIDE=1' >"$bash_login_only_home/.bash_login"
+ bash_login_only_output=$(run_installer "$bash_login_only_home" "$case_root/bash-login-only-install" "$bash_login_only_bin" "$stable_tag" 2>&1)
+ grep -Fq "export PATH=\"$bash_login_only_bin:\$PATH\"" "$bash_login_only_home/.bash_login" ||
+ fail "$interpreter_name existing .bash_login must receive the managed block"
+ [[ ! -e "$bash_login_only_home/.bash_profile" ]] ||
+ fail "$interpreter_name an existing .bash_login must not be shadowed by a new .bash_profile"
+ assert_contains "$bash_login_only_output" 'Configured bash shell setup in ~/.bashrc and ~/.bash_login.' "$interpreter_name .bash_login disclosure"
+ assert_login_bash_path "$bash_login_only_home" "$bash_login_only_bin" "$interpreter_name .bash_login login shell"
+
+ # --- Setup write failures stay non-fatal: the binary stays installed and the ending stays truthful ---
+
+ # Delegated path: CLI --shell fails, inline fallback also fails.
+ reset_case
+ CASE_SHELL_VALUE=/bin/zsh
+ CASE_INSTALL_EXIT=23
+ wf_delegated_home="$case_root/write-failure-delegated-home"
+ wf_delegated_install="$case_root/write-failure-delegated-install"
+ mkdir -p "$wf_delegated_home/.zshrc"
+ wf_delegated_output=$(run_installer "$wf_delegated_home" "$wf_delegated_install" "$case_root/write-failure-delegated-bin" "$stable_tag" 2>&1) ||
+ fail "$interpreter_name delegated setup failure must keep the install successful"
+ [[ -x "$wf_delegated_install/composio" ]] || fail "$interpreter_name delegated setup failure must retain the binary"
+ assert_contains "$wf_delegated_output" 'warning: Automatic PATH setup for zsh failed' "$interpreter_name delegated setup failure warning"
+ assert_contains "$wf_delegated_output" 'COMPOSIO_DEBUG=1' "$interpreter_name delegated setup failure points at the captured output"
+ assert_tail "$wf_delegated_output" "$(recovery_tail later "$wf_delegated_install/composio")" "$interpreter_name delegated setup failure recovery tail"
+
+ # Inline path: helper failure inside a conditional must propagate explicitly.
+ # COMPOSIO_QUIET=1 and COMPOSIO_INSTALL_HELP=0 are set on purpose: both only
+ # gate the normal-success final block, so this one case also proves they are
+ # no-ops on the setup-failure path — the warning and the recovery tail reach
+ # the user even with all optional output suppressed.
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ CASE_QUIET=1
+ CASE_HELP=0
+ wf_inline_home="$case_root/write-failure-inline-home"
+ wf_inline_install="$case_root/write-failure-inline-install"
+ mkdir -p "$wf_inline_home/.bashrc"
+ wf_inline_output=$(run_installer "$wf_inline_home" "$wf_inline_install" "$case_root/write-failure-inline-bin" "$stable_tag" 2>&1) ||
+ fail "$interpreter_name inline setup failure must keep the install successful"
+ [[ -x "$wf_inline_install/composio" ]] || fail "$interpreter_name inline setup failure must retain the binary"
+ assert_contains "$wf_inline_output" 'warning: Automatic PATH setup for bash failed' "$interpreter_name inline setup failure warning"
+ assert_tail "$wf_inline_output" "$(recovery_tail later "$wf_inline_install/composio")" "$interpreter_name inline setup failure recovery tail"
+
+ # --- Managed-block reconciliation: a rerun replaces stale blocks instead of stacking duplicates ---
+
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ CASE_SHELL_VALUE=/bin/zsh
+ reconcile_home="$case_root/reconcile-home"
+ reconcile_install="$case_root/reconcile-install"
+ reconcile_bin_a="$case_root/reconcile-bin-a"
+ reconcile_bin_b="$case_root/reconcile-bin-b"
+ mkdir -p "$reconcile_home"
+ printf '%s\n' 'alias reconcile-before=1' >"$reconcile_home/.zshrc"
+ reconcile_first=$(run_installer "$reconcile_home" "$reconcile_install" "$reconcile_bin_a" "$stable_tag" 2>&1)
+ assert_contains "$reconcile_first" 'Updated ~/.zshrc' "$interpreter_name inline setup update disclosure"
+ grep -Fq "export PATH=\"$reconcile_bin_a:\$PATH\"" "$reconcile_home/.zshrc" || fail "$interpreter_name first managed block"
+ printf '%s\n' 'alias reconcile-after=1' >>"$reconcile_home/.zshrc"
+ reconcile_second=$(run_installer "$reconcile_home" "$reconcile_install" "$reconcile_bin_a" "$stable_tag" 2>&1)
+ assert_contains "$reconcile_second" 'already' "$interpreter_name inline setup already-current disclosure"
+ [[ $(grep -Fc '# Composio CLI' "$reconcile_home/.zshrc") -eq 1 ]] || fail "$interpreter_name idempotent rerun keeps one marker block"
+ reconcile_third=$(run_installer "$reconcile_home" "$reconcile_install" "$reconcile_bin_b" "$stable_tag" 2>&1)
+ assert_contains "$reconcile_third" 'Updated ~/.zshrc' "$interpreter_name reconcile update disclosure"
+ [[ $(grep -Fc '# Composio CLI' "$reconcile_home/.zshrc") -eq 1 ]] || fail "$interpreter_name reconcile keeps exactly one marker block"
+ grep -Fq "export PATH=\"$reconcile_bin_b:\$PATH\"" "$reconcile_home/.zshrc" || fail "$interpreter_name reconciled managed block"
+ if grep -Fq "$reconcile_bin_a" "$reconcile_home/.zshrc"; then
+ fail "$interpreter_name stale managed path must be replaced"
+ fi
+ grep -Fq 'alias reconcile-before=1' "$reconcile_home/.zshrc" || fail "$interpreter_name unmanaged content preserved (before block)"
+ grep -Fq 'alias reconcile-after=1' "$reconcile_home/.zshrc" || fail "$interpreter_name unmanaged content preserved (after block)"
+
+ # A marker followed by unmanaged content is malformed. Remove only the
+ # marker, preserve every following line, and append the current managed block
+ # after the orphaned stale assignment so the new bin dir wins PATH order.
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ CASE_SHELL_VALUE=/bin/zsh
+ malformed_home="$case_root/malformed-block-home"
+ malformed_bin="$case_root/malformed-block-bin"
+ mkdir -p "$malformed_home"
+ printf '%s\n' \
+ 'alias malformed-before=1' \
+ '# Composio CLI' \
+ '# keep this dotfile-manager annotation' \
+ '' \
+ 'export PATH="/stale/malformed-bin:$PATH"' \
+ 'alias malformed-after=1' >"$malformed_home/.zshrc"
+ malformed_output=$(run_installer "$malformed_home" "$case_root/malformed-block-install" "$malformed_bin" "$stable_tag" 2>&1)
+ assert_contains "$malformed_output" 'Updated ~/.zshrc' "$interpreter_name malformed block update disclosure"
+ grep -Fq '# keep this dotfile-manager annotation' "$malformed_home/.zshrc" || fail "$interpreter_name malformed block preserves the line after its marker"
+ grep -Fq 'export PATH="/stale/malformed-bin:$PATH"' "$malformed_home/.zshrc" || fail "$interpreter_name malformed block preserves an orphaned stale assignment"
+ grep -Fq 'alias malformed-before=1' "$malformed_home/.zshrc" || fail "$interpreter_name malformed block preserves content before its marker"
+ grep -Fq 'alias malformed-after=1' "$malformed_home/.zshrc" || fail "$interpreter_name malformed block preserves content after its marker"
+ [[ $(grep -Fc '# Composio CLI' "$malformed_home/.zshrc") -eq 1 ]] || fail "$interpreter_name malformed block leaves one fresh marker"
+ malformed_tail=$(tail -n 2 "$malformed_home/.zshrc")
+ [[ $malformed_tail == "# Composio CLI
+export PATH=\"$malformed_bin:\$PATH\"" ]] || fail "$interpreter_name malformed block appends the current assignment last"
+
+ # --- Symlinked startup files and mode preservation (managed dotfiles) ---
+
+ # Inline setup must write through a symlinked rc file: the symlink survives
+ # and its target receives the managed block (mirrors the CLI unit test
+ # 'preserves a symlinked .zshrc').
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ CASE_SHELL_VALUE=/bin/zsh
+ symlink_home="$case_root/symlink-home"
+ symlink_store="$case_root/symlink-store"
+ symlink_bin="$case_root/symlink-bin"
+ mkdir -p "$symlink_home" "$symlink_store"
+ printf '%s\n' 'alias dotfiles-managed=1' >"$symlink_store/zshrc"
+ ln -s "$symlink_store/zshrc" "$symlink_home/.zshrc"
+ symlink_output=$(run_installer "$symlink_home" "$case_root/symlink-install" "$symlink_bin" "$stable_tag" 2>&1)
+ assert_contains "$symlink_output" 'Updated ~/.zshrc' "$interpreter_name symlinked rc update disclosure"
+ [[ -L "$symlink_home/.zshrc" ]] || fail "$interpreter_name symlinked rc must stay a symlink"
+ [[ $(readlink "$symlink_home/.zshrc") == "$symlink_store/zshrc" ]] || fail "$interpreter_name symlinked rc target must not change"
+ [[ $(grep -Fc '# Composio CLI' "$symlink_store/zshrc") -eq 1 ]] || fail "$interpreter_name symlink target must hold one managed block"
+ grep -Fq "export PATH=\"$symlink_bin:\$PATH\"" "$symlink_store/zshrc" || fail "$interpreter_name symlink target managed line"
+ grep -Fq 'alias dotfiles-managed=1' "$symlink_store/zshrc" || fail "$interpreter_name symlink target unmanaged content preserved"
+
+ # The inline rewrite must preserve the startup file's permission bits.
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ CASE_SHELL_VALUE=/bin/zsh
+ mode_home="$case_root/mode-home"
+ mkdir -p "$mode_home"
+ printf '%s\n' 'alias mode-check=1' >"$mode_home/.zshrc"
+ chmod 600 "$mode_home/.zshrc"
+ run_installer "$mode_home" "$case_root/mode-install" "$case_root/mode-bin" "$stable_tag" >/dev/null 2>&1
+ grep -Fq '# Composio CLI' "$mode_home/.zshrc" || fail "$interpreter_name mode-preservation run must write the block"
+ case $(uname) in
+ Darwin) mode_actual=$(stat -f '%Lp' "$mode_home/.zshrc") ;;
+ *) mode_actual=$(stat -c '%a' "$mode_home/.zshrc") ;;
+ esac
+ [[ $mode_actual == 600 ]] || fail "$interpreter_name inline rewrite must preserve the file mode (got $mode_actual)"
+
+ # --- Delegated setup verification (stale managed blocks) ---
+
+ # A delegated CLI that exits 0 without reconciling a pre-seeded stale block
+ # must not be trusted: the installer verifies the startup file, reconciles
+ # inline, and reports the fallback disclosure with the Case B ending.
+ reset_case
+ CASE_INSTALL_SHELL=zsh
+ CASE_INSTALL_RECONCILE=0
+ stale_home="$case_root/stale-delegated-home"
+ stale_bin="$case_root/stale-delegated-bin"
+ mkdir -p "$stale_home"
+ printf '%s\n' 'alias stale-guard=1' '' '# Composio CLI' 'export PATH="/stale/old-bin:$PATH"' >"$stale_home/.zshrc"
+ stale_output=$(run_installer "$stale_home" "$case_root/stale-delegated-install" "$stale_bin" "$stable_tag" 2>&1)
+ grep -Fq "|installer|$stale_bin|install --shell zsh" "$composio_log" || fail "$interpreter_name stale delegation still delegates first"
+ assert_contains "$stale_output" "$(configured_line zsh)" "$interpreter_name stale delegation reconciles inline"
+ [[ $(grep -Fc '# Composio CLI' "$stale_home/.zshrc") -eq 1 ]] || fail "$interpreter_name stale reconcile keeps one marker block"
+ grep -Fq "export PATH=\"$stale_bin:\$PATH\"" "$stale_home/.zshrc" || fail "$interpreter_name stale reconcile names the current bin dir"
+ if grep -Fq '/stale/old-bin' "$stale_home/.zshrc"; then
+ fail "$interpreter_name stale managed path must be replaced after delegation"
+ fi
+ grep -Fq 'alias stale-guard=1' "$stale_home/.zshrc" || fail "$interpreter_name stale reconcile preserves unmanaged content"
+ assert_tail "$stale_output" "$case_b_tail" "$interpreter_name stale delegation Case B tail"
+
+ # --- Unsafe resolved bin dirs under the default flow: shell metacharacters never reach rc files ---
+
++ # Only characters double quotes still expand are rejected: `;` is literal
++ # inside them and stays legal, so it is deliberately not probed here.
+ unsafe_auto_index=0
- for unsafe_character in ';' '$'; do
++ for unsafe_character in '$' '`'; do
+ unsafe_auto_index=$((unsafe_auto_index + 1))
+ reset_case
+ unsafe_auto_home="$case_root/unsafe-auto-$unsafe_auto_index-home"
+ unsafe_auto_install="$case_root/unsafe-auto-$unsafe_auto_index-install"
+ unsafe_auto_bin="$case_root/unsafe-auto${unsafe_character}$unsafe_auto_index-bin"
+ unsafe_auto_output=$(run_installer "$unsafe_auto_home" "$unsafe_auto_install" "$unsafe_auto_bin" "$stable_tag" 2>&1) ||
+ fail "$interpreter_name unsafe auto bin dir with $unsafe_character must keep the install successful"
+ if grep -Fq 'install --shell' "$composio_log"; then
+ fail "$interpreter_name unsafe auto bin dir must be rejected before delegation"
+ fi
+ [[ ! -e "$unsafe_auto_home/.bashrc" && ! -e "$unsafe_auto_home/.bash_profile" ]] ||
+ fail "$interpreter_name unsafe auto bin dir must not write startup files"
+ [[ -x "$unsafe_auto_install/composio" ]] || fail "$interpreter_name unsafe auto bin dir must retain the binary"
+ assert_contains "$unsafe_auto_output" "$unsafe_auto_bin" "$interpreter_name unsafe auto warning names the rejected path"
+ assert_tail "$unsafe_auto_output" "$(recovery_tail later "$unsafe_auto_install/composio")" "$interpreter_name unsafe auto recovery tail"
+ done
+
+ # A valid absolute install dir containing spaces stays copy-paste safe in
+ # recovery output: the printed command executes the installed binary as-is.
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ space_home="$case_root/space-home"
+ space_install="$case_root/space install/dir"
+ mkdir -p "$space_home/.bashrc"
+ space_output=$(run_installer "$space_home" "$space_install" "$case_root/space-bin" "$stable_tag" 2>&1) ||
+ fail "$interpreter_name spaced install dir setup failure must keep the install successful"
+ assert_tail "$space_output" "$(recovery_tail later "'$space_install/composio'")" "$interpreter_name spaced recovery tail"
+ space_recovery_line=$(printf '%s\n' "$space_output" | tail -n 1)
+ space_recovery_command=${space_recovery_line# }
+ space_recovery_command=${space_recovery_command% login}
+ space_paste_output=$(env TEST_COMPOSIO_LOG="$composio_log" "$interpreter" -c "$space_recovery_command --version") ||
+ fail "$interpreter_name spaced recovery command must execute when pasted"
+ [[ $space_paste_output == 'composio fake 98.0.0' ]] || fail "$interpreter_name spaced recovery command output"
+
+ # --- Final-block contract combinations: exactly one truthful ending, always last ---
+
+ # Plugin output completes before the final block.
+ reset_case
+ CASE_PLUGINS=1
+ plugin_order_output=$(run_installer "$case_root/plugin-order-home" "$case_root/plugin-order-install" "$case_root/plugin-order-bin" "$stable_tag" 2>&1)
+ assert_contains "$plugin_order_output" 'Installing plugins for detected agent hosts...' "$interpreter_name plugin status printed"
+ assert_tail "$plugin_order_output" "$case_b_tail" "$interpreter_name plugin output precedes the final block"
+
+ # --agent, setup succeeds, command not yet resolvable: completed state plus
+ # only the new-terminal notice; never a second login command.
+ reset_case
+ agent_home="$case_root/agent-home"
+ agent_output=$(run_installer "$agent_home" "$case_root/agent-install" "$case_root/agent-bin" "$stable_tag" --agent 2>&1)
+ grep -Fq 'login --agent --no-skill-install' "$composio_log" || fail "$interpreter_name agent login invocation"
+ assert_not_contains "$agent_output" 'composio login' "$interpreter_name agent flow must not print a generic login command"
+ assert_tail "$agent_output" $'Composio agent login complete.\nOpen a new terminal to use the composio command.' "$interpreter_name agent Case B tail"
+
+ # --agent with the installed command already resolvable: completed state only.
+ reset_case
+ agent_ready_bin="$case_root/agent-ready-bin"
+ CASE_PATH_PREFIX="$agent_ready_bin:"
+ agent_ready_output=$(run_installer "$case_root/agent-ready-home" "$case_root/agent-ready-install" "$agent_ready_bin" "$stable_tag" --agent 2>&1)
+ assert_not_contains "$agent_ready_output" 'Open a new terminal' "$interpreter_name agent ready flow needs no terminal notice"
+ assert_tail "$agent_ready_output" 'Composio agent login complete.' "$interpreter_name agent Case A tail"
+
+ # --agent with setup failure: completed state plus warning and trusted
+ # installed-path guidance; still no generic login command.
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ agent_fail_home="$case_root/agent-fail-home"
+ agent_fail_install="$case_root/agent-fail-install"
+ mkdir -p "$agent_fail_home/.bashrc"
+ agent_fail_output=$(run_installer "$agent_fail_home" "$agent_fail_install" "$case_root/agent-fail-bin" "$stable_tag" --agent 2>&1) ||
+ fail "$interpreter_name agent setup failure must keep the install successful"
+ assert_contains "$agent_fail_output" 'Composio agent login complete.' "$interpreter_name agent completion survives setup failure"
+ assert_contains "$agent_fail_output" 'warning: Automatic PATH setup for bash failed' "$interpreter_name agent setup failure warning"
+ assert_not_contains "$agent_fail_output" 'composio login' "$interpreter_name agent setup failure must not print a login command"
+ assert_tail "$agent_fail_output" $'Run composio from its installed location:\n\n '"$agent_fail_install/composio --help" "$interpreter_name agent setup failure recovery tail"
+
+ # --agent with setup skipped (none): completed state plus installed-path guidance.
+ reset_case
+ CASE_INSTALL_SHELL=none
+ agent_none_install="$case_root/agent-none-install"
+ agent_none_output=$(run_installer "$case_root/agent-none-home" "$agent_none_install" "$case_root/agent-none-bin" "$stable_tag" --agent 2>&1)
+ assert_not_contains "$agent_none_output" 'composio login' "$interpreter_name agent none flow must not print a login command"
+ assert_tail "$agent_none_output" $'Composio agent login complete.\nRun composio from its installed location:\n\n '"$agent_none_install/composio --help" "$interpreter_name agent none tail"
+
printf 'install scripts passed under %s\n' "$interpreter_name"
done
diff --cc ts/packages/cli/CHANGELOG.md
index 56556c8ba,21a797634..f88246096
--- a/ts/packages/cli/CHANGELOG.md
+++ b/ts/packages/cli/CHANGELOG.md
@@@ -4,21 -4,47 +4,54 @@@
### Minor Changes
-- `composio install` gains a `--shell <zsh|bash|fish>` flag that overrides `$SHELL` detection, in preparation for the mise-style installer rewrite. The bin-dir PATH target now resolves through `COMPOSIO_BIN_DIR`, an existing `~/.local/bin/composio`, or the real binary's own directory, in that order, instead of hardcoding `~/.composio`; rc blocks write only a PATH line (the `export COMPOSIO_INSTALL_DIR=...` line is gone, since that variable identifies the install bundle, not the PATH entry point). Bash now also writes the PATH line to `~/.bash_profile` or `~/.bash_login` when either already exists, so `bash -ilc` picks it up. The restart hint bug is fixed: bash now prints `source ~/.bashrc` instead of the literal string `exec $SHELL`.
+- The installer (`curl -fsSL https://composio.dev/install | sh`) now configures your shell automatically: `COMPOSIO_INSTALL_SHELL` defaults to `auto`, which infers the login shell from `$SHELL` (zsh, bash, or fish) and always runs idempotent PATH setup for it; `COMPOSIO_INSTALL_SHELL=none` keeps the old install-only behavior for CI, Docker, and dotfile managers. Startup-file setup failures no longer fail the install — the installer keeps the binary, warns, and prints a runnable absolute-path command. `composio install` now reconciles an existing managed PATH block whose bin directory changed (one block per physical file, symlink-aware) and suppresses its boxed restart hint when invoked by the installer, which owns the final message.
+- `composio install` gains a `--shell <zsh|bash|fish>` flag that overrides `$SHELL` detection, in preparation for the mise-style installer rewrite. The bin-dir PATH target now resolves through `COMPOSIO_BIN_DIR`, an existing `~/.local/bin/composio`, or the real binary's own directory, in that order, instead of hardcoding `~/.composio`; rc blocks write only a PATH line (the `export COMPOSIO_INSTALL_DIR=...` line is gone, since that variable identifies the install bundle, not the PATH entry point). Bash now always writes the PATH line to a login-mode startup file as well as `~/.bashrc`, so `bash -ilc` (and macOS Terminal.app, which starts a login shell) picks it up: the first existing of `~/.bash_profile` or `~/.bash_login`, or a newly created `~/.bash_profile` when neither exists. A `~/.bash_profile` created this way shadows `~/.profile`, so it is seeded to source it first; `~/.profile` itself is never modified. The restart hint bug is fixed: bash now prints `source ~/.bashrc` instead of the literal string `exec $SHELL`.
+ - `COMPOSIO_BIN_DIR` is a documented public override: set it to the absolute directory `composio install` should add to `PATH` when the entry point users reach is a shim or symlink rather than the binary itself. See the CLI README for the full resolution order.
+ - `composio install` now exits non-zero, having written nothing, when it cannot produce a safe PATH line. There are two abort conditions: the resolved bin directory is not absolute, or it contains a character that cannot be embedded in a quoted rc line. A non-zero exit is what makes `install.sh` run its inline PATH fallback, so an aborted run still leaves the user with a working `PATH` — previously the command exited 0 and the fallback never ran.
+ - The unsafe-character set is narrower than the one first shipped in this entry. The bin dir is only ever written inside double quotes, where `;`, `|`, `&`, `(`, `)`, and `'` are literal — only `` ` ``, `$`, `"`, `\`, newline, carriage return, and the `:` PATH separator abort now. Paths like `/Users/o'brien/.composio` are accepted instead of rejected.
-- An rc file that carries the older three-line Composio block (`export COMPOSIO_INSTALL_DIR=...` plus a PATH line derived from it), written by a previous CLI or by `install.sh`'s fallback, is migrated to the current single-line block in place instead of being treated as configured forever. Re-running the command is still idempotent, and a completions block elsewhere in the file is untouched.
++- An rc file that carries the older three-line Composio block (`export COMPOSIO_INSTALL_DIR=...` plus a PATH line derived from it), written by a previous CLI or by `install.sh`'s fallback, is migrated to the current single-line block instead of being treated as configured forever. The stale managed lines are removed where they stood and one refreshed block is appended after the remaining content, so your own lines keep their order and the last-sourced PATH line wins. Re-running the command is still idempotent, and a completions block elsewhere in the file is untouched.
+ - `composio install` no longer skips the rc write when the bin directory happens to be on the invoking process's `$PATH`. That said nothing about future shells — an ad-hoc `export` or a version-manager shim made the command persist nothing and still report success.
+ - Note for custom install directories: the rc block no longer records `COMPOSIO_INSTALL_DIR`. If you installed to a custom directory with `COMPOSIO_INSTALL_DIR=... curl ... | bash` and later re-run the install script without re-specifying it, the script installs a second copy under `~/.composio` while your rc `PATH` still points at the old one. Re-specify `COMPOSIO_INSTALL_DIR` when reinstalling, or use `composio upgrade`, which replaces the running binary in place.
### Patch Changes
+- Fix Linux `composio upgrade` failures with `ETXTBSY` by staging CLI files in
+ the install directory and renaming the executable last. The installer and
+ companion repair use the same replacement strategy, and the running binary
+ now reports its compiled version when `release-tag.txt` disagrees. Users on
+ an affected build must re-run `install.sh` once to install the first fixed
+ version.
- - Make GitHub release metadata the sole version authority for standalone CLI
- binaries. Release builds now embed their exact tag version, manual skill
- installation follows the packaged release tag, and stable releases can only
- promote a tested beta.
+ - Connected-account statuses added by the server no longer break
+ `connected-accounts`, `link`, or `listen`. Piped output still strips
+ credential fields, and schema warnings no longer print raw response values.
+ - `composio login --poll` now reports unreadable cache files as I/O errors
+ instead of treating them as invalid session data.
+
+ ## 0.3.1
+
+ ### Minor Changes
+
+ - The CLI now points Claude Code and Codex users to `composio setup` when the
+ Composio agent plugin is missing. The hint goes to stderr, appears at most
+ once every 24 hours, remains visible in non-TTY agent sessions, and stays
+ suppressed inside `composio run` children.
+ - Telemetry now goes directly to PostHog. This captures `install` and `setup`
+ events before login without changing existing opt-outs.
+ - Telemetry events now include `journey_stage` (`install`, `setup`, `login`,
+ `connect`, `execute`, or `other`) and `cli_channel` (`stable` or `beta`).
+ `install.sh` also labels `composio install` with
+ `invocation_origin: installer`, so script installs can be separated from
+ manual runs. npm and Homebrew installs do not pass through `install.sh` and
+ therefore have no installer origin.
+
+ ## 0.3.0
+
+ ### Patch Changes
+
+ - The GitHub release tag is now the only version source for standalone CLI
+ binaries. Release builds embed the exact tag version, manual skill
+ installation uses that tag, and stable releases can only promote a tested
+ beta.
## 0.2.33
diff --cc ts/packages/cli/src/commands/install.cmd.ts
index e28dda2d6,ef82ac3dc..e5f4f2949
--- a/ts/packages/cli/src/commands/install.cmd.ts
+++ b/ts/packages/cli/src/commands/install.cmd.ts
@@@ -62,8 -62,24 +62,25 @@@ interface ShellConfig
const MARKER = '# Composio CLI';
const COMPLETIONS_MARKER = '# Composio CLI completions';
- /** Reject bin-dir paths containing shell metacharacters to prevent injection into rc files. */
- const UNSAFE_PATH_CHARS = /[:;`$|&"'()\n\r\\]/;
+ /**
+ * Reject bin-dir paths that cannot be embedded safely in a managed rc line.
+ *
+ * The resolved dir is only ever emitted inside double quotes — `export
+ * PATH="<dir>:$PATH"` for bash/zsh and `set --export PATH "<dir>" $PATH` for
- * fish — so the set is deliberately narrow:
++ * fish — so the set is deliberately narrow and mirrors `is_unsafe_path` in
++ * install.sh, keeping the inline fallback and this command on one contract:
+ *
+ * - `` ` ``, `$`, `\`, `"`: the only characters bash and zsh still expand
+ * inside double quotes (`!` history expansion does not apply to sourced
+ * files). fish expands a strict subset of those. Everything else — `;`, `|`,
+ * `&`, `(`, `)`, `'` — is literal there, so a path like
+ * `/Users/o'brien/.composio` is written verbatim rather than rejected.
+ * - `\n`, `\r`: structural, not a quoting concern — either would split the
+ * managed block into extra rc lines.
+ * - `:`: structural too, as the PATH separator: a dir containing one would
+ * silently prepend more than one entry.
+ */
+ const UNSAFE_PATH_CHARS = /[`$"\\\n\r:]/;
const isUnsafePath = (p: string): boolean => UNSAFE_PATH_CHARS.test(p);
// SHELL, PATH, and COMPOSIO_BIN_DIR are read from the literal environment: SHELL
@@@ -252,340 -241,40 +269,331 @@@ const buildShellConfig =
completionBlock: completionScript ? `${COMPLETIONS_MARKER}\n${completionScript}` : undefined,
});
-/** Check whether a file already contains a given marker line. */
+/**
+ * Check whether a file already contains a given marker line. Byte-exact, like
+ * install.sh's awk `$0 == "# Composio CLI"` match: a marker mangled by CRLF
+ * endings or stray whitespace is not ours and is left alone on both sides.
+ */
const fileContains = (contents: string, marker: string): boolean =>
- contents.split('\n').some(line => line.trim() === marker.trim());
+ contents.split('\n').some(line => line === marker);
+
+/** Outcome of reconciling a startup file's managed PATH block against the resolved bin dir. */
+type ManagedPathBlockState =
+ | { readonly state: 'absent' }
+ | { readonly state: 'current' }
+ | { readonly state: 'stale'; readonly reconciled: string };
/**
- * Splice the current managed PATH block over the one already in `contents`.
- *
- * The managed block runs from its `# Composio CLI` marker line up to the first
- * blank line, the completions marker, or end of file — the exact layout both
- * this command and install.sh's inline fallback produce, since blocks are
- * always separated by a blank line. That is what lets a legacy three-line block
- * (`export COMPOSIO_INSTALL_DIR=...` plus a PATH line derived from it) be
- * migrated to the current single-line form without touching a completions block
- * further down the file.
+ * A line this installer could have written as the managed PATH assignment:
+ * POSIX `export PATH="<dir>:$PATH"` or fish `set --export PATH "<dir>" $PATH`.
+ * Matched structurally on the prefix/suffix (any bin dir) so stale blocks
+ * recording another directory are still recognized as ours.
+ */
+const isManagedPathAssignment = (line: string): boolean => {
+ const trimmed = line.trim();
+ return (
+ (trimmed.startsWith('export PATH="') && trimmed.endsWith(':$PATH"')) ||
+ (trimmed.startsWith('set --export PATH "') && trimmed.endsWith('" $PATH'))
+ );
+};
+
+const LEGACY_POSIX_INSTALL_DIR_PREFIX = 'export COMPOSIO_INSTALL_DIR="';
+const LEGACY_FISH_INSTALL_DIR_PREFIX = 'set --export COMPOSIO_INSTALL_DIR "';
+
+/**
+ * The install-dir assignment the previously released installer wrote as the
+ * second line of its three-line managed block: POSIX
+ * `export COMPOSIO_INSTALL_DIR="<dir>"` or fish
+ * `set --export COMPOSIO_INSTALL_DIR "<dir>"`. Matched structurally on the
+ * prefix/quotes (any dir), like `isManagedPathAssignment`.
+ */
+const isLegacyInstallDirAssignment = (line: string): boolean => {
+ const trimmed = line.trim();
+ return (
+ (trimmed.startsWith(LEGACY_POSIX_INSTALL_DIR_PREFIX) &&
+ trimmed.endsWith('"') &&
+ trimmed.length > LEGACY_POSIX_INSTALL_DIR_PREFIX.length) ||
+ (trimmed.startsWith(LEGACY_FISH_INSTALL_DIR_PREFIX) &&
+ trimmed.endsWith('"') &&
+ trimmed.length > LEGACY_FISH_INSTALL_DIR_PREFIX.length)
+ );
+};
+
+/**
+ * True when `first` and `second` are the two export lines of the legacy
+ * three-line block, in the same shell dialect. The closing PATH line is
+ * matched byte-for-byte (modulo surrounding whitespace) against the exact
+ * text the legacy installer emitted, so anything else after an install-dir
+ * assignment is user content and stays untouched.
+ */
+const isLegacyManagedPair = (first: string, second: string): boolean => {
+ if (!isLegacyInstallDirAssignment(first)) return false;
+ const secondTrimmed = second.trim();
+ return first.trim().startsWith(LEGACY_POSIX_INSTALL_DIR_PREFIX)
+ ? secondTrimmed === 'export PATH="$COMPOSIO_INSTALL_DIR:$PATH"'
+ : secondTrimmed === 'set --export PATH $COMPOSIO_INSTALL_DIR $PATH';
+};
+
+/**
+ * Append managed blocks after existing content, separated by one blank line
+ * and ending with a newline. Content lacking a final newline gains one first,
+ * exactly as install.sh's line-based awk rewrite normalizes it.
+ */
+export const appendManagedBlocks = (contents: string, blocks: readonly string[]): string => {
+ const base = contents === '' || contents.endsWith('\n') ? contents : `${contents}\n`;
+ return `${base}\n${blocks.join('\n\n')}\n`;
+};
+
+/**
+ * Reconcile the managed PATH block — the `MARKER` line plus the PATH
+ * assignment right below it — with the currently resolved bin directory.
*
- * Returns `None` when the file carries no marker at all, so the caller appends.
+ * This mirrors install.sh's write_path_block awk program step for step, and
+ * the shared fixtures under test/managed-block-fixtures pin both
+ * implementations to byte-identical outputs — any behavioral edit here must
+ * land in install.sh too. A file whose single byte-exact marker is directly
+ * followed by the expected assignment is current and left untouched.
+ * Otherwise every managed line — each marker, plus the next line only when it
+ * is a recognizable managed PATH assignment, or the next two lines when they
+ * are the exact export pair of the legacy three-line block (marker,
+ * `export COMPOSIO_INSTALL_DIR=...`, PATH line, in POSIX or fish form);
+ * anything else (a user annotation, a blank line, another marker) is not
+ * ours to delete — is removed and one fresh block is appended after the
+ * remaining content. No
+ * user content is ever deleted, and because these prepend-style assignments
+ * make the last-sourced line win, the new bin dir takes PATH precedence over
+ * any orphaned stale assignment that had to be preserved.
*/
-const replaceManagedPathBlock = (contents: string, block: string): Option.Option<string> => {
+export const reconcileManagedPathBlock = (
+ contents: string,
+ pathBlock: string
+): ManagedPathBlockState => {
const lines = contents.split('\n');
- const isBlockEnd = (line: string): boolean =>
- line.trim() === '' || line.trim() === COMPLETIONS_MARKER;
-
- return Arr.findFirstIndex(lines, line => line.trim() === MARKER).pipe(
- Option.map(markerIndex => {
- const endIndex = Arr.findFirstIndex(Arr.drop(lines, markerIndex + 1), isBlockEnd).pipe(
- Option.map(offset => markerIndex + 1 + offset),
- Option.getOrElse(() => lines.length)
- );
- return Arr.appendAll(
- Arr.appendAll(Arr.take(lines, markerIndex), block.split('\n')),
- Arr.drop(lines, endIndex)
- ).join('\n');
+ const markerIndexes = lines.flatMap((line, index) => (line === MARKER ? [index] : []));
+ const firstMarkerIndex = markerIndexes[0];
+ if (firstMarkerIndex === undefined) return { state: 'absent' };
+
+ const blockLines = pathBlock.split('\n');
+ if (markerIndexes.length === 1 && lines[firstMarkerIndex + 1] === blockLines[1]) {
+ return { state: 'current' };
+ }
+
+ // Managed lines: each marker line, plus the next line only when it is a
+ // recognizable managed PATH assignment, or the next two lines when they are
+ // the exact export pair of the legacy three-line block — anything else is
+ // not ours to delete.
+ const managedLineIndexes = new Set<number>(
+ markerIndexes.flatMap(markerIndex => {
+ const assignment = lines[markerIndex + 1];
+ if (assignment === undefined) return [markerIndex];
+ if (isManagedPathAssignment(assignment)) return [markerIndex, markerIndex + 1];
+ const legacyPathLine = lines[markerIndex + 2];
+ if (legacyPathLine !== undefined && isLegacyManagedPair(assignment, legacyPathLine)) {
+ return [markerIndex, markerIndex + 1, markerIndex + 2];
+ }
+ return [markerIndex];
})
);
+
+ // Like the awk rewrite, kept content is a sequence of newline-terminated
+ // lines: drop the split's trailing sentinel and re-terminate the last line.
+ const keptLines = lines.filter((_, index) => !managedLineIndexes.has(index));
+ const contentLines = keptLines[keptLines.length - 1] === '' ? keptLines.slice(0, -1) : keptLines;
+ const kept = contentLines.length === 0 ? '' : contentLines.join('\n') + '\n';
+ return { state: 'stale', reconciled: appendManagedBlocks(kept, [pathBlock]) };
+};
+
+interface ManagedBlockReplacement {
+ readonly contents: string;
+ readonly displayPath: string;
+}
+
+interface PathBlockWritePlan {
+ readonly appendPathFiles: readonly string[];
+ readonly replacementsByTarget: ReadonlyMap<string, ManagedBlockReplacement>;
+ readonly loginOverrideWritten: boolean;
+}
+
+/**
+ * Decide, per configured PATH file, whether the managed block must be appended
+ * (absent), replaced in place (stale bin dir), or left alone (already
+ * current). Both appends and replacements are deduplicated by physical write
+ * target so two logical paths aliasing the same file (a dotfiles symlink
+ * setup) keep exactly one managed block.
+ */
+const planPathBlockWrites = (params: {
+ readonly pathFiles: readonly string[];
+ readonly existingByFile: ReadonlyMap<string, string>;
+ readonly pathFileTargets: ReadonlyMap<string, string>;
+ readonly pathBlock: string;
+ readonly bashLoginOverride: string | undefined;
- readonly skipPathWriteForReachability: boolean;
+}): PathBlockWritePlan => {
+ const appendPathFiles: string[] = [];
+ const replacementsByTarget = new Map<string, ManagedBlockReplacement>();
+ const queuedPathTargets = new Set<string>();
+ let loginOverrideWritten = false;
+ for (const filePath of params.pathFiles) {
+ const existing = params.existingByFile.get(filePath) ?? '';
+ const target = params.pathFileTargets.get(filePath)!;
+ const reconciliation = reconcileManagedPathBlock(existing, params.pathBlock);
+ if (reconciliation.state === 'stale') {
+ if (!replacementsByTarget.has(target)) {
+ replacementsByTarget.set(target, {
+ contents: reconciliation.reconciled,
+ displayPath: filePath,
+ });
+ if (filePath === params.bashLoginOverride) loginOverrideWritten = true;
+ }
+ continue;
+ }
- if (
- reconciliation.state === 'current' ||
- params.skipPathWriteForReachability ||
- queuedPathTargets.has(target)
- ) {
++ // Only a byte-exact current block is a no-op. A `$PATH` that already
++ // resolves in the invoking process is deliberately not a reason to skip:
++ // it is transient evidence that says nothing about future shells.
++ if (reconciliation.state === 'current' || queuedPathTargets.has(target)) {
+ continue;
+ }
+ appendPathFiles.push(filePath);
+ queuedPathTargets.add(target);
+ if (filePath === params.bashLoginOverride) loginOverrideWritten = true;
+ }
+ return { appendPathFiles, replacementsByTarget, loginOverrideWritten };
+};
+
+/**
+ * Replace an rc file's contents via the shared atomic-write helper, preserving
+ * the existing file's mode so a private rc stays private across the rewrite.
+ */
+const replaceFilePreservingMode = (
+ fs: FileSystem.FileSystem,
+ target: string,
+ contents: string
+): Effect.Effect<void, PlatformError> =>
+ atomicWriteFileString({ fs, target, contents, preserveMode: true });
+
+/** Append each file's queued blocks in one atomic, mode-preserving rewrite per file. */
+const appendQueuedBlocks = (params: {
+ readonly blocksByFile: ReadonlyMap<string, ReadonlyArray<string>>;
+ readonly pathFileTargets: ReadonlyMap<string, string>;
+ readonly fs: FileSystem.FileSystem;
+ readonly path: Path.Path;
+ readonly homedir: string;
+ readonly report: (message: string) => Effect.Effect<void>;
+}): Effect.Effect<void, PlatformError> =>
+ Effect.gen(function* () {
+ const { fs, path } = params;
+ for (const [filePath, blocks] of params.blocksByFile.entries()) {
+ // Re-read instead of reusing the pre-check snapshot: two configured paths
+ // can alias the same physical file through symlinks, and this write must
+ // not discard a previous iteration's append.
+ const existingContents = yield* readMaybeMissingFile(filePath, fs);
+ // PATH files were already resolved by the caller; only the completion
+ // file needs a fresh resolve.
+ const writeTarget =
+ params.pathFileTargets.get(filePath) ?? (yield* resolveWriteTarget(filePath, fs));
+
+ yield* fs
+ .makeDirectory(path.dirname(writeTarget), { recursive: true })
+ .pipe(
+ Effect.catchAll(e =>
+ Effect.logDebug('Could not create parent directory (may already exist):', e)
+ )
+ );
+
+ yield* replaceFilePreservingMode(
+ fs,
+ writeTarget,
+ appendManagedBlocks(existingContents, blocks)
+ );
+ yield* params.report(`Updated ${tildify(filePath, params.homedir)}`);
+ }
+ });
+
+/** Atomically rewrite each reconciled physical target, preserving its file mode. */
+const writeReconciledTargets = (params: {
+ readonly replacementsByTarget: ReadonlyMap<string, ManagedBlockReplacement>;
+ readonly fs: FileSystem.FileSystem;
+ readonly homedir: string;
+ readonly report: (message: string) => Effect.Effect<void>;
+}): Effect.Effect<void, PlatformError> =>
+ Effect.gen(function* () {
+ for (const [writeTarget, replacement] of params.replacementsByTarget.entries()) {
+ yield* replaceFilePreservingMode(params.fs, writeTarget, replacement.contents);
+ yield* params.report(`Updated ${tildify(replacement.displayPath, params.homedir)}`);
+ }
+ });
+
+/** Completion status line, plus whether the completion block still needs appending. */
+const planCompletionWrite = (params: {
+ readonly shell: Shell;
+ readonly completionsRequested: boolean;
+ readonly completionBlock: string | undefined;
+ readonly completionFile: string;
+ readonly existingCompletionFile: string;
+ readonly homedir: string;
+}): { readonly statusLine: string; readonly append: boolean } => {
+ if (params.shell === 'zsh') {
+ return { statusLine: 'Completions: skipped for zsh', append: false };
+ }
+ if (!params.completionsRequested) {
+ return {
+ statusLine: 'Completions: skipped by default (pass --completions to enable)',
+ append: false,
+ };
+ }
+ if (!params.completionBlock) {
+ return { statusLine: 'Completions: not available for this shell', append: false };
+ }
+ if (fileContains(params.existingCompletionFile, COMPLETIONS_MARKER)) {
+ return { statusLine: 'Completions: already configured', append: false };
+ }
+ return {
+ statusLine:
+ params.shell === 'fish'
+ ? `Completions: will install fish completions to ${tildify(params.completionFile, params.homedir)}`
+ : 'Completions: will install shell completions',
+ append: true,
+ };
+};
+
+/** Status lines summarizing the planned PATH work, in print order. */
+const pathStatusLines = (params: {
+ readonly pathWritten: boolean;
+ readonly pathReplaced: boolean;
- readonly skipPathWriteForReachability: boolean;
+ readonly renderedBinDir: string;
+}): readonly string[] => {
+ const lines: string[] = [];
+ if (params.pathWritten) lines.push(`PATH: will add ${params.renderedBinDir} to $PATH`);
+ if (params.pathReplaced) {
+ lines.push(`PATH: will update the managed block to ${params.renderedBinDir}`);
+ }
- if (lines.length === 0) {
- lines.push(
- params.skipPathWriteForReachability
- ? 'PATH: already on $PATH — nothing to do.'
- : 'PATH: already configured'
- );
- }
++ if (lines.length === 0) lines.push('PATH: already configured');
+ return lines;
+};
+
+/** Shell-specific body of the restart hint printed after a change. */
+const restartHintBody = (params: {
+ readonly shell: Shell;
+ readonly zshPathFile: string;
+ readonly bashrc: string;
+ readonly bashLoginOverride: string | undefined;
+ readonly loginOverrideWritten: boolean;
+ readonly homedir: string;
+}): string => {
+ switch (params.shell) {
+ case 'fish':
+ return 'exec fish';
+ case 'zsh':
+ return `source ${tildify(params.zshPathFile, params.homedir)}`;
+ case 'bash': {
+ const hintLines = [`source ${tildify(params.bashrc, params.homedir)}`];
+ if (params.loginOverrideWritten && params.bashLoginOverride) {
+ hintLines.push(
+ `${tildify(params.bashLoginOverride, params.homedir)} was also updated — that entry applies to new login shells too.`
+ );
+ }
+ return hintLines.join('\n');
+ }
+ }
};
const tildify = (p: string, homedir: string): string =>
@@@ -683,15 -445,6 +691,14 @@@ export const installShellIntegration =
return yield* new ShellSetupAbortError({ message });
}
+ // The installer owns the closing message: when install.sh delegates to
+ // this command it passes COMPOSIO_CLI_INVOCATION_ORIGIN=installer and
+ // prints the final action block itself. Keep the concise per-file status
+ // lines but suppress the boxed restart hint so the CLI never prints a
+ // competing instruction.
+ const invocationOrigin = yield* readOptionalEnv('COMPOSIO_CLI_INVOCATION_ORIGIN');
+ const installerOwnsFinalMessaging = invocationOrigin === 'installer';
+
- const isExplicitShell = params.shell !== undefined;
const shellEnv = yield* readEnvWithDefault('SHELL', '');
const shell = params.shell ?? detectShellFromEnv(path, shellEnv);
@@@ -761,82 -520,78 +773,69 @@@
}
};
- // Auto-detected mode may skip the PATH write entirely when the bin dir is
- // already reachable; an explicit --shell always configures its files.
- // Only applies to a genuinely fresh install: if any target file already
- // carries our marker from a prior run, a file that appeared since then
- // (e.g. a freshly created .bash_profile) still needs its own write, even
- // though the invoking process's current $PATH already resolves.
- const anyPathFileAlreadyMarked = config.pathFiles.some(filePath =>
- fileContains(existingByFile.get(filePath) ?? '', MARKER)
- );
- const skipPathWriteForReachability =
- !isExplicitShell && binDirOnPath && !anyPathFileAlreadyMarked;
- // Path files whose existing managed block is stale and must be replaced in
- // place rather than appended to.
- const pathRewrites = new Set<string>();
- let pathWritten = false;
- let loginOverrideWritten = false;
- const queuedPathTargets = new Set<string>();
- for (const filePath of config.pathFiles) {
- const existing = existingByFile.get(filePath) ?? '';
- const target = pathFileTargets.get(filePath)!;
- if (queuedPathTargets.has(target)) continue;
- // The marker alone does not mean "configured": a block written by a
- // pre-`--shell` CLI or by install.sh's inline fallback still carries the
- // legacy `export COMPOSIO_INSTALL_DIR=` pair, and a block written for a
- // different bin dir points shells at the wrong binary. Only the exact
- // rendered line for the resolved bin dir is a no-op.
- if (fileContains(existing, config.pathLine)) continue;
- if (fileContains(existing, MARKER)) {
- pathRewrites.add(filePath);
- } else {
- pushBlock(filePath, config.pathBlock);
- }
- queuedPathTargets.add(target);
- pathWritten = true;
- if (filePath === bashLoginOverride) loginOverrideWritten = true;
+ const writePlan = planPathBlockWrites({
+ pathFiles: config.pathFiles,
+ existingByFile,
+ pathFileTargets,
+ pathBlock: config.pathBlock,
+ bashLoginOverride,
- skipPathWriteForReachability,
+ });
+ const { replacementsByTarget, loginOverrideWritten } = writePlan;
+ // A `.bash_profile` created here takes over from an existing `~/.profile`,
+ // so it leads with the passthrough that keeps sourcing it.
+ if (
+ bashLoginFile?.seedsProfilePassthrough === true &&
+ writePlan.appendPathFiles.includes(bashLoginFile.file)
+ ) {
+ pushBlock(bashLoginFile.file, BASH_PROFILE_PASSTHROUGH);
}
-
- if (pathWritten) {
- yield* step(`PATH: will add ${tildify(binDir, os.homedir)} to $PATH`);
- } else {
- yield* step('PATH: already configured');
+ for (const filePath of writePlan.appendPathFiles) {
+ pushBlock(filePath, config.pathBlock);
}
+ const pathWritten = writePlan.appendPathFiles.length > 0;
+
+ yield* Effect.forEach(
+ pathStatusLines({
+ pathWritten,
+ pathReplaced: replacementsByTarget.size > 0,
- skipPathWriteForReachability,
+ renderedBinDir: tildify(binDir, os.homedir),
+ }),
+ step
+ );
- if (shell === 'zsh') {
- yield* step('Completions: skipped for zsh');
- } else if (!params.completions) {
- yield* step('Completions: skipped by default (pass --completions to enable)');
- } else if (!config.completionBlock) {
- yield* step('Completions: not available for this shell');
- } else {
- const existingCompletionFile = existingByFile.get(config.completionFile) ?? '';
- if (!fileContains(existingCompletionFile, COMPLETIONS_MARKER)) {
- pushBlock(config.completionFile, config.completionBlock);
- yield* step(
- config.shell === 'fish'
- ? `Completions: will install fish completions to ${tildify(config.completionFile, os.homedir)}`
- : 'Completions: will install shell completions'
- );
- } else {
- yield* step('Completions: already configured');
- }
+ const completionWrite = planCompletionWrite({
+ shell,
+ completionsRequested: params.completions,
+ completionBlock: config.completionBlock,
+ completionFile: config.completionFile,
+ existingCompletionFile: existingByFile.get(config.completionFile) ?? '',
+ homedir: os.homedir,
+ });
+ if (completionWrite.append && config.completionBlock) {
+ pushBlock(config.completionFile, config.completionBlock);
}
+ yield* step(completionWrite.statusLine);
+
+ // Reconcile stale managed blocks first so any completion append below
+ // (which re-reads from disk) lands on top of the replaced contents.
+ yield* writeReconciledTargets({
+ replacementsByTarget,
+ fs,
+ homedir: os.homedir,
+ report: success,
+ });
- const filesToWrite = [...new Set([...pathRewrites, ...blocksByFile.keys()])];
-
- if (filesToWrite.length > 0) {
- for (const filePath of filesToWrite) {
- // A stale managed block is replaced where it stands, so the user's own
- // ordering survives; everything else is appended.
- yield* applyFileChanges({
- filePath,
- resolvedWriteTarget: Option.fromNullable(pathFileTargets.get(filePath)),
- rewritePathBlock: pathRewrites.has(filePath)
- ? Option.some(config.pathBlock)
- : Option.none(),
- appendBlocks: blocksByFile.get(filePath) ?? [],
- fs,
- path,
- });
+ yield* appendQueuedBlocks({
+ blocksByFile,
+ pathFileTargets,
+ fs,
+ path,
+ homedir: os.homedir,
+ report: success,
+ });
- yield* success(`Updated ${tildify(filePath, os.homedir)}`);
- }
- } else {
+ const changesWritten = blocksByFile.size > 0 || replacementsByTarget.size > 0;
+ if (!changesWritten) {
yield* success('Shell integration already configured — nothing to do.');
}
diff --cc ts/packages/cli/test/src/commands/install.cmd.test.ts
index 7a739b081,ac376057b..4ec066089
--- a/ts/packages/cli/test/src/commands/install.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/install.cmd.test.ts
@@@ -711,130 -564,116 +711,233 @@@ describe('CLI: composio install', () =
});
});
+ describe('[When] an rc file carries the legacy install.sh managed block', () => {
- layer(TestInstallLive())(it => {
- it.scoped('[Then] the stale block is migrated in place, not left or duplicated', () =>
++ layer(InstallTestLive())(it => {
++ it.scoped('[Then] the legacy pair is migrated, not left behind or duplicated', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/zsh');
+ const expectedBinDir = expectedRuntimeBinDir();
+
+ const rcPath = path.join(os.homedir, '.zshrc');
+ yield* fs.writeFileString(
+ rcPath,
+ [
+ '# user config above',
- '',
+ '# Composio CLI',
+ 'export COMPOSIO_INSTALL_DIR="$HOME/.composio"',
+ 'export PATH="$COMPOSIO_INSTALL_DIR:$PATH"',
- '',
+ '# user config below',
+ '',
+ ].join('\n')
+ );
+
+ yield* install();
+
+ const contents = yield* fs.readFileString(rcPath);
+ expect(contents).not.toContain('COMPOSIO_INSTALL_DIR');
+ expect(contents).toContain(`export PATH="${expectedBinDir}:$PATH"`);
+ expect(contents.match(/^# Composio CLI$/gm)?.length ?? 0).toBe(1);
- // The block is replaced where it stood: the user's own lines keep
- // their relative order around it.
++ // User content keeps its own relative order; the refreshed block is
++ // appended after it, exactly as install.sh's awk rewrite does.
+ expect(contents.indexOf('# user config above')).toBeLessThan(
- contents.indexOf('# Composio CLI')
- );
- expect(contents.indexOf('# Composio CLI')).toBeLessThan(
+ contents.indexOf('# user config below')
+ );
-
- const output = (yield* MockConsole.getLines()).join('\n');
- expect(output).toContain('PATH: will add');
++ expect(contents.indexOf('# user config below')).toBeLessThan(
++ contents.indexOf('# Composio CLI')
++ );
+ })
+ );
+ });
+ });
+
+ describe('[When] a legacy block sits above an existing completions block', () => {
- layer(TestInstallLive())(it => {
++ layer(InstallTestLive())(it => {
+ it.scoped('[Then] migrating the PATH block leaves the completions block intact', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/bash');
+ const expectedBinDir = expectedRuntimeBinDir();
+
+ const rcPath = path.join(os.homedir, '.bashrc');
+ yield* fs.writeFileString(
+ rcPath,
+ [
+ '# Composio CLI',
+ 'export COMPOSIO_INSTALL_DIR="$HOME/.composio"',
+ 'export PATH="$COMPOSIO_INSTALL_DIR:$PATH"',
+ '',
+ '# Composio CLI completions',
+ '_composio_completions() { :; }',
+ '',
+ ].join('\n')
+ );
+
- yield* install({ completions: true });
++ yield* install();
+
+ const contents = yield* fs.readFileString(rcPath);
+ expect(contents).not.toContain('COMPOSIO_INSTALL_DIR');
+ expect(contents).toContain(`export PATH="${expectedBinDir}:$PATH"`);
+ expect(contents).toContain('_composio_completions() { :; }');
+ expect(contents.match(/^# Composio CLI$/gm)?.length ?? 0).toBe(1);
+ expect(contents.match(/^# Composio CLI completions$/gm)?.length ?? 0).toBe(1);
+ })
+ );
+ });
+ });
+
+ describe('[When] a migrated rc file is installed into a second time', () => {
- layer(TestInstallLive())(it => {
++ layer(InstallTestLive())(it => {
+ it.scoped('[Then] the second run is a no-op', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/zsh');
+
+ const rcPath = path.join(os.homedir, '.zshrc');
+ yield* fs.writeFileString(
+ rcPath,
+ '# Composio CLI\nexport COMPOSIO_INSTALL_DIR="$HOME/.composio"\nexport PATH="$COMPOSIO_INSTALL_DIR:$PATH"\n'
+ );
+
+ yield* install();
+ const afterFirst = yield* fs.readFileString(rcPath);
+ yield* install();
+ const afterSecond = yield* fs.readFileString(rcPath);
+
+ expect(afterSecond).toBe(afterFirst);
+ expect(afterSecond.match(/^# Composio CLI$/gm)?.length ?? 0).toBe(1);
+ })
+ );
+ });
+ });
+
+ describe('[When] .bashrc and .bash_profile alias one physical file with a stale managed block', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] the physical file ends with exactly one current block', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/bash');
+ const expectedBinDir = expectedRuntimeBinDir();
+
+ const bashrcPath = path.join(os.homedir, '.bashrc');
+ const bashProfilePath = path.join(os.homedir, '.bash_profile');
+ const managedPath = path.join(os.homedir, '.managed-bashrc');
+ yield* fs.remove(bashrcPath, { force: true });
+ yield* fs.writeFileString(
+ managedPath,
+ '# managed prologue\n# Composio CLI\nexport PATH="/stale/bin:$PATH"\n'
+ );
+ yield* fs.symlink(managedPath, bashrcPath);
+ yield* fs.symlink(managedPath, bashProfilePath);
+
+ yield* install();
+
+ const contents = yield* fs.readFileString(managedPath);
+ expect(contents.match(/^# Composio CLI$/gm)?.length ?? 0).toBe(1);
+ expect(contents).toContain(`export PATH="${expectedBinDir}:$PATH"`);
+ expect(contents).not.toContain('/stale/bin');
+ expect(contents).toContain('# managed prologue');
+
+ // Both aliases must survive as symlinks to the same physical file.
+ expect(yield* fs.readLink(bashrcPath)).toBe(managedPath);
+ expect(yield* fs.readLink(bashProfilePath)).toBe(managedPath);
+ yield* expectNoTmpLitter(fs, managedPath);
+ })
+ );
+ });
+ });
+
+ describe('[When] the atomic write cannot replace the target file', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] the error propagates and no .composio-tmp file is left behind', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/zsh');
+
+ // A directory at the rc path makes the final rename(file, dir) fail
+ // after the temp file was already written.
+ const rcPath = path.join(os.homedir, '.zshrc');
+ yield* fs.remove(rcPath, { force: true, recursive: true });
+ yield* fs.makeDirectory(rcPath);
+
+ const exit = yield* install().pipe(Effect.exit);
+
+ expect(Exit.isFailure(exit)).toBe(true);
+ yield* expectNoTmpLitter(fs, rcPath);
+ })
+ );
+ });
+ });
+
+ describe('[When] COMPOSIO_CLI_INVOCATION_ORIGIN=installer delegates shell setup', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] keeps the Updated status line but suppresses the restart hint', () =>
+ Effect.gen(function* () {
+ vi.stubEnv('SHELL', '/bin/zsh');
+ vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'installer');
+
+ yield* install();
+
+ const output = (yield* MockConsole.getLines()).join('\n');
+ expect(output).toContain('Updated ~/.zshrc');
+ expect(output).not.toContain('Restart your shell');
+ expect(output).not.toContain('source ~/.zshrc');
+ })
+ );
+ });
+ });
+
+ describe('[When] COMPOSIO_CLI_INVOCATION_ORIGIN=installer and integration is already current', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] keeps the already-current status line', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/zsh');
+ vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'installer');
+ const expectedBinDir = expectedRuntimeBinDir();
+
+ const rcPath = path.join(os.homedir, '.zshrc');
+ yield* fs.writeFileString(
+ rcPath,
+ `# Composio CLI\nexport PATH="${expectedBinDir}:$PATH"\n`
+ );
+
+ yield* install();
+
+ const output = (yield* MockConsole.getLines()).join('\n');
+ expect(output).toContain('Shell integration already configured');
+ expect(output).not.toContain('Restart your shell');
+ })
+ );
+ });
+ });
+
+ describe('[When] COMPOSIO_CLI_INVOCATION_ORIGIN has a non-installer value', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] the restart hint still prints', () =>
+ Effect.gen(function* () {
+ vi.stubEnv('SHELL', '/bin/zsh');
+ vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'agent');
+
+ yield* install();
+
+ const output = (yield* MockConsole.getLines()).join('\n');
+ expect(output).toContain('Updated ~/.zshrc');
+ expect(output).toContain('Restart your shell to apply changes');
+ expect(output).toContain('source ~/.zshrc');
+ })
+ );
+ });
+ });
+
describe('[When] shell cannot be detected', () => {
- layer(TestInstallLive())(it => {
+ layer(InstallTestLive())(it => {
it.scoped('[Then] shows manual setup instructions', () =>
Effect.gen(function* () {
vi.stubEnv('SHELL', '');
@@@ -972,8 -811,8 +1075,28 @@@
});
});
++ describe('[When] --shell and --completions are combined on the public CLI', () => {
++ layer(InstallTestLive())(it => {
++ it.scoped('[Then] the overridden shell gets both the PATH block and completions', () =>
++ Effect.gen(function* () {
++ const os = yield* NodeOs;
++ const fs = yield* FileSystem.FileSystem;
++ vi.stubEnv('SHELL', '/bin/zsh');
++ const expectedBinDir = expectedRuntimeBinDir();
++
++ yield* cli(['install', '--shell', 'bash', '--completions']);
++
++ const contents = yield* fs.readFileString(path.join(os.homedir, '.bashrc'));
++ expect(contents).toContain(`export PATH="${expectedBinDir}:$PATH"`);
++ expect(contents).toContain('# Composio CLI completions');
++ expect(yield* fs.exists(path.join(os.homedir, '.zshrc'))).toBe(false);
++ })
++ );
++ });
++ });
++
describe('[When] --shell bash overrides a conflicting $SHELL', () => {
- layer(TestInstallLive())(it => {
+ layer(InstallTestLive())(it => {
it.scoped('[Then] writes ~/.bashrc, not ~/.zshrc', () =>
Effect.gen(function* () {
const os = yield* NodeOs;
@@@ -1027,9 -866,9 +1150,9 @@@
});
});
- describe('[When] auto-detected shell has its bin dir already on $PATH', () => {
+ describe('[When] auto-detected shell has its bin dir already on the invoking $PATH', () => {
- layer(TestInstallLive())(it => {
+ layer(InstallTestLive())(it => {
- it.scoped('[Then] writes nothing and reports already on PATH, with no restart hint', () =>
+ it.scoped('[Then] the rc file is still written, since a transient $PATH proves nothing', () =>
Effect.gen(function* () {
const os = yield* NodeOs;
vi.stubEnv('SHELL', '/bin/zsh');
@@@ -1050,34 -890,33 +1174,33 @@@
});
});
- describe('[When] a new .bash_profile appears after .bashrc was already configured, and the bin dir is already on $PATH', () => {
+ describe('[When] a new .bash_profile appears after .bashrc was already configured', () => {
- layer(TestInstallLive())(it => {
+ layer(InstallTestLive())(it => {
- it.scoped(
- '[Then] the new .bash_profile still gets the PATH block, not skipped by the reachability check',
- () =>
- Effect.gen(function* () {
- const os = yield* NodeOs;
- const fs = yield* FileSystem.FileSystem;
- vi.stubEnv('SHELL', '/bin/bash');
- const binDir = expectedRuntimeBinDir();
- vi.stubEnv('PATH', `${SAFE_PATH}:${binDir}`);
-
- // Simulate a prior `composio install` run that already configured .bashrc.
- const bashrcPath = path.join(os.homedir, '.bashrc');
- yield* fs.writeFileString(
- bashrcPath,
- `# Composio CLI\nexport PATH="${binDir}:$PATH"\n`
- );
+ it.scoped('[Then] the new .bash_profile gets the PATH block and .bashrc is left alone', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/bash');
+ const binDir = expectedRuntimeBinDir();
+ vi.stubEnv('PATH', `${SAFE_PATH}:${binDir}`);
- // .bash_profile shows up afterward and was never configured.
- const bashProfilePath = path.join(os.homedir, '.bash_profile');
- yield* fs.writeFileString(bashProfilePath, '# existing login config\n');
+ // Simulate a prior `composio install` run that already configured .bashrc.
+ const bashrcPath = path.join(os.homedir, '.bashrc');
+ yield* fs.writeFileString(bashrcPath, `# Composio CLI\nexport PATH="${binDir}:$PATH"\n`);
- yield* install();
+ // .bash_profile shows up afterward and was never configured.
+ const bashProfilePath = path.join(os.homedir, '.bash_profile');
+ yield* fs.writeFileString(bashProfilePath, '# existing login config\n');
- const bashProfileContents = yield* fs.readFileString(bashProfilePath);
- expect(bashProfileContents).toContain('# Composio CLI');
- })
+ yield* install();
+
+ const bashProfileContents = yield* fs.readFileString(bashProfilePath);
+ expect(bashProfileContents).toContain('# Composio CLI');
+ // .bashrc already carries the exact current line, so it is untouched.
+ expect(yield* fs.readFileString(bashrcPath)).toBe(
+ `# Composio CLI\nexport PATH="${binDir}:$PATH"\n`
+ );
+ })
);
});
});
@@@ -1253,8 -1109,8 +1376,8 @@@
});
});
- describe('[When] COMPOSIO_BIN_DIR contains shell metacharacters', () => {
+ describe('[When] COMPOSIO_BIN_DIR contains characters that expand inside double quotes', () => {
- layer(TestInstallLive())(it => {
+ layer(InstallTestLive())(it => {
it.scoped('[Then] aborts with an error', () =>
Effect.gen(function* () {
vi.stubEnv('SHELL', '/bin/zsh');
@@@ -1310,8 -1166,8 +1433,25 @@@
});
});
++ describe('[When] the resolved bin dir contains an apostrophe', () => {
++ layer(InstallTestLive({ execPath: "/opt/o'brien/bin/composio" }))(it => {
++ it.scoped("[Then] it is written verbatim, since `'` is literal inside double quotes", () =>
++ Effect.gen(function* () {
++ const os = yield* NodeOs;
++ const fs = yield* FileSystem.FileSystem;
++ vi.stubEnv('SHELL', '/bin/zsh');
++
++ yield* install();
++
++ const contents = yield* fs.readFileString(path.join(os.homedir, '.zshrc'));
++ expect(contents).toContain(`export PATH="/opt/o'brien/bin:$PATH"`);
++ })
++ );
++ });
++ });
++
describe('[When] the runtime executable resolves to an unsafe directory', () => {
- layer(InstallTestLive({ execPath: "/tmp/o'brien/composio" }))(it => {
- layer(TestInstallLive({ execPath: '/tmp/we`ird/composio' }))(it => {
++ layer(InstallTestLive({ execPath: '/tmp/we`ird/composio' }))(it => {
it.scoped('[Then] reports an origin-neutral error', () =>
Effect.gen(function* () {
vi.stubEnv('SHELL', '/bin/zsh');