Metadata-Version: 2.5
Name: quark-ai
Version: 0.3.0
Summary: Lightning-fast micro-agent. A stripped-down alternative to heavy AI agents, executing tasks with minimal prompt overhead.
Project-URL: Homepage, https://github.com/rmoya81/Quark
Project-URL: Repository, https://github.com/rmoya81/Quark
Project-URL: Issues, https://github.com/rmoya81/Quark/issues
Author: rmoya81
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: textual>=0.80
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Description-Content-Type: text/markdown

# Quark

[![PyPI](https://img.shields.io/pypi/v/quark-ai)](https://pypi.org/project/quark-ai/)

Lightning-fast micro-agent. A stripped-down alternative to heavy AI agents, executing tasks with minimal prompt overhead.

Quark is a minimal CLI agent loop: send a message, let the model call tools (read/edit/write files, list directories, search file names/contents, optionally run shell commands), and get an answer back — with conversation history persisted to disk between runs. It talks to any LLM provider through a small abstraction layer (Anthropic, OpenAI, and Ollama/any OpenAI-compatible endpoint included) instead of depending on a heavy vendor SDK.

Two things it optimizes for on purpose:
- **Lightweight**: no framework, no heavy SDKs (just `httpx`), a short default system prompt, and an `edit_file` tool so the model can make targeted changes instead of re-sending whole files.
- **Productive by default, secure by default**: file tools are confined to a workspace directory (symlink escapes included), `run_shell` is off unless you opt in, and if a `QUARK.md`/`AGENTS.md` file exists it's folded into the system prompt automatically so the agent already knows about your project.

## Install

Requires Python 3.10+. Works anywhere Python does, including WSL2 — nothing platform-specific.

From [PyPI](https://pypi.org/project/quark-ai/):

```bash
pip install quark-ai
```

This installs the `quark` command (the PyPI distribution name doesn't have to match the console script it installs), including the terminal UI (`textual`) — see [Terminal UI](#terminal-ui) below.

On Debian/Ubuntu (including most current WSL2 distros), a bare `pip install` is blocked by default with `externally-managed-environment` (PEP 668). Use [pipx](https://pipx.pypa.io/) instead — it installs CLI tools like Quark in their own isolated environment and puts them on your `PATH`:

```bash
sudo apt install pipx
pipx ensurepath
# open a new terminal (or: source ~/.bashrc)
pipx install quark-ai
```

For local development, clone the repo instead:

```bash
./install.sh
```

Creates `.venv`, installs Quark editable with dev deps, and copies `.env.example` to `.env` if you don't already have one. Safe to re-run (reuses the venv, never overwrites an existing `.env`).

Or by hand:

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
```

## Configure

### Interactive setup (recommended)

The first time you run `quark chat` or `quark tui`, if nothing has been configured yet, Quark asks a short series of questions — provider, model (for Ollama it detects your locally pulled models and lets you pick one), workspace, tool mode, whether to allow `run_shell` — and saves your answers to `~/.quark/config.json` so you never have to repeat the same flags again. Entirely local: this wizard never contacts a model or sends any context anywhere, except one optional ping to your own Ollama server to list its models.

```bash
quark chat "hola"   # first run only: asks a few questions, then answers
quark chat "qué hora es"   # every run after: no questions, uses what you picked
```

Re-run it anytime with `quark init`, or edit `~/.quark/config.json` directly. Any `--flag` or env var still overrides a saved value for a single run — saved config is just the fallback default. If an API key is entered during setup, it's saved to `~/.quark/.env` (`chmod 600`), never into `config.json`.

Skipped automatically for non-interactive use (piped input, CI, no tty) so it can never hang waiting on a prompt that can't arrive.

### Manual configuration

Alternatively, copy `.env.example` to `.env` (done automatically by `install.sh`) and fill in the key(s) for the provider(s) you want to use:

```bash
cp .env.example .env
```

```
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
QUARK_PROVIDER=anthropic
```

`.env` is loaded automatically from the current working directory, then `~/.quark/.env` as a fallback. You can also export the variables directly, or pass `--api-key` on the command line.

## Usage

```bash
# One-shot message, prints the reply and exits
quark chat "list the files in this directory"

# Interactive REPL (Ctrl+D or 'exit' to quit)
quark chat

# Choose a provider/model
quark --provider openai --model gpt-4o chat "what's in README.md?"

# Run fully locally against Ollama (ollama serve + ollama pull llama3.2 first) — no API key needed
quark --provider ollama chat "what's in README.md?"

# Named sessions keep separate histories on disk
quark --session project-a chat "remember that we're using Postgres"
quark --session project-a chat "what database are we using?"

# Confine file tools to a specific directory (default: cwd)
quark --workspace ./my-project chat "list the files here"

# Opt in to the run_shell tool (off by default)
quark --allow-shell chat "run the test suite"

# Read-only mode: only read_file + list_dir, smallest tool-schema footprint, no escape hatch
quark --minimal-tools chat "what does this project do?"

# Progressive mode: starts like --minimal-tools, but the model can unlock
# write_file/edit_file/delete_file itself the moment it actually needs them
quark --progressive-tools chat "fix the typo in README.md"

# Print the full reply at once instead of streaming it token by token
quark --no-stream chat "what's in README.md?"

# Lower the threshold for auto-summarizing older turns (in estimated tokens)
quark --compact-threshold 4000 chat "..."

# Redo the interactive setup, or set it up for the first time without waiting for a prompt
quark init

# Manage sessions
quark sessions list
quark sessions clear project-a
```

Sessions are stored as JSON under `~/.quark/sessions/<name>.json`.

### Terminal UI

```bash
quark
```

Running `quark` with no subcommand launches the terminal UI by default — a scrollable chat with rendered markdown (real tables, not raw `| pipes |`), colored bubbles per role, a fixed input box, and streaming replies — the same way running bare `claude` does. You can also ask for it explicitly with `quark tui`. All the usual flags apply (`--provider`, `--model`, `--session`, `--workspace`, etc.):

```bash
quark --provider ollama --model qwen3.5-4b-coder-128k:latest
```

It's a thin view on top of the same `Agent` used everywhere else — no separate request/tool/session logic, so anything that works in `quark chat` works in the TUI. `textual` is a core dependency, so `pip install quark-ai` pulls it in automatically; if it's somehow missing, bare `quark` falls back to the plain `quark chat` REPL instead of erroring out.

Not shown yet in the TUI: individual tool calls (you'll see the final reply, not "calling read_file…" in between) and `quark sessions`/`--compact-threshold` have no visual equivalent — those still need the regular CLI.

### Local models (Ollama, or any OpenAI-compatible endpoint)

```bash
ollama serve                 # if not already running
ollama pull llama3.2         # or whatever model you want
quark --provider ollama chat "hola"
```

`--provider ollama` reuses the OpenAI provider against Ollama's OpenAI-compatible API (`http://localhost:11434/v1` by default) — no API key required, nothing to configure beyond having Ollama running. Override the endpoint with `--base-url` (also `QUARK_BASE_URL`), which works for `--provider openai` too — useful for any other OpenAI-compatible server (vLLM, LM Studio, a proxy, etc.), not just Ollama. Tool-calling quality depends entirely on the local model: not every model Ollama can run supports it well, so results with `write_file`/`edit_file`/etc. will vary more than with Claude or GPT.

### Project context

If a `QUARK.md` or `AGENTS.md` file exists at the workspace root, its contents are appended to the system prompt automatically — a cheap way to give the agent standing context (stack, conventions, gotchas) without repeating it every session.

### Progressive tool disclosure

`--progressive-tools` (also `QUARK_PROGRESSIVE_TOOLS=1`) starts a turn with just `read_file`, `list_dir`, and one cheap extra tool, `request_more_tools` (no parameters). Its description tells the model to call it if it needs to write, edit, or delete files. If the model calls it, Quark registers `write_file`/`edit_file`/`delete_file` on the spot, drops `request_more_tools` (no longer needed), and the *same* `agent.step()` call retries with the expanded set — so the model still gets everything it needs, in the same turn, it just asks first.

This is deliberately not a heuristic: matching intent from text (keywords, embeddings, a classifier) always trades accuracy for cost and can silently withhold a tool the model actually needed on some phrasing you didn't anticipate. Letting the model itself request more tools can't misfire that way — the only cost is one extra round trip, and only on turns that actually mutate something. `run_shell` stays independently gated behind `--allow-shell`; progressive mode never unlocks it.

`--minimal-tools` is the stricter sibling: same starting set, but with no `request_more_tools` escape hatch at all, for when you want a hard read-only guarantee. Passing both flags together, `--minimal-tools` wins.

### Streaming

Replies print as the model generates them — both providers use `stream: true` and parse server-sent events, calling back into the CLI for each text chunk. Tool calls are accumulated silently (their JSON arguments arrive fragmented) and only run once complete; nothing changes about tool behavior, just how text reaches your terminal. Pass `--no-stream` to wait for the full reply and print it in one shot instead (e.g. for piping output into another program).

### Context compaction

Quark estimates the session's token count (a `len(text) // 4` heuristic — no tokenizer dependency) before each turn. Once it's over `--compact-threshold` (default 20000, also `QUARK_COMPACT_THRESHOLD`), it asks the model for a short summary of the older turns and folds that summary into the oldest turn it keeps, dropping everything before it. It only ever cuts at a turn boundary — right after a completed assistant reply, never mid-tool-call — so this can't break the strict user/assistant alternation Anthropic's API requires. Pass `--compact-threshold 0` to disable it.

### Token overhead

On the first turn (empty session), before the model generates anything, Quark sends the system prompt plus the JSON schema of every registered tool. Rough token counts (`tiktoken` `cl100k_base`, an approximation — Claude's real tokenizer isn't public — but the right order of magnitude either way):

| Mode | Tools registered | Tool-schema tokens | Total (system + tools + a short message) |
|---|---|---|---|
| default | `read_file`, `list_dir`, `search_files`, `write_file`, `edit_file`, `delete_file` | ~530 | ~565 |
| `--minimal-tools` | `read_file`, `list_dir`, `search_files` | ~270 | ~305 |
| `--progressive-tools`, before unlocking | `read_file`, `list_dir`, `search_files`, `request_more_tools` | ~315 | ~350 |
| `--progressive-tools`, after unlocking | same as default | ~530 | ~565 |
| default + `--allow-shell` | + `run_shell` | ~530 + ~80 | ~650 |

`--minimal-tools` is cheapest but can never write/edit/delete. `--progressive-tools` costs a little more than minimal on read-only turns (~350 vs ~305) but is capability-equivalent to the default the moment it's actually needed — it only pays the full ~565 on turns that mutate something. `search_files` is in every mode, including minimal, since searching never mutates anything. Every subsequent turn in a session also carries the accumulated conversation history on top of these numbers.

## Architecture

```
quark/
  message.py       Internal Message/ToolCall representation
  session.py        Persistent, named conversation history
  agent.py           The chat + tool-calling loop
  compact.py          Token-threshold-based history summarization
  providers/          Provider abstraction (unified request/response shape)
    base.py
    anthropic.py       Anthropic Messages API, streamed (SSE)
    openai.py           OpenAI Chat Completions API, streamed (SSE) — also backs --provider ollama
  tools/               Built-in tools the agent can call
    base.py             Tool + ToolRegistry
    workspace.py         Path confinement (resolve_within)
    fs.py                read_file / write_file / edit_file / delete_file / list_dir
    search.py            search_files (literal filename/content search)
    shell.py             run_shell (opt-in)
    meta.py              request_more_tools (--progressive-tools)
  cli.py               argparse-based entry point
  onboarding.py        Interactive first-run setup (quark init)
  tui.py               Textual UI (default bare `quark` invocation, also `quark tui`)
```

Adding a provider means implementing `Provider.complete()` in `quark/providers/` and registering it in `quark/providers/__init__.py`. Adding a tool means subclassing `Tool` in `quark/tools/` and adding it to `default_registry()`.

## Security note

- `read_file`, `write_file`, `edit_file`, `delete_file`, and `list_dir` are confined to `--workspace` (default: the current directory); paths that escape it, including via symlinks, are rejected.
- `run_shell` executes arbitrary shell commands and is **off by default** — enable it with `--allow-shell` or `QUARK_ALLOW_SHELL=1` only when you trust the prompts/provider you're running against.
- `write_file` and `delete_file` still mutate the filesystem inside the workspace without asking for confirmation. Only point Quark at trusted providers/prompts, and run it in an environment you're comfortable with an autonomous agent touching.
- If you enter an API key during `quark init`, it's written in plaintext to `~/.quark/.env` (permissions set to `600`, readable only by you) — never to `~/.quark/config.json`, which holds only non-secret preferences (provider, model, workspace, tool mode).

## Development

```bash
pip install -e ".[dev]"
pytest
```

Tests mock the HTTP layer (`httpx.stream`), so the suite runs offline with no API keys required. The TUI test uses Textual's headless `run_test()` (via `pytest-asyncio`, a dev-only dependency) and sticks to a smoke check — mount, type, submit, see the bubble — since asserting on the agent's actual reply would mean waiting on a background worker thread from the test, which is a source of flaky CI. `Agent.step()` itself already has non-flaky coverage in `tests/test_agent.py` and `tests/test_compact.py`.

## Publishing to PyPI

Published as [`quark-ai`](https://pypi.org/project/quark-ai/). `.github/workflows/publish.yml` publishes to PyPI via [Trusted Publishing](https://docs.pypi.org/trusted-publishers/) (OIDC) whenever a GitHub Release is published — no API token stored in the repo. The pending-publisher setup (PyPI project `quark-ai`, owner `rmoya81`, repository `Quark`, workflow `publish.yml`, environment `pypi`) is already done; a new release is just:

1. Bump `version` in `pyproject.toml` and merge that to `main`.
2. Cut a GitHub Release with a matching tag (e.g. `v0.2.0`) — the workflow builds the sdist/wheel and publishes them automatically.

(`quark` and `quark-agent` were already taken by unrelated projects on PyPI, which is why the distribution name is `quark-ai` instead — the installed command is still `quark`.)
