ricklamers / shell-ai

LangChain powered shell command generator and runner CLI
MIT License
1.01k stars 61 forks source link

Feature Request: Responses should be for the current shell type #25

Open kmickeletto opened 1 year ago

kmickeletto commented 1 year ago

Add Support for Specifying Shell Type to Generate Appropriate Commands

Feature Description

The shell-ai application currently generates shell commands without considering the type of shell the user is working in. This leads to generic suggestions that might not be fully optimized for specific shell environments like PowerShell, Bash, Zsh, etc. I propose adding a feature that allows the application to automatically detect the user's shell type, or let the user specify it via a command-line argument, to generate shell-appropriate commands.

Use Case

Consider two examples:

  1. Running from PowerShell without specifying shell type

    PS C:\Users\myuser> shai open output.json and parse it as json
    ? Select a command:
    ❯ jq '.' output.json
      cat output.json | jq
  2. Running from PowerShell with shell type specified

    PS C:\Users\myuser> shai My current shell is Powershell, open output.json and parse it as json
    ? Select a command:
    ❯ Get-Content -Raw output.json | ConvertFrom-Json
      Get-Content output.json | ConvertFrom-Json

By knowing the shell type, the application can provide commands that are more natural and idiomatic for the user's environment.

Proposed Implementation

Something like the following logic should be enough to instruct the LLM which shell to generate the commands for.


import os

# Try to import psutil
psutil_loaded = False
try:
    import psutil
    psutil_loaded = True
except ImportError:
    pass

def detect_shell_from_env():
    shell = os.environ.get('SHELL', '')
    if 'bash' in shell:
        return 'bash'
    elif 'zsh' in shell:
        return 'zsh'
    elif 'fish' in shell:
        return 'fish'

    term = os.environ.get('TERM', '')
    if 'xterm' in term:
        return 'xterm'

    ps_version = os.environ.get('PSVersionTable', '')
    if ps_version:
        return 'PowerShell'

    comspec = os.environ.get('COMSPEC', '')
    if 'cmd.exe' in comspec:
        return 'cmd.exe'

    return 'Unknown'

def get_parent_shell():
    parent_pid = os.getppid()
    if psutil_loaded:
        parent = psutil.Process(parent_pid)
        return parent.name()
    else:
        return detect_shell_from_env()

print(f"The parent shell is: {get_parent_shell()}")
ricklamers commented 11 months ago

Related https://github.com/ricklamers/shell-ai/pull/26