oshell 0.1.1__py3-none-any.whl

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.
oshell/tools.py ADDED
@@ -0,0 +1,150 @@
1
+ """Tools the coding agent can invoke.
2
+
3
+ Every tool is sandboxed to a *workspace root*: paths are resolved and must
4
+ stay inside that root, so the agent cannot read or clobber files elsewhere
5
+ on the machine. Mutating tools (``write_file``, ``run_command``) go through
6
+ an approval callback so the user stays in control.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import subprocess
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Callable, Dict
15
+
16
+ # A callback the agent uses to ask the user before a risky action.
17
+ # Receives a human-readable description and returns True to proceed.
18
+ ApprovalFn = Callable[[str, str], bool]
19
+
20
+ MAX_READ_BYTES = 100_000
21
+ COMMAND_TIMEOUT = 120 # seconds
22
+
23
+
24
+ @dataclass
25
+ class ToolResult:
26
+ """Outcome of running a tool, fed back to the model as an observation."""
27
+
28
+ ok: bool
29
+ output: str
30
+
31
+ def render(self) -> str:
32
+ status = "OK" if self.ok else "ERROR"
33
+ return f"[{status}] {self.output}"
34
+
35
+
36
+ class Toolbox:
37
+ """Holds the workspace root and exposes the agent's tools."""
38
+
39
+ def __init__(self, root: Path, approve: ApprovalFn, auto_approve: bool = False):
40
+ self.root = root.resolve()
41
+ self.approve = approve
42
+ self.auto_approve = auto_approve
43
+
44
+ # ----- path safety ---------------------------------------------------
45
+ def _resolve(self, rel: str) -> Path:
46
+ """Resolve ``rel`` inside the workspace, rejecting escapes."""
47
+ target = (self.root / rel).resolve()
48
+ if target != self.root and self.root not in target.parents:
49
+ raise ValueError(
50
+ f"Path '{rel}' is outside the workspace root and is not allowed."
51
+ )
52
+ return target
53
+
54
+ def _confirm(self, summary: str, detail: str) -> bool:
55
+ if self.auto_approve:
56
+ return True
57
+ return self.approve(summary, detail)
58
+
59
+ # ----- tools ---------------------------------------------------------
60
+ def read_file(self, path: str) -> ToolResult:
61
+ try:
62
+ target = self._resolve(path)
63
+ except ValueError as exc:
64
+ return ToolResult(False, str(exc))
65
+ if not target.is_file():
66
+ return ToolResult(False, f"File not found: {path}")
67
+ data = target.read_bytes()[:MAX_READ_BYTES]
68
+ text = data.decode("utf-8", errors="replace")
69
+ return ToolResult(True, text)
70
+
71
+ def write_file(self, path: str, content: str) -> ToolResult:
72
+ try:
73
+ target = self._resolve(path)
74
+ except ValueError as exc:
75
+ return ToolResult(False, str(exc))
76
+
77
+ action = "Overwrite" if target.exists() else "Create"
78
+ preview = content if len(content) < 800 else content[:800] + "\n… (truncated)"
79
+ if not self._confirm(
80
+ f"{action} file: {path}",
81
+ preview,
82
+ ):
83
+ return ToolResult(False, f"User declined to write '{path}'.")
84
+
85
+ target.parent.mkdir(parents=True, exist_ok=True)
86
+ target.write_text(content, encoding="utf-8")
87
+ return ToolResult(True, f"Wrote {len(content)} chars to {path}.")
88
+
89
+ def list_dir(self, path: str = ".") -> ToolResult:
90
+ try:
91
+ target = self._resolve(path)
92
+ except ValueError as exc:
93
+ return ToolResult(False, str(exc))
94
+ if not target.is_dir():
95
+ return ToolResult(False, f"Not a directory: {path}")
96
+ entries = []
97
+ for child in sorted(target.iterdir()):
98
+ mark = "/" if child.is_dir() else ""
99
+ entries.append(child.name + mark)
100
+ listing = "\n".join(entries) if entries else "(empty)"
101
+ return ToolResult(True, listing)
102
+
103
+ def run_command(self, command: str) -> ToolResult:
104
+ if not self._confirm("Run shell command", command):
105
+ return ToolResult(False, f"User declined to run: {command}")
106
+ try:
107
+ proc = subprocess.run(
108
+ command,
109
+ shell=True,
110
+ cwd=str(self.root),
111
+ capture_output=True,
112
+ text=True,
113
+ timeout=COMMAND_TIMEOUT,
114
+ )
115
+ except subprocess.TimeoutExpired:
116
+ return ToolResult(False, f"Command timed out after {COMMAND_TIMEOUT}s.")
117
+ out = (proc.stdout or "") + (proc.stderr or "")
118
+ out = out.strip() or "(no output)"
119
+ if len(out) > MAX_READ_BYTES:
120
+ out = out[:MAX_READ_BYTES] + "\n… (truncated)"
121
+ return ToolResult(proc.returncode == 0, f"exit={proc.returncode}\n{out}")
122
+
123
+ # ----- dispatch ------------------------------------------------------
124
+ def dispatch(self, action: str, args: Dict) -> ToolResult:
125
+ """Run a named tool with the given args dict."""
126
+ handlers = {
127
+ "read_file": lambda a: self.read_file(a.get("path", "")),
128
+ "write_file": lambda a: self.write_file(
129
+ a.get("path", ""), a.get("content", "")
130
+ ),
131
+ "list_dir": lambda a: self.list_dir(a.get("path", ".")),
132
+ "run_command": lambda a: self.run_command(a.get("command", "")),
133
+ }
134
+ handler = handlers.get(action)
135
+ if handler is None:
136
+ return ToolResult(False, f"Unknown action: {action!r}")
137
+ try:
138
+ return handler(args or {})
139
+ except Exception as exc: # noqa: BLE001 - report tool failures to the model
140
+ return ToolResult(False, f"Tool raised: {exc}")
141
+
142
+
143
+ TOOL_REFERENCE = """\
144
+ Available tools (use exactly these action names):
145
+ - read_file args: {"path": "relative/path"} -> returns file contents
146
+ - write_file args: {"path": "relative/path", "content": "..."} -> creates/overwrites a file
147
+ - list_dir args: {"path": "relative/dir"} -> lists directory entries
148
+ - run_command args: {"command": "shell command"} -> runs a command in the workspace
149
+ - finish args: {"summary": "what you accomplished"} -> ends the task
150
+ """
@@ -0,0 +1,286 @@
1
+ Metadata-Version: 2.4
2
+ Name: oshell
3
+ Version: 0.1.1
4
+ Summary: A fast, beautiful terminal chat for any LLM — OpenAI or local Ollama. Zero config.
5
+ Project-URL: Homepage, https://github.com/djaferiurim/oshell
6
+ Project-URL: Issues, https://github.com/djaferiurim/oshell/issues
7
+ Author: djaferiurim
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: ai,chat,chatgpt,cli,llm,ollama,openai,terminal
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Utilities
17
+ Requires-Python: >=3.9
18
+ Requires-Dist: httpx>=0.27
19
+ Requires-Dist: platformdirs>=4.0
20
+ Requires-Dist: rich>=13.7
21
+ Requires-Dist: typer>=0.12
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
24
+ Requires-Dist: pytest>=8.0; extra == 'dev'
25
+ Description-Content-Type: text/markdown
26
+
27
+ <div align="center">
28
+
29
+ # 🐚 oshell
30
+
31
+ ### Chat with any LLM, right from your terminal. Local or cloud. Zero config.
32
+
33
+ [![PyPI](https://img.shields.io/badge/pip-oshell-blue)](https://pypi.org/project/oshell/)
34
+ [![Python](https://img.shields.io/badge/python-3.9%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
35
+ [![CI](https://github.com/djaferiurim/oshell/actions/workflows/ci.yml/badge.svg)](https://github.com/djaferiurim/oshell/actions/workflows/ci.yml)
36
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
37
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](#contributing)
38
+
39
+ **One command. Streaming answers. Markdown rendering. Pipe-friendly. Works offline with [Ollama](https://ollama.com) or online with OpenAI.**
40
+
41
+ ![oshell demo](demo.gif)
42
+
43
+ </div>
44
+
45
+ ---
46
+
47
+ ```bash
48
+ $ ai "explain monads like I'm five"
49
+ ```
50
+
51
+ > A monad is like a **box** 📦 you put a value in. The box knows how to
52
+ > open itself, do something with the value, and put the result back —
53
+ > so you never have to unwrap it by hand…
54
+
55
+ *(answer streams in live, rendered as Markdown)*
56
+
57
+ ---
58
+
59
+ ## ✨ Why oshell?
60
+
61
+ - 🚀 **Instant** — ask a question without leaving your shell
62
+ - 🤖 **Coding agent** — it can read, write, and run code to finish a task for you
63
+ - 🎬 **Media agent** — generate images & video, or a multi-scene storyboard
64
+ - 🧠 **Chat with your files** — index a folder and ask questions (local RAG)
65
+ - 🪄 **`ai do`** — turn plain English into a shell command, then run it
66
+ - 🎭 **Personas** — swap the assistant's style with named presets
67
+ - 🔌 **Provider-agnostic** — OpenAI, Anthropic, Groq, Gemini, or local Ollama
68
+ - 🔒 **Private by default** — runs fully offline with Ollama, nothing leaves your machine
69
+ - 🎨 **Beautiful** — live streaming + rich Markdown in the terminal
70
+ - 🪄 **Pipe-friendly** — `cat error.log | ai "what broke?"`
71
+ - 💾 **Remembers** — every chat is saved as a session you can revisit
72
+ - 🪶 **Tiny** — pure Python, four small dependencies, no Node, no Docker
73
+
74
+ ## 📦 Install
75
+
76
+ ```bash
77
+ pip install oshell
78
+ ```
79
+
80
+ That's it. You get two commands: `oshell` and the shortcut `ai`.
81
+
82
+ ## ⚡ Quickstart
83
+
84
+ ### Option A — fully local & free (Ollama)
85
+
86
+ ```bash
87
+ # 1. Install Ollama: https://ollama.com
88
+ ollama pull llama3.2
89
+
90
+ # 2. Chat!
91
+ ai "write a haiku about garbage collection"
92
+ ```
93
+
94
+ ### Option B — OpenAI
95
+
96
+ ```bash
97
+ export OPENAI_API_KEY="sk-..."
98
+ ai --provider openai --model gpt-4o-mini "refactor this regex: ^\d{4}-\d{2}$"
99
+ ```
100
+
101
+ ## 🧑‍💻 Usage
102
+
103
+ ```bash
104
+ # Interactive chat (type /help inside for commands)
105
+ ai
106
+
107
+ # One-shot question
108
+ ai "what's the time complexity of quicksort?"
109
+
110
+ # Pipe context in from anything
111
+ cat main.py | ai "find the bug"
112
+ git diff | ai "write a commit message"
113
+
114
+ # Pick a provider / model on the fly
115
+ ai -p openai -m gpt-4o "summarize the news"
116
+ ai -p anthropic -m claude-3-5-sonnet-latest "explain this"
117
+ ai -p groq -m llama-3.3-70b-versatile "fast answer please"
118
+ ai -p ollama -m qwen2.5-coder "optimize this loop"
119
+
120
+ # List available models
121
+ ai models
122
+ ```
123
+
124
+ ### Inside an interactive session
125
+
126
+ | Command | What it does |
127
+ | --------------- | ---------------------------------- |
128
+ | `/help` | Show available commands |
129
+ | `/clear` | Forget the conversation so far |
130
+ | `/system <txt>` | Change the system prompt on the go |
131
+ | `/exit` | Quit |
132
+
133
+ ## 🤖 Coding agent
134
+
135
+ oshell ships with an autonomous **coding agent** that can read your files,write new ones, and run commands to complete a task — all sandboxed to the
136
+ current directory, and asking before each write or command.
137
+
138
+ ```bash
139
+ # Let the agent build something for you
140
+ ai agent "create a FastAPI hello-world app with a /health endpoint"
141
+
142
+ # Point it at a specific folder
143
+ ai agent -d ./my-project "add unit tests for utils.py and run them"
144
+
145
+ # Skip confirmations (use with care!)
146
+ ai agent --yolo "fix the failing tests"
147
+
148
+ # Interactive mode — keep giving follow-up tasks, agent remembers context
149
+ ai agent -i
150
+ ```
151
+
152
+ How it works: the agent thinks step-by-step and uses a small set of tools —
153
+ `read_file`, `write_file`, `list_dir`, and `run_command`. Every file write and
154
+ shell command shows you a preview and waits for your **yes** (unless `--yolo`).
155
+ It's confined to the workspace root, so it can't touch files elsewhere.
156
+
157
+ > 🔒 **Safety first.** The agent cannot escape the workspace directory, and
158
+ > mutating actions require your approval by default.
159
+
160
+ ## 🎬 Media agent
161
+
162
+ Turn a one-line brief into polished media. The agent first uses the chat LLM
163
+ to **enhance** your brief into a detailed, model-ready prompt (composition,
164
+ lighting, camera, mood…), then generates the image or video.
165
+
166
+ ```bash
167
+ # Images (OpenAI gpt-image-1 / DALL·E 3)
168
+ ai image "a fox in a misty forest at dawn"
169
+ ai image -n 3 -s 1024x1536 "retro sci-fi book cover"
170
+ ai image --raw "exact prompt, no LLM rewrite"
171
+
172
+ # Video (Replicate text-to-video models)
173
+ ai video "a drone shot flying over a neon cyberpunk city at night"
174
+ ai video -m minimax/video-01 "timelapse of a blooming flower"
175
+ ```
176
+
177
+ Generated files are saved to your Pictures folder under `oshell/` (configurable
178
+ via `media_output_dir`).
179
+
180
+ **Setup**
181
+
182
+ ```bash
183
+ # Images reuse your OpenAI key:
184
+ export OPENAI_API_KEY="sk-..."
185
+
186
+ # Video uses Replicate:
187
+ export REPLICATE_API_TOKEN="r8_..."
188
+ # or: ai config set replicate_api_token r8_...
189
+ ```
190
+
191
+ > 💡 Any text-to-video model on [Replicate](https://replicate.com/explore) works —
192
+ > just set `video_model` (e.g. `minimax/video-01`, `luma/ray`, etc.).
193
+
194
+ ### 🎥 Storyboard mode
195
+
196
+ Turn a one-line story into a multi-scene video. The LLM acts as a **director**,
197
+ breaking your brief into scenes, generating an image for each, then stitching
198
+ them into an MP4 (requires `ffmpeg` for the final stitch).
199
+
200
+ ```bash
201
+ ai storyboard "a seed growing into a giant tree across the seasons"
202
+ ai storyboard -n 6 --seconds 3 "the history of computing in 6 frames"
203
+ ```
204
+
205
+ Each scene image is saved too, so you get usable output even without ffmpeg.
206
+
207
+ ## 🧠 Chat with your files (RAG)
208
+
209
+ Index a folder once, then ask questions answered from *your* content. Embeddings
210
+ run locally through Ollama (or OpenAI), and the vector store is plain JSON — no
211
+ heavy dependencies.
212
+
213
+ ```bash
214
+ # With Ollama, grab an embedding model first (one time):
215
+ ollama pull nomic-embed-text
216
+
217
+ ai index ./docs # build the index
218
+ ai ask "how do I configure logging?"
219
+ ai ask -k 8 "summarize the auth flow"
220
+ ```
221
+
222
+ ## 🪄 Natural-language shell (`ai do`)
223
+
224
+ Describe what you want; oshell suggests the exact command and runs it after you
225
+ confirm.
226
+
227
+ ```bash
228
+ ai do "compress all PNGs in this folder"
229
+ ai do "find the 5 largest files under /var/log"
230
+ ```
231
+
232
+ > The command is always shown and requires your **yes** before running.
233
+
234
+ ## 🎭 Personas
235
+
236
+ Swap the assistant's behaviour with named presets (built-ins: `reviewer`,
237
+ `teacher`, `shell`, `rubber-duck`, `concise`, `pirate`).
238
+
239
+ ```bash
240
+ ai --persona reviewer "look at this function" # one-off
241
+ ai persona list # see them all
242
+ ai persona use teacher # set a default
243
+ ai persona add legal "You are a contracts expert. Be precise."
244
+ ```
245
+
246
+ ## ⚙️ Configuration
247
+
248
+ Set defaults once and forget them:
249
+
250
+ ```bash
251
+ ai config set provider openai
252
+ ai config set model gpt-4o-mini
253
+ ai config set openai_api_key sk-...
254
+ ai config show
255
+ ```
256
+
257
+ Or use environment variables: `OPENAI_API_KEY`, `OPENAI_BASE_URL`,
258
+ `ANTHROPIC_API_KEY`, `GROQ_API_KEY`, `GEMINI_API_KEY`, `REPLICATE_API_TOKEN`,
259
+ `OLLAMA_HOST`, `OSHELL_PROVIDER`, `OSHELL_MODEL`.
260
+
261
+ > 💡 Because oshell speaks the OpenAI API, you can point `OPENAI_BASE_URL`
262
+ > at **any** compatible endpoint (Groq, Together, LM Studio, vLLM…).
263
+
264
+ ## 🛠️ Development
265
+
266
+ ```bash
267
+ git clone https://github.com/djaferiurim/oshell
268
+ cd oshell
269
+ pip install -e ".[dev]"
270
+ ai --version
271
+
272
+ # Run the test suite
273
+ pytest
274
+
275
+ # Regenerate the demo GIF (pure Python, no extra tools)
276
+ python tools/make_demo.py demo.gif
277
+ ```
278
+
279
+ ## 🤝 Contributing
280
+
281
+ PRs and ideas welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, project
282
+ layout, and good first issues. Release notes live in [CHANGELOG.md](CHANGELOG.md).
283
+
284
+ ## 📄 License
285
+
286
+ MIT © djaferiurim
@@ -0,0 +1,17 @@
1
+ oshell/__init__.py,sha256=L1E9Xb0wedWKgJk7EoFDFoMrKw6pS1lXHsl-gVTcbZM,85
2
+ oshell/agent.py,sha256=tyxV8QzKcxj9NTFR9tvL02l_nJTSgxzhYOK25UD_Yu4,5346
3
+ oshell/cli.py,sha256=ZmIeLTDwNjY_Y7XLX5siyZCrekkmN6rDiO1Cjjxw1j0,28278
4
+ oshell/config.py,sha256=JRX5z9AG0UjB5iakz2bMVmotb6O_LQPLjcMXFn4LSVM,3086
5
+ oshell/history.py,sha256=Sf_bOhFSTBYdHAuMNVGQHO3oBqkAR4MiWFMbCSPzLYc,1450
6
+ oshell/media.py,sha256=6ejs_cRitK2xnHHMM6SVXF-ckdzFZrP0u_CavPFJ_-Q,6213
7
+ oshell/media_agent.py,sha256=Ur06QMHyK48ZaU2KZfOIGpkDiEYdi_LBkdSJ1Nf5kkY,2335
8
+ oshell/personas.py,sha256=_sDozvDG6dh-yu5LmtDJRmK0PtmuZiuN_9t-jp3LYNc,2860
9
+ oshell/providers.py,sha256=vWHm4B9jmMCnQE8kfTlai59K_WPv6rfO-uH8L6F5Kzc,8809
10
+ oshell/retrieval.py,sha256=Cb8_KQMEIZvgpJLKA8zcy4klm_3w8tycwhXfGqhjzTE,5687
11
+ oshell/storyboard.py,sha256=zIJFBtpTQ9t8EjHmP-nz5leUxYwt5Cq4FTlwPgMiyOI,5451
12
+ oshell/tools.py,sha256=QRKYsLbGBnBnUyZTMVnIR81lELm_4aY8SGhRP2LCS2I,5873
13
+ oshell-0.1.1.dist-info/METADATA,sha256=aIV3A6GaNk-V38WB6VpoVi46-ilwQw2UOFl7-i6U_uU,9138
14
+ oshell-0.1.1.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
15
+ oshell-0.1.1.dist-info/entry_points.txt,sha256=YURcQB5kCTLoT2RgF2pSrbVCJZP6BEuQ8JhPkQQCaXU,76
16
+ oshell-0.1.1.dist-info/licenses/LICENSE,sha256=Ki_ISRgwF3HS1i3jLR5SQSt6PYaJ-7R5EIb0xdK3fXU,1068
17
+ oshell-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ ai = oshell.cli:main_entry
3
+ oshell = oshell.cli:main_entry
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 djaferiurim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.