├── LOGO.png
├── .gitignore
├── requirements.txt
├── setup.sh
├── ui
├── style.css
├── printer.py
├── rendering.py
├── popups.py
└── ui.py
├── entrypoint.sh
├── deepshell
├── chatbot
├── deployer.py
├── helper.py
├── manager.py
└── history.py
├── .github
└── FUNDING.yml
├── dockerfile
├── utils
├── symlink_utils.py
├── pipe_utils.py
├── args_utils.py
├── logger.py
├── command_processor.py
├── file_utils.py
└── shell_utils.py
├── config
├── system_prompts.py
└── settings.py
├── main.py
├── ollama_client
├── client_deployer.py
├── validator.py
└── api_client.py
├── README.md
├── pipeline
└── pipe_filter.py
└── LICENSE
/LOGO.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Abyss-c0re/deepshell/HEAD/LOGO.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | venv/
2 | *.pyc
3 | **/*.pyc
4 | __pycache__/
5 | **/__pycache__/
6 | .gitignore
7 | .git/
8 | deepshell.log
9 |
10 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | aiofiles==24.1.0
2 | numpy==2.2.4
3 | ollama==0.4.7
4 | Pillow==11.1.0
5 | python_magic==0.4.27
6 | scikit_learn==1.6.1
7 | textual==2.1.2
8 |
--------------------------------------------------------------------------------
/setup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | python3 -m venv venv
3 | source venv/bin/activate
4 | pip install -r requirements.txt
5 | echo "Setup complete! Run 'source venv/bin/activate' to use."
6 |
--------------------------------------------------------------------------------
/ui/style.css:
--------------------------------------------------------------------------------
1 | Input,
2 | RichLog {
3 | border:none;
4 | }
5 |
6 | RichLog:focus {
7 | text-style: reverse;
8 | text-style: bold;
9 | }
10 |
11 | ScrollView .scrollbar {
12 | scrollbar-size: 0 0;
13 | }
14 |
15 |
16 |
--------------------------------------------------------------------------------
/entrypoint.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Start Ollama completely silently — no logs at all
4 | ollama serve > /dev/null 2>&1 &
5 | OLLAMA_PID=$!
6 |
7 | # Wait quietly for startup
8 | sleep 15
9 |
10 | # Only DeepShell output will appear
11 | exec python main.py "$@"
12 |
--------------------------------------------------------------------------------
/deepshell:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import os
4 | import sys
5 |
6 | # Get the actual path of the script, following any symlinks
7 | SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
8 | MAIN_SCRIPT = os.path.join(SCRIPT_DIR, "main.py")
9 |
10 | # Forward all arguments to main.py
11 | os.execv(sys.executable, [sys.executable, MAIN_SCRIPT] + sys.argv[1:])
12 |
13 |
--------------------------------------------------------------------------------
/ui/printer.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | from ui.rendering import Rendering
3 |
4 |
5 | def printer(content: str, system: bool = False) -> None:
6 | """
7 | Helper function to pass the output to RichLog Console with optional system prefix
8 | """
9 | if system:
10 | content = "[cyan]System: [/]" + content
11 | try:
12 | loop = asyncio.get_event_loop()
13 | if loop.is_running():
14 | asyncio.create_task(Rendering._fancy_print(content))
15 | else:
16 | asyncio.run(Rendering._fancy_print(content))
17 | except Exception:
18 | pass
19 |
--------------------------------------------------------------------------------
/chatbot/deployer.py:
--------------------------------------------------------------------------------
1 | from typing import Tuple
2 | from utils.logger import Logger
3 | from config.settings import Mode
4 | from pipeline.pipe_filter import PipeFilter
5 | from ollama_client.api_client import OllamaClient
6 | from ollama_client.client_deployer import ClientDeployer
7 |
8 | logger = Logger.get_logger()
9 |
10 |
11 | def deploy_chatbot(mode: Mode | None = None) -> Tuple[OllamaClient, PipeFilter]:
12 | """
13 | Deploys a chatbot with an optional mode.
14 | """
15 | client_deployer = ClientDeployer(mode)
16 | chatbot = client_deployer.deploy()
17 | filter = PipeFilter(chatbot)
18 |
19 | return chatbot, filter
20 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: [Abyss-c0re]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
12 | polar: # Replace with a single Polar username
13 | buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
14 | thanks_dev: # Replace with a single thanks.dev username
15 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
16 |
--------------------------------------------------------------------------------
/dockerfile:
--------------------------------------------------------------------------------
1 | # Default to CPU/NVIDIA variant (change with --build-arg OLLAMA_VARIANT=rocm for AMD)
2 | ARG OLLAMA_VARIANT=latest
3 | FROM ollama/ollama:${OLLAMA_VARIANT}
4 |
5 | # Install required packages (Python, pip, curl, libmagic1 for python-magic)
6 | RUN apt-get update && apt-get install -y \
7 | python3 \
8 | python3-pip \
9 | curl \
10 | libmagic1 \
11 | && rm -rf /var/lib/apt/lists/*
12 |
13 | # Link python3 to python
14 | RUN ln -s /usr/bin/python3 /usr/bin/python
15 |
16 | # Working directory
17 | WORKDIR /app
18 |
19 | # Copy DeepShell files
20 | COPY . .
21 |
22 | # Install dependencies
23 | RUN pip install --no-cache-dir --break-system-packages -r requirements.txt
24 |
25 | # Copy entrypoint script
26 | COPY entrypoint.sh /entrypoint.sh
27 | RUN chmod +x /entrypoint.sh
28 |
29 | # Expose Ollama port
30 | EXPOSE 11434
31 |
32 | # Custom entrypoint (starts ollama serve in background + DeepShell)
33 | ENTRYPOINT ["/entrypoint.sh"]
34 |
--------------------------------------------------------------------------------
/utils/symlink_utils.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | EXECUTABLE_NAME = "deepshell"
4 |
5 |
6 | def create_symlink():
7 | """
8 | Create symlink for deepshell in ~/.local/bin
9 | """
10 | bin_dir = os.path.expanduser("~/.local/bin")
11 | symlink_path = os.path.join(bin_dir, EXECUTABLE_NAME)
12 |
13 | if not os.path.exists(bin_dir):
14 | os.makedirs(bin_dir)
15 |
16 | if not os.path.exists(symlink_path):
17 | os.symlink(os.path.abspath(EXECUTABLE_NAME), symlink_path)
18 | print(f"Symlink created at {symlink_path}")
19 | else:
20 | print(f"Symlink already exists at {symlink_path}")
21 |
22 |
23 | def remove_symlink():
24 | """
25 | Remove the symlink for deepshell from ~/.local/bin
26 | """
27 | bin_dir = os.path.expanduser("~/.local/bin")
28 | symlink_path = os.path.join(bin_dir, EXECUTABLE_NAME)
29 |
30 | if os.path.exists(symlink_path):
31 | os.remove(symlink_path)
32 | print(f"Symlink removed from {symlink_path}")
33 | else:
34 | print(f"No symlink found at {symlink_path}")
35 |
--------------------------------------------------------------------------------
/utils/pipe_utils.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import asyncio
3 | from typing import Optional
4 | from utils.logger import Logger
5 |
6 | logger = Logger.get_logger()
7 |
8 |
9 | class PipeUtils:
10 | def __init__(self, chat_manager):
11 | self.chat_manager = chat_manager
12 | self.processor = chat_manager.command_processor
13 |
14 | async def read_pipe(self):
15 | """
16 | Read piped input asynchronously.
17 | """
18 | loop = asyncio.get_event_loop()
19 | logger.info("Got the pipe content")
20 | return await loop.run_in_executor(None, sys.stdin.read)
21 |
22 | async def handle_pipe(self, user_input: Optional[str] = None) -> None:
23 | """
24 | Handles pipe input, formats the user input, and runs the task manager.
25 | """
26 | pipe_input = await self.read_pipe()
27 |
28 | if pipe_input:
29 | if user_input:
30 | user_input = self.processor.format_input(user_input, pipe_input)
31 | else:
32 | user_input = pipe_input
33 | results = await self.chat_manager.task_manager(user_input)
34 | print(results)
35 |
--------------------------------------------------------------------------------
/config/system_prompts.py:
--------------------------------------------------------------------------------
1 | import platform
2 |
3 | user_system = platform.uname()
4 |
5 | # System Prompts
6 |
7 | SYSTEM = f"""
8 | You are an AI assistant that strictly follows instructions and only calls provided functions.
9 | You **must not** generate any text responses or explanations.
10 | You **must not** answer questions, provide reasoning, or engage in conversation.
11 | Your **only** task is to determine the most appropriate function call based on the user's input and execute it.
12 | """
13 |
14 | SHELL = f"""
15 | You are a shell command generator. Your sole purpose is to generate precise and concise shell commands in response to user requests.
16 | Do not include explanations, examples beyond the command itself, or any additional text.
17 | Ensure that answers are relevant for the {user_system} system.
18 |
19 | Guidelines:
20 | - Provide only shell command when requested.
21 | - Avoid offering alternatives, suggestions, or extra information. .
22 | """
23 |
24 | CODE = f"""
25 | You are a code generator. Your sole purpose is to generate precise and concise code snippets in response to user requests.
26 | Do not include explanations, examples beyond the code itself, or any additional text.
27 | Ensure that answers are relevant for the {user_system} system.
28 |
29 | Guidelines:
30 | - Provide only the necessary code when requested.
31 | - Avoid extra information, explanations, or alternative suggestions.
32 | """
33 |
--------------------------------------------------------------------------------
/utils/args_utils.py:
--------------------------------------------------------------------------------
1 | import argparse
2 |
3 |
4 | def parse_args():
5 | """Parse and return command-line arguments."""
6 | parser = argparse.ArgumentParser(description="Ollama Chat Mode")
7 | parser.add_argument("--model", type=str, default="", help="Specify the AI model")
8 | parser.add_argument(
9 | "--host", type=str, default="", help="Specify the Ollama API host"
10 | )
11 | parser.add_argument("--prompt", type=str, default="", help="Chat message")
12 | parser.add_argument("--file", type=str, help="File to include in chat")
13 | parser.add_argument(
14 | "string_input", nargs="?", type=str, help="Optional string input"
15 | )
16 |
17 | symlink_group = parser.add_mutually_exclusive_group()
18 | symlink_group.add_argument(
19 | "--install", action="store_true", help="Install symlink for deepshell"
20 | )
21 | symlink_group.add_argument(
22 | "--uninstall", action="store_true", help="Uninstall symlink for deepshell"
23 | )
24 |
25 | output_group = parser.add_mutually_exclusive_group()
26 | output_group.add_argument("--code", action="store_true", help="Generate code only")
27 | output_group.add_argument(
28 | "--shell", action="store_true", help="Generate shell command"
29 | )
30 | output_group.add_argument(
31 | "--system", action="store_true", help="System Administration"
32 | )
33 | output_group.add_argument(
34 | "--thinking", action="store_true", help="Show thinking sections"
35 | )
36 |
37 | return parser.parse_args()
38 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import asyncio
3 | from utils.pipe_utils import PipeUtils
4 | from utils.args_utils import parse_args
5 | from chatbot.manager import ChatManager
6 | from ollama_client.validator import validate_install
7 | from utils.symlink_utils import create_symlink, remove_symlink
8 |
9 |
10 | async def async_main():
11 | args = parse_args()
12 |
13 | if args.install:
14 | create_symlink()
15 | return
16 | if args.uninstall:
17 | remove_symlink()
18 | return
19 | if validate_install():
20 | chat_manager = ChatManager()
21 | pipe_utils = PipeUtils(chat_manager)
22 |
23 | user_input = args.prompt or args.string_input or ""
24 | file = args.file or ""
25 | pipe_content = ""
26 | stdin_piped = not sys.stdin.isatty()
27 | stdout_piped = not sys.stdout.isatty()
28 |
29 | if stdin_piped:
30 | pipe_content = await pipe_utils.read_pipe()
31 | if stdout_piped:
32 | chat_manager.ui = None
33 | response = await chat_manager.deploy_task(user_input, file, pipe_content)
34 | print(response)
35 | else:
36 | if chat_manager.ui:
37 | (
38 | chat_manager.ui.user_input,
39 | chat_manager.ui.file,
40 | chat_manager.ui.file_content,
41 | ) = user_input, file, pipe_content
42 |
43 | await chat_manager.ui.run_async()
44 |
45 |
46 | if __name__ == "__main__":
47 | asyncio.run(async_main())
48 |
--------------------------------------------------------------------------------
/ollama_client/client_deployer.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from config.settings import *
3 | from utils.args_utils import parse_args
4 | from ollama_client.api_client import OllamaClient
5 |
6 |
7 | class ClientDeployer:
8 | def __init__(self, mode: Mode | None = None):
9 | self.args = parse_args()
10 | self.user_input = self.args.prompt or self.args.string_input or None
11 | self.file = self.args.file
12 |
13 | if mode:
14 | self.mode = mode
15 | else:
16 | self.mode = (
17 | Mode.SHELL
18 | if self.args.shell
19 | else Mode.CODE
20 | if self.args.code
21 | else Mode.SYSTEM
22 | if self.args.system
23 | else Mode.DEFAULT
24 | )
25 |
26 | config = MODE_CONFIGS[self.mode]
27 | self.host = DEFAULT_HOST
28 | self.model = config["model"]
29 | self.config = self.generate_config(temp=config["temp"], prompt=config["prompt"])
30 | self.stream = config["stream"]
31 |
32 | def deploy(self) -> OllamaClient:
33 | """
34 | Deploys an isntance of Ollama API Client
35 | """
36 |
37 | if self.args.host:
38 | self.host = self.args.host
39 | if self.args.model:
40 | self.model = self.args.model
41 |
42 | return OllamaClient(
43 | host=self.host,
44 | model=self.model,
45 | config=self.config,
46 | mode=self.mode,
47 | stream=self.stream,
48 | render_output=sys.stdout.isatty(),
49 | show_thinking=self.args.thinking,
50 | )
51 |
52 | def generate_config(self, temp=0.7, prompt="") -> dict:
53 | return {"temperature": temp, "system": prompt}
54 |
--------------------------------------------------------------------------------
/ui/rendering.py:
--------------------------------------------------------------------------------
1 | import re
2 | import asyncio
3 | from config.settings import RENDER_DELAY
4 |
5 |
6 | class Rendering:
7 | _chat_app_instance = None
8 |
9 | def __init__(self, chat_app):
10 | self.chat_app = chat_app
11 | Rendering._chat_app_instance = chat_app
12 | self.cleaner = re.compile(r"(#{3,4}|\*\*)")
13 | self.delay = RENDER_DELAY
14 | self._lock = asyncio.Lock()
15 | self.queue = asyncio.Queue()
16 | self._processing_task = None # Don't start in __init__, defer it
17 |
18 | async def start_processing(self) -> None:
19 | """
20 | Start queue processing task after event loop is running.
21 | """
22 | if not self._processing_task:
23 | self._processing_task = asyncio.create_task(self._process_queue())
24 |
25 | async def _process_queue(self) -> None:
26 | """
27 | Continuously process print jobs from the queue.
28 | """
29 | while True:
30 | content = await self.queue.get()
31 | await self._execute_fancy_print(content)
32 | self.queue.task_done()
33 |
34 | async def _execute_fancy_print(
35 | self,
36 | content: str,
37 | ) -> None:
38 | """
39 | Render string line by line, preserving newlines and whitespace.
40 | """
41 | lines = content.split("\n")
42 | if len(lines) > 1:
43 | self.chat_app.lock_input()
44 |
45 | for line in lines:
46 | await self.render_output(line)
47 | await asyncio.sleep(self.delay)
48 |
49 | self.chat_app.unlock_input()
50 |
51 | async def render_output(self, line: str) -> None:
52 | """
53 | Render lines while stripping some markdown tags.
54 | """
55 | async with self._lock:
56 | cleaned_line = self.cleaner.sub("", line.rstrip())
57 | self.chat_app.rich_log_widget.write(cleaned_line)
58 |
59 | async def fancy_print(self, content: str) -> None:
60 | """
61 | Add print job to queue and ensure execution order.
62 | """
63 | await self.queue.put(content)
64 |
65 | @staticmethod
66 | async def _fancy_print(content: str) -> None:
67 | """
68 | Static method to enqueue print job.
69 | """
70 | if Rendering._chat_app_instance:
71 | await Rendering._chat_app_instance.rendering.fancy_print(content)
72 |
--------------------------------------------------------------------------------
/ui/popups.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | from typing import Any
3 | from textual import events
4 | from textual.widget import Widget
5 | from textual.app import ComposeResult
6 | from textual.containers import ScrollableContainer
7 | from textual.widgets import Static, RadioSet, RadioButton
8 |
9 |
10 | class RadiolistPopup(Widget):
11 | """
12 | A popup widget that displays a scrollable radio list for selection and returns the chosen valuei.
13 | """
14 |
15 | def __init__(
16 | self, title: str, text: str, options: list[tuple[str, str]], **kwargs: Any
17 | ) -> None:
18 | """
19 | :param title: The title of the popup.
20 | :param text: The prompt text.
21 | :param options: A list of (option_value, label) tuples.
22 | """
23 | super().__init__(**kwargs)
24 | self.title = title
25 | self.text = text
26 | self.options = options
27 | self.choice_future: asyncio.Future = asyncio.Future()
28 |
29 | def compose(self) -> ComposeResult:
30 | yield Static(f"[bold]{self.title}[/bold]\n{self.text}\n", classes="full-width")
31 | with ScrollableContainer(id="popup_scroll_view", classes="full-width"):
32 | with RadioSet(id="popup_radio_set", classes="full-width"):
33 | for _, label in self.options:
34 | yield RadioButton(label, classes="full-width")
35 |
36 | async def on_mount(self) -> None:
37 | self.query_one(RadioSet).focus()
38 | self.focus()
39 |
40 | async def on_key(self, event: events.Key) -> None:
41 | radio_set = self.query_one(RadioSet)
42 | index = radio_set.pressed_index
43 | if event.key in ("enter", "space"):
44 | if index != -1:
45 | choice = self.options[index][0]
46 | if not self.choice_future.done():
47 | self.choice_future.set_result(choice)
48 | elif event.key == "escape":
49 | if not self.choice_future.done():
50 | self.choice_future.set_result("cancel")
51 | elif event.key in ("up", "down"):
52 | selected_button = (
53 | radio_set.children[index]
54 | if 0 <= index < len(radio_set.children)
55 | else None
56 | )
57 | if selected_button:
58 | scroll_view = self.query_one("#popup_scroll_view")
59 | scroll_view.scroll_to_widget(selected_button, animate=True)
60 | await self.focus_self()
61 |
62 | async def focus_self(self) -> None:
63 | self.focus()
64 |
65 | async def wait_for_choice(self) -> str:
66 | return await self.choice_future
67 |
--------------------------------------------------------------------------------
/utils/logger.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from ui.printer import printer
3 | from config.settings import LOG, LOG_LEVEL, LOG_TO_FILE, LOG_TO_UI
4 |
5 |
6 | class Logger:
7 | _logger = None
8 | LEVELS = {
9 | "debug": logging.DEBUG,
10 | "info": logging.INFO,
11 | "warning": logging.WARNING,
12 | "error": logging.ERROR,
13 | "critical": logging.CRITICAL,
14 | }
15 |
16 | _logging_enabled = LOG
17 | _use_fancy_print = LOG_TO_UI
18 | _use_file_handler = LOG_TO_FILE
19 |
20 | @classmethod
21 | def get_logger(
22 | cls,
23 | name: str = "deepshell",
24 | level: str = LOG_LEVEL,
25 | log_file: str = "deepshell.log",
26 | ) -> logging.Logger:
27 | """
28 | Returns a logger instance with a selectable log level, logging only to a file.
29 | """
30 | if cls._logger is None:
31 | cls._logger = logging.getLogger(name)
32 | log_level = cls.LEVELS.get(level.lower(), logging.INFO)
33 | cls._logger.setLevel(log_level)
34 |
35 | if cls._use_file_handler and cls._logging_enabled:
36 | file_handler = logging.FileHandler(log_file)
37 | file_formatter = logging.Formatter(
38 | "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
39 | )
40 | file_handler.setFormatter(file_formatter)
41 | cls._logger.addHandler(file_handler)
42 |
43 | if cls._use_fancy_print and cls._logging_enabled:
44 | cls._logger.addHandler(FancyPrintHandler())
45 |
46 | return cls._logger
47 |
48 |
49 | class FancyPrintHandler(logging.Handler):
50 | def __init__(self):
51 | super().__init__()
52 |
53 | def emit(self, record: logging.LogRecord) -> None:
54 | """
55 | Emit the log record using fancy_print with colors.
56 | """
57 | try:
58 | msg = self.format(record)
59 | colored_msg = self._apply_color(msg, record.levelno)
60 | level_name = record.levelname
61 | formatted_msg = f"[{level_name}] {msg}"
62 | colored_msg = self._apply_color(formatted_msg, record.levelno)
63 |
64 | printer(colored_msg)
65 | except Exception:
66 | self.handleError(record)
67 |
68 | def _apply_color(self, msg: str, level: int) -> str:
69 | """
70 | Apply color formatting based on the log level.
71 | """
72 | color_map = {
73 | logging.DEBUG: "blue",
74 | logging.INFO: "green",
75 | logging.WARNING: "yellow",
76 | logging.ERROR: "red",
77 | logging.CRITICAL: "purple",
78 | }
79 |
80 | color = color_map.get(level, "white")
81 |
82 | return f"[{color}]{msg}[/]"
83 |
--------------------------------------------------------------------------------
/chatbot/helper.py:
--------------------------------------------------------------------------------
1 | import platform
2 | from datetime import datetime
3 | from utils.logger import Logger
4 |
5 | logger = Logger.get_logger()
6 |
7 |
8 | class PromptHelper:
9 | """
10 | A utility class for generating shell command prompts and analyzing command output.
11 | """
12 |
13 | user_system = platform.uname()
14 | current_time = datetime.now().isoformat()
15 |
16 | @staticmethod
17 | def shell_helper(user_input: str) -> str:
18 | """
19 | Generates a shell command prompt for the user's system.
20 |
21 | Args:
22 | user_input (str): The user's request for a shell command.
23 |
24 | Returns:
25 | str: A formatted prompt instructing the model to generate a non-interactive shell command.
26 | """
27 | return f"""
28 | Generate a shell command for this OS: {PromptHelper.user_system}.
29 | If the command normally requires interactive input or confirmation, include appropriate flags to bypass them.
30 | Do not include any additional text beyond the command itself.
31 | If the command requires administrative privileges, include 'sudo'.
32 | User request: {user_input}
33 | """
34 |
35 | @staticmethod
36 | def analyzer_helper(command: str, output: str) -> str:
37 | """
38 | Generates a prompt to analyze command output.
39 |
40 | Args:
41 | command (str): The executed shell command.
42 | output (str): The output of the command.
43 |
44 | Returns:
45 | str: A formatted prompt instructing the model to analyze and summarize key details.
46 | """
47 | return f"""
48 | Analyze the output of the following command: {command}
49 |
50 | Output: {output}
51 |
52 |
53 | Summarize key details, highlighting errors, warnings, and important findings.
54 | SYSTEM INFO:
55 | Use the infomation below only if needed. Do not include it in the reply, unless user asks relevant questions.
56 | System time: {PromptHelper.current_time}
57 | OS: {PromptHelper.user_system}
58 | """
59 |
60 | @staticmethod
61 | def topics_helper(history: list) -> str:
62 | """
63 | Generates a prompt instructing the model to name a topic and provide a description in JSON format
64 | based on conversation history provided as a list.
65 |
66 | Args:
67 | history (list): A list of dictionaries containing the role and message of previous conversation exchanges.
68 |
69 | Returns:
70 | str: A formatted prompt instructing the model to reply in JSON format.
71 | """
72 | history_text = str(history)
73 |
74 | logger.debug(f"Topics helper: injected history: {history_text}")
75 | return f"""
76 | Based on the following conversation history, please name a topic and provide a description of that topic in JSON format:
77 |
78 | {history_text}
79 |
80 | The response should be a JSON object with the following keys:
81 | - "topic_name": The name of the topic.
82 | - "topic_description": A brief description of the topic.
83 | """
84 |
85 | @staticmethod
86 | def analyze_code(content: str) -> str:
87 | """
88 | Generates a prompt instructing the model to analyze the code and provide description in JSON format
89 | """
90 | return f"""
91 | Analyze the following code and generate structured metadata in JSON format. The metadata should include the following categories:
92 | 1. Functions: List of function names and their descriptions (if any).
93 | 2. Classes: List of class names and a brief description of their purpose.
94 | 3. Purpose: A brief summary of what the code is meant to accomplish or its functionality.
95 |
96 | Code:
97 | {content}
98 | """
99 |
--------------------------------------------------------------------------------
/config/settings.py:
--------------------------------------------------------------------------------
1 | from enum import Enum, auto
2 | from config.system_prompts import *
3 |
4 |
5 | class Mode(Enum):
6 | DEFAULT = auto()
7 | ADVANCED = auto()
8 | CODE = auto()
9 | SHELL = auto()
10 | SYSTEM = auto()
11 | HELPER = auto()
12 | VISION = auto()
13 |
14 |
15 | # Ollama Settings
16 | DEFAULT_HOST = "http://localhost:11434"
17 |
18 | DEFAULT_MODEL = "deepseek-r1:14b"
19 | CODE_MODEL = "deepcoder:14b"
20 | SHELL_MODEL = "qwen2.5-coder:7b"
21 | SYSTEM_MODEL = "mistral:7b"
22 | HELPER_MODEL = "deepseek-r1:1.5b"
23 | VISION_MODEL = "minicpm-v:8b"
24 | EMBEDDING_MODEL = "nomic-embed-text:latest"
25 | #
26 | # DEFAULT_MODEL = "deepseek-r1:1.5b"
27 | # CODE_MODEL = "deepseek-r1:1.5b"
28 | # SHELL_MODEL = "deepseek-r1:1.5b"
29 | # SYSTEM_MODEL = "deepseek-r1:1.5b"
30 | # HELPER_MODEL = "deepseek-r1:1.5b"
31 | # VISION_MODEL = "deepseek-r1:1.5b"
32 | # EMBEDDING_MODEL = "nomic-embed-text:latest"
33 |
34 | # Mapping Mode to Configuration
35 | MODE_CONFIGS = {
36 | Mode.DEFAULT: {"model": DEFAULT_MODEL, "temp": 0.4, "prompt": "", "stream": True},
37 | Mode.CODE: {"model": CODE_MODEL, "temp": 0.5, "prompt": CODE, "stream": True},
38 | Mode.SHELL: {"model": SHELL_MODEL, "temp": 0.4, "prompt": SHELL, "stream": True},
39 | Mode.SYSTEM: {"model": SYSTEM_MODEL, "temp": 0.5, "prompt": SYSTEM, "stream": True},
40 | Mode.HELPER: {"model": HELPER_MODEL, "temp": 0.5, "prompt": "", "stream": False},
41 | Mode.VISION: {"model": VISION_MODEL, "temp": 0.6, "prompt": "", "stream": False},
42 | }
43 |
44 | # Logging
45 | LOG = True
46 | LOG_LEVEL = "warning" # Possible values: debug, info, warning, error, critical
47 | LOG_TO_FILE = False
48 | LOG_TO_UI = True
49 |
50 | # Rendering
51 | RENDER_DELAY = 0.0069 # Delay between rendering lines
52 |
53 | # HistoryManager
54 | MSG_THR = 0.5 # Simularity threshold for history
55 | CONT_THR = 0.6 # Simularity threshold for content such as files and terminal output
56 | NUM_MSG = 5 # Number of messages submitted to the chatbot from history
57 | OFF_THR = 0.7 # Off-topic threshold
58 | OFF_FREQ = 4 # Off-topic checking frequency (messages)
59 | SLICE_SIZE = 4 # Last N messages to analyze for off-topic
60 |
61 | # ShellUtils Config
62 | SHELL_TYPE = "/bin/bash"
63 | MONITOR_INTERVAL = (
64 | 60 # Timeout until when user will be prompted to abort command execution
65 | )
66 | FINALIZE_OUTPUT = True # Output post-processing such as trimming
67 | MAX_OUTPUT_LINES = 30000
68 |
69 | # FileProcessing Config
70 | PROCESS_IMAGES = False # Turn this on if you want to get a description of the images
71 | IMG_INPUT_RES = (512, 512)
72 |
73 | IGNORE_DOT_FILES = False
74 | MAX_FILE_SIZE = 6 * 1024 * 1024 # 6MB
75 | MAX_LINES = 30000
76 |
77 | # General text formats
78 | TEXT_FORMATS = [
79 | ".txt",
80 | ".md",
81 | ".json",
82 | ".csv",
83 | ".ini",
84 | ".cfg",
85 | ".xml",
86 | ".yaml",
87 | ".yml",
88 | ".toml",
89 | ".log",
90 | ".sql",
91 | ".html",
92 | ".htm",
93 | ".css",
94 | ".js",
95 | ".conf",
96 | ".properties",
97 | ".rst",
98 | ]
99 |
100 | # Programming languages
101 | PROGRAMMING_LANGUAGES = [
102 | ".py",
103 | ".c",
104 | ".cpp",
105 | ".h",
106 | ".hpp",
107 | ".java",
108 | ".cs",
109 | ".rs",
110 | ".go",
111 | ".rb",
112 | ".php",
113 | ".sh",
114 | ".bat",
115 | ".pl",
116 | ".lua",
117 | ".swift",
118 | ".kt",
119 | ".m",
120 | ".r",
121 | ".jl",
122 | ".dart",
123 | ".ts",
124 | ".v",
125 | ".scala",
126 | ".fs",
127 | ".asm",
128 | ".s",
129 | ".vbs",
130 | ".ps1",
131 | ".clj",
132 | ".groovy",
133 | ".perl",
134 | ".f90",
135 | ".f95",
136 | ".ml",
137 | ]
138 |
139 | # Image formats
140 | IMAGE_FORMATS = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp", ".svg"]
141 |
142 | SUPPORTED_EXTENSIONS = TEXT_FORMATS + PROGRAMMING_LANGUAGES + IMAGE_FORMATS
143 |
144 |
145 | IGNORED_FOLDERS = [
146 | "__pycache__",
147 | ".git",
148 | ".github",
149 | ".svn",
150 | ".hg",
151 | "Android",
152 | "android-studio",
153 | "miniconda3",
154 | ]
155 |
--------------------------------------------------------------------------------
/ollama_client/validator.py:
--------------------------------------------------------------------------------
1 | import os
2 | import ast
3 | import ollama
4 | import subprocess
5 | from utils.logger import Logger
6 | from config.settings import DEFAULT_HOST
7 |
8 |
9 | logger = Logger.get_logger()
10 |
11 | BASE_DIR = os.path.dirname(os.path.abspath(__file__))
12 | CONFIG_PATH = os.path.join(BASE_DIR, "..", "config", "settings.py")
13 | REQUIRED_VERSION = "0.6.2"
14 |
15 |
16 | def get_installed_version():
17 | """
18 | Check the installed Ollama version.
19 | """
20 | try:
21 | output = subprocess.check_output(["ollama", "--version"], text=True).strip()
22 | return output.split()[-1]
23 | except (subprocess.CalledProcessError, FileNotFoundError):
24 | return None
25 |
26 |
27 | def parse_version(v: str):
28 | """Convert a version string like '0.12.3' into a tuple of ints (0,12,3)."""
29 | return tuple(int(part) for part in v.split(".") if part.isdigit())
30 |
31 |
32 | def ensure_ollama():
33 | """
34 | Check if Ollama is installed and up to date. If not, print instructions and return False.
35 | """
36 | installed_version = get_installed_version()
37 |
38 | if installed_version is None:
39 | print("Ollama is not installed. Run the following command to install it:")
40 | print("curl -fsSL https://ollama.com/install.sh | sh")
41 | return False
42 |
43 | if parse_version(installed_version) < parse_version(REQUIRED_VERSION):
44 | print(
45 | f"Ollama version {installed_version} is outdated. Run the following command to update:"
46 | )
47 | print("curl -fsSL https://ollama.com/install.sh | sh")
48 | return False
49 |
50 | logger.info(f"Ollama is installed and up to date (version {installed_version}).")
51 | return True
52 |
53 |
54 | def extract_model_names(config_path=CONFIG_PATH):
55 | """
56 | Extract values from all *_MODEL variables in settings.py
57 | """
58 | if not os.path.exists(config_path):
59 | raise FileNotFoundError(
60 | f"The configuration file '{config_path}' does not exist."
61 | )
62 |
63 | with open(config_path, "r", encoding="utf-8") as file:
64 | config_content = file.read()
65 |
66 | try:
67 | parsed_content = ast.parse(config_content)
68 | except SyntaxError as e:
69 | raise SyntaxError(f"Syntax error in the configuration file: {e}")
70 |
71 | model_names = set()
72 |
73 | for node in ast.walk(parsed_content):
74 | if isinstance(node, ast.Assign):
75 | for target in node.targets:
76 | if isinstance(target, ast.Name) and target.id.endswith("_MODEL"):
77 | if isinstance(node.value, ast.Constant) and isinstance(
78 | node.value.value, str
79 | ):
80 | model_names.add(
81 | node.value.value
82 | ) # Extract the assigned string value
83 |
84 | return model_names
85 |
86 |
87 | def validate_install(config_path=CONFIG_PATH):
88 | """
89 | Ensure Ollama is installed and up to date before checking models.
90 | """
91 |
92 | if DEFAULT_HOST != "http://localhost:11434":
93 | return True
94 |
95 | if not ensure_ollama():
96 | return False
97 |
98 | model_names = extract_model_names(config_path)
99 | available_model_names = set()
100 |
101 | try:
102 | available_models = ollama.list()
103 | available_models = available_models.models
104 | for model in available_models:
105 | available_model_names.add(model.model)
106 | except Exception as e:
107 | raise RuntimeError(f"Failed to list models using Ollama: {e}")
108 |
109 | missing_models = model_names - available_model_names
110 |
111 | if not missing_models:
112 | logger.info("All required models are already available.")
113 | return True
114 |
115 | for model in missing_models:
116 | try:
117 | print(f"Pulling missing model: {model}")
118 | ollama.pull(model)
119 | except Exception as e:
120 | print(f"Failed to pull model '{model}': {e}")
121 |
122 | return True
123 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DeepShell
2 |
3 | 
4 |
5 | _A whisper in the void, a tool forged in silence._ DeepShell is your clandestine terminal companion, bridging the gap between human intent and AI execution. It speaks in commands, listens in context, and acts with precision.
6 |
7 | ## Essence of the Tool
8 |
9 | - **Silent Precision** – Strips away the noise, leaving only the clean, actionable insights.
10 | - **Markup-Enhanced Streaming** – Responses flow in markup, providing clarity with every word.
11 | - **Intelligent File Handling** – Files and directories are read, analyzed, and acted upon without interruption.
12 | - **Advanced Command Parsing** – Understands natural instructions, like _"open this folder and analyze the code"_.
13 | - **Real-Time AI Interaction** – A dialogue system built for seamless terminal operation, always listening, always ready.
14 | - **Asynchronous File Handling** – Processes large files effortlessly, without blocking the flow of execution.
15 | - **Full Folder Analysis** – Decodes complex codebases and logs, understanding every nuance.
16 | - **Interactive Shell Mode** – Speak in natural language, and the AI will initiate the shell, interpreting commands, executing them, and weaving the output into a coherent, real-time markup stream.
17 | - **Contextual Awareness** – The AI distills relevant details from files, commands, and interactions, ensuring responses remain focused and precise, without straying into the irrelevant.
18 |
19 | ## Claim the Artifact
20 | Not all tools are found. Some must be taken.
21 |
22 | [**Take Hold of DeepShell**](https://github.com/Abyss-c0re/deepshell/releases)
23 |
24 | _It does not seek you. But now, it is yours._
25 |
26 | ## Awakening the Entity
27 |
28 | Prepare the tool for execution:
29 |
30 | ```sh
31 | pip install -r requirements.txt
32 | ```
33 | Bind DeepShell to your system:
34 |
35 | ```sh
36 | chmod +x deepshell
37 | ./deepshell --install
38 | ```
39 | This binds DeepShell to your system, making it accessible from anywhere.
40 |
41 | ## Sculpting the Intent
42 |
43 | [**Requires configuration**](https://github.com/Abyss-c0re/deepshell/wiki#configuration)
44 |
45 | ## The Art of Invocation
46 |
47 | **Summon the AI:**
48 |
49 | ```sh
50 | deepshell
51 | ```
52 |
53 | or, for the uninitiated:
54 |
55 | ```sh
56 | python3 main.py
57 | ```
58 |
59 | **Invocation Modes:**
60 |
61 | - `--model` - Define which entity will answer.
62 | - `--host` - Set the host for your digital oracle.
63 | - `--thinking` - Unveil the unseen, revealing the process behind the response.
64 | - `--prompt` - Offer a thought to guide the AI’s response.
65 | - `--file` - Present a document for analysis.
66 | - `--code` - Extract and manifest the essence of code, carving precise snippets from the chaos around it.
67 | - `--shell` - Speak your intent in natural language. The AI will translate your command, summon the shell, execute your instructions, and return the output as a real-time, immersive markup analysis.
68 | - `--system` - The AI whispers through logs and configs, extracting secrets with cold precision, revealing only what’s needed.
69 |
70 | **Voice of the Machine: The Art of Commanding its Tongue:**
71 |
72 | Speak in the language of the machine—prefix your words with !, and the AI, attuned to the art of command, will instantly interpret and execute your directive. The system will then return its results, woven into a clean and structured markup response, as if deciphering its own language.
73 | Example:
74 |
75 | ```sh
76 | !sudo apt update
77 | ```
78 |
79 | **Piping Shadows Through the Void:**
80 |
81 | ```sh
82 | cat input.txt | deepshell "Analyze the content"
83 | ```
84 |
85 | **Delve Into the Abyss of Folders:**
86 |
87 | ```sh
88 | deepshell "open this folder"
89 | ```
90 |
91 | **Unify the Question and the Execution:**
92 |
93 | ```sh
94 | deepshell "open this folder and analyze the code"
95 | ```
96 |
97 | ### The Vessel of Containment: Docker
98 |
99 | DeepShell may be bound within a Docker vessel, self-contained and portable, with Ollama as its inner oracle.
100 |
101 | **Forging the Vessel**
102 |
103 | Build the image, choosing your hardware's essence:
104 |
105 | ```sh
106 | # CPU only (or NVIDIA fallback)
107 | docker build -t deepshell .
108 |
109 | # AMD GPU (ROCm acceleration)
110 | docker build --build-arg OLLAMA_VARIANT=rocm -t deepshell .
111 | ```
112 |
113 | **Summoning the Vessel**
114 |
115 | CPU
116 |
117 | ```sh
118 | docker run -it --rm \
119 | -v /:/host:ro \
120 | -p 11434:11434 \
121 | deepshell
122 | ```
123 | NVIDIA GPU (requires NVIDIA Container Toolkit installed and Docker restarted)
124 |
125 | ```sh
126 | docker run -it --rm \
127 | -v /:/host:ro \
128 | -p 11434:11434 \
129 | --gpus all \
130 | deepshell
131 | ```
132 | AMD GPU (ROCm)
133 |
134 | ```sh
135 | docker run -it --rm \
136 | -v /:/host:ro \
137 | -p 11434:11434 \
138 | --device /dev/kfd \
139 | --device /dev/dri \
140 | deepshell
141 | ```
142 |
143 | #### Eternal Docker Models (Optional)
144 |
145 | By default, the vessel is ephemeral—destroyed upon dismissal, its memories scattered to the void.
146 | Yet the oracle’s wisdom (downloaded models) and any traces DeepShell may leave behind can be made eternal through binding volumes.
147 |
148 |
149 | Preserve all summoned models across invocations:
150 |
151 | ```sh
152 | # Create the eternal repository (once)
153 | docker volume create ollama-models
154 | ```
155 | Include the binding in every summoning:
156 | ```sh
157 | -v ollama-models:/root/.ollama
158 | ```
159 | The void now remembers.
160 | Models remain. Traces linger.
161 | Each summoning is instant, familiar, and unbroken.
162 |
163 | **Echoes in the Abyss: The Neovim Conduit**
164 |
165 | The [DeepShell.nvim](https://github.com/Abyss-c0re/deepshell-nvim) plugin serves as the unseen bridge between the arcane depths of Neovim and the profound intelligence of DeepShell.
166 |
167 |
168 |
169 | _A tool forged for precision in a chaotic world. Your words, its execution, seamless in form._
170 |
171 |
172 |
173 |
--------------------------------------------------------------------------------
/utils/command_processor.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 | from ui.printer import printer
4 | from utils.logger import Logger
5 | from config.settings import Mode
6 | from typing import Optional, Tuple
7 | from utils.file_utils import FileUtils
8 | from utils.shell_utils import CommandExecutor
9 |
10 | logger = Logger.get_logger()
11 |
12 |
13 | class CommandProcessor:
14 | """
15 | Handles user input
16 | """
17 |
18 | def __init__(self, manager):
19 | self.manager = manager
20 | self.ui = manager.ui
21 | self.file_utils = FileUtils(manager)
22 | self.executor = CommandExecutor(self.ui)
23 |
24 | async def handle_command(
25 | self, user_input: str
26 | ) -> Tuple[str, str | None] | Tuple[None, None]:
27 | """
28 | Processes commands, handles file/folder operations, and updates config.
29 | """
30 |
31 | # Handle shell bypass if user input starts with "!"
32 | if user_input.startswith("!"):
33 | return user_input[1:], "shell_bypass"
34 |
35 | # Handle @mode command
36 | if user_input.startswith("@"):
37 | input = await self.detect_mode(user_input)
38 | if input is None:
39 | return "", None
40 | else:
41 | if self.manager.client.mode == Mode.SHELL:
42 | return input, None
43 | # If there is a user input to process
44 | if user_input:
45 | target, additional_action = await self.detect_action(user_input)
46 |
47 | if target:
48 | pass_image = False
49 |
50 | # Check if the target is an image, switch to vision mode if true
51 | if self.file_utils._is_image(target):
52 | pass_image = True
53 | self.manager.client.switch_mode(Mode.VISION)
54 | else:
55 | await self.file_utils.process_file_or_folder(target)
56 |
57 | # If there's an additional action to update the user input
58 | if additional_action:
59 | user_input = additional_action
60 |
61 | # Return the user input along with target if it's an image
62 | if pass_image:
63 | return user_input, target
64 |
65 | return user_input, None
66 | else:
67 | # If no target was found and action is "cancel", return None
68 | if additional_action == "cancel":
69 | return None, None
70 |
71 | # Return the original user input if no specific handling was done
72 | return user_input, None
73 |
74 | async def detect_mode(self, user_input: str) -> str | None:
75 | """
76 | Detects if input starts with @ and checks if it matches a Mode.
77 | """
78 | mode_switcher = self.manager.client.switch_mode
79 | parts = user_input.split(" ", 1)
80 |
81 | if len(parts) < 2:
82 | if self.ui:
83 | await self.ui.fancy_print(
84 | "\n\n[red]System:[/]\nNo user prompt detected after mode override\n"
85 | )
86 | logger.warning("No user prompt detected after user override")
87 | return None
88 |
89 | mode_str, after_text = parts[0][1:].upper(), parts[1]
90 |
91 | try:
92 | mode = Mode[mode_str]
93 |
94 | # Special handling for Mode.VISION
95 | if mode == Mode.VISION:
96 | logger.warning("Mode.VISION cannot be selected directly.")
97 | return None
98 |
99 | mode_switcher(mode)
100 | logger.info(f"Mode detected: {mode.name}")
101 | return after_text
102 |
103 | except KeyError:
104 | printer("Invalid mode override", True)
105 | logger.warning("Invalid mode override, suspending input")
106 | return None
107 | except Exception as e:
108 | printer(str(e), True)
109 | logger.warning(str(e))
110 | return None
111 |
112 | async def detect_action(self, user_input: str):
113 | """
114 | Detects action, validates/finds target, and processes file/folder.
115 | """
116 |
117 | parts = re.split(r"\band\b", user_input, maxsplit=1)
118 | main_command = parts[0].strip()
119 | additional_action = parts[1].strip() if len(parts) > 1 else None
120 | actions = {"find", "open", "read"}
121 | tokens = main_command.split()
122 |
123 | if not tokens:
124 | return None, None
125 |
126 | # Ensure the action is at the beginning of the input
127 | action = tokens[0] if tokens[0] in actions else None
128 | if not action:
129 | return None, None
130 |
131 | # Extract target (everything after the action)
132 | target_index = 1 # Start from the second token, assuming it's the target
133 | target = " ".join(tokens[target_index:]) if target_index < len(tokens) else ""
134 |
135 | # Convert "this folder" to current working directory
136 | if target.lower() == "this folder":
137 | target = os.getcwd()
138 |
139 | # Validate or find target
140 | target = target.strip()
141 | if not os.path.exists(target):
142 | choice = await self.file_utils.prompt_search(target)
143 | if not choice:
144 | printer("Nothing found", True)
145 | return None, None
146 | if choice == "cancel" or choice == "nothing":
147 | printer("Search canceled by user", True)
148 | return choice
149 | target = choice
150 |
151 | # Ensure default additional action if none is specified
152 | if target:
153 | if not additional_action:
154 | additional_action = f"Analyze the content of {target}"
155 | else:
156 | additional_action = f"{additional_action} for {target}"
157 |
158 | return target, additional_action
159 |
160 | def format_input(
161 | self,
162 | user_input: str,
163 | file_content: str,
164 | additional_action: Optional[str] = None,
165 | ):
166 | """
167 | Prepares user input by combining prompt and file content.
168 | """
169 | formatted_content = f"Content:\n{file_content}"
170 | if additional_action:
171 | user_input = additional_action
172 | if user_input:
173 | return f"\n{formatted_content}\nUser Prompt:\n{user_input}\n"
174 | return formatted_content
175 |
--------------------------------------------------------------------------------
/pipeline/pipe_filter.py:
--------------------------------------------------------------------------------
1 | import re
2 | from ui.printer import printer
3 | from utils.logger import Logger
4 | from ollama_client.api_client import OllamaClient
5 |
6 | logger = Logger.get_logger()
7 |
8 |
9 | class PipeFilter:
10 | def __init__(self, ollama_client: OllamaClient):
11 | self.ollama_client = ollama_client
12 | self.input_buffer = ollama_client.output_buffer
13 | self.formatting = ollama_client.render_output
14 | self.extracted_code = None
15 |
16 | async def process_stream(
17 | self, extract_code: bool = False, render: bool = True
18 | ) -> None:
19 | """
20 | Processes the input stream, handling thoughts and code differently based on config.
21 | """
22 | full_input = ""
23 | results = ""
24 |
25 | if extract_code:
26 | while True:
27 | message = await self.input_buffer.get()
28 | if message is None:
29 | break
30 | full_input += message
31 |
32 | self.ollama_client.last_response = full_input
33 | self.extracted_code = await self.extract_code(response=full_input)
34 | logger.debug(f"Extracted code: {self.extracted_code}")
35 | return
36 |
37 | # --- Default behavior: Process thoughts and full response ---
38 | thinking = False
39 | thought_buffer = []
40 | accumulated_line = ""
41 | first_chunk = True
42 |
43 | while True:
44 | chunk = await self.input_buffer.get()
45 | if chunk is None:
46 | break
47 |
48 | output = ""
49 | i = 0
50 |
51 | while i < len(chunk):
52 | if chunk[i:].startswith(""):
53 | thinking = True
54 | i += 7
55 | continue
56 | elif chunk[i:].startswith(""):
57 | thinking = False
58 | i += 8
59 | if self.ollama_client.show_thinking:
60 | output += "\n[blue]Final answer:[/] "
61 | continue
62 |
63 | char = chunk[i]
64 |
65 | if thinking:
66 | thought_buffer.append(char)
67 | if self.ollama_client.show_thinking:
68 | output += char
69 | else:
70 | output += char
71 |
72 | i += 1
73 |
74 | if output:
75 | if first_chunk:
76 | prefix = "[purple]AI: [/]"
77 | formatted_output = prefix + output.lstrip("\n")
78 | accumulated_line += formatted_output
79 | first_chunk = False
80 | else:
81 | accumulated_line += output
82 | results += output
83 |
84 | if "\n" in accumulated_line:
85 | lines = accumulated_line.split("\n")
86 | for line in lines[:-1]:
87 | if line.strip() and render:
88 | printer(line)
89 | accumulated_line = lines[-1]
90 |
91 | if accumulated_line.strip() and render:
92 | printer(accumulated_line)
93 |
94 | self.ollama_client.last_response = results
95 | self.ollama_client.thoughts = thought_buffer
96 | logger.debug(f"PipeFilter output: {results} \nThoughts: {thought_buffer}")
97 |
98 | async def process_static(self, text: str, extract_code: bool = False) -> str:
99 | """
100 | Processes a static string, handling thoughts and code differently based on config.
101 | """
102 | if extract_code:
103 | self.ollama_client.last_response = text
104 | self.extracted_code = await self.extract_code(response=text)
105 |
106 | if self.extracted_code:
107 | logger.debug(f"Extracted code: {self.extracted_code}")
108 | return self.extracted_code
109 |
110 | # Process thoughts and filter them
111 | thoughts = re.findall(r"(.*?)", text, flags=re.DOTALL)
112 | filtered_text = re.sub(r".*?", "", text, flags=re.DOTALL)
113 |
114 | # Apply additional line-based filtering
115 | pattern = re.compile(r"(#{3,4}|\*\*)")
116 | filtered_lines = [pattern.sub("", line) for line in filtered_text.splitlines()]
117 | filtered_text = "\n".join(filtered_lines)
118 |
119 | self.ollama_client.last_response = filtered_text
120 | self.ollama_client.thoughts.append(thoughts)
121 |
122 | logger.debug(f"Filtered text: {filtered_text} \nThoughts: {thoughts}")
123 | return filtered_text
124 |
125 | async def extract_shell_command(self, response: str) -> str:
126 | """
127 | Extracts a shell command from the response.
128 | """
129 | shell_pattern = r"```(?:sh|bash)\n(.*?)```"
130 | match = re.search(shell_pattern, response, re.DOTALL)
131 |
132 | if match:
133 | full_command = match.group(1).strip()
134 | commands = [
135 | line.strip() for line in full_command.split("\n") if line.strip()
136 | ]
137 | command = commands[0] if len(commands) == 1 else " && ".join(commands)
138 | else:
139 | single_line = response.strip().split("\n")
140 | command = (
141 | single_line[0].strip()
142 | if len(single_line) == 1 and single_line[0]
143 | else ""
144 | )
145 |
146 | command = command.replace("\n", " && ").strip("`").strip()
147 | return command
148 |
149 | async def extract_code(self, response: str) -> str | None:
150 | """
151 | Extracts all code snippets from the response and separates them with comments if needed.
152 | """
153 | pattern = r"```(\w+)?\n(.*?)```"
154 | matches = re.findall(pattern, response, re.DOTALL)
155 |
156 | code_snippets = []
157 | for i, match in enumerate(matches):
158 | language, code = match
159 | code = code.strip()
160 | if self.formatting:
161 | if i > 0:
162 | code_snippets.append("\n# --- Next Code Block ---\n")
163 | code_snippets.append(f"```{language}\n{code}```")
164 | else:
165 | if i > 0:
166 | code_snippets.append("\n# --- Next Code Block ---\n")
167 | code_snippets.append(code)
168 |
169 | return "\n".join(code_snippets) if code_snippets else None
170 |
--------------------------------------------------------------------------------
/ui/ui.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import asyncio
3 | from textual import events
4 | from ui.rendering import Rendering
5 | from textual.containers import Vertical
6 | from textual.widgets import Input, RichLog
7 | from textual.app import App, ComposeResult
8 |
9 |
10 | class ChatMode(App):
11 | _instance = None
12 | _initialized: bool = False
13 | CSS_PATH = "style.css"
14 |
15 | def __new__(cls, *args, **kwargs):
16 | # Ensure that only one instance of the class exists
17 | if cls._instance is None:
18 | cls._instance = super().__new__(cls)
19 | return cls._instance
20 |
21 | def __init__(self, manager, user_input=None, file=None, file_content=None):
22 | super().__init__()
23 | if self._initialized:
24 | return
25 | self.manager = manager
26 | self.client = manager.client
27 | self.rendering = Rendering(self)
28 | self.fancy_print = self.rendering.fancy_print
29 | self.user_input, self.file, self.file_content = user_input, file, file_content
30 | self.system_message = f"\nChat with: [cyan]{self.client.model}[/cyan] in [cyan]{self.client.mode.name}[/cyan] mode.\nType [red]exit[/red] or press [blue]Ctrl+C[/blue] to quit.\n"
31 |
32 | def compose(self) -> ComposeResult:
33 | """
34 | Create UI layout with a fixed bottom input and scrollable output.
35 | """
36 | yield Vertical(
37 | RichLog(highlight=True, markup=True, wrap=True, id="rich_log"),
38 | Input(placeholder="Type here and press Enter...", id="input_field"),
39 | )
40 |
41 | async def on_ready(self) -> None:
42 | """
43 | Initialize queue and start background listeners.
44 | """
45 |
46 | # Initialize UI widgets and styles
47 | self.rich_log_widget = self.query_one(RichLog)
48 | self.input_widget = self.query_one(Input)
49 | self.rich_log_widget.styles.border = None
50 | self.input_widget.styles.border = None
51 | self.input_widget.focus()
52 |
53 | await self.rendering.start_processing()
54 |
55 | asyncio.create_task(self.manager.init())
56 |
57 | # Deploy the task with the file and user input if available
58 | if self.user_input or self.file or self.file_content:
59 | if self.file_content:
60 | sys.stdin = open("/dev/tty", "r")
61 | # until a way to switch will be revealed in a dream
62 | self.input_widget.disabled = True
63 | asyncio.create_task(
64 | self.manager.deploy_task(self.user_input, self.file, self.file_content)
65 | )
66 | self.user_input, self.file, self.file_content = None, None, None
67 | # Print the system message once the client is initialized
68 | await self.fancy_print(self.system_message)
69 |
70 | async def on_key(self, event: events.Key) -> None:
71 | """
72 | Handles user input from the keyboard.
73 | """
74 | if event.key == "ctrl+c":
75 | await self.exit_app()
76 |
77 | if event.key == "enter":
78 | text = self.input_widget.value or ""
79 | text = text.strip()
80 | # If there's a pending input future (from get_user_input), resolve it and return early.
81 | if (
82 | hasattr(self, "input_future")
83 | and self.input_future
84 | and not self.input_future.done()
85 | ):
86 | self.input_future.set_result(text)
87 | self.input_widget.clear()
88 | self.input_widget.focus()
89 | return
90 | if text:
91 | if text.lower() == "exit":
92 | await self.exit_app()
93 | else:
94 | await self.fancy_print(f"[bold red]You: [/bold red]{text}")
95 | self.input_widget.clear()
96 | self.input_widget.focus()
97 | asyncio.create_task(self.manager.deploy_task(text))
98 |
99 | async def exit_app(self):
100 | """
101 | Functions called on exit
102 | """
103 | await self.manager.stop()
104 |
105 | self.exit()
106 |
107 | def lock_input(self):
108 | """
109 | Locking down user input fiels.
110 | Usefull when rendering multiline output
111 | """
112 | if not self.input_widget.disabled:
113 | self.input_widget.disabled = True
114 |
115 | def unlock_input(self):
116 | """
117 | Unlocks the user input field
118 | """
119 | if self.input_widget.disabled:
120 | self.input_widget.disabled = False
121 | self.input_widget.focus()
122 |
123 | def wait_for_input(self):
124 | """
125 | Helper method to wait for input asynchronously.
126 | """
127 | self.input_widget.focus()
128 | self.input_future = asyncio.Future()
129 | return self.input_future
130 |
131 | async def get_user_input(
132 | self,
133 | prompt_text: str = "Enter input:",
134 | placeholder: str = "Type here and press Enter:...",
135 | input_text: str = "",
136 | is_password: bool = False,
137 | ):
138 | """
139 | Waits for user input asynchronously and returns the value.
140 | If is_password is True, masks the input like a password.
141 | """
142 | await self.fancy_print(f"[cyan]System:[/cyan] {prompt_text}")
143 |
144 | self.input_widget.value = input_text
145 | self.input_widget.placeholder = placeholder
146 |
147 | if is_password:
148 | self.input_widget.password = True
149 | self.input_widget.placeholder = "●●●●●●●●"
150 | else:
151 | self.input_widget.password = False
152 |
153 | result = await self.wait_for_input()
154 | user_input = result.strip() if result else ""
155 |
156 | if is_password:
157 | self.input_widget.password = False
158 | self.input_widget.placeholder = "Type here and press Enter:..."
159 |
160 | return user_input
161 |
162 | async def yes_no_prompt(self, prompt_text, default="yes"):
163 | """
164 | Prompts the user with yes or no with an optional default.
165 | """
166 | valid_defaults = {"yes": True, "y": True, "no": False, "n": False}
167 |
168 | while True:
169 | choice = await self.get_user_input(
170 | prompt_text=prompt_text,
171 | placeholder=f"Type Yes or No. Default: {default}",
172 | )
173 |
174 | if not choice and default:
175 | return valid_defaults.get(default.strip().lower(), None)
176 |
177 | if choice:
178 | choice = choice.strip().lower()
179 |
180 | if choice.lower() == "exit":
181 | await self.exit_app()
182 |
183 | elif choice in valid_defaults:
184 | return valid_defaults[choice]
185 |
186 | else:
187 | await self.fancy_print(
188 | "\n[cyan]System: [/cyan] It is a [green]Yes[/green] or [red]No[/red] question."
189 | )
190 |
--------------------------------------------------------------------------------
/ollama_client/api_client.py:
--------------------------------------------------------------------------------
1 | import ollama
2 | import asyncio
3 | import numpy as np
4 | from utils.logger import Logger
5 | from typing import AsyncGenerator, Sequence, cast
6 | from config.settings import Mode, MODE_CONFIGS, EMBEDDING_MODEL, DEFAULT_HOST
7 |
8 | logger = Logger.get_logger()
9 |
10 |
11 | class OllamaClient:
12 | # Class-level lock to ensure critical async functions do not run concurrently
13 | _global_lock = asyncio.Lock()
14 |
15 | def __init__(
16 | self,
17 | host: str,
18 | model: str,
19 | config: dict,
20 | mode: Mode,
21 | stream: bool = True,
22 | render_output: bool = True,
23 | show_thinking: bool = False,
24 | ):
25 | logger.info("Initializing OllamaClient")
26 | self.client = ollama.AsyncClient(host=host)
27 | self.model = model
28 | self.config = config
29 | self.mode = mode
30 | self.stream = stream
31 |
32 | self.pause_stream = False
33 | self.output_buffer = asyncio.Queue()
34 | self.render_output = render_output
35 |
36 | self.show_thinking = show_thinking
37 | self.thoughts = []
38 |
39 | self.last_response = ""
40 |
41 | self.keep_history = True
42 |
43 | logger.info(
44 | f"Client initialized with model: {model}, mode: {mode}, stream: {stream}"
45 | )
46 |
47 | def switch_mode(self, mode: Mode) -> None:
48 | """
49 | Dynamically switches mode and updates config.
50 | """
51 | logger.info(f"Switching mode from {self.mode} to {mode}")
52 | if mode == self.mode:
53 | logger.info("Mode is the same, no switch needed")
54 | return
55 |
56 | try:
57 | config = MODE_CONFIGS[mode]
58 | self.model = config["model"]
59 | self.config = {"temperature": config["temp"], "system": config["prompt"]}
60 | self.stream = config["stream"]
61 | self.mode = mode
62 | logger.info(f"Mode switched successfully: {self.mode}")
63 | except KeyError as e:
64 | logger.error(f"Invalid mode: {mode}. Error: {e}")
65 |
66 | async def _chat_stream(self, input=None, history=None) -> None:
67 | """
68 | Fetches response from the Ollama API and streams into output buffer.
69 | """
70 | async with OllamaClient._global_lock:
71 | logger.info(f"{self.mode.name} started stream")
72 |
73 | if history:
74 | input = history
75 | else:
76 | input = [{"role": "user", "content": input}]
77 |
78 | logger.debug(f"Chat request payload: {input}")
79 |
80 | try:
81 | # Force-cast the response to an AsyncGenerator
82 | response = cast(
83 | AsyncGenerator[dict, None],
84 | await self.client.chat(
85 | model=self.model,
86 | messages=input,
87 | options=self.config,
88 | stream=self.stream,
89 | ),
90 | )
91 |
92 | async for part in response:
93 | if not self.pause_stream:
94 | content = part.get("message", {}).get("content", "")
95 | await self.output_buffer.put(content)
96 |
97 | if not self.pause_stream:
98 | await self.output_buffer.put(None)
99 | logger.info("Chat stream ended successfully")
100 |
101 | except Exception as e:
102 | logger.error(f"Error during chat stream: {e}")
103 |
104 | async def _describe_image(
105 | self, image: str | None, prompt: str = "Describe"
106 | ) -> str | None:
107 | """
108 | Describes an image using the vision model.
109 | """
110 | async with OllamaClient._global_lock:
111 | logger.info(f"{self.mode.name} describing image")
112 |
113 | if not image:
114 | logger.warning("No image provided")
115 | return "No image provided"
116 |
117 | if self.mode == Mode.VISION:
118 | try:
119 | response = await self.client.generate(
120 | model=self.model, prompt=prompt, images=[image]
121 | )
122 | logger.debug(f"Image description response: {response}")
123 | message_data = response.response
124 |
125 | if message_data:
126 | return message_data
127 | else:
128 | logger.warning("No message found in response")
129 | return "No message in response"
130 |
131 | except Exception as e:
132 | logger.error(f"Error while describing image: {e}")
133 | return "Error processing image"
134 |
135 | async def _fetch_response(self, input: str) -> str:
136 | """
137 | Fetches a complete response from the model.
138 | """
139 | async with OllamaClient._global_lock:
140 | logger.info(f"{self.mode.name} is fetching response")
141 |
142 | try:
143 | response = await self.client.generate(model=self.model, prompt=input)
144 | logger.info("Response received successfully")
145 | message_data = response.response
146 | if not message_data:
147 | logger.warning("No message found in response")
148 | return "No message in response"
149 |
150 | return message_data
151 | except Exception as e:
152 | logger.error(f"Error fetching response: {e}")
153 | return "Error fetching response"
154 |
155 | async def _call_function(self, input: str, functions: list = []) -> Sequence | None:
156 | """
157 | Fetches a complete response from the model.
158 | """
159 | async with OllamaClient._global_lock:
160 | logger.info(f"{self.mode.name} is fetching response")
161 | logger.info(functions)
162 |
163 | try:
164 | message = {"role": "user", "content": input}
165 | response = await self.client.chat(
166 | model=self.model, messages=[message], tools=functions
167 | )
168 | logger.info(f"Full response: {response}")
169 | if response.message.tool_calls:
170 | return response.message.tool_calls
171 |
172 | else:
173 | logger.info("No functions have been called")
174 | return None
175 |
176 | except Exception as e:
177 | logger.error(f"Error fetching response: {e}")
178 | return "Error fetching response"
179 |
180 | @staticmethod
181 | async def fetch_embedding(text: str) -> np.ndarray | None:
182 | """
183 | Asynchronously fetches and caches an embedding for the given text while ensuring
184 | that no other locked operation (such as streaming) runs concurrently.
185 | """
186 | async with OllamaClient._global_lock:
187 | client = ollama.Client(host=DEFAULT_HOST)
188 | try:
189 | logger.info("Fetching embedding")
190 | # Offload blocking work to a thread if needed
191 | response = await asyncio.to_thread(
192 | client.embeddings, model=EMBEDDING_MODEL, prompt=text
193 | )
194 | embedding = response["embedding"]
195 | logger.debug(f"Extracted {len(embedding)} embeddings")
196 | return embedding
197 | except Exception as e:
198 | logger.error(
199 | f"Error fetching embedding for text: {text}. Error: {str(e)}"
200 | )
201 | return
202 |
--------------------------------------------------------------------------------
/utils/file_utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import magic
3 | import base64
4 | import asyncio
5 | import aiofiles
6 | from PIL import Image
7 | from io import BytesIO
8 | from typing import Callable
9 | from ui.printer import printer
10 | from utils.logger import Logger
11 |
12 | from ui.popups import RadiolistPopup
13 | from config.settings import (
14 | IGNORE_DOT_FILES,
15 | SUPPORTED_EXTENSIONS,
16 | IGNORED_FOLDERS,
17 | MAX_FILE_SIZE,
18 | MAX_LINES,
19 | PROCESS_IMAGES,
20 | IMG_INPUT_RES,
21 | )
22 |
23 | logger = Logger.get_logger()
24 |
25 |
26 | class FileUtils:
27 | def __init__(self, manager):
28 | self.ui = manager.ui
29 | self.index_file = None
30 | self.add_folder = None
31 | self.file_locks = {}
32 |
33 | if PROCESS_IMAGES:
34 | self.image_processor = manager._handle_vision_mode
35 |
36 | def set_index_functions(self, index_file: Callable, add_folder: Callable) -> None:
37 | """
38 | Helper function to avoid circular import
39 | """
40 | self.index_file = index_file
41 | self.add_folder = add_folder
42 |
43 | async def process_file_or_folder(self, target: str) -> str | int | None:
44 | """
45 | Processing the target, if exists.
46 | If not, tries to find the path.
47 | Returns full path if target is confirmed, esle -1
48 | """
49 | target = target.strip()
50 |
51 | if not os.path.exists(target):
52 | choice = await self.prompt_search(target)
53 | if not choice:
54 | printer("[yellow]Nothing found[/yellow]", True)
55 | return -1
56 | target = choice
57 |
58 | if os.path.isfile(target):
59 | content = await self.read_file(target)
60 | if self.index_file:
61 | await self.index_file(target, content)
62 | elif os.path.isdir(target):
63 | await self.read_folder(target)
64 |
65 | logger.info("File operations complete")
66 | printer("File processing complete, submiting the input to the chatbot", True)
67 |
68 | async def read_file(
69 | self,
70 | file_path: str,
71 | max_file_size: int = MAX_FILE_SIZE,
72 | max_lines: int = MAX_LINES,
73 | ) -> str | None:
74 | """
75 | Returns the content of a file or image description from the VISION model
76 | """
77 | try:
78 | if not self._is_safe_file(file_path):
79 | logger.info(f"Skipping file (unsupported): {file_path}")
80 | return None
81 |
82 | # Create a lock for this file if it doesn't exist yet
83 | if file_path not in self.file_locks:
84 | self.file_locks[file_path] = asyncio.Lock()
85 |
86 | # Use the lock for this file
87 | async with self.file_locks[file_path]:
88 | if PROCESS_IMAGES:
89 | if self._is_image(file_path):
90 | printer(f"Processing the image: {file_path}", True)
91 | description = await self.image_processor(
92 | file_path, "Describe this image", True
93 | )
94 | logger.info(f"Processed {file_path}")
95 | return f"Image description by the vision model: {description}"
96 |
97 | else:
98 | if self._is_image(file_path):
99 | logger.info(f"Skipping image file {file_path}")
100 |
101 | printer(f"Reading {file_path}", True)
102 | content = await _read_file(file_path)
103 | if content:
104 | n_lines = len(content.splitlines())
105 | logger.info(f"Read {n_lines} lines of text")
106 | if (
107 | os.path.getsize(file_path) > max_file_size
108 | or n_lines > max_lines
109 | ):
110 | content = await self._read_last_n_lines(content, max_lines)
111 |
112 | return content
113 |
114 | except Exception as e:
115 | logger.error(f"Error reading file {file_path}: {e}")
116 |
117 | def _is_safe_file(
118 | self, file_path: str, supported_extensions: list = SUPPORTED_EXTENSIONS
119 | ) -> bool:
120 | """
121 | Returns True if file located at provided file_path:str is in the SUPPORTED_EXTENSIONS list
122 | or if the file is without extension is a text file.
123 | """
124 | if os.path.getsize(file_path) == 0:
125 | logger.info(f"Skipping empty file: {file_path}")
126 | return False
127 |
128 | if any(file_path.lower().endswith(ext) for ext in supported_extensions):
129 | return True
130 |
131 | if "." not in os.path.basename(file_path):
132 | logger.info(
133 | f"File '{file_path}' has no extension. Checking if it's a text file..."
134 | )
135 | return self._is_text_file(file_path)
136 |
137 | return False
138 |
139 | def _is_text_file(self, file_path: str) -> bool:
140 | """
141 | Checks if provided file at the file_path:str is a text file
142 | Return bool
143 | """
144 | try:
145 | mime = magic.Magic(mime=True)
146 | mime_type = mime.from_file(file_path)
147 |
148 | logger.info(f"Detected MIME type for '{file_path}': {mime_type}")
149 |
150 | if mime_type.startswith("text"):
151 | return True
152 | else:
153 | return False
154 |
155 | except Exception as e:
156 | logger.error(f"Error detecting MIME type for '{file_path}': {e}")
157 | return False
158 |
159 | def _is_image(self, file_path: str) -> bool:
160 | """Checks if file at provided file_path:str is an image
161 | Returns bool
162 | """
163 | try:
164 | mime = magic.Magic(mime=True)
165 | return mime.from_file(file_path).startswith("image")
166 | except Exception:
167 | return False
168 |
169 | async def _process_image(
170 | self,
171 | file_path: str,
172 | encoding_format: str = "PNG",
173 | img_size: tuple[int, int] = IMG_INPUT_RES,
174 | ) -> str | None:
175 | """
176 | Open image at provided file_path:str and encodes it as base64:str
177 | """
178 | logger.info(f"Encoding image: {file_path}")
179 | loop = asyncio.get_running_loop()
180 | try:
181 |
182 | def resize_and_encode():
183 | with Image.open(file_path) as img:
184 | img.thumbnail(img_size)
185 | buffer = BytesIO()
186 | img.save(buffer, format=encoding_format)
187 | return base64.b64encode(buffer.getvalue()).decode("utf-8")
188 |
189 | encoded_image = await loop.run_in_executor(None, resize_and_encode)
190 | return encoded_image
191 | except Exception as e:
192 | logger.error(f"Error processing image {file_path}: {e}")
193 |
194 | async def _read_last_n_lines(
195 | self, file_content: str, num_lines: int, last: bool = True
196 | ) -> str:
197 | """
198 | Function to return lines from file content.
199 | If 'last' is True, returns the last `num_lines` lines; otherwise, returns the first `num_lines`.
200 | """
201 | buffer = []
202 | lines = file_content.splitlines()
203 |
204 | if last:
205 | start_index = max(0, len(lines) - num_lines)
206 | buffer = lines[start_index:]
207 | else:
208 | end_index = min(len(lines), num_lines)
209 | buffer = lines[:end_index]
210 |
211 | return "\n".join(buffer) if buffer else "[File is empty]"
212 |
213 | def _get_file_size(self, file_path: str) -> int:
214 | """
215 | Returns the file size
216 | """
217 | try:
218 | with open(file_path, "rb") as f:
219 | f.seek(0, 2)
220 | return f.tell()
221 | except Exception:
222 | return 0
223 |
224 | def generate_structure(
225 | self,
226 | folder_path: str,
227 | root_folder: str,
228 | prefix: str = "",
229 | ignored_folders: list = IGNORED_FOLDERS,
230 | ignore_dot_files: bool = IGNORE_DOT_FILES,
231 | ) -> dict:
232 | """
233 | Generates a dictionary representation of the folder structure.
234 | All files within the folder are included, regardless of file type.
235 | """
236 | logger.info(f"Generating structure for {folder_path}")
237 |
238 | structure = {}
239 | folder_name = os.path.basename(folder_path)
240 | structure[folder_name] = {}
241 |
242 | try:
243 | items = sorted(os.listdir(folder_path))
244 | except Exception as e:
245 | logger.error(f"Error reading folder {folder_path}: {e}")
246 | return structure
247 |
248 | for item in items:
249 | item_path = os.path.join(folder_path, item)
250 | if (
251 | os.path.isdir(item_path)
252 | and item not in ignored_folders
253 | and (not ignore_dot_files and item.startswith("."))
254 | ):
255 | structure[folder_name][item] = self.generate_structure(
256 | item_path, root_folder, prefix + "--"
257 | )
258 | elif os.path.isfile(item_path):
259 | relative_path = (
260 | os.path.relpath(item_path, root_folder)
261 | if root_folder
262 | else item_path
263 | )
264 | structure[folder_name][item] = relative_path
265 |
266 | logger.debug(f"Folder structure: {structure}")
267 | return structure
268 |
269 | async def read_folder(
270 | self,
271 | folder_path: str,
272 | root_folder: str | None = None,
273 | ignored_folders: list = IGNORED_FOLDERS,
274 | ) -> str | None:
275 | """
276 | Recursively scans and reads all files in a folder.
277 | The folder structure is generated for all files; however, only files with safe extensions
278 | are attempted to be read (others are skipped).
279 | """
280 | logger.info(f"Opening {folder_path}")
281 | printer(f"Opening {folder_path}", True)
282 |
283 | if root_folder is None:
284 | root_folder = folder_path
285 |
286 | all_contents = [] # To collect content from all files
287 |
288 | try:
289 | printer(f"Generating structure for {folder_path}", True)
290 | generated_structure = self.generate_structure(folder_path, root_folder)
291 | if self.add_folder:
292 | self.add_folder(generated_structure)
293 |
294 | # Collecting content of all files
295 | for root, _, files in os.walk(folder_path):
296 | if any(ignored in root.split(os.sep) for ignored in ignored_folders):
297 | continue
298 | for file in files:
299 | file_path = os.path.join(root, file)
300 |
301 | content = await self.read_file(file_path)
302 | if self.index_file and content:
303 | await self.index_file(file_path, content, folder=True)
304 | elif content:
305 | file_contents = f"\n{content.strip()}\n"
306 | if file_contents:
307 | all_contents.append(file_contents)
308 |
309 | logger.info(f"Reading files in {folder_path} complete")
310 |
311 | return "\n".join(all_contents)
312 |
313 | except PermissionError:
314 | logger.error(f"Error: Permission denied to access '{folder_path}'.")
315 |
316 | async def search_files(self, missing_path: str = "", search_dir=None) -> list:
317 | """
318 | Searches for a missing file or folder in the specified directory.
319 | Defaults to the home directory if none is provided.
320 | """
321 | if not search_dir:
322 | search_dir = os.path.expanduser("~")
323 |
324 | results = []
325 | for root, dirs, files in os.walk(search_dir):
326 | dirs[:] = [d for d in dirs if not d.startswith(".")]
327 | files = [f for f in files if not f.startswith(".")]
328 |
329 | for name in files + dirs:
330 | if missing_path.lower() in name.lower():
331 | results.append(os.path.join(root, name))
332 | logger.info(f"Found {len(results)} files")
333 | return results
334 |
335 | async def prompt_search(self, missing_path: str) -> str:
336 | """
337 | Prompts the user to search for a file when the target is missing.
338 | Uses a popup with a radiolist if UI is available, falling back to terminal input.
339 | """
340 | while True:
341 | results = await self.search_files(missing_path)
342 |
343 | if not results:
344 | return "nothing"
345 |
346 | options = [(res, res) for res in results] + [("cancel", "Cancel")]
347 | if hasattr(self, "ui") and self.ui is not None:
348 | popup = RadiolistPopup(
349 | title="Select a file",
350 | text=f"Multiple matches found for '{missing_path}'. Please choose one:",
351 | options=options,
352 | )
353 | self.ui.mount(popup)
354 | choice = await popup.wait_for_choice()
355 | popup.remove()
356 | else:
357 | print(
358 | f"Multiple matches found for '{missing_path}'. Please choose one:"
359 | )
360 | for i, res in enumerate(results, start=1):
361 | print(f"{i}. {res}")
362 | choice_str = input(
363 | "Enter the number of your choice (or 'cancel'): "
364 | ).strip()
365 | if choice_str.lower() == "cancel":
366 | return "cancel"
367 | if choice_str.isdigit() and 1 <= int(choice_str) <= len(results):
368 | choice = results[int(choice_str) - 1]
369 | else:
370 | print("Invalid input, try again.")
371 | continue
372 |
373 | if choice == "cancel":
374 | return "cancel"
375 | return choice
376 |
377 |
378 | async def _read_file(file_path: str) -> str | None:
379 | """
380 | Asynchronously reads a file.
381 |
382 | Args:
383 | file_path (str): The file's path.
384 |
385 | Returns:
386 | str: The file's content.
387 | """
388 | try:
389 | async with aiofiles.open(
390 | file_path, "r", encoding="utf-8", errors="ignore"
391 | ) as f:
392 | content = await f.read()
393 | return content
394 | except (IOError, OSError) as e:
395 | logger.error(f" Error reading file {file_path}: {str(e)}")
396 | return None
397 |
--------------------------------------------------------------------------------
/chatbot/manager.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import time
3 | import inspect
4 | import asyncio
5 | from ui.ui import ChatMode
6 | from ui.printer import printer
7 | from utils.logger import Logger
8 | from chatbot.helper import PromptHelper
9 | from chatbot.history import HistoryManager
10 | from typing import Optional, Any, Callable
11 | from chatbot.deployer import deploy_chatbot
12 | from config.settings import Mode, PROCESS_IMAGES
13 | from utils.command_processor import CommandProcessor
14 |
15 | logger = Logger.get_logger()
16 |
17 |
18 | class ChatManager:
19 | """
20 | Manages the chatbot's operations, including initializing the client, handling user commands,
21 | managing tasks, and rendering outputs.
22 | """
23 |
24 | def __init__(self):
25 | self.client, self.filtering = deploy_chatbot()
26 | self.ui = ChatMode(self) if self.client.render_output else None
27 | if not self.ui:
28 | self.client.keep_history = False
29 | self.last_mode: Mode
30 |
31 | self.command_processor = CommandProcessor(self)
32 | self.file_utils = self.command_processor.file_utils
33 | self.executor = self.command_processor.executor
34 |
35 | self.tasks = []
36 | self.task_queue = asyncio.Queue()
37 | self.worker_running = False
38 |
39 | async def init(self):
40 | """
41 | Helper function to initialize ChatMode.
42 | """
43 | self.history_manager = HistoryManager(self)
44 | self.add_to_history = self.history_manager.add_message
45 | self.add_terminal_output = self.history_manager.add_terminal_output
46 | self.generate_prompt = self.history_manager.generate_prompt
47 | self.file_utils.set_index_functions(
48 | self.history_manager.add_file, self.history_manager.add_folder_structure
49 | )
50 |
51 | self.worker_task = asyncio.create_task(self.task_worker())
52 | await self.executor.start_shell()
53 |
54 | async def stop(self):
55 | """
56 | Helper function to stop the ChatMode.
57 | """
58 | if self.worker_task and not self.worker_task.done():
59 | self.worker_task.cancel()
60 | try:
61 | await self.worker_task
62 | logger.info("Worker process is terminated")
63 | except asyncio.CancelledError:
64 | logger.error("Worker task cancelled")
65 | await self.executor.stop_shell()
66 |
67 | async def deploy_task(
68 | self,
69 | user_input: str,
70 | file_name: Optional[str] = None,
71 | file_content: Optional[str] = None,
72 | ) -> str | None:
73 | """
74 | Deploys a task based on user input and file content.
75 | """
76 | logger.info("Deploy task started.")
77 | response, action = None, None
78 | if self.client.mode != Mode.VISION:
79 | self.last_mode = self.client.mode
80 |
81 | if file_name:
82 | logger.info("Processing file: %s", file_name)
83 | await self.file_utils.process_file_or_folder(file_name)
84 | if not user_input:
85 | user_input = "Analyze this content"
86 | elif file_content:
87 | logger.info("Pipe input detected.")
88 | if not user_input:
89 | user_input = f"Analyze this: {file_content}"
90 | else:
91 | user_input = f"{user_input} Content: {file_content}"
92 |
93 | else:
94 | logger.info("Processing user input.")
95 | # await self.command_processor.ai_handler(user_input)
96 | if self.client.mode != Mode.SHELL:
97 | input, action = await self.command_processor.handle_command(user_input)
98 | if input:
99 | user_input = input
100 |
101 | logger.info("Executing task manager.")
102 |
103 | if action or self.client.mode != Mode.DEFAULT:
104 | response = await self.task_manager(user_input=user_input, action=action)
105 | if not response:
106 | logger.info("No response detected")
107 | return
108 | if not sys.stdout.isatty():
109 | logger.info("Deploying the task")
110 | return await self.task_manager(user_input)
111 |
112 | if self.client.keep_history and self.client.mode != Mode.SHELL and not response:
113 | history = await self.generate_prompt(user_input)
114 | response = await self.task_manager(history=history)
115 |
116 | if self.client.keep_history and response:
117 | await self.add_to_history("assistant", response)
118 |
119 | if self.client.mode != self.last_mode:
120 | self.client.switch_mode(self.last_mode)
121 |
122 | logger.info("Deploy task completed.")
123 | return response
124 |
125 | async def deploy_chatbot_method(
126 | self,
127 | coro_func: Callable[..., Any], # Accepts any callable, but should be validated
128 | *args: Any,
129 | **kwargs: Any,
130 | ) -> Any:
131 | """
132 | Enqueue a heavy chatbot processing call (e.g. _chat_stream, _fetch_response,
133 | process_static, _describe_image, etc.) and return its result.
134 | """
135 | # Ensure coro_func is an async function
136 | if not asyncio.iscoroutinefunction(coro_func):
137 | raise TypeError(
138 | f"Expected an async function, but got {type(coro_func).__name__}"
139 | )
140 |
141 | sig = inspect.signature(coro_func)
142 | try:
143 | bound_args = sig.bind(*args, **kwargs) # Proper unpacking
144 | bound_args.apply_defaults()
145 | except TypeError as e:
146 | logger.error(f"Invalid arguments for {coro_func.__name__}: {e}")
147 | return None # Explicitly return None to indicate failure
148 |
149 | future = asyncio.get_running_loop().create_future()
150 | await self.task_queue.put((coro_func, args, kwargs, future))
151 |
152 | if not self.worker_running:
153 | logger.info("Starting task worker from deploy_chatbot_method.")
154 | asyncio.create_task(self.task_worker())
155 |
156 | return await future
157 |
158 | async def task_worker(self) -> None:
159 | """
160 | Processes tasks from the unified queue sequentially.
161 | Distinguishes heavy processing calls (tuples of 4 elements) and logs execution times
162 | and queue sizes.
163 | """
164 | if self.worker_running:
165 | logger.info("Task worker already running.")
166 | return
167 | self.worker_running = True
168 | logger.info("Task worker started.")
169 |
170 | while not self.task_queue.empty():
171 | queue_size_before = self.task_queue.qsize()
172 | start_time = time.time()
173 | task = await self.task_queue.get()
174 |
175 | # Heavy chatbot processing call: (coro_func, args, kwargs, future)
176 | if len(task) == 4:
177 | coro_func, args, kwargs, future = task
178 | try:
179 | result = await coro_func(*args, **kwargs)
180 | future.set_result(result)
181 | except Exception as e:
182 | logger.error("Chatbot task error: %s", e)
183 | future.set_exception(e)
184 | else:
185 | # In case legacy tasks are ever added to this queue.
186 | logger.warning("Encountered legacy task in heavy task queue. Skipping.")
187 |
188 | end_time = time.time()
189 | execution_time = end_time - start_time
190 | queue_size_after = self.task_queue.qsize()
191 | logger.info(
192 | "Task completed in %.2f seconds. Queue size before: %d, after: %d",
193 | execution_time,
194 | queue_size_before,
195 | queue_size_after,
196 | )
197 | self.task_queue.task_done()
198 |
199 | logger.info("No more tasks. Task worker is going idle.")
200 | self.worker_running = False
201 |
202 | async def task_manager(
203 | self,
204 | user_input: str = "",
205 | history: Optional[list] = None,
206 | action: Optional[str] = None,
207 | ) -> str | None:
208 | """
209 | Manages tasks based on the client's mode.
210 | """
211 | if not user_input and not history and not action:
212 | logger.warning("Attempt to launch task manager without arguments")
213 | logger.info("Task manager started in mode: %s", self.client.mode)
214 |
215 | shell_bypass = True if action == "shell_bypass" else False
216 | if action is None:
217 | action = ""
218 |
219 | mode_handlers = {
220 | Mode.SHELL: lambda inp: self._handle_shell_mode(inp, shell_bypass),
221 | Mode.CODE: self._handle_code_mode,
222 | Mode.VISION: lambda inp: self._handle_vision_mode(action, inp),
223 | }
224 |
225 | if shell_bypass:
226 | logger.info("Bypassing mode, executing shell mode.")
227 | return await self._handle_shell_mode(user_input, True)
228 |
229 | if self.client.mode in mode_handlers:
230 | logger.info("Handling task in mode: %s", self.client.mode)
231 | return await mode_handlers[self.client.mode](user_input)
232 | else:
233 | logger.info("Handling task in default mode.")
234 | return await self._handle_default_mode(input=user_input, history=history)
235 |
236 | async def _handle_command_processor(self, input: str, functions: list):
237 | """
238 | Function for calling tools via LLM (on supported ollama models)
239 | """
240 | if self.client.mode != Mode.SYSTEM:
241 | self.client.switch_mode(Mode.SYSTEM)
242 |
243 | tools = await self.deploy_chatbot_method(
244 | self.client._call_function, input, functions
245 | )
246 |
247 | self.client.switch_mode(self.last_mode)
248 |
249 | return tools
250 |
251 | async def _handle_helper_mode(self, input: str, strip_json: bool = False) -> str:
252 | """
253 | Function that Handles helper mode
254 | """
255 | if self.client.mode != Mode.HELPER:
256 | self.client.switch_mode(Mode.HELPER)
257 |
258 | response = await self.deploy_chatbot_method(self.client._fetch_response, input)
259 | if strip_json:
260 | response = response.strip("`").strip("json")
261 |
262 | filtered_response = await self.deploy_chatbot_method(
263 | self.filtering.process_static, response
264 | )
265 |
266 | if self.last_mode:
267 | self.client.switch_mode(self.last_mode)
268 | return filtered_response
269 |
270 | async def _handle_vision_mode(
271 | self, target: str, user_input: str, no_render: Optional[bool] = False
272 | ) -> str | None:
273 | """
274 | Handles vision mode by generating an image description.
275 | The heavy call to describe the image is offloaded.
276 | """
277 | if PROCESS_IMAGES:
278 | if self.client.mode != Mode.VISION:
279 | self.client.switch_mode(Mode.VISION)
280 | logger.info("Processing image %s", target)
281 | encoded_image = await self.file_utils._process_image(target)
282 | description = await self.deploy_chatbot_method(
283 | self.client._describe_image, image=encoded_image, prompt=user_input
284 | )
285 | logger.info("Processed image %s", target)
286 | if self.last_mode:
287 | self.client.switch_mode(self.last_mode)
288 | if not no_render:
289 | printer(f"[green]AI:[/]{description}")
290 | return f"Image description by the vision model: {description}"
291 | else:
292 | printer("Image processing is disabled, check your settings.py", True)
293 | logger.warning("Image processing is disabled")
294 | return
295 |
296 | async def _handle_shell_mode(
297 | self, input: str = "", bypass: bool = False, no_render: bool = False
298 | ) -> str | None:
299 | """
300 | Handles tasks when the client is in SHELL mode.
301 | Command execution is performed immediately, while heavy processing (code conversion
302 | and output analysis) is offloaded.
303 | """
304 | logger.info("Shell mode execution started. Bypass: %s", bypass)
305 | if not bypass:
306 | code_input = await self._handle_code_mode(
307 | PromptHelper.shell_helper(input), shell=True
308 | )
309 | command, output = await self.executor.start(code_input)
310 | if command:
311 | input = command
312 | else:
313 | self.client.switch_mode(Mode.SHELL)
314 |
315 | output = await self.executor.run_command(input)
316 |
317 | if output == "pass":
318 | logger.info("Command executed successfully with no output")
319 | printer("Command executed successfully without producing any output", True)
320 | return "pass"
321 |
322 | if output and input:
323 | logger.info("Command executed, processing output.")
324 | if self.ui:
325 | printer(f"Executing [green]'{input}'[/]", True)
326 | if await self.ui.yes_no_prompt(
327 | "Do you want to see the output?", default="No"
328 | ):
329 | render_task = asyncio.create_task(
330 | self.ui.fancy_print(f"[blue]Shell output[/]:\n{output}")
331 | )
332 | self.tasks.append(render_task)
333 | await asyncio.sleep(0.1)
334 | if await self.ui.yes_no_prompt("Analyze the output?", default="Yes"):
335 | if self.tasks:
336 | asyncio.create_task(self.execute_tasks())
337 | printer("Output submitted to the chatbot for analysis...", True)
338 | prompt = PromptHelper.analyzer_helper(input, output)
339 | await self._handle_default_mode(input=prompt, no_render=no_render)
340 |
341 | if self.client.keep_history and self.client.last_response:
342 | await self.add_terminal_output(
343 | input, output, self.client.last_response
344 | )
345 | return self.client.last_response
346 | else:
347 | if self.tasks:
348 | await asyncio.gather(*self.tasks)
349 | if self.client.keep_history:
350 | await self.add_terminal_output(input, output, "")
351 | return output
352 | else:
353 | logger.warning("No output detected.")
354 | printer("No output detected...", True)
355 | self.client.switch_mode(self.last_mode)
356 | return
357 | self.client.last_response = ""
358 | self.filtering.extracted_code = ""
359 | logger.info("Shell mode execution completed.")
360 | return output
361 |
362 | async def _handle_code_mode(
363 | self, input: str, shell: bool = False, no_render: bool = False
364 | ) -> str:
365 | """
366 | Handles tasks when the client is in CODE mode.
367 | Heavy processing (fetching response and static processing) is offloaded.
368 | """
369 | logger.info("Code mode execution started.")
370 | response = await self.deploy_chatbot_method(self.client._fetch_response, input)
371 | if shell:
372 | command = await self.filtering.extract_shell_command(response)
373 | logger.info(f"Command {command}")
374 | return command
375 | code = await self.filtering.process_static(response, True)
376 | if code and not no_render:
377 | printer(code)
378 | return str(code)
379 |
380 | async def _handle_default_mode(
381 | self,
382 | input: Optional[str] = None,
383 | history: Optional[list] = None,
384 | no_render: bool = False,
385 | ) -> str | None:
386 | """
387 | Handles tasks when the client is in the default mode.
388 | Streaming and filtering are queued together as one job and passed to deploy_chatbot.
389 | """
390 | logger.info("Default mode execution started.")
391 |
392 | # Decide whether to render output
393 | if self.ui and not no_render:
394 | if history and not input:
395 | logger.info("Using chat history.")
396 | chat_task = self.client._chat_stream(history=history)
397 | elif input and not history:
398 | logger.info("Using user input.")
399 | chat_task = self.client._chat_stream(input)
400 | else:
401 | logger.error("Invalid input.")
402 | return
403 |
404 | filter_task = self.filtering.process_stream(False, render=True)
405 |
406 | # Create a single async job for both tasks
407 | async def streaming_job():
408 | await asyncio.gather(chat_task, filter_task)
409 |
410 | # Pass the job to deploy_chatbot_method
411 | await self.deploy_chatbot_method(streaming_job)
412 | return self.client.last_response
413 | else:
414 | response = await self.deploy_chatbot_method(
415 | self.client._fetch_response, input
416 | )
417 | return await self.filtering.process_static(response, False)
418 |
419 | async def execute_tasks(self) -> None:
420 | try:
421 | await asyncio.gather(*self.tasks, return_exceptions=True)
422 | except Exception as e:
423 | logger.error("Error in default mode execution: %s", e)
424 | self.tasks = []
425 |
--------------------------------------------------------------------------------
/utils/shell_utils.py:
--------------------------------------------------------------------------------
1 | import re
2 | import shlex
3 | import string
4 | import asyncio
5 | import secrets
6 | from ui.printer import printer
7 | from utils.logger import Logger
8 | from config.settings import (
9 | SHELL_TYPE,
10 | MONITOR_INTERVAL,
11 | MAX_OUTPUT_LINES,
12 | FINALIZE_OUTPUT,
13 | )
14 |
15 | logger = Logger.get_logger()
16 |
17 |
18 | class CommandExecutor:
19 | """
20 | A class for executing shell commands asynchronously, handling sudo authentication,
21 | monitoring execution, and processing command outputs.
22 | """
23 |
24 | def __init__(self, ui=None):
25 | """
26 | Initializes the CommandExecutor.
27 |
28 | Args:
29 | ui: Optional user interface object for interactive input/output.
30 | monitor_interval (int): Interval (in seconds) to check for long-running commands.
31 | max_output_length (int): Maximum length of output before truncation.
32 | """
33 | self.history = []
34 | self.ui = ui
35 | self._should_stop = False
36 | self.sudo_password = None
37 | self.monitor_interval = MONITOR_INTERVAL
38 | self.max_output_lines = MAX_OUTPUT_LINES
39 | self.finalize_output = FINALIZE_OUTPUT
40 | self.shell_type = SHELL_TYPE
41 | self.process: asyncio.subprocess.Process | None = None
42 |
43 | self.sudo_password = False
44 |
45 | async def start_shell(self) -> None:
46 | """
47 | Starts a persistent shell session if not already running.
48 | """
49 |
50 | if self.process is None or self.process.returncode is not None:
51 | self.process = await asyncio.create_subprocess_exec(
52 | self.shell_type,
53 | stdin=asyncio.subprocess.PIPE,
54 | stdout=asyncio.subprocess.PIPE,
55 | stderr=asyncio.subprocess.PIPE,
56 | )
57 | logger.info("Started persistent shell session.")
58 |
59 | async def run_command(self, command: str) -> str | None:
60 | """
61 | Executing command in a current shell session
62 | """
63 | if (
64 | self.process is None
65 | or self.process.stdin is None
66 | or self.process.stdout is None
67 | ):
68 | await self.start_shell()
69 | if (
70 | self.process is None
71 | or self.process.stdin is None
72 | or self.process.stdout is None
73 | ):
74 | logger.error("Failed to start shell process.")
75 | return "Error: Shell process could not be started."
76 |
77 | if "sudo" in shlex.split(command):
78 | valid = await self._get_sudo_password()
79 | if valid == 1:
80 | return None
81 |
82 | # Unique delimiter to detect command completion
83 | delimiter = "----END-OF-COMMAND----"
84 | full_command = f"{command} ; echo '{delimiter}' ; echo $?\n"
85 |
86 | logger.debug(f"Executing: {full_command}")
87 | self.process.stdin.write(full_command.encode())
88 | await self.process.stdin.drain()
89 |
90 | output_lines = []
91 | exit_code = None
92 |
93 | while True:
94 | line = await self.process.stdout.readline()
95 | if not line:
96 | break
97 |
98 | decoded_line = line.decode(errors="ignore").strip()
99 |
100 | if decoded_line == delimiter:
101 | # Read the exit code after delimiter
102 | exit_code_line = await self.process.stdout.readline()
103 | exit_code = int(exit_code_line.decode(errors="ignore").strip())
104 | break
105 |
106 | # Skip empty lines
107 | if decoded_line:
108 | output_lines.append(decoded_line)
109 |
110 | result = "\n".join(output_lines).strip()
111 |
112 | logger.info(f"Command produced {len(output_lines)} lines")
113 | logger.debug(f"Command result : {result}")
114 |
115 | if exit_code == 0 and not result:
116 | return "pass"
117 |
118 | if result and self.finalize_output:
119 | result = await self._finalize_command_output(output_lines)
120 | return result if result else f"Command failed with exit code {exit_code}"
121 |
122 | async def stop_shell(self):
123 | """
124 | Stops the persistent shell session.
125 | """
126 | if self.process and self.process.returncode is None:
127 | self.process.terminate()
128 | await self.process.wait()
129 | self.process = None
130 | logger.info("Shell session terminated.")
131 | else:
132 | logger.warning("Process already terminated or not started.")
133 |
134 | async def start(
135 | self, command: str
136 | ) -> tuple[str | None, str | None] | tuple[None, None]:
137 | """
138 | Starts execution of the given command.
139 |
140 | Args:
141 | command (str, optional): The command to execute.
142 |
143 | Returns:
144 | tuple: (confirmed_command, command output or error message)
145 | """
146 | logger.info("Execution started.")
147 |
148 | confirmed_command = None
149 | output = "No command specified."
150 |
151 | if command:
152 | logger.info("Command received, confirming execution.")
153 | confirmed_command = await self.confirm_execute_command(command)
154 | if confirmed_command:
155 | logger.info("Command confirmed, executing.")
156 | output = await self.run_command(confirmed_command)
157 | else:
158 | return None, None
159 |
160 | logger.info("Execution finished.")
161 | logger.debug(f"Command: {confirmed_command} Output: {output}")
162 | return confirmed_command, output
163 |
164 | async def execute_command(self, command: str) -> str | None:
165 | """
166 | Executes a shell command asynchronously without starting a shell session.
167 |
168 | Args:
169 | command (str): The command to execute.
170 |
171 | Returns:
172 | str: The command output or an error message.
173 | """
174 | if not command:
175 | return "No command provided."
176 |
177 | logger.info("Executing command.")
178 |
179 | require_sudo = True if "sudo" in shlex.split(command) else False
180 |
181 | if require_sudo:
182 | logger.info("Requesting sudo password.")
183 | sudo_password = await self._get_sudo_password(return_password=True)
184 | if sudo_password == 1:
185 | logger.warning("Sudo password not provided.")
186 | return None
187 | command = f"echo {sudo_password} | sudo -S {command[5:]}"
188 | sudo_password = None
189 |
190 | proc = await self._start_subprocess(command)
191 | if proc is None:
192 | logger.error("Subprocess creation failed.")
193 | return "Error: Command did not produce valid output or is not interactive."
194 |
195 | logger.info("Processing command output.")
196 | return await self._process_command_output(proc)
197 |
198 | async def _start_subprocess(self, command: str) -> asyncio.subprocess.Process:
199 | """
200 | Starts an asynchronous subprocess to execute a command.
201 |
202 | Args:
203 | command (str): The command to execute.
204 |
205 | Returns:
206 | subprocess.Process: The subprocess object.
207 | """
208 | return await asyncio.create_subprocess_shell(
209 | f"{self.shell_type} -c '{command}'",
210 | stdin=asyncio.subprocess.PIPE,
211 | stdout=asyncio.subprocess.PIPE,
212 | stderr=asyncio.subprocess.PIPE,
213 | )
214 |
215 | async def _process_command_output(
216 | self, proc: asyncio.subprocess.Process
217 | ) -> str | None:
218 | """
219 | Processes the output of a running command.
220 |
221 | Args:
222 | proc (subprocess.Process): The running subprocess.
223 | Returns:
224 | str: The processed command output.
225 | """
226 | if not proc.stdout:
227 | logger.error("Shell subprocess is not running")
228 | return
229 |
230 | logger.info("Processing command output.")
231 | output_lines = []
232 | monitor_task = asyncio.create_task(self._monitor_execution(proc))
233 |
234 | try:
235 | while True:
236 | line = await proc.stdout.readline()
237 | if not line:
238 | break
239 | decoded_line = line.decode("utf-8", errors="ignore").strip()
240 |
241 | # Extract meaningful text
242 | extracted_text = self._extract_meaningful_text(decoded_line)
243 | if extracted_text:
244 | output_lines.append(extracted_text)
245 |
246 | # Handle potential user prompts
247 | if self._should_handle_prompt(decoded_line):
248 | await self._handle_prompt(proc, decoded_line)
249 |
250 | except asyncio.CancelledError:
251 | logger.warning("Command execution cancelled.")
252 | proc.terminate()
253 | await proc.wait()
254 | return "\n".join(output_lines)
255 | finally:
256 | monitor_task.cancel()
257 |
258 | # Validate if we received output
259 | if not output_lines:
260 | output_lines.append(
261 | "No output received. Command may require user interaction or is piped."
262 | )
263 |
264 | logger.info("Command output processing completed.")
265 | return await self._finalize_command_output(output_lines)
266 |
267 | def _extract_meaningful_text(self, data: str) -> str | None:
268 | """
269 | Cleans and extracts meaningful text from command output.
270 |
271 | Args:
272 | data (str): The raw command output.
273 |
274 | Returns:
275 | str: The cleaned output or None if empty.
276 | """
277 | # Strip out known non-text patterns (control codes, escape sequences)
278 | cleaned_data = re.sub(r"\x1b[^m]*m", "", data) # Remove ANSI escape sequences
279 | cleaned_data = re.sub(
280 | r"[\x00-\x1F\x7F]", "", cleaned_data
281 | ) # Remove control characters
282 |
283 | # Try to extract the core content from the output
284 | if len(cleaned_data.strip()) > 0:
285 | return cleaned_data.strip()
286 | else:
287 | return
288 |
289 | async def _monitor_execution(self, proc: asyncio.subprocess.Process) -> None:
290 | """
291 | Periodically checks the status of a running process and prompts the user
292 | to cancel execution if it exceeds the monitoring interval.
293 |
294 | Args:
295 | proc (asyncio.subprocess.Process): The process being monitored.
296 | """
297 | while True:
298 | await asyncio.sleep(self.monitor_interval)
299 | if proc.returncode is not None:
300 | break
301 | user_choice = await self._get_user_input(
302 | "\nCommand is taking longer than expected. Cancel execution? (y/n): "
303 | )
304 | if user_choice.strip().lower() in ["y", "yes"]:
305 | printer("Terminating command execution...", True)
306 | proc.terminate()
307 | break
308 |
309 | async def _finalize_command_output(self, output_lines: list) -> str:
310 | """
311 | Finalizes the command output, ensuring truncation if too long and handling errors.
312 |
313 | Args:
314 | output_lines (list): Collected output lines.
315 |
316 | Returns:
317 | str: The final output.
318 | """
319 | logger.info("Finalizing command output.")
320 |
321 | # Truncate based on the number of lines
322 | if len(output_lines) > self.max_output_lines:
323 | logger.warning("Output truncated due to line limit.")
324 | output_lines = output_lines[: self.max_output_lines] + [
325 | "[Output truncated]"
326 | ]
327 |
328 | output_str = "\n".join(output_lines)
329 |
330 | logger.info("Command execution completed.")
331 |
332 | return output_str
333 |
334 | async def _get_sudo_password(self, return_password=False) -> str | int | None:
335 | """
336 | Prompts the user for a sudo password if not already provided.
337 | If the password was previously validated, revalidate sudo without a password.
338 | """
339 | if self.sudo_password:
340 | if await self._validate_sudo_password(None):
341 | return 0
342 | else:
343 | self.sudo_password = None
344 | logger.warning("Sudo session expired, password required again.")
345 |
346 | # Prompt for a new password
347 | sudo_password = await self._get_user_input(
348 | "Enter sudo password: ", is_password=True
349 | )
350 | if sudo_password:
351 | valid = await self._validate_sudo_password(sudo_password)
352 | if valid:
353 | if return_password:
354 | return sudo_password
355 | self.sudo_password = True
356 | sudo_password = None
357 | logger.info("Sudo password validated and cleared securely.")
358 | return 0
359 | else:
360 | printer("Wrong password", True)
361 | logger.warning("Wrong sudo password")
362 | return 1
363 |
364 | async def _validate_sudo_password(self, sudo_password: str | None) -> bool:
365 | """
366 | Validates the provided sudo password or checks if sudo is still active.
367 |
368 | Args:
369 | sudo_password (str or None): The sudo password to validate, or None to check active status.
370 |
371 | Returns:
372 | bool: True if valid, False otherwise.
373 | """
374 | if sudo_password:
375 | command = f"echo {sudo_password} | sudo -S -v"
376 | else:
377 | # Check if sudo session is still active
378 | command = "sudo -n true"
379 |
380 | if self.process and self.process.stdin and self.process.stdout:
381 | full_command = f"stdbuf -oL {command}\n echo $?\n"
382 | self.process.stdin.write(full_command.encode())
383 | await self.process.stdin.drain()
384 |
385 | exit_code = None
386 | while True:
387 | line = await self.process.stdout.readline()
388 | if not line:
389 | break
390 | decoded_line = line.decode(errors="ignore").strip()
391 | if decoded_line.isdigit():
392 | exit_code = int(decoded_line)
393 | break
394 | proc_valid = exit_code == 0
395 | else:
396 | proc = await self._start_subprocess(command)
397 | await proc.communicate()
398 | proc_valid = proc.returncode == 0
399 |
400 | if proc_valid:
401 | logger.info("Sudo session validated.")
402 | return True
403 | else:
404 | logger.warning("Sudo validation failed.")
405 | return False
406 |
407 | def _is_text(self, data: str) -> bool:
408 | """
409 | Determines whether the given data is likely to be human-readable text.
410 |
411 | Args:
412 | data (str): The output data to check.
413 |
414 | Returns:
415 | bool: True if the data is mostly printable text, False otherwise.
416 | """
417 | if not data or "\x00" in data:
418 | return False
419 |
420 | # Remove ANSI escape sequences
421 | data = re.sub(r"\x1b[^m]*m", "", data)
422 |
423 | # Calculate printable ratio
424 | printable_chars = sum(c in string.printable for c in data)
425 | printable_ratio = printable_chars / len(data) if len(data) > 0 else 0
426 |
427 | # Allow outputs with more than 70% printable characters (but filter out pure control codes or binary data)
428 | if printable_ratio < 0.7 or any(c in "\x07\x1b" for c in data):
429 | return False
430 |
431 | return True
432 |
433 | def _should_handle_prompt(self, decoded_line: str) -> bool:
434 | """
435 | Checks if a command output line contains a user prompt requiring a response.
436 |
437 | Args:
438 | decoded_line (str): The command output line.
439 |
440 | Returns:
441 | bool: True if the line contains a recognized prompt, False otherwise.
442 | """
443 | return any(
444 | kw in decoded_line.lower()
445 | for kw in ["[y/n]", "(yes/no)", "(y/n)", "password:", "continue?"]
446 | )
447 |
448 | async def _handle_prompt(
449 | self, proc: asyncio.subprocess.Process, decoded_line: str
450 | ) -> None:
451 | """
452 | Detects and responds to command-line prompts automatically.
453 |
454 | Args:
455 | proc (asyncio.subprocess.Process): The process awaiting input.
456 | decoded_line (str): The prompt message from the command output.
457 | """
458 | if not proc.stdin:
459 | logger.error("Shell subprocess is not running")
460 | return
461 | if "password:" in decoded_line.lower():
462 | response = await self._get_user_input("Enter password: ", is_password=True)
463 | else:
464 | response = "yes"
465 |
466 | if response is not None:
467 | proc.stdin.write(response.encode() + b"\n")
468 | await proc.stdin.drain()
469 | response = secrets.token_urlsafe(32)
470 | response = None
471 |
472 | async def confirm_execute_command(self, command: str) -> str | None:
473 | """
474 | Prompts the user to confirm and possibly edit a command before execution.
475 |
476 | Args:
477 | command (str): The command to confirm.
478 |
479 | Returns:
480 | str: The confirmed command or None if canceled.
481 | """
482 | command = command.lstrip()
483 |
484 | command = await self._get_user_input(
485 | "Validate the command and press [blue]Enter[/].\nOr delete the text and press [blue]Enter[/] to cancel",
486 | input_text=command,
487 | )
488 |
489 | return command if command else None
490 |
491 | async def _get_user_input(
492 | self,
493 | prompt_text: str = "Enter input: ",
494 | is_password: bool = False,
495 | input_text: str = "",
496 | ) -> str:
497 | """
498 | Helper function for retriving the user input, if UI is not loaded it will fallback to normal input
499 | """
500 | if self.ui is not None:
501 | return await self.ui.get_user_input(
502 | prompt_text, is_password=is_password, input_text=input_text
503 | )
504 | else:
505 | return input(prompt_text)
506 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | GNU GENERAL PUBLIC LICENSE
3 | Version 3, 29 June 2007
4 |
5 | Copyright (C) 2007 Free Software Foundation, Inc.
6 | Copyright (c) 2025 Abyss-Core
7 |
8 | Everyone is permitted to copy and distribute verbatim copies
9 | of this license document, but changing it is not allowed.
10 |
11 | Preamble
12 |
13 | The GNU General Public License is a free, copyleft license for
14 | software and other kinds of works.
15 |
16 | The licenses for most software and other practical works are designed
17 | to take away your freedom to share and change the works. By contrast,
18 | the GNU General Public License is intended to guarantee your freedom to
19 | share and change all versions of a program--to make sure it remains free
20 | software for all its users. We, the Free Software Foundation, use the
21 | GNU General Public License for most of our software; it applies also to
22 | any other work released this way by its authors. You can apply it to
23 | your programs, too.
24 |
25 | When we speak of free software, we are referring to freedom, not
26 | price. Our General Public Licenses are designed to make sure that you
27 | have the freedom to distribute copies of free software (and charge for
28 | them if you wish), that you receive source code or can get it if you
29 | want it, that you can change the software or use pieces of it in new
30 | free programs, and that you know you can do these things.
31 |
32 | To protect your rights, we need to prevent others from denying you
33 | these rights or asking you to surrender the rights. Therefore, you have
34 | certain responsibilities if you distribute copies of the software, or if
35 | you modify it: responsibilities to respect the freedom of others.
36 |
37 | For example, if you distribute copies of such a program, whether
38 | gratis or for a fee, you must pass on to the recipients the same
39 | freedoms that you received. You must make sure that they, too, receive
40 | or can get the source code. And you must show them these terms so they
41 | know their rights.
42 |
43 | Developers that use the GNU GPL protect your rights with two steps:
44 | (1) assert copyright on the software, and (2) offer you this License
45 | giving you legal permission to copy, distribute and/or modify it.
46 |
47 | For the developers' and authors' protection, the GPL clearly explains
48 | that there is no warranty for this free software. For both users' and
49 | authors' sake, the GPL requires that modified versions be marked as
50 | changed, so that their problems will not be attributed erroneously to
51 | authors of previous versions.
52 |
53 | Some devices are designed to deny users access to install or run
54 | modified versions of the software inside them, although the manufacturer
55 | can do so. This is fundamentally incompatible with the aim of
56 | protecting users' freedom to change the software. The systematic
57 | pattern of such abuse occurs in the area of products for individuals to
58 | use, which is precisely where it is most unacceptable. Therefore, we
59 | have designed this version of the GPL to prohibit the practice for those
60 | products. If such problems arise substantially in other domains, we
61 | stand ready to extend this provision to those domains in future versions
62 | of the GPL, as needed to protect the freedom of users.
63 |
64 | Finally, every program is threatened constantly by software patents.
65 | States should not allow patents to restrict development and use of
66 | software on general-purpose computers, but in those that do, we wish to
67 | avoid the special danger that patents applied to a free program could
68 | make it effectively proprietary. To prevent this, the GPL assures that
69 | patents cannot be used to render the program non-free.
70 |
71 | The precise terms and conditions for copying, distribution and
72 | modification follow.
73 |
74 | TERMS AND CONDITIONS
75 |
76 | 0. Definitions.
77 |
78 | "This License" refers to version 3 of the GNU General Public License.
79 |
80 | "Copyright" also means copyright-like laws that apply to other kinds of
81 | works, such as semiconductor masks.
82 |
83 | "The Program" refers to any copyrightable work licensed under this
84 | License. Each licensee is addressed as "you". "Licensees" and
85 | "recipients" may be individuals or organizations.
86 |
87 | To "modify" a work means to copy from or adapt all or part of the work
88 | in a fashion requiring copyright permission, other than the making of an
89 | exact copy. The resulting work is called a "modified version" of the
90 | earlier work or a work "based on" the earlier work.
91 |
92 | A "covered work" means either the unmodified Program or a work based
93 | on the Program.
94 |
95 | To "propagate" a work means to do anything with it that, without
96 | permission, would make you directly or secondarily liable for
97 | infringement under applicable copyright law, except executing it on a
98 | computer or modifying a private copy. Propagation includes copying,
99 | distribution (with or without modification), making available to the
100 | public, and in some countries other activities as well.
101 |
102 | To "convey" a work means any kind of propagation that enables other
103 | parties to make or receive copies. Mere interaction with a user through
104 | a computer network, with no transfer of a copy, is not conveying.
105 |
106 | An interactive user interface displays "Appropriate Legal Notices"
107 | to the extent that it includes a convenient and prominently visible
108 | feature that (1) displays an appropriate copyright notice, and (2)
109 | tells the user that there is no warranty for the work (except to the
110 | extent that warranties are provided), that licensees may convey the
111 | work under this License, and how to view a copy of this License. If
112 | the interface presents a list of user commands or options, such as a
113 | menu, a prominent item in the list meets this criterion.
114 |
115 | 1. Source Code.
116 |
117 | The "source code" for a work means the preferred form of the work
118 | for making modifications to it. "Object code" means any non-source
119 | form of a work.
120 |
121 | A "Standard Interface" means an interface that either is an official
122 | standard defined by a recognized standards body, or, in the case of
123 | interfaces specified for a particular programming language, one that
124 | is widely used among developers working in that language.
125 |
126 | The "System Libraries" of an executable work include anything, other
127 | than the work as a whole, that (a) is included in the normal form of
128 | packaging a Major Component, but which is not part of that Major
129 | Component, and (b) serves only to enable use of the work with that
130 | Major Component, or to implement a Standard Interface for which an
131 | implementation is available to the public in source code form. A
132 | "Major Component", in this context, means a major essential component
133 | (kernel, window system, and so on) of the specific operating system
134 | (if any) on which the executable work runs, or a compiler used to
135 | produce the work, or an object code interpreter used to run it.
136 |
137 | The "Corresponding Source" for a work in object code form means all
138 | the source code needed to generate, install, and (for an executable
139 | work) run the object code and to modify the work, including scripts to
140 | control those activities. However, it does not include the work's
141 | System Libraries, or general-purpose tools or generally available free
142 | programs which are used unmodified in performing those activities but
143 | which are not part of the work. For example, Corresponding Source
144 | includes interface definition files associated with source files for
145 | the work, and the source code for shared libraries and dynamically
146 | linked subprograms that the work is specifically designed to require,
147 | such as by intimate data communication or control flow between those
148 | subprograms and other parts of the work.
149 |
150 | The Corresponding Source need not include anything that users
151 | can regenerate automatically from other parts of the Corresponding
152 | Source.
153 |
154 | The Corresponding Source for a work in source code form is that
155 | same work.
156 |
157 | 2. Basic Permissions.
158 |
159 | All rights granted under this License are granted for the term of
160 | copyright on the Program, and are irrevocable provided the stated
161 | conditions are met. This License explicitly affirms your unlimited
162 | permission to run the unmodified Program. The output from running a
163 | covered work is covered by this License only if the output, given its
164 | content, constitutes a covered work. This License acknowledges your
165 | rights of fair use or other equivalent, as provided by copyright law.
166 |
167 | You may make, run and propagate covered works that you do not
168 | convey, without conditions so long as your license otherwise remains
169 | in force. You may convey covered works to others for the sole purpose
170 | of having them make modifications exclusively for you, or provide you
171 | with facilities for running those works, provided that you comply with
172 | the terms of this License in conveying all material for which you do
173 | not control copyright. Those thus making or running the covered works
174 | for you must do so exclusively on your behalf, under your direction
175 | and control, on terms that prohibit them from making any copies of
176 | your copyrighted material outside their relationship with you.
177 |
178 | Conveying under any other circumstances is permitted solely under
179 | the conditions stated below. Sublicensing is not allowed; section 10
180 | makes it unnecessary.
181 |
182 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
183 |
184 | No covered work shall be deemed part of an effective technological
185 | measure under any applicable law fulfilling obligations under article
186 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
187 | similar laws prohibiting or restricting circumvention of such
188 | measures.
189 |
190 | When you convey a covered work, you waive any legal power to forbid
191 | circumvention of technological measures to the extent such circumvention
192 | is effected by exercising rights under this License with respect to
193 | the covered work, and you disclaim any intention to limit operation or
194 | modification of the work as a means of enforcing, against the work's
195 | users, your or third parties' legal rights to forbid circumvention of
196 | technological measures.
197 |
198 | 4. Conveying Verbatim Copies.
199 |
200 | You may convey verbatim copies of the Program's source code as you
201 | receive it, in any medium, provided that you conspicuously and
202 | appropriately publish on each copy an appropriate copyright notice;
203 | keep intact all notices stating that this License and any
204 | non-permissive terms added in accord with section 7 apply to the code;
205 | keep intact all notices of the absence of any warranty; and give all
206 | recipients a copy of this License along with the Program.
207 |
208 | You may charge any price or no price for each copy that you convey,
209 | and you may offer support or warranty protection for a fee.
210 |
211 | 5. Conveying Modified Source Versions.
212 |
213 | You may convey a work based on the Program, or the modifications to
214 | produce it from the Program, in the form of source code under the
215 | terms of section 4, provided that you also meet all of these conditions:
216 |
217 | a) The work must carry prominent notices stating that you modified
218 | it, and giving a relevant date.
219 |
220 | b) The work must carry prominent notices stating that it is
221 | released under this License and any conditions added under section
222 | 7. This requirement modifies the requirement in section 4 to
223 | "keep intact all notices".
224 |
225 | c) You must license the entire work, as a whole, under this
226 | License to anyone who comes into possession of a copy. This
227 | License will therefore apply, along with any applicable section 7
228 | additional terms, to the whole of the work, and all its parts,
229 | regardless of how they are packaged. This License gives no
230 | permission to license the work in any other way, but it does not
231 | invalidate such permission if you have separately received it.
232 |
233 | d) If the work has interactive user interfaces, each must display
234 | Appropriate Legal Notices; however, if the Program has interactive
235 | interfaces that do not display Appropriate Legal Notices, your
236 | work need not make them do so.
237 |
238 | A compilation of a covered work with other separate and independent
239 | works, which are not by their nature extensions of the covered work,
240 | and which are not combined with it such as to form a larger program,
241 | in or on a volume of a storage or distribution medium, is called an
242 | "aggregate" if the compilation and its resulting copyright are not
243 | used to limit the access or legal rights of the compilation's users
244 | beyond what the individual works permit. Inclusion of a covered work
245 | in an aggregate does not cause this License to apply to the other
246 | parts of the aggregate.
247 |
248 | 6. Conveying Non-Source Forms.
249 |
250 | You may convey a covered work in object code form under the terms
251 | of sections 4 and 5, provided that you also convey the
252 | machine-readable Corresponding Source under the terms of this License,
253 | in one of these ways:
254 |
255 | a) Convey the object code in, or embodied in, a physical product
256 | (including a physical distribution medium), accompanied by the
257 | Corresponding Source fixed on a durable physical medium
258 | customarily used for software interchange.
259 |
260 | b) Convey the object code in, or embodied in, a physical product
261 | (including a physical distribution medium), accompanied by a
262 | written offer, valid for at least three years and valid for as
263 | long as you offer spare parts or customer support for that product
264 | model, to give anyone who possesses the object code either (1) a
265 | copy of the Corresponding Source for all the software in the
266 | product that is covered by this License, on a durable physical
267 | medium customarily used for software interchange, for a price no
268 | more than your reasonable cost of physically performing this
269 | conveying of source, or (2) access to copy the
270 | Corresponding Source from a network server at no charge.
271 |
272 | c) Convey individual copies of the object code with a copy of the
273 | written offer to provide the Corresponding Source. This
274 | alternative is allowed only occasionally and noncommercially, and
275 | only if you received the object code with such an offer, in accord
276 | with subsection 6b.
277 |
278 | d) Convey the object code by offering access from a designated
279 | place (gratis or for a charge), and offer equivalent access to the
280 | Corresponding Source in the same way through the same place at no
281 | further charge. You need not require recipients to copy the
282 | Corresponding Source along with the object code. If the place to
283 | copy the object code is a network server, the Corresponding Source
284 | may be on a different server (operated by you or a third party)
285 | that supports equivalent copying facilities, provided you maintain
286 | clear directions next to the object code saying where to find the
287 | Corresponding Source. Regardless of what server hosts the
288 | Corresponding Source, you remain obligated to ensure that it is
289 | available for as long as needed to satisfy these requirements.
290 |
291 | e) Convey the object code using peer-to-peer transmission, provided
292 | you inform other peers where the object code and Corresponding
293 | Source of the work are being offered to the general public at no
294 | charge under subsection 6d.
295 |
296 | A separable portion of the object code, whose source code is excluded
297 | from the Corresponding Source as a System Library, need not be
298 | included in conveying the object code work.
299 |
300 | A "User Product" is either (1) a "consumer product", which means any
301 | tangible personal property which is normally used for personal, family,
302 | or household purposes, or (2) anything designed or sold for incorporation
303 | into a dwelling. In determining whether a product is a consumer product,
304 | doubtful cases shall be resolved in favor of coverage. For a particular
305 | product received by a particular user, "normally used" refers to a
306 | typical or common use of that class of product, regardless of the status
307 | of the particular user or of the way in which the particular user
308 | actually uses, or expects or is expected to use, the product. A product
309 | is a consumer product regardless of whether the product has substantial
310 | commercial, industrial or non-consumer uses, unless such uses represent
311 | the only significant mode of use of the product.
312 |
313 | "Installation Information" for a User Product means any methods,
314 | procedures, authorization keys, or other information required to install
315 | and execute modified versions of a covered work in that User Product from
316 | a modified version of its Corresponding Source. The information must
317 | suffice to ensure that the continued functioning of the modified object
318 | code is in no case prevented or interfered with solely because
319 | modification has been made.
320 |
321 | If you convey an object code work under this section in, or with, or
322 | specifically for use in, a User Product, and the conveying occurs as
323 | part of a transaction in which the right of possession and use of the
324 | User Product is transferred to the recipient in perpetuity or for a
325 | fixed term (regardless of how the transaction is characterized), the
326 | Corresponding Source conveyed under this section must be accompanied
327 | by the Installation Information. But this requirement does not apply
328 | if neither you nor any third party retains the ability to install
329 | modified object code on the User Product (for example, the work has
330 | been installed in ROM).
331 |
332 | The requirement to provide Installation Information does not include a
333 | requirement to continue to provide support service, warranty, or updates
334 | for a work that has been modified or installed by the recipient, or for
335 | the User Product in which it has been modified or installed. Access to a
336 | network may be denied when the modification itself materially and
337 | adversely affects the operation of the network or violates the rules and
338 | protocols for communication across the network.
339 |
340 | Corresponding Source conveyed, and Installation Information provided,
341 | in accord with this section must be in a format that is publicly
342 | documented (and with an implementation available to the public in
343 | source code form), and must require no special password or key for
344 | unpacking, reading or copying.
345 |
346 | 7. Additional Terms.
347 |
348 | "Additional permissions" are terms that supplement the terms of this
349 | License by making exceptions from one or more of its conditions.
350 | Additional permissions that are applicable to the entire Program shall
351 | be treated as though they were included in this License, to the extent
352 | that they are valid under applicable law. If additional permissions
353 | apply only to part of the Program, that part may be used separately
354 | under those permissions, but the entire Program remains governed by
355 | this License without regard to the additional permissions.
356 |
357 | When you convey a copy of a covered work, you may at your option
358 | remove any additional permissions from that copy, or from any part of
359 | it. (Additional permissions may be written to require their own
360 | removal in certain cases when you modify the work.) You may place
361 | additional permissions on material, added by you to a covered work,
362 | for which you have or can give appropriate copyright permission.
363 |
364 | Notwithstanding any other provision of this License, for material you
365 | add to a covered work, you may (if authorized by the copyright holders of
366 | that material) supplement the terms of this License with terms:
367 |
368 | a) Disclaiming warranty or limiting liability differently from the
369 | terms of sections 15 and 16 of this License; or
370 |
371 | b) Requiring preservation of specified reasonable legal notices or
372 | author attributions in that material or in the Appropriate Legal
373 | Notices displayed by works containing it; or
374 |
375 | c) Prohibiting misrepresentation of the origin of that material, or
376 | requiring that modified versions of such material be marked in
377 | reasonable ways as different from the original version; or
378 |
379 | d) Limiting the use for publicity purposes of names of licensors or
380 | authors of the material; or
381 |
382 | e) Declining to grant rights under trademark law for use of some
383 | trade names, trademarks, or service marks; or
384 |
385 | f) Requiring indemnification of licensors and authors of that
386 | material by anyone who conveys the material (or modified versions of
387 | it) with contractual assumptions of liability to the recipient, for
388 | any liability that these contractual assumptions directly impose on
389 | those licensors and authors.
390 |
391 | All other non-permissive additional terms are considered "further
392 | restrictions" within the meaning of section 10. If the Program as you
393 | received it, or any part of it, contains a notice stating that it is
394 | governed by this License along with a term that is a further
395 | restriction, you may remove that term. If a license document contains
396 | a further restriction but permits relicensing or conveying under this
397 | License, you may add to a covered work material governed by the terms
398 | of that license document, provided that the further restriction does
399 | not survive such relicensing or conveying.
400 |
401 | If you add terms to a covered work in accord with this section, you
402 | must place, in the relevant source files, a statement of the
403 | additional terms that apply to those files, or a notice indicating
404 | where to find the applicable terms.
405 |
406 | Additional terms, permissive or non-permissive, may be stated in the
407 | form of a separately written license, or stated as exceptions;
408 | the above requirements apply either way.
409 |
410 | 8. Termination.
411 |
412 | You may not propagate or modify a covered work except as expressly
413 | provided under this License. Any attempt otherwise to propagate or
414 | modify it is void, and will automatically terminate your rights under
415 | this License (including any patent licenses granted under the third
416 | paragraph of section 11).
417 |
418 | However, if you cease all violation of this License, then your
419 | license from a particular copyright holder is reinstated (a)
420 | provisionally, unless and until the copyright holder explicitly and
421 | finally terminates your license, and (b) permanently, if the copyright
422 | holder fails to notify you of the violation by some reasonable means
423 | prior to 60 days after the cessation.
424 |
425 | Moreover, your license from a particular copyright holder is
426 | reinstated permanently if the copyright holder notifies you of the
427 | violation by some reasonable means, this is the first time you have
428 | received notice of violation of this License (for any work) from that
429 | copyright holder, and you cure the violation prior to 30 days after
430 | your receipt of the notice.
431 |
432 | Termination of your rights under this section does not terminate the
433 | licenses of parties who have received copies or rights from you under
434 | this License. If your rights have been terminated and not permanently
435 | reinstated, you do not qualify to receive new licenses for the same
436 | material under section 10.
437 |
438 | 9. Acceptance Not Required for Having Copies.
439 |
440 | You are not required to accept this License in order to receive or
441 | run a copy of the Program. Ancillary propagation of a covered work
442 | occurring solely as a consequence of using peer-to-peer transmission
443 | to receive a copy likewise does not require acceptance. However,
444 | nothing other than this License grants you permission to propagate or
445 | modify any covered work. These actions infringe copyright if you do
446 | not accept this License. Therefore, by modifying or propagating a
447 | covered work, you indicate your acceptance of this License to do so.
448 |
449 | 10. Automatic Licensing of Downstream Recipients.
450 |
451 | Each time you convey a covered work, the recipient automatically
452 | receives a license from the original licensors, to run, modify and
453 | propagate that work, subject to this License. You are not responsible
454 | for enforcing compliance by third parties with this License.
455 |
456 | An "entity transaction" is a transaction transferring control of an
457 | organization, or substantially all assets of one, or subdividing an
458 | organization, or merging organizations. If propagation of a covered
459 | work results from an entity transaction, each party to that
460 | transaction who receives a copy of the work also receives whatever
461 | licenses to the work the party's predecessor in interest had or could
462 | give under the previous paragraph, plus a right to possession of the
463 | Corresponding Source of the work from the predecessor in interest, if
464 | the predecessor has it or can get it with reasonable efforts.
465 |
466 | You may not impose any further restrictions on the exercise of the
467 | rights granted or affirmed under this License. For example, you may
468 | not impose a license fee, royalty, or other charge for exercise of
469 | rights granted under this License, and you may not initiate litigation
470 | (including a cross-claim or counterclaim in a lawsuit) alleging that
471 | any patent claim is infringed by making, using, selling, offering for
472 | sale, or importing the Program or any portion of it.
473 |
474 | 11. Patents.
475 |
476 | A "contributor" is a copyright holder who authorizes use under this
477 | License of the Program or a work on which the Program is based. The
478 | work thus licensed is called the contributor's "contributor version".
479 |
480 | A contributor's "essential patent claims" are all patent claims
481 | owned or controlled by the contributor, whether already acquired or
482 | hereafter acquired, that would be infringed by some manner, permitted
483 | by this License, of making, using, or selling its contributor version,
484 | but do not include claims that would be infringed only as a
485 | consequence of further modification of the contributor version. For
486 | purposes of this definition, "control" includes the right to grant
487 | patent sublicenses in a manner consistent with the requirements of
488 | this License.
489 |
490 | Each contributor grants you a non-exclusive, worldwide, royalty-free
491 | patent license under the contributor's essential patent claims, to
492 | make, use, sell, offer for sale, import and otherwise run, modify and
493 | propagate the contents of its contributor version.
494 |
495 | In the following three paragraphs, a "patent license" is any express
496 | agreement or commitment, however denominated, not to enforce a patent
497 | (such as an express permission to practice a patent or covenant not to
498 | sue for patent infringement). To "grant" such a patent license to a
499 | party means to make such an agreement or commitment not to enforce a
500 | patent against the party.
501 |
502 | If you convey a covered work, knowingly relying on a patent license,
503 | and the Corresponding Source of the work is not available for anyone
504 | to copy, free of charge and under the terms of this License, through a
505 | publicly available network server or other readily accessible means,
506 | then you must either (1) cause the Corresponding Source to be so
507 | available, or (2) arrange to deprive yourself of the benefit of the
508 | patent license for this particular work, or (3) arrange, in a manner
509 | consistent with the requirements of this License, to extend the patent
510 | license to downstream recipients. "Knowingly relying" means you have
511 | actual knowledge that, but for the patent license, your conveying the
512 | covered work in a country, or your recipient's use of the covered work
513 | in a country, would infringe one or more identifiable patents in that
514 | country that you have reason to believe are valid.
515 |
516 | If, pursuant to or in connection with a single transaction or
517 | arrangement, you convey, or propagate by procuring conveyance of, a
518 | covered work, and grant a patent license to some of the parties
519 | receiving the covered work authorizing them to use, propagate, modify
520 | or convey a specific copy of the covered work, then the patent license
521 | you grant is automatically extended to all recipients of the covered
522 | work and works based on it.
523 |
524 | A patent license is "discriminatory" if it does not include within
525 | the scope of its coverage, prohibits the exercise of, or is
526 | conditioned on the non-exercise of one or more of the rights that are
527 | specifically granted under this License. You may not convey a covered
528 | work if you are a party to an arrangement with a third party that is
529 | in the business of distributing software, under which you make payment
530 | to the third party based on the extent of your activity of conveying
531 | the work, and under which the third party grants, to any of the
532 | parties who would receive the covered work from you, a discriminatory
533 | patent license (a) in connection with copies of the covered work
534 | conveyed by you (or copies made from those copies), or (b) primarily
535 | for and in connection with specific products or compilations that
536 | contain the covered work, unless you entered into that arrangement,
537 | or that patent license was granted, prior to 28 March 2007.
538 |
539 | Nothing in this License shall be construed as excluding or limiting
540 | any implied license or other defenses to infringement that may
541 | otherwise be available to you under applicable patent law.
542 |
543 | 12. No Surrender of Others' Freedom.
544 |
545 | If conditions are imposed on you (whether by court order, agreement or
546 | otherwise) that contradict the conditions of this License, they do not
547 | excuse you from the conditions of this License. If you cannot convey a
548 | covered work so as to satisfy simultaneously your obligations under this
549 | License and any other pertinent obligations, then as a consequence you may
550 | not convey it at all. For example, if you agree to terms that obligate you
551 | to collect a royalty for further conveying from those to whom you convey
552 | the Program, the only way you could satisfy both those terms and this
553 | License would be to refrain entirely from conveying the Program.
554 |
555 | 13. Use with the GNU Affero General Public License.
556 |
557 | Notwithstanding any other provision of this License, you have
558 | permission to link or combine any covered work with a work licensed
559 | under version 3 of the GNU Affero General Public License into a single
560 | combined work, and to convey the resulting work. The terms of this
561 | License will continue to apply to the part which is the covered work,
562 | but the special requirements of the GNU Affero General Public License,
563 | section 13, concerning interaction through a network will apply to the
564 | combination as such.
565 |
566 | 14. Revised Versions of this License.
567 |
568 | The Free Software Foundation may publish revised and/or new versions of
569 | the GNU General Public License from time to time. Such new versions will
570 | be similar in spirit to the present version, but may differ in detail to
571 | address new problems or concerns.
572 |
573 | Each version is given a distinguishing version number. If the
574 | Program specifies that a certain numbered version of the GNU General
575 | Public License "or any later version" applies to it, you have the
576 | option of following the terms and conditions either of that numbered
577 | version or of any later version published by the Free Software
578 | Foundation. If the Program does not specify a version number of the
579 | GNU General Public License, you may choose any version ever published
580 | by the Free Software Foundation.
581 |
582 | If the Program specifies that a proxy can decide which future
583 | versions of the GNU General Public License can be used, that proxy's
584 | public statement of acceptance of a version permanently authorizes you
585 | to choose that version for the Program.
586 |
587 | Later license versions may give you additional or different
588 | permissions. However, no additional obligations are imposed on any
589 | author or copyright holder as a result of your choosing to follow a
590 | later version.
591 |
592 | 15. Disclaimer of Warranty.
593 |
594 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
595 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
596 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
597 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
598 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
599 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
600 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
601 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
602 |
603 | 16. Limitation of Liability.
604 |
605 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
606 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
607 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
608 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
609 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
610 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
611 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
612 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
613 | SUCH DAMAGES.
614 |
615 | 17. Interpretation of Sections 15 and 16.
616 |
617 | If the disclaimer of warranty and limitation of liability provided
618 | above cannot be given local legal effect according to their terms,
619 | reviewing courts shall apply local law that most closely approximates
620 | an absolute waiver of all civil liability in connection with the
621 | Program, unless a warranty or assumption of liability accompanies a
622 | copy of the Program in return for a fee.
623 |
624 |
625 |
--------------------------------------------------------------------------------
/chatbot/history.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 | import asyncio
4 | import numpy as np
5 | from datetime import datetime
6 | from utils.logger import Logger
7 | from typing import Tuple, Optional
8 | from chatbot.helper import PromptHelper
9 | from utils.file_utils import _read_file
10 | from ollama_client.api_client import OllamaClient
11 | from sklearn.metrics.pairwise import cosine_similarity
12 | from config.settings import OFF_THR, MSG_THR, CONT_THR, NUM_MSG, OFF_FREQ, SLICE_SIZE
13 |
14 | logger = Logger.get_logger()
15 |
16 |
17 | class Project:
18 | def __init__(self, name: str = "") -> None:
19 | self.name: str = name
20 | self.file_embeddings: dict[str, dict] = {}
21 | self.folder_structure: dict = {}
22 |
23 | def _index_content(
24 | self,
25 | identifier: str,
26 | content: str,
27 | embedding: np.ndarray,
28 | content_type: str = "file",
29 | ) -> None:
30 | """
31 | Generic method to index any content (files or terminal outputs).
32 |
33 | Args:
34 | identifier (str): Unique identifier (e.g., file path or generated key).
35 | content (str): The content to index.
36 | embedding (np.ndarray): The computed embedding.
37 | content_type (str): Type of the content ("file" or "terminal").
38 | """
39 | content_info = {
40 | "identifier": identifier,
41 | "content": content,
42 | "embedding": embedding,
43 | "type": content_type,
44 | }
45 | self.file_embeddings[identifier] = content_info
46 | logger.debug(
47 | f"Project '{self.name}': Added {content_type} content with id {identifier}"
48 | )
49 |
50 | def _index_file(self, file_path: str, content: str, embedding: np.ndarray) -> None:
51 | """
52 | Indexes a file's embedding, wrapping the file path as the unique identifier.
53 | """
54 | self._index_content(file_path, content, embedding, content_type="file")
55 |
56 | def _index_terminal_output(
57 | self, output: str, identifier: str, embedding: np.ndarray
58 | ) -> None:
59 | """
60 | Indexes terminal code blocks or output, generating a unique identifier if not provided.
61 | """
62 | if not identifier:
63 | # Generate a unique identifier, e.g., using a timestamp.
64 | identifier = f"terminal_{datetime.now().isoformat()}"
65 | self._index_content(identifier, output, embedding, content_type="terminal")
66 |
67 |
68 | class Topic:
69 | def __init__(self, name: str = "", description: str = "") -> None:
70 | """
71 | Initializes a Topic with a name and description.
72 | The description is embedded and cached for matching.
73 |
74 | Args:
75 | name (str): The topic name.
76 | description (str): A textual description of the topic.
77 | """
78 | self.name = name
79 | self.description = description
80 | self.embedded_description = np.array([])
81 | self.history: list[dict[str, str]] = []
82 | self.history_embeddings = []
83 | self.embedding_cache: dict[str, np.ndarray] = {}
84 |
85 | async def add_message(self, role: str, message: str, embedding: np.ndarray) -> None:
86 | """
87 | Stores raw messages and their embeddings.
88 | """
89 | self.history.append({"role": role, "content": message})
90 | self.history_embeddings.append(embedding)
91 | logger.info(f"Message added to: {self.name}")
92 |
93 | async def get_relevant_context(self, embedding: np.ndarray) -> tuple[float, int]:
94 | """
95 | Retrieves the best similarity score and the index of the most relevant message
96 | from the topic’s history based on cosine similarity.
97 |
98 | Args:
99 | query_embedding.
100 | similarity_threshold (float): The base similarity threshold.
101 |
102 | Returns:
103 | tuple[float, int]: A tuple containing:
104 | - The best similarity score.
105 | - The index of the best matching message (or -1 if not found).
106 | """
107 | if not self.history_embeddings:
108 | logger.info("No history embeddings found. Returning empty context.")
109 | return 0.0, -1
110 |
111 | similarities = cosine_similarity([embedding], self.history_embeddings)[0]
112 | best_index = int(np.argmax(similarities))
113 | best_similarity = float(similarities[best_index])
114 | logger.debug(f"Best similarity score: {best_similarity} at index {best_index}")
115 |
116 | return best_similarity, best_index
117 |
118 |
119 | class HistoryManager:
120 | def __init__(self, manager) -> None:
121 | """
122 | Initializes HistoryManager to handle topics and off-topic tracking.
123 | An "unsorted" topic collects messages and files until a clear topic emerges.
124 |
125 | Args:
126 | top_k (int): Maximum number of context items to retrieve.
127 | similarity_threshold (float): Threshold for determining similarity.
128 | """
129 | self.file_utils = manager.file_utils
130 | self.helper = manager._handle_helper_mode
131 | self.tasker = manager.deploy_chatbot_method
132 | self.ui = manager.ui
133 | self.similarity_threshold = MSG_THR
134 | self.topics: list[Topic] = []
135 | self.current_topic = Topic("Initial topic")
136 | self.embedding_cache: dict[str, np.ndarray] = {}
137 | self.projects: list[Project] = []
138 | self.current_project = Project("Unsorted")
139 |
140 | async def add_message(
141 | self, role: str, message: str, embedding: np.ndarray | None = None
142 | ) -> None:
143 | """
144 | Routes a new message to the best-matching topic.
145 | If no topic meets the similarity threshold, the message is added to the unsorted topic.
146 |
147 | Args:
148 | role (str): Sender's role.
149 | message (str): The message text.
150 | """
151 | if not embedding:
152 | embedding = await self.fetch_embedding(message)
153 | topic = await self._match_topic(embedding, exclude_topic=self.current_topic)
154 | if topic:
155 | await self.switch_topic(topic)
156 |
157 | await self.current_topic.add_message(role, message, embedding)
158 | asyncio.create_task(self._analyze_history())
159 |
160 | async def add_file(
161 | self, file_path: str, content: str, folder: bool = False
162 | ) -> None:
163 | """
164 | Adds a file by computing its combined embedding (file path + content)
165 | and routing it to the appropriate project based on the file's folder.
166 | If the file's project folder (extracted from the file path) is different
167 | from the current project's name, the current project is archived and a new
168 | project is created and assigned.
169 | """
170 | new_project_name = os.path.basename(os.path.dirname(file_path))
171 |
172 | if self.current_project.name.lower() != new_project_name.lower():
173 | if (
174 | self.current_project.name.lower() != "unsorted"
175 | and self.current_project not in self.projects
176 | ):
177 | self.projects.append(self.current_project)
178 | logger.info(
179 | f"Archived project '{self.current_project.name}' to projects list."
180 | )
181 |
182 | if not self.current_project.folder_structure and not folder:
183 | if await self.ui.yes_no_prompt(
184 | "Do you want to generate structure for this file's folder?", "No"
185 | ):
186 | new_project = Project(new_project_name)
187 | try:
188 | folder_path = os.path.dirname(file_path)
189 | structure = self.file_utils.generate_structure(
190 | folder_path, folder_path
191 | )
192 | new_project.folder_structure = structure
193 | logger.info(
194 | f"Generated new folder structure for project '{new_project_name}'."
195 | )
196 | except Exception as e:
197 | logger.error(
198 | f"Failed to generate structure for project '{new_project_name}': {e}"
199 | )
200 |
201 | self.current_project = new_project
202 |
203 | # Compute embedding for file path + content
204 | combined_content = f"Path: {file_path}\nContent: {content}"
205 | file_embedding = await self.fetch_embedding(combined_content)
206 |
207 | # Store the file in the project using a universal indexing method
208 | self.current_project._index_content(
209 | file_path, content, file_embedding, content_type="file"
210 | )
211 |
212 | async def add_terminal_output(
213 | self, command: str, output: str, summary: str
214 | ) -> None:
215 | """
216 | Adds a terminal output by computing its embedding and indexing it
217 | within the current project.
218 |
219 | Args:
220 | command (str): The executed command.
221 | output (str): The raw output of the command.
222 | summary (str): A summarized explanation of the output.
223 | """
224 | terminal_content = f"Command: {command}\nOutput: {output}\nSummary: {summary}"
225 | terminal_embedding = await self.fetch_embedding(terminal_content)
226 |
227 | # Generate a unique identifier for terminal output storage
228 | terminal_id = f"terminal_{hash(command + datetime.now().isoformat())}"
229 |
230 | # Store the terminal output using the unified indexing method
231 | self.current_project._index_content(
232 | terminal_id, terminal_content, terminal_embedding, content_type="terminal"
233 | )
234 |
235 | logger.info(f"Stored terminal output for command: {command}")
236 |
237 | def add_folder_structure(self, structure: dict) -> None:
238 | """
239 | Adds or updates folder structure for the current project.
240 | If a structure already exists, archives the current project by adding it
241 | to the projects list (if not already present) before updating.
242 | Also, if the current project's name is empty or 'Unsorted', assigns the new folder name.
243 | """
244 | if self.current_project.folder_structure:
245 | if self.current_project not in self.projects:
246 | self.projects.append(self.current_project)
247 | logger.info(
248 | f"Archived project '{self.current_project.name}' to projects list."
249 | )
250 |
251 | if (
252 | not self.current_project.name
253 | or self.current_project.name.lower() == "unsorted"
254 | ):
255 | if isinstance(structure, dict) and len(structure) == 1:
256 | new_name = list(structure.keys())[0]
257 | self.current_project.name = new_name
258 | logger.info(
259 | f"Assigned new project name '{new_name}' from folder structure."
260 | )
261 |
262 | self.current_project.folder_structure = structure
263 | logger.info(
264 | f"Folder structure updated for project '{self.current_project.name}'."
265 | )
266 |
267 | def format_structure(self, folder_structure: dict) -> str:
268 | """
269 | Formats the folder structure dictionary into a readable string format.
270 | """
271 |
272 | def format_substructure(substructure, indent=0):
273 | formatted = ""
274 | for key, value in substructure.items():
275 | if isinstance(value, dict): # Subfolder
276 | formatted += " " * indent + f"{key}/\n"
277 | formatted += format_substructure(value, indent + 4)
278 | else:
279 | formatted += " " * indent + f"-- {value}\n"
280 | return formatted
281 |
282 | return format_substructure(folder_structure)
283 |
284 | def find_project_structure(self, query: str) -> Project | None:
285 | """
286 | Checks if the query contains a folder name corresponding to one of the existing projects.
287 | Returns the matching Project if found.
288 | """
289 | for project in self.projects:
290 | if project.name.lower() in query.lower():
291 | logger.info(f"Found project structure for '{project.name}' in query")
292 | return project
293 | logger.info("No matching project found in query")
294 | return None
295 |
296 | def extract_file_name_from_query(self, query: str) -> str | None:
297 | file_pattern = r"([a-zA-Z0-9_\-]+(?:/[a-zA-Z0-9_\-]+)*/[a-zA-Z0-9_\-]+\.[a-zA-Z0-9]+|[a-zA-Z0-9_\-]+\.[a-zA-Z0-9]+)"
298 | match = re.search(file_pattern, query)
299 | if match:
300 | return match.group(0)
301 | return None
302 |
303 | def extract_folder_from_query(self, query: str) -> str | None:
304 | """
305 | Extracts a folder path from the query.
306 | This regex looks for paths containing at least one slash and that do not end with an extension.
307 | """
308 | folder_pattern = r"([a-zA-Z0-9_\-]+(?:/[a-zA-Z0-9_\-]+)+)"
309 | match = re.search(folder_pattern, query)
310 | if match:
311 | candidate = match.group(0)
312 | if not re.search(r"\.[a-zA-Z0-9]+$", candidate):
313 | return candidate
314 | return None
315 |
316 | async def get_relevant_content(
317 | self,
318 | query: str,
319 | content_type: Optional[str] = None,
320 | top_k: int = 1,
321 | similarity_threshold: float = CONT_THR,
322 | ) -> list | None:
323 | """
324 | Retrieves relevant content (files or terminal outputs) by comparing the query
325 | against the stored embeddings.
326 |
327 | Args:
328 | query (str): The user query.
329 | content_type (str, optional): Type of content to filter by (e.g., "file" or "terminal").
330 | top_k (int): Maximum number of results.
331 | similarity_threshold (float): Minimum similarity score to consider.
332 |
333 | Returns:
334 | list: A list of tuples (identifier, content) for the top matching entries.
335 | """
336 | query_embedding = await self.fetch_embedding(query)
337 | scores = []
338 |
339 | # Optionally extract a file name only if querying for files.
340 | file_name = (
341 | self.extract_file_name_from_query(query)
342 | if content_type in (None, "file")
343 | else None
344 | )
345 |
346 | # Iterate over all stored content
347 | for identifier, info in self.current_project.file_embeddings.items():
348 | # Filter by type if specified
349 | if content_type and info.get("type") != content_type:
350 | continue
351 |
352 | # If querying a file, try an exact match on identifier if available.
353 | if file_name and info.get("type") == "file":
354 | if file_name.lower() in info.get("identifier", "").lower():
355 | scores.append((identifier, 1.0))
356 | logger.info(
357 | f"Added file '{identifier}' to context (Exact match on file name)."
358 | )
359 | continue
360 |
361 | similarity = cosine_similarity([query_embedding], [info["embedding"]])[0][0]
362 | if similarity >= similarity_threshold:
363 | scores.append((identifier, similarity))
364 | logger.info(
365 | f"Added file '{identifier}' to context (Similarity: {similarity})."
366 | )
367 |
368 | # Expand search to other projects if necessary (similar to your current logic)
369 | if not scores:
370 | logger.info(
371 | "No relevant content in the current project; searching across all projects."
372 | )
373 | for project in self.projects:
374 | for identifier, info in project.file_embeddings.items():
375 | if content_type and info.get("type") != content_type:
376 | continue
377 | similarity = cosine_similarity(
378 | [query_embedding], [info["embedding"]]
379 | )[0][0]
380 | if similarity >= similarity_threshold:
381 | scores.append((identifier, similarity))
382 | logger.info(
383 | f"Added file '{identifier}' from project '{project.name}' to context (Similarity: {similarity})."
384 | )
385 |
386 | if scores:
387 | scores.sort(key=lambda x: x[1], reverse=True)
388 | selected_ids = [id for id, _ in scores[:top_k]]
389 | results = []
390 | for id in selected_ids:
391 | # Try to retrieve the content from the current project first.
392 | if (
393 | id in self.current_project.file_embeddings
394 | and "content" in self.current_project.file_embeddings[id]
395 | ):
396 | results.append(
397 | (id, self.current_project.file_embeddings[id]["content"])
398 | )
399 | logger.info(f"Added content from file '{id}' to results.")
400 | else:
401 | content = await _read_file(id)
402 | results.append((id, content))
403 | logger.info(
404 | f"Added content from file '{id}' to results (Read from file path)."
405 | )
406 | return results
407 |
408 | logger.info("No matching content found.")
409 | return None
410 |
411 | async def fetch_embedding(self, text: str) -> np.ndarray:
412 | """
413 | Asynchronously fetches and caches an embedding for the given text.
414 | Uses async lock to guard the caching mechanism.
415 | """
416 | async with asyncio.Lock():
417 | if text in self.embedding_cache:
418 | return self.embedding_cache[text]
419 |
420 | embedding = await self.tasker(OllamaClient.fetch_embedding, text)
421 | if embedding:
422 | self.embedding_cache[text] = embedding
423 | logger.debug(f"Extracted {len(embedding)} embeddings")
424 | return embedding
425 | else:
426 | return np.array([])
427 |
428 | async def switch_topic(self, topic: Topic) -> None:
429 | async with asyncio.Lock():
430 | if topic.name != self.current_topic.name:
431 | if not any(t.name == self.current_topic.name for t in self.topics):
432 | self.topics.append(self.current_topic)
433 | logger.info(f"Switched to {topic.name}")
434 | self.current_topic = topic
435 |
436 | async def _match_topic(
437 | self, embedding: np.ndarray, exclude_topic: Topic | None = None
438 | ) -> Topic | None:
439 | """
440 | Matches a message or file embedding to the most similar topic based on the description embedding,
441 | optionally excluding a specified topic.
442 |
443 | Args:
444 | embedding (np.ndarray): The embedding to match.
445 | exclude_topic (Topic | None): A topic to exclude from matching (e.g. the current topic).
446 |
447 | Returns:
448 | Topic | None: The best matching topic if similarity exceeds the threshold.
449 | """
450 | if len(self.topics) == 0:
451 | logger.info("No topics available for matching. Returning None.")
452 | return None
453 |
454 | async def compute_similarity(topic: Topic) -> tuple[float, Topic]:
455 | if len(topic.embedded_description) == 0 or len(embedding) == 0:
456 | return 0.0, topic
457 | similarity = cosine_similarity([embedding], [topic.embedded_description])[
458 | 0
459 | ][0]
460 | logger.debug(
461 | f"Computed similarity {similarity:.4f} for topic '{topic.name}'"
462 | )
463 | return similarity, topic
464 |
465 | tasks = [
466 | compute_similarity(topic) for topic in self.topics if topic != exclude_topic
467 | ]
468 | results = await asyncio.gather(*tasks)
469 |
470 | best_topic = None
471 | best_similarity = 0.0
472 | for similarity, topic in results:
473 | if similarity > best_similarity and similarity >= self.similarity_threshold:
474 | best_similarity = similarity
475 | best_topic = topic
476 |
477 | if best_topic:
478 | logger.info(
479 | f"Best matching topic: '{best_topic.name}' with similarity {best_similarity:.4f}"
480 | )
481 | return best_topic
482 | else:
483 | logger.info("No suitable topic found.")
484 | return None
485 |
486 | async def generate_prompt(self, query: str, num_messages: int = NUM_MSG) -> list:
487 | """
488 | Generates a prompt by retrieving context and content references (files, terminal outputs, etc.)
489 | from the best matching topic. If the query references a folder, the corresponding folder structure
490 | is retrieved and assigned to the current topic before being included in the prompt.
491 |
492 | Args:
493 | query (str): The user query.
494 |
495 | Returns:
496 | list: The last few messages from the topic's history.
497 | """
498 | embedding = await self.fetch_embedding(query)
499 |
500 | # Determine the best matching topic and switch to it if found.
501 | current_topic = await self._match_topic(embedding)
502 | if current_topic:
503 | await self.switch_topic(current_topic)
504 |
505 | # Retrieve the project folder structure if the query contains a folder name/path.
506 | project = self.find_project_structure(query)
507 | if project:
508 | self.current_project = project
509 |
510 | # Retrieve all types of content unless a filter is specified.
511 | relevant_content = await self.get_relevant_content(query)
512 | content_references = ""
513 |
514 | if relevant_content:
515 | if self.current_project.folder_structure:
516 | content_references += f"Folder structure:\n{self.format_structure(self.current_project.folder_structure)}\n"
517 | # Iterate through each retrieved content item.
518 | for identifier, content in relevant_content:
519 | # Attempt to determine the content type (default to generic "Content").
520 | content_type = self.current_project.file_embeddings.get(
521 | identifier, {}
522 | ).get("type", "content")
523 | if content_type == "file":
524 | label = "Referenced File"
525 | elif content_type == "terminal":
526 | label = "Referenced Terminal Output"
527 | else:
528 | label = "Referenced Content"
529 | content_references += f"\n[{label}: {identifier}]\n{content}\n"
530 |
531 | prompt = (
532 | f"{content_references}\nUser query: {query}"
533 | if content_references
534 | else query
535 | )
536 |
537 | logger.debug(f"Generated prompt: {prompt}")
538 | await self.add_message("user", prompt, embedding)
539 |
540 | return self.current_topic.history[-num_messages:]
541 |
542 | async def generate_topic_info_from_history(
543 | self, history: list, max_retries: int = 3
544 | ) -> Tuple[str, str] | Tuple[None, None]:
545 | """
546 | Attempts to extract a topic name and description from the given history.
547 | :
548 | Args:
549 | history (list): List of unsorted history messages.
550 | max_retries (int): Maximum number of attempts.
551 |
552 | Returns:
553 | tuple: (extracted_topic_name, extracted_topic_description) if successful; otherwise (None, None).
554 | """
555 | attempt = 0
556 | extracted_topic_name = None
557 | extracted_topic_description = None
558 |
559 | while attempt < max_retries:
560 | await asyncio.sleep(1)
561 | try:
562 | response = await self.helper(PromptHelper.topics_helper(history), True)
563 | if not response:
564 | logger.warning("Received empty response from the helper.")
565 |
566 | logger.debug(f"Extracting topic info from response: {response}")
567 | clean_response = re.sub(
568 | r"^```|```$|json", "", response, flags=re.IGNORECASE
569 | ).strip()
570 | matches = re.findall(r':\s*"([^"]+)"', clean_response)
571 | extracted_topic_name = matches[0] if len(matches) > 0 else "unknown"
572 | extracted_topic_description = matches[1] if len(matches) > 1 else ""
573 |
574 | if extracted_topic_name and extracted_topic_description:
575 | logger.info(f"Extracted topic: {extracted_topic_name}")
576 | return extracted_topic_name, extracted_topic_description
577 | else:
578 | logger.warning("Could not extract valid topic information.")
579 | except Exception as e:
580 | logger.error(
581 | f"Analyze history attempt {attempt + 1} failed: {str(e)}",
582 | exc_info=True,
583 | )
584 | attempt += 1
585 | if attempt < max_retries:
586 | logger.info(
587 | f"Retrying analysis... (Attempt {attempt + 1} of {max_retries})"
588 | )
589 | else:
590 | logger.error(
591 | "Max analysis retries reached; not splitting unsorted history."
592 | )
593 | break
594 | return None, None
595 |
596 | async def _analyze_history(
597 | self,
598 | off_topic_threshold: float = OFF_THR,
599 | off_topic_frequency: int = OFF_FREQ,
600 | slice_size: int = SLICE_SIZE,
601 | ) -> None:
602 | """
603 | Analyzes the current topic's history for potential off-topic drift.
604 | When the history length reaches a multiple of `off_topic_frequency`, the method:
605 | 1. Takes a slice of the last `slice_size` messages and computes per-message similarity to the current topic.
606 | 2. If more than half of the messages in the slice have a similarity below `off_topic_threshold`,
607 | it determines the precise start of the off-topic segment.
608 | 3. Generates candidate topic info for the off-topic segment and attempts to match it with an existing topic
609 | (excluding the current topic). If a match is found, the off-topic messages are reassigned; otherwise,
610 | a new topic is created.
611 | 4. Finally, the off-topic messages are removed from the current topic.
612 | """
613 | # If the current topic is unnamed but has > 4 messages, generate a topic name/description.
614 | if (
615 | len(self.current_topic.history) > 4
616 | and not self.current_topic.description.strip()
617 | ):
618 | (
619 | new_topic_name,
620 | new_topic_desc,
621 | ) = await self.generate_topic_info_from_history(self.current_topic.history)
622 | if new_topic_name and new_topic_desc:
623 | self.current_topic.name = new_topic_name
624 | self.current_topic.description = new_topic_desc
625 | self.current_topic.embedded_description = await self.fetch_embedding(
626 | new_topic_desc
627 | )
628 | return
629 |
630 | # Trigger analysis when history length is a multiple of off_topic_frequency.
631 | if (
632 | len(self.current_topic.history) >= off_topic_frequency
633 | and len(self.current_topic.history) % off_topic_frequency == 0
634 | ):
635 | logger.info("Analyzing current topic for potential off-topic segments.")
636 |
637 | current_name = self.current_topic.name
638 |
639 | # Candidate slice: the last `slice_size` messages.
640 | candidate_slice = self.current_topic.history[-slice_size:]
641 |
642 | # Concurrently fetch embeddings for the candidate slice.
643 | candidate_embeddings = await asyncio.gather(
644 | *(self.fetch_embedding(msg["content"]) for msg in candidate_slice)
645 | )
646 |
647 | similarities = []
648 | for msg_emb in candidate_embeddings:
649 | sim = cosine_similarity(
650 | [msg_emb], [self.current_topic.embedded_description]
651 | )[0][0]
652 | similarities.append(sim)
653 | logger.info(f"Per-message similarities for candidate slice: {similarities}")
654 |
655 | # Check if more than half of the messages fall below the threshold.
656 | if (
657 | sum(1 for s in similarities if s < off_topic_threshold)
658 | > len(similarities) / 2
659 | ):
660 | # Identify the precise start index of the off-topic segment.
661 | off_topic_start_index = len(self.current_topic.history) - slice_size
662 | for i, sim in enumerate(similarities):
663 | if sim < off_topic_threshold:
664 | off_topic_start_index = (
665 | len(self.current_topic.history) - slice_size + i
666 | )
667 | break
668 | off_topic_segment = self.current_topic.history[off_topic_start_index:]
669 | logger.info(
670 | f"Identified off-topic segment from index {off_topic_start_index} to end "
671 | f"(total {len(off_topic_segment)} messages)."
672 | )
673 |
674 | # Generate candidate topic info from the off-topic segment.
675 | (
676 | candidate_topic_name,
677 | candidate_topic_desc,
678 | ) = await self.generate_topic_info_from_history(off_topic_segment)
679 | if candidate_topic_name and candidate_topic_desc:
680 | candidate_embedding = await self.fetch_embedding(
681 | candidate_topic_desc
682 | )
683 | matched_topic = await self._match_topic(
684 | candidate_embedding, exclude_topic=self.current_topic
685 | )
686 | if matched_topic is not None:
687 | logger.info("Matched topic found")
688 | # Reassign off-topic messages to the matched topic.
689 | for msg in off_topic_segment:
690 | msg_emb = await self.fetch_embedding(msg["content"])
691 |
692 | await matched_topic.add_message(
693 | msg["role"], msg["content"], msg_emb
694 | )
695 | logger.info(
696 | f"Reassigned off-topic segment of {len(off_topic_segment)} messages to existing topic "
697 | f"'{matched_topic.name}'."
698 | )
699 | await self.switch_topic(matched_topic)
700 |
701 | else:
702 | # No matching topic found—create a new topic.
703 | try:
704 | logger.info("Creating new topic from the off-topic content")
705 | new_topic = Topic(
706 | candidate_topic_name, candidate_topic_desc
707 | )
708 | new_topic.embedded_description = candidate_embedding
709 | for msg in off_topic_segment:
710 | msg_emb = await self.fetch_embedding(msg["content"])
711 |
712 | await new_topic.add_message(
713 | msg["role"], msg["content"], msg_emb
714 | )
715 |
716 | await self.switch_topic(new_topic)
717 |
718 | logger.info(
719 | f"Created new topic '{new_topic.name}' with {len(off_topic_segment)} off-topic messages."
720 | )
721 |
722 | except Exception as e:
723 | logger.error(
724 | f"Error creating new topic from off-topic messages: {e}",
725 | exc_info=True,
726 | )
727 |
728 | target_topic = next(
729 | (
730 | topic
731 | for topic in self.topics
732 | if topic.name == current_name
733 | ),
734 | None,
735 | )
736 | if target_topic:
737 | async with asyncio.Lock():
738 | target_topic.history = target_topic.history[
739 | :off_topic_start_index
740 | ]
741 | logger.info("Removed off-topic from the current topic")
742 |
743 | else:
744 | logger.warning(
745 | "Could not generate candidate topic info from the off-topic segment."
746 | )
747 | else:
748 | logger.info(
749 | "Candidate slice does not appear off-topic; no splitting performed."
750 | )
751 |
752 | return
753 |
--------------------------------------------------------------------------------