ai_shell_history 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2018 The Python Packaging Authority
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai_shell_history
3
+ Version: 0.0.1
4
+ Summary: Shell history, enhanced with AI.
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.14
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: e80-sdk==0.1.0a15
10
+ Requires-Dist: textual[syntax]>=8.2.8
11
+ Requires-Dist: textual-dev>=1.8.0
12
+ Requires-Dist: pathspec>=1.1.1
13
+ Requires-Dist: pydantic>=2.14.1
14
+ Requires-Dist: aiofiles>=25.1.0
15
+ Dynamic: license-file
16
+
17
+ # AI Shell History
18
+
19
+ A shell history replacement tool that is powered by the 8080 API. It supports:
20
+
21
+ - Exact prefix matching
22
+ - Fuzzy and natural language matching powered by LLM
23
+ - AI generated suggestions
24
+
25
+ ## In Action:
26
+
27
+ ### Exact prefix matching
28
+
29
+ https://github.com/user-attachments/assets/8813ad1e-538e-4a71-ab5a-1978c03321e9
30
+
31
+ ### AI fuzzy matching / natural language matching
32
+
33
+ https://github.com/user-attachments/assets/e9f661c7-da33-42d4-9791-ec6218f7c5a0
34
+
35
+ ### AI generated suggestions
36
+
37
+ https://github.com/user-attachments/assets/2881b687-2a03-45c9-beeb-3116e0ddaca3
38
+
39
+ ## Installing and Running
40
+
41
+ Before getting started, you must have an API key on [8080.io][8080]
42
+ You can install the tool globally using [uv][uv].
43
+
44
+ ```sh
45
+ uv tool install ai_shell_history
46
+ ```
47
+
48
+ Install the `ctrl+R` keybinding by adding the following to your `.zshrc`:
49
+
50
+ ```sh
51
+ [ -f "$(which ai_shell_history)" ] && source <(ai_shell_history install zsh)
52
+ ```
53
+
54
+ On first run, you will be prompted for your [8080.io][8080] API key.
55
+
56
+ You can manually change your API key by running `ai_shell_history login`.
57
+
58
+ ## Development
59
+
60
+ The project is built using [Textual](https://textual.textualize.io/) and [uv][uv].
61
+
62
+ To run:
63
+
64
+ ```sh
65
+ uv sync
66
+ uv run textual run --dev ai_shell_history/main.py # Run in Textual dev mode
67
+ ```
68
+
69
+ [uv]: (https://docs.astral.sh/uv/)
70
+ [8080]: https://8080.io
@@ -0,0 +1,54 @@
1
+ # AI Shell History
2
+
3
+ A shell history replacement tool that is powered by the 8080 API. It supports:
4
+
5
+ - Exact prefix matching
6
+ - Fuzzy and natural language matching powered by LLM
7
+ - AI generated suggestions
8
+
9
+ ## In Action:
10
+
11
+ ### Exact prefix matching
12
+
13
+ https://github.com/user-attachments/assets/8813ad1e-538e-4a71-ab5a-1978c03321e9
14
+
15
+ ### AI fuzzy matching / natural language matching
16
+
17
+ https://github.com/user-attachments/assets/e9f661c7-da33-42d4-9791-ec6218f7c5a0
18
+
19
+ ### AI generated suggestions
20
+
21
+ https://github.com/user-attachments/assets/2881b687-2a03-45c9-beeb-3116e0ddaca3
22
+
23
+ ## Installing and Running
24
+
25
+ Before getting started, you must have an API key on [8080.io][8080]
26
+ You can install the tool globally using [uv][uv].
27
+
28
+ ```sh
29
+ uv tool install ai_shell_history
30
+ ```
31
+
32
+ Install the `ctrl+R` keybinding by adding the following to your `.zshrc`:
33
+
34
+ ```sh
35
+ [ -f "$(which ai_shell_history)" ] && source <(ai_shell_history install zsh)
36
+ ```
37
+
38
+ On first run, you will be prompted for your [8080.io][8080] API key.
39
+
40
+ You can manually change your API key by running `ai_shell_history login`.
41
+
42
+ ## Development
43
+
44
+ The project is built using [Textual](https://textual.textualize.io/) and [uv][uv].
45
+
46
+ To run:
47
+
48
+ ```sh
49
+ uv sync
50
+ uv run textual run --dev ai_shell_history/main.py # Run in Textual dev mode
51
+ ```
52
+
53
+ [uv]: (https://docs.astral.sh/uv/)
54
+ [8080]: https://8080.io
File without changes
@@ -0,0 +1,175 @@
1
+ import re
2
+ import tomllib
3
+ import traceback
4
+ from collections.abc import Callable
5
+
6
+ from e80_sdk.agents.definitions.state import Agent, Message, State
7
+ from e80_sdk.agents.definitions.usage import UsageByModel
8
+ from e80_sdk.agents.harness import run_agent_async
9
+ from e80_sdk.agents.toolbox import Toolbox
10
+ from e80_sdk.agents.usage import add_usages
11
+ from e80_sdk.clients import AsyncApi
12
+ from pydantic import BaseModel
13
+
14
+
15
+ async def reason_about_search_query(
16
+ client: AsyncApi, user_input: str
17
+ ) -> tuple[str, UsageByModel]:
18
+ system_message = """You are given a user's search query for the shell history.
19
+
20
+ What do you think the user is searching for? Explain why.
21
+ """
22
+ working_state = State(
23
+ agent=Agent(
24
+ name="Natural Language Judge",
25
+ model="qwen/qwen3-32b",
26
+ instructions=system_message,
27
+ tools=[],
28
+ ),
29
+ message_history=[
30
+ Message(
31
+ role="user",
32
+ content=user_input,
33
+ )
34
+ ],
35
+ )
36
+
37
+ result = await run_agent_async(
38
+ working_state,
39
+ Toolbox.get_global_instance(),
40
+ client=client,
41
+ )
42
+
43
+ return result.llm_response.content or "", result.usage
44
+
45
+
46
+ async def find_similar_commands(
47
+ client: AsyncApi, analysis: str
48
+ ) -> tuple[Output, UsageByModel]:
49
+ system_message = f"""You are given a snippet of analysis of a user's query
50
+ to search through their shell history.
51
+
52
+ Write regex queries that matches the commands in the query analysis. The regex should match any amount of
53
+ whitespace between parameters. Arguments that aren't essential should be optional. Parameter order should
54
+ not matter. For argument values, search for similar values.
55
+
56
+ {_REGEX_OUTPUT}
57
+
58
+ {_TOML_OUTPUT}
59
+ """
60
+ working_state = State(
61
+ agent=Agent(
62
+ name="Similar History Finder",
63
+ model="qwen/qwen3-32b",
64
+ instructions=system_message,
65
+ tools=[],
66
+ ),
67
+ message_history=[
68
+ Message(
69
+ role="user",
70
+ content=analysis,
71
+ )
72
+ ],
73
+ )
74
+
75
+ total_usage = UsageByModel(model_usages=[])
76
+
77
+ output = await _agent_in_loop(working_state, client, total_usage, _output_work)
78
+
79
+ return output
80
+
81
+
82
+ async def generate_suggestions(
83
+ client: AsyncApi, analysis: str
84
+ ) -> tuple[Output, UsageByModel]:
85
+ system_message = f"""A user is searching for a shell command.
86
+
87
+ You are given the analysis of what the user is searching for. Generate
88
+ commands that may match what the user was originally searching for. Do NOT generate
89
+ commands that search for the command.
90
+
91
+ {_TOML_OUTPUT}
92
+ ```
93
+ """
94
+ working_state = State(
95
+ agent=Agent(
96
+ name="Natural Language Judge",
97
+ model="qwen/qwen3-32b",
98
+ instructions=system_message,
99
+ tools=[],
100
+ ),
101
+ message_history=[
102
+ Message(
103
+ role="user",
104
+ content=analysis,
105
+ )
106
+ ],
107
+ )
108
+
109
+ total_usage = UsageByModel(model_usages=[])
110
+
111
+ output = await _agent_in_loop(working_state, client, total_usage, _output_work)
112
+
113
+ return output
114
+
115
+
116
+ def _output_work(content: str) -> Output:
117
+ return Output.model_validate(tomllib.loads(_extract_toml(content)))
118
+
119
+
120
+ class Suggestion(BaseModel):
121
+ item: str
122
+
123
+
124
+ class Output(BaseModel):
125
+ suggestions: list[Suggestion]
126
+
127
+
128
+ _REGEX_OUTPUT = """
129
+ While writing regex, remember that you're outputting a string, and to escape backslashes, so '\\' for a single
130
+ backslash.
131
+ """
132
+
133
+ _TOML_OUTPUT = """
134
+ Return your output in TOML like such:
135
+
136
+ ```toml
137
+ # Feel free to write comments to explain each suggestion.
138
+ [[suggestions]]
139
+ item = ""
140
+
141
+ [[suggestions]]
142
+ item = ""
143
+ ```
144
+ """
145
+
146
+
147
+ def _extract_toml(text: str) -> str:
148
+ match = re.search(r"```toml\s*\n(.*?)\n```", text, re.DOTALL)
149
+ return match.group(1) if match else text
150
+
151
+
152
+ async def _agent_in_loop[T](
153
+ state: State, client: AsyncApi, usage: UsageByModel, work: Callable[[str], T]
154
+ ) -> tuple[T, UsageByModel]:
155
+ for _ in range(2):
156
+ result = await run_agent_async(
157
+ state,
158
+ Toolbox.get_global_instance(),
159
+ client=client,
160
+ )
161
+
162
+ usage = add_usages(result.usage, usage)
163
+
164
+ try:
165
+ return work(result.llm_response.content or ""), usage
166
+ except Exception as e: # noqa: BLE001
167
+ print("BAD CONTENT", result.llm_response.content)
168
+ traceback.print_exc()
169
+ state.message_history.append(
170
+ Message(
171
+ role="user",
172
+ content=f"Error in message format: {e}",
173
+ )
174
+ )
175
+ raise Exception("Agent stuck in a loop") # noqa: TRY002
@@ -0,0 +1,28 @@
1
+ import tomllib
2
+ from pathlib import Path
3
+
4
+ from pydantic import BaseModel
5
+
6
+
7
+ class Config(BaseModel):
8
+ api_key: str | None = None
9
+
10
+
11
+ def load_config(config_path: Path) -> Config | None:
12
+ if not config_path.exists():
13
+ return None
14
+
15
+ with config_path.open("r") as f:
16
+ return Config.model_validate(tomllib.loads(f.read()))
17
+
18
+
19
+ def write_config(config_path: Path, config: Config) -> None:
20
+ config_folder = (config_path / "..").resolve()
21
+
22
+ if not config_folder.exists():
23
+ config_folder.mkdir(exist_ok=True, parents=True)
24
+ if not config_path.exists():
25
+ config_path.touch()
26
+
27
+ with config_path.open("w") as f:
28
+ f.write(f'api_key = "{config.api_key}"')
@@ -0,0 +1,22 @@
1
+ def zsh_install() -> str:
2
+ return """\
3
+ # ai_shell_history zsh integration.
4
+ # Add `source ~/.ai_shell_history/zsh_install.sh` to your ~/.zshrc.
5
+
6
+ _ai_shell_history_widget() {
7
+ local selected ret
8
+ selected=$(ai_shell_history history "$BUFFER" </dev/tty)
9
+ ret=$?
10
+ if [[ -n $selected ]]; then
11
+ BUFFER=$selected
12
+ CURSOR=${#BUFFER}
13
+ fi
14
+ zle reset-prompt
15
+ return $ret
16
+ }
17
+
18
+ zle -N _ai_shell_history_widget
19
+ bindkey -M emacs '^R' _ai_shell_history_widget
20
+ bindkey -M viins '^R' _ai_shell_history_widget
21
+ bindkey -M vicmd '^R' _ai_shell_history_widget
22
+ """
@@ -0,0 +1,71 @@
1
+ import argparse
2
+ import asyncio
3
+ import getpass
4
+ import warnings
5
+ from pathlib import Path
6
+
7
+ warnings.filterwarnings("ignore", module="e80_sdk")
8
+
9
+ from ai_shell_history.install import zsh_install
10
+ from ai_shell_history.shell_history import ZshHistory
11
+ from ai_shell_history.tui import AIShellHistoryApp
12
+
13
+ parser = argparse.ArgumentParser(prog="ai_shell_history")
14
+ subparsers = parser.add_subparsers(dest="command", required=True)
15
+
16
+ login_parser = subparsers.add_parser("login", help="Save an API key to the config.")
17
+ login_parser.add_argument(
18
+ "--api-key",
19
+ help="The API key to save. If omitted, you will be prompted for it.",
20
+ )
21
+
22
+ history_parser = subparsers.add_parser("history", help="Search your shell history.")
23
+ history_parser.add_argument(
24
+ "query", nargs="?", default=None, help="Initial search query."
25
+ )
26
+
27
+ install_parser = subparsers.add_parser(
28
+ "install", help="Print a shell integration script."
29
+ )
30
+ install_subparsers = install_parser.add_subparsers(dest="shell", required=True)
31
+ install_subparsers.add_parser("zsh", help="Print the zsh integration script.")
32
+
33
+
34
+ CONFIG_DIR = Path.home() / ".ai_shell_history"
35
+ CONFIG_PATH = CONFIG_DIR / "config.toml"
36
+
37
+
38
+ async def history(query: str | None) -> str | None:
39
+ shell_history = await ZshHistory.load()
40
+ selected = await AIShellHistoryApp(
41
+ shell_history, initial=query, config_path=CONFIG_PATH
42
+ ).run_async()
43
+ return selected
44
+
45
+
46
+ def main():
47
+ args = parser.parse_args()
48
+
49
+ if args.command == "login":
50
+ _maybe_write_config(args.api_key)
51
+ elif args.command == "history":
52
+ if not CONFIG_PATH.exists():
53
+ _maybe_write_config(None)
54
+ selected = asyncio.run(history(args.query))
55
+ if selected:
56
+ print(selected)
57
+ elif args.command == "install" and args.shell == "zsh":
58
+ print(zsh_install(), end="")
59
+
60
+
61
+ def _maybe_write_config(api_key: str | None) -> str:
62
+ from ai_shell_history.config import Config, write_config
63
+
64
+ if api_key is None:
65
+ api_key = getpass.getpass(prompt="Enter your 8080 API key: ")
66
+ write_config(CONFIG_PATH, Config(api_key=api_key))
67
+ return api_key
68
+
69
+
70
+ if __name__ == "__main__":
71
+ main()
@@ -0,0 +1,71 @@
1
+ import os
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+
5
+ import aiofiles
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class HistoryLine:
10
+ command: str
11
+ time_epoch_secs: int
12
+ return_code: int
13
+
14
+
15
+ class ZshHistory:
16
+ """Parsed, read-only contents of a zsh history file. Create with `load()`."""
17
+
18
+ def __init__(self, entries: list[HistoryLine]) -> None:
19
+ self._entries = entries
20
+
21
+ @property
22
+ def entries(self) -> list[HistoryLine]:
23
+ return self._entries
24
+
25
+ @staticmethod
26
+ async def load(path: Path | None = None) -> ZshHistory:
27
+ if path is None:
28
+ histfile = os.environ.get("HISTFILE")
29
+ path = (
30
+ Path(histfile).expanduser()
31
+ if histfile
32
+ else Path.home() / ".zsh_history"
33
+ )
34
+
35
+ async with aiofiles.open(path) as f:
36
+ lines = await f.readlines()
37
+
38
+ entries: list[HistoryLine] = []
39
+ expects_new_entry = True
40
+ current_command_lines: list[str] = []
41
+ current_return_code = 0
42
+ current_time_epoch_secs = 0
43
+
44
+ for fl in lines:
45
+ line = fl.removesuffix("\n")
46
+
47
+ if expects_new_entry:
48
+ meta, line = line.split(";", 1)
49
+ meta_split = meta.split(":")
50
+ current_time_epoch_secs = int(meta_split[1].strip())
51
+ current_return_code = int(meta_split[2].strip())
52
+
53
+ if line.endswith("\\"):
54
+ current_command_lines.append(line.removesuffix("\\"))
55
+ expects_new_entry = False
56
+ else:
57
+ current_command_lines.append(line)
58
+ expects_new_entry = True
59
+
60
+ entries.append(
61
+ HistoryLine(
62
+ "\n".join(current_command_lines),
63
+ current_time_epoch_secs,
64
+ current_return_code,
65
+ )
66
+ )
67
+ current_command_lines = []
68
+ current_return_code = 0
69
+ current_time_epoch_secs = 0
70
+
71
+ return ZshHistory(list(reversed(entries)))
@@ -0,0 +1,411 @@
1
+ import asyncio
2
+ import os
3
+ import re
4
+ import traceback
5
+ import typing
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from textwrap import indent
9
+
10
+ from rich.markup import escape
11
+ from rich.text import Text
12
+ from textual import work
13
+ from textual.app import App, ComposeResult, RenderResult
14
+ from textual.containers import Horizontal
15
+ from textual.drivers.linux_driver import LinuxDriver
16
+ from textual.reactive import reactive
17
+ from textual.screen import Screen
18
+ from textual.timer import Timer
19
+ from textual.widget import Widget
20
+ from textual.widgets import Input, ListItem, ListView, OptionList, Static
21
+
22
+ from ai_shell_history.shell_history import HistoryLine, ZshHistory
23
+
24
+ if typing.TYPE_CHECKING:
25
+ from e80_sdk.clients import AsyncApi
26
+
27
+ from ai_shell_history.agent import (
28
+ Suggestion,
29
+ )
30
+
31
+
32
+ class AIShellHistoryApp(App[str]):
33
+ CSS = """
34
+ Screen {
35
+ layout: vertical;
36
+ }
37
+
38
+ #options {
39
+ height: 1fr;
40
+ background: $background;
41
+ border-top: solid $border;
42
+
43
+
44
+ & > .--highlight {
45
+ background: $boost;
46
+ color: red;
47
+ text-style: bold;
48
+ }
49
+
50
+ & > .--hover {
51
+ background: $surface;
52
+ }
53
+ }
54
+
55
+ #prompt {
56
+ background: $background;
57
+ padding-top: 1;
58
+ padding-left: 1;
59
+ height: auto;
60
+ border: none;
61
+ }
62
+
63
+ .bottom-bar {
64
+ background: $panel;
65
+ height: auto;
66
+ padding: 0 1;
67
+ }
68
+
69
+ #usage {
70
+ width: auto;
71
+ }
72
+
73
+ #instructions {
74
+ width: 1fr;
75
+ }
76
+ """
77
+
78
+ BINDINGS: typing.ClassVar = [
79
+ ("ctrl+q", "quit", "Quit"),
80
+ ("ctrl+c", "quit", "Quit"),
81
+ ("up", "select_up", "Selection Up"),
82
+ ("down", "select_down", "Selection Down"),
83
+ ]
84
+
85
+ _client: AsyncApi | None
86
+
87
+ def __init__(
88
+ self, history: ZshHistory, initial: str | None, config_path: Path
89
+ ) -> None:
90
+ super().__init__(driver_class=FixedLinuxDriver)
91
+ self._client = None
92
+ self._timer: Timer | None = None
93
+ self._config_path = config_path
94
+ self._latest_input = initial
95
+ self._history = history
96
+ self._exact_matches: list[HistoryLine] = []
97
+
98
+ def compose(self) -> ComposeResult:
99
+ with Horizontal(classes="bottom-bar"):
100
+ yield Static(
101
+ "[bold]^q[/bold] exit [bold]up/down/enter[/bold] select",
102
+ id="instructions",
103
+ )
104
+ yield Usage(id="usage")
105
+ yield Input(placeholder="Type a prompt…", id="prompt", value=self._latest_input)
106
+ yield UnfocusableList(*[], id="options")
107
+
108
+ async def on_mount(self) -> None:
109
+ self._load_everything()
110
+
111
+ async def on_unmount(self) -> None:
112
+ if self._client:
113
+ await self._client.client.aclose()
114
+
115
+ def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
116
+ self.exit(str(event.option.prompt))
117
+
118
+ def on_input_submitted(self, event: Input.Submitted) -> None:
119
+ option_list = self._get_option_list()
120
+ option_list.action_select_cursor()
121
+
122
+ def action_select_up(self):
123
+ option_list = self._get_option_list()
124
+ if option_list.index is not None:
125
+ option_list.index = option_list.validate_index(option_list.index - 1)
126
+ else:
127
+ option_list.index = option_list.validate_index(0)
128
+
129
+ def action_select_down(self):
130
+ option_list = self._get_option_list()
131
+
132
+ if option_list.index is not None:
133
+ option_list.index = option_list.validate_index(option_list.index + 1)
134
+ else:
135
+ option_list.index = option_list.validate_index(0)
136
+
137
+ async def on_input_changed(self, event: Input.Changed):
138
+ self._latest_input = event.value
139
+
140
+ self._history_starting_with()
141
+ if self._timer is None:
142
+ self._timer = self.set_timer(0.1, self._get_suggestions, pause=True)
143
+
144
+ self._timer.reset()
145
+ self._timer.resume()
146
+
147
+ async def on_list_view_selected(self, event: ListView.Selected):
148
+ if not event.item.children:
149
+ return
150
+
151
+ first_child = event.item.children[0]
152
+
153
+ if isinstance(first_child, ShellHistoryItem):
154
+ self.exit(str(first_child.value))
155
+
156
+ @work(exclusive=True, thread=True)
157
+ async def _load_everything(self) -> None:
158
+ from e80_sdk import Eighty80
159
+
160
+ from ai_shell_history.config import load_config
161
+
162
+ config = load_config(self._config_path)
163
+ if config == None:
164
+ self.push_screen(ConfigErrorScreen())
165
+ else:
166
+ self._client = Eighty80(api_key=config.api_key).api_async()
167
+
168
+ @work(exclusive=True)
169
+ async def _history_starting_with(self) -> None:
170
+ option_list = self._get_option_list()
171
+ option_list.clear()
172
+ self._exact_matches.clear()
173
+
174
+ if not self._latest_input:
175
+ return
176
+
177
+ option_count = 0
178
+ for hist in self._history.entries:
179
+ if option_count > 5:
180
+ break
181
+ if hist.command.startswith(self._latest_input):
182
+ option_count += 1
183
+ option_list.append(
184
+ ListItem(
185
+ ShellHistoryItem("PREFIX", hist.command, hist.time_epoch_secs)
186
+ )
187
+ )
188
+ self._exact_matches.append(hist)
189
+ option_list.index = option_list.validate_index(0)
190
+
191
+ @work(exclusive=True)
192
+ async def _get_suggestions(self) -> None:
193
+ import e80_sdk # noqa: F401 For some reason, this line is needed, probably due to async importing.
194
+ from e80_sdk.agents.definitions.usage import UsageByModel
195
+ from e80_sdk.agents.usage import add_usages
196
+
197
+ from ai_shell_history.agent import (
198
+ find_similar_commands,
199
+ generate_suggestions,
200
+ reason_about_search_query,
201
+ )
202
+
203
+ if not self._client:
204
+ return
205
+
206
+ self._timer = None
207
+
208
+ if not self._latest_input:
209
+ return
210
+
211
+ option_list = self._get_option_list()
212
+
213
+ now = datetime.now()
214
+ usages = UsageByModel(model_usages=[])
215
+
216
+ try:
217
+ reasoning, reasoning_usages = await reason_about_search_query(
218
+ self._client, self._latest_input
219
+ )
220
+
221
+ usages = add_usages(reasoning_usages, usages)
222
+
223
+ async with asyncio.TaskGroup() as tg:
224
+ similar_task = tg.create_task(
225
+ find_similar_commands(self._client, reasoning)
226
+ )
227
+ suggested_task = tg.create_task(
228
+ generate_suggestions(self._client, reasoning)
229
+ )
230
+
231
+ similar_regexes, similar_usages = similar_task.result()
232
+ usages = add_usages(similar_usages, usages)
233
+
234
+ regexes = _compile_regexps(similar_regexes.suggestions)
235
+ suggestion_count = 0
236
+
237
+ existing_commands = {em.command for em in self._exact_matches}
238
+
239
+ for hist in self._history.entries:
240
+ if suggestion_count > 5:
241
+ break
242
+ for r in regexes:
243
+ if r.match(hist.command):
244
+ if hist.command in existing_commands:
245
+ continue
246
+ suggestion_count += 1
247
+ option_list.append(
248
+ ListItem(
249
+ ShellHistoryItem(
250
+ "FUZZY", hist.command, hist.time_epoch_secs
251
+ )
252
+ )
253
+ )
254
+
255
+ suggested_output, suggested_usages = suggested_task.result()
256
+ usages = add_usages(suggested_usages, usages)
257
+
258
+ option_list.extend(
259
+ [
260
+ ListItem(ShellHistoryItem("AI", s.item, None))
261
+ for s in suggested_output.suggestions
262
+ ]
263
+ )
264
+
265
+ td = datetime.now() - now
266
+ millisecs = td.seconds * 1000 + int(td.microseconds / 1000)
267
+ model_usage = usages.model_usages[0]
268
+
269
+ usage_widget = self.query_one("#usage", Usage)
270
+ usage_widget.millisecs = millisecs
271
+
272
+ usage_widget.decode_rate = model_usage.completion_token_rate or 0.0
273
+ usage_widget.decode_tokens = model_usage.completion_tokens
274
+ usage_widget.prefill_rate = model_usage.prompt_token_rate or 0.0
275
+ usage_widget.prefill_tokens = model_usage.prompt_tokens
276
+ except asyncio.CancelledError:
277
+ pass
278
+ except: # noqa: E722
279
+ traceback.print_exc()
280
+ self.notify("Got an error")
281
+
282
+ def _get_option_list(self) -> UnfocusableList:
283
+ return self.query_one("#options", UnfocusableList)
284
+
285
+
286
+ def _compile_regexps(items: list[Suggestion]) -> list[re.Pattern[str]]:
287
+ patterns = []
288
+ for i in items:
289
+ try:
290
+ patterns.append(re.compile(i.item, 0))
291
+ except re.PatternError as e:
292
+ print(f"Failed to compile {i}: {e}")
293
+
294
+ return patterns
295
+
296
+
297
+ type _OptionTypes = typing.Literal["PREFIX", "FUZZY", "AI"]
298
+
299
+
300
+ class ShellHistoryItem(Static):
301
+ source: str
302
+ value: str
303
+ timestamp_epoch_secs: int | None
304
+
305
+ def __init__(
306
+ self, source: _OptionTypes, value: str, timestamp_epoch_secs: int | None
307
+ ):
308
+ super().__init__()
309
+
310
+ self.source = source
311
+ self.value = value
312
+ self.timestamp_epoch_secs = timestamp_epoch_secs
313
+
314
+ def render(self) -> RenderResult:
315
+ text = Text(" ")
316
+ match self.source:
317
+ case "PREFIX":
318
+ text.append("match", style="turquoise4")
319
+ case "FUZZY":
320
+ text.append("fuzzy", style="gold3")
321
+ case "AI":
322
+ text.append(" ai ", style="light_steel_blue")
323
+
324
+ time_ago = ""
325
+ if self.timestamp_epoch_secs:
326
+ td = datetime.now() - datetime.fromtimestamp(self.timestamp_epoch_secs)
327
+ if td.days and td.days >= 1000:
328
+ time_ago = "999+d"
329
+ elif td.days:
330
+ time_ago = f"{td.days}d"
331
+ elif td.seconds and td.seconds > (60 * 60):
332
+ time_ago = f"{int(td.seconds / (60 * 60))}h"
333
+ elif td.seconds and td.seconds > (60):
334
+ time_ago = f"{int(td.seconds / (60))}m"
335
+ elif td.seconds:
336
+ time_ago = f"{td.seconds}s"
337
+ else:
338
+ time_ago = "now"
339
+ else:
340
+ time_ago = ".✧*"
341
+
342
+ text.append(time_ago.center(7), style="bold")
343
+
344
+ start = 6 + 7 + 1
345
+
346
+ indented = indent(escape(self.value), " " * start)
347
+ text.append(" ")
348
+ text.append(text=indented[start:])
349
+ return text
350
+
351
+
352
+ class UnfocusableList(ListView, can_focus=False):
353
+ pass
354
+
355
+
356
+ class Usage(Widget):
357
+ DEFAULT_CSS = """
358
+ Usage {
359
+ height: auto;
360
+ padding-left: 1;
361
+ }
362
+ """
363
+ decode_rate = reactive(0.0)
364
+ decode_tokens = reactive(0)
365
+ prefill_rate = reactive(0.0)
366
+ prefill_tokens = reactive(0)
367
+ millisecs = reactive(0)
368
+
369
+ def render(self):
370
+ ss = "bold green"
371
+ return f"decode: [{ss}]{self.decode_tokens}tok[/{ss}] [{ss}]{self.decode_rate:.2f}tok/s[/{ss}] prefill: [{ss}]{self.prefill_tokens}tok[/{ss}] [{ss}]{self.prefill_rate:.2f}tok/s[/{ss}] total time: [{ss}]{self.millisecs}ms[{ss}]"
372
+
373
+
374
+ class ConfigErrorScreen(Screen):
375
+ CSS = """
376
+ ConfigErrorScreen {
377
+ align: center middle;
378
+ }
379
+ """
380
+
381
+ BINDINGS: typing.ClassVar = [
382
+ ("ctrl+q", "quit", "Quit"),
383
+ ("ctrl+c", "quit", "Quit"),
384
+ ]
385
+
386
+ def compose(self) -> ComposeResult:
387
+ yield Static("There was an error reading your config")
388
+ yield Static("Please run [bold]ai_shell_history login[/bold]")
389
+
390
+
391
+ class FixedLinuxDriver(LinuxDriver):
392
+ """
393
+ A Textual Linux driver, with size detection from stderr instead of stdout.
394
+
395
+ stdout might be redirected, which means you cannot use it to find the terminal size.
396
+ The Textual app is drawn on stderr, which means if that is redirected, you're not gonna
397
+ see anything. In that case, stderr is a better candidate for getting the size.
398
+ """
399
+
400
+ @typing.override
401
+ def _get_terminal_size(self) -> tuple[int, int]:
402
+ try:
403
+ width, height = os.get_terminal_size(2)
404
+ except AttributeError, ValueError, OSError:
405
+ try:
406
+ width, height = os.get_terminal_size(2)
407
+ except AttributeError, ValueError, OSError:
408
+ pass
409
+ width = width or 80
410
+ height = height or 25
411
+ return width, height
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai_shell_history
3
+ Version: 0.0.1
4
+ Summary: Shell history, enhanced with AI.
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.14
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: e80-sdk==0.1.0a15
10
+ Requires-Dist: textual[syntax]>=8.2.8
11
+ Requires-Dist: textual-dev>=1.8.0
12
+ Requires-Dist: pathspec>=1.1.1
13
+ Requires-Dist: pydantic>=2.14.1
14
+ Requires-Dist: aiofiles>=25.1.0
15
+ Dynamic: license-file
16
+
17
+ # AI Shell History
18
+
19
+ A shell history replacement tool that is powered by the 8080 API. It supports:
20
+
21
+ - Exact prefix matching
22
+ - Fuzzy and natural language matching powered by LLM
23
+ - AI generated suggestions
24
+
25
+ ## In Action:
26
+
27
+ ### Exact prefix matching
28
+
29
+ https://github.com/user-attachments/assets/8813ad1e-538e-4a71-ab5a-1978c03321e9
30
+
31
+ ### AI fuzzy matching / natural language matching
32
+
33
+ https://github.com/user-attachments/assets/e9f661c7-da33-42d4-9791-ec6218f7c5a0
34
+
35
+ ### AI generated suggestions
36
+
37
+ https://github.com/user-attachments/assets/2881b687-2a03-45c9-beeb-3116e0ddaca3
38
+
39
+ ## Installing and Running
40
+
41
+ Before getting started, you must have an API key on [8080.io][8080]
42
+ You can install the tool globally using [uv][uv].
43
+
44
+ ```sh
45
+ uv tool install ai_shell_history
46
+ ```
47
+
48
+ Install the `ctrl+R` keybinding by adding the following to your `.zshrc`:
49
+
50
+ ```sh
51
+ [ -f "$(which ai_shell_history)" ] && source <(ai_shell_history install zsh)
52
+ ```
53
+
54
+ On first run, you will be prompted for your [8080.io][8080] API key.
55
+
56
+ You can manually change your API key by running `ai_shell_history login`.
57
+
58
+ ## Development
59
+
60
+ The project is built using [Textual](https://textual.textualize.io/) and [uv][uv].
61
+
62
+ To run:
63
+
64
+ ```sh
65
+ uv sync
66
+ uv run textual run --dev ai_shell_history/main.py # Run in Textual dev mode
67
+ ```
68
+
69
+ [uv]: (https://docs.astral.sh/uv/)
70
+ [8080]: https://8080.io
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ ai_shell_history/__init__.py
5
+ ai_shell_history/agent.py
6
+ ai_shell_history/config.py
7
+ ai_shell_history/install.py
8
+ ai_shell_history/main.py
9
+ ai_shell_history/shell_history.py
10
+ ai_shell_history/tui.py
11
+ ai_shell_history.egg-info/PKG-INFO
12
+ ai_shell_history.egg-info/SOURCES.txt
13
+ ai_shell_history.egg-info/dependency_links.txt
14
+ ai_shell_history.egg-info/entry_points.txt
15
+ ai_shell_history.egg-info/requires.txt
16
+ ai_shell_history.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ai_shell_history = ai_shell_history.main:main
@@ -0,0 +1,6 @@
1
+ e80-sdk==0.1.0a15
2
+ textual[syntax]>=8.2.8
3
+ textual-dev>=1.8.0
4
+ pathspec>=1.1.1
5
+ pydantic>=2.14.1
6
+ aiofiles>=25.1.0
@@ -0,0 +1 @@
1
+ ai_shell_history
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "ai_shell_history"
3
+ description = "Shell history, enhanced with AI."
4
+ version = "0.0.1"
5
+ license = "MIT"
6
+ license-files = ["LICEN[CS]E*"]
7
+ readme = "README.md"
8
+ requires-python = ">=3.14"
9
+ dependencies = [
10
+ "e80-sdk==0.1.0a15",
11
+ "textual[syntax]>=8.2.8",
12
+ "textual-dev>=1.8.0",
13
+ "pathspec>=1.1.1",
14
+ "pydantic>=2.14.1",
15
+ "aiofiles>=25.1.0",
16
+ ]
17
+
18
+ [project.scripts]
19
+ ai_shell_history = "ai_shell_history.main:main"
20
+
21
+ [tool.uv]
22
+ package = true
23
+
24
+ [dependency-groups]
25
+ dev = [
26
+ "pre-commit>=4.7.0",
27
+ "ruff>=0.17.1",
28
+ "ty>=0.0.107",
29
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+