Metadata-Version: 2.4
Name: temaq-agent
Version: 15.5.1
Summary: Single-purpose AI coding agent powered by llama.cpp -- local-first, terminal-based, MCP-aware.
Author: ek15072809
License: MIT
Project-URL: Homepage, https://github.com/ek15072809/Tema_Q-Agent
Project-URL: Repository, https://github.com/ek15072809/Tema_Q-Agent
Project-URL: Issues, https://github.com/ek15072809/Tema_Q-Agent/issues
Keywords: llm,agent,coding-agent,llama-cpp,mcp,local-llm
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Code Generators
Classifier: Topic :: Text Editors :: Integrated Development Environments (IDE)
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: rich>=13.0.0
Requires-Dist: prompt_toolkit>=3.0.0
Provides-Extra: browser
Requires-Dist: playwright>=1.40.0; extra == "browser"
Provides-Extra: yaml
Requires-Dist: pyyaml>=6.0; extra == "yaml"
Provides-Extra: tokens
Requires-Dist: tiktoken>=0.5.0; extra == "tokens"
Provides-Extra: all
Requires-Dist: playwright>=1.40.0; extra == "all"
Requires-Dist: pyyaml>=6.0; extra == "all"
Requires-Dist: tiktoken>=0.5.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: playwright>=1.40.0; extra == "dev"
Requires-Dist: pyyaml>=6.0; extra == "dev"
Requires-Dist: tiktoken>=0.5.0; extra == "dev"
Dynamic: license-file

<div align="center">

# Tema_Q-Agent

 **Agent for Avant-Garde searching, writing, coding and so on**

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Python 3.9+](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org/downloads/)
[![Version](https://img.shields.io/badge/version-15.5.1-informational.svg)](temaq_agent/__init__.py)

Tema_Q-Agent is a terminal-based coding agent that talks to a **local, OpenAI-compatible `llama.cpp` server** instead of a cloud API. It ships with a file-editing/shell tool loop, a permission engine, session persistence, MCP client support, hooks, checkpoints/undo, persistent memory, an optional Playwright-driven browser tool, and an opt-in RAG-backed security mode.

[Features](#features) •
[Installation](#installation) •
[Quick Start](#quick-start) •
[Usage](#usage) •
[Configuration](#configuration) •
[Slash Commands](#slash-commands) •
[Skills](#skills) •
[Architecture](#architecture) •
[Security](#security-mode) •
[Citation](#citation) •
[License](#license)

</div>

---

<div align="center">
  <img src="docs/screenshot.gif" alt="Tema_Q-Agent running in the terminal" >
</div>

## Overview

Tema_Q-Agent runs entirely against a local model served by `llama.cpp`'s OpenAI-compatible HTTP endpoint, so your code, prompts, and shell output never leave your machine. It exposes a tool-calling agent loop (read/write/edit files, run shell commands, search the web, manage git, look up symbols, save memory/snippets, spawn sub-agents, and more) behind a minimalist terminal UI, with a three-state permission system (`allow` / `ask` / `deny`) standing between the model and your filesystem. Defaults can be set once in a `~/.temaq/config.yaml` file instead of being repeated as CLI flags every time.

## Features

- **Local-first** — talks to any `llama.cpp` server (or compatible endpoint) over a minimal OpenAI-style client; no external API keys required. The client backend (`llama_cpp`, `ollama`, `openai_compat`, `vllm`) is configurable.
- **Two primary agents** — `build` (default, makes changes) and `plan` (read-only planning/analysis).
- **Rich tool set** — `read`, `write`, `edit`, `multiedit`, `patch`, `bash`, `glob`, `grep`, `symbol`, `list`, `todo`, `question`, `webfetch`, `webgrep`, `websearch`, `git`, `memory`, `snippet`, and `task` (sub-agent dispatch), plus any tools exposed by connected MCP servers.
  - `multiedit` applies several edits across one or more files atomically, in a single tool call.
  - `symbol` performs AST-aware symbol search (functions/classes/methods) for Python, with a regex-based fallback for JS/TS/Go/Rust/Java.
  - `git` wraps common git operations (status, diff, add, commit, log, branch, etc.) with sandboxed, structured JSON output; destructive operations still require permission approval.
  - `memory` is a persistent, cross-session key/value fact store backed by a human-readable `~/.temaq/memory.md` file.
  - `snippet` is a file-backed library of reusable prompt/code snippets under `~/.temaq/snippets/`.
- **MCP client** — connect to external [Model Context Protocol](https://modelcontextprotocol.io/) servers (stdio or SSE/HTTP transport) configured in `config.yaml`; their tools become available to the agent alongside the built-in ones.
- **Hooks** — run arbitrary shell commands at `pre_tool` / `post_tool` / `pre_llm` / `post_llm` lifecycle points, with event details (tool name, args, file path, session id, etc.) passed in as environment variables. A non-zero exit from a `pre_tool` or `pre_llm` hook blocks the call.
- **Checkpoints & `/undo`** — before any tool call that could modify workspace files, affected files are snapshotted to `~/.temaq/checkpoints/`; `/undo` restores the most recent checkpoint (including deleting files that were newly created).
- **Auto-compaction & session stats** — older turns are summarized once estimated context usage crosses a configurable budget, and a running count of LLM calls, tool calls, and estimated input/output tokens is available via `/cost` (and an optional footer in the terminal UI).
- **Repo map** — a compact, on-demand file + top-level-symbol tree of the workspace that the agent can consult to navigate a codebase without grepping everything first.
- **`temaq init`** — writes a fully commented starter `~/.temaq/config.yaml`, so configuration doesn't require hand-editing YAML from scratch.
- **Permission engine** — every tool call is checked against a three-state (`allow`/`ask`/`deny`) policy with glob-pattern support, so destructive actions require explicit approval.
- **Sandboxed shell** — the `bash` tool is filtered against a deny-list of destructive patterns (`rm -rf /`, fork bombs, `curl | sh`, disk-device writes, firewall flushes, etc.) before execution.
- **Session persistence** — conversations are saved under `~/.temaq/sessions` and can be resumed with `--session`.
- **Minimalist or classic TUI** — a compact default terminal UI, or `--classic` for the original `rich` + `prompt_toolkit` interface.
- **Optional `--security` mode** — registers a `security_search` tool backed by a user-editable, Markdown-based RAG knowledge base (`security.md`) that the agent consults before generating or reviewing code, so it can recognize and refuse malware-like or phishing-like patterns.
- **Optional `--browser` mode** — a private (incognito), Playwright-driven Chromium tool (`navigate`, `snapshot`, `click`, `type`, `close`) that shares no cookies, credentials, or history with your main browser profile.
- **Optional `--server` mode** — launches a stdlib-only HTTP server that reproduces the terminal UI in a browser, so any device on the LAN can connect and operate the agent (see [Usage](#usage) for `--host`/`--port`).
- **Compatibility flags** — `--nomemory` disables the `memory` tool, `--no-mcp` / `--no-checkpoints` / `--no-hooks` disable the corresponding subsystem, and `--v9.0.0` reproduces the pre-config-file, pre-MCP/hooks/checkpoints tool set and behavior exactly, for cases where one of these subsystems needs to be ruled out.
- **Bundled sample templates** — the `read`/`edit`/`list` tools can browse and copy from a set of read-only starter HTML templates under `sample/` without ever mutating the originals.
- **Project rules** — drop an `AGENTS.md` into your workspace (or `~/.temaq/AGENTS.md` globally) to give the agent persistent project-specific instructions.
- **Skills** — Claude-compatible skills stored in a `skill/` directory. Each skill is a folder with a `SKILL.md` (YAML frontmatter + Markdown body). Skills auto-invoke when the model decides a task matches a skill's description, or can be activated explicitly with `/<skill_name>`. Skills not found locally are fetched automatically from the `Tema_Q-Agent-skill` repo `https://github.com/ek15072809/Tema_Q-Agent-skill`.

## Architecture

```
Tema_Q-Agent/
├── agent.py               # entry point (auto-installs Playwright/Chromium)
├── temaq_agent.py          # thin entry point (no Playwright bootstrap)
├── security.md             # editable RAG knowledge base for --security mode
├── temaq_agent/
│   ├── cli.py               # argparse, workspace bootstrap, runtime wiring
│   ├── config.py             # constants & env-driven configuration
│   ├── user_config.py        # ~/.temaq/config.yaml loader + `temaq init` writer
│   ├── runtime.py            # agent tool-call loop, auto-compaction, session stats
│   ├── agents.py             # built-in agent presets (build / plan)
│   ├── agents_security.py    # security-mode prompt augmentation
│   ├── agents_browser.py     # browser-mode prompt augmentation
│   ├── llm.py                 # minimal OpenAI-compatible llama.cpp client
│   ├── http_util.py           # shared HTTP helpers for the llama.cpp client
│   ├── tokenizer.py           # dependency-free token estimator (tiktoken fallback)
│   ├── permissions.py         # three-state permission engine
│   ├── sandbox.py             # destructive shell-command filter
│   ├── security_rag.py        # security.md indexer / retriever
│   ├── session.py             # session persistence
│   ├── subagent.py            # sub-agent (task tool) dispatch
│   ├── rules.py               # AGENTS.md project-rule loader
│   ├── skills.py              # Claude-compatible skill discovery / fetch
│   ├── thinking.py            # strips model-emitted reasoning from visible output
│   ├── mcp_client.py          # MCP client (stdio / sse / http transports)
│   ├── hooks.py               # pre/post tool & LLM shell-command hooks
│   ├── checkpoint.py          # file snapshotting for /undo
│   ├── repo_map.py            # compact file + symbol tree for context
│   ├── cui.py / cui_fix.py    # terminal UI implementations
│   ├── cui_security.py        # red theme applied in --security mode
│   ├── sample/                 # bundled read-only HTML templates (used by read/edit/list tools)
│   ├── tools/                  # individual tool implementations
│   │   ├── multiedit.py          # atomic batch edits across files
│   │   ├── symbol.py             # AST-aware symbol search
│   │   ├── git.py                # sandboxed git operations
│   │   ├── memory.py             # persistent cross-session memory
│   │   ├── snippet.py            # reusable snippet library
│   │   ├── browser.py            # Playwright browser tool (--browser)
│   │   └── security_search.py    # security RAG search (--security)
│   └── web/                    # HTTP server + browser-based CUI for --server mode
├── scripts/                # smoke / visual-check scripts
└── tests/                  # unit tests + mock llama.cpp server
```

## Installation

### Prerequisites

- Python 3.9+
- A running [`llama.cpp`](https://github.com/ggerganov/llama.cpp) server exposing an OpenAI-compatible endpoint (default: `http://127.0.0.1:8080`)

### Steps

```bash
git clone https://github.com/ek15072809/Tema_Q-Agent.git
cd Tema_Q-Agent
pip install -r requirements.txt
```

The `--browser` flag requires Playwright:

```bash
pip install playwright
playwright install chromium
```

When launched from agent.py, the installation of playwright and chromium, and the activation of the UI display will be applied.

> Running `agent.py` directly will attempt to install Playwright and Chromium automatically the first time it starts.

### Installing as a command (`temaq` / `temaq-agent`)

Instead of invoking `python agent.py` directly, you can install the package in editable mode to get the `temaq` and `temaq-agent` console commands on your `PATH`:

```bash
pip install -e .
# optional extras, e.g. browser tool + YAML config + tiktoken:
pip install -e ".[all]"
```

Once installed, run the agent from any directory with:

```bash
temaq
# or
temaq-agent
```

Both commands accept the same flags as `python agent.py` / `python temaq_agent.py` (see [Usage](#usage) below). Note that `agent.py`'s automatic Playwright/Chromium bootstrap only runs when launching via `python agent.py` directly; when using the installed `temaq`/`temaq-agent` command, install Playwright manually first if you plan to use `--browser`.

## Quick Start

1. Start your local `llama.cpp` server:

   ```bash
   ./llama-server -m /path/to/your-model.gguf --host 127.0.0.1 --port 8080
   ```

2. (Optional) Write a starter config file:

   ```bash
   python agent.py init
   ```

3. Launch the agent from your project directory:

   ```bash
   python agent.py
   ```

4. Or run a single non-interactive prompt:

   ```bash
   python agent.py --prompt "Summarize the structure of this repository"
   ```

## Usage

```
usage: Tema_Q-Agent [-h] [--agent {build,plan}] [--model MODEL] [--url URL]
                     [--prompt PROMPT] [--session SESSION] [--auto]
                     [--max-steps MAX_STEPS] [--timeout TIMEOUT]
                     [--workspace WORKSPACE] [--classic] [--security]
                     [--browser] [--server] [--host HOST] [--port PORT]
                     [--nomemory] [--v9.0.0] [--no-mcp] [--no-checkpoints]
                     [--no-hooks] [--config CONFIG] [--version]
                     {init} ...
```

| Flag | Description |
|---|---|
| `--agent {build,plan}` | Primary agent to start with (default: `build`) |
| `--model MODEL` | Model id sent to the llama.cpp server |
| `--url URL` | llama.cpp server URL (default: `http://127.0.0.1:8080`) |
| `--prompt PROMPT` | Run a single prompt non-interactively |
| `--session SESSION` | Resume a previous session by id |
| `--auto` | Auto-approve non-`deny` permissions |
| `--max-steps N` | Override the agent's max tool-call steps |
| `--timeout N` | LLM request timeout in seconds (default: 900) |
| `--workspace DIR` | Workspace directory (default: `./workspace`) |
| `--classic` | Use the original `TemaQCUI` instead of the default minimalist TUI |
| `--security` | Enable security mode (see [below](#security-mode)) |
| `--browser` | Enable the sandboxed Playwright browser tool |
| `--server` | Launch a web server instead of the terminal CUI, so any device on the LAN can operate the agent from a browser |
| `--host HOST` | Bind address for `--server` mode (default: `0.0.0.0`) |
| `--port PORT` | TCP port for `--server` mode (default: `8765`) |
| `--nomemory` | Disable the persistent `memory` tool |
| `--v9.0.0` | Disable MCP, hooks, checkpoints, the config file, and the added tools (`multiedit`, `git`, `symbol`, `memory`, `snippet`), reproducing the earlier fixed tool set |
| `--no-mcp` | Don't start any configured MCP servers |
| `--no-checkpoints` | Disable the checkpoint/undo system |
| `--no-hooks` | Disable the hooks system |
| `--config PATH` | Path to a config file (default: `~/.temaq/config.yaml`) |
| `--version` | Print the version and exit |
| `init` | Write a starter `config.yaml` to `~/.temaq/` and exit (`--force` to overwrite) |

Configuration can also be supplied via environment variables, including `LLAMA_CPP_URL`, `TEMAQ_MODEL`, `TEMAQ_LLM_TIMEOUT`, `TEMAQ_HOME`, `TEMAQ_WORKSPACE`, `TEMAQ_MAX_STEPS`, `TEMAQ_AUTOMODE`, and per-tool network budgets (`TEMAQ_MAX_WEBFETCH_PER_TURN`, `TEMAQ_MAX_WEBSEARCH_PER_TURN`, `TEMAQ_MAX_WEBGREP_PER_TURN`).

## Configuration

Running `python agent.py init` writes a commented starter file to `~/.temaq/config.yaml` (or pass `--config PATH` to use a different location). Priority order, later wins: built-in defaults → config file → environment variables → CLI flags. The config file can set, among other things:

- `llm:` — server URL, model name, timeout, temperature, max tokens, and backend type (`llama_cpp`, `ollama`, `openai_compat`, `vllm`)
- `agent`, `workspace`, `max_steps`, `auto`, `security`, `browser`, `server`, `host`, `port`
- `web_search:` — provider (`duckduckgo` by default, or `brave`/`tavily`/`serper` with an API key) and result count
- `mcp_servers:` — a list of MCP server entries (`name`, `transport`, `command`/`args`/`env` for stdio, or `url` for sse/http)
- `hooks:` — `pre_tool` / `post_tool` / `pre_llm` / `post_llm` shell commands
- `context_budget`, `context_keep_recent`, `show_token_footer` — auto-compaction and token-footer behavior
- `enable_checkpoints`, `max_checkpoints` — checkpoint/undo behavior

Unknown keys are kept but ignored, so the schema is forward-compatible.

## Slash Commands

| Command | Description |
|---|---|
| `/new`, `/clear` | Clear the conversation and start a new session |
| `/sessions` | List saved sessions |
| `/resume` | Resume a session by id |
| `/compact` | Summarize older messages to free context |
| `/agent` | Switch active agent (`build` \| `plan`) |
| `/tools` | List tools available to the current agent |
| `/rules` | Show loaded project rules |
| `/save` | Force-save the current session |
| `/export` | Export the current session to markdown |
| `/history` | Show this session's conversation history |
| `/models` | Show configured model + server status |
| `/workspace` | Show / open the workspace directory |
| `/auto` | Toggle auto-approve-all mode on/off |
| `/about` | Print version & config |
| `/cost` | Show this session's token / call stats |
| `/undo` | Undo the most recent file-modifying tool call |
| `/diff` | Show uncommitted changes (`git diff`) in the workspace |
| `/mcp` | List connected MCP servers and their tools |
| `/memory` | List entries in the persistent memory store |
| `/snippet` | List saved snippets |
| `/checkpoint` | Show recent checkpoint history |
| `/repomap` | Print a compact repo map (file + symbol tree) |
| `/skills` | List installed skills ; type `/<skill_name>` to use one |

## Skills

v14.0.0 introduces **Claude-compatible skills** — reusable instruction sets the agent loads on demand. Skills are simpler to set up than MCP servers: just drop a folder into the `skill/` directory.

The skill is available at `https://github.com/ek15072809/Tema_Q-Agent-skill`. Please download it and place it in the `skill` folder, or install it individually using the command.

### Main skills

The `Tema_Q-Agent-skill` repo currently ships the following skills. Each one can be installed individually with `/<skill_name>` (see [On-demand fetch](#three-ways-to-use-a-skill) below), or all at once by downloading the whole repo into `skill/`.

| Skill | What it does |
| --- | --- |
| `docx` | Generates Microsoft Word (`.docx`) files with `python-docx` — TOC, styles, tables, images, headers/footers. |
| `pptx` | Generates PowerPoint (`.pptx`) files with `python-pptx` — master layouts, tables, charts, shapes. |
| `xlsx` | Generates Excel (`.xlsx`) files with `openpyxl` — multi-sheet, formulas, charts, conditional formatting. |
| `pdf` | Generates PDFs from HTML (via headless Chromium) or converts Office files to PDF (via LibreOffice). |
| `mail` | Drafts emails and letters in Japanese or American business/personal style. |
| `note` | Writes note.com articles, researching trending posts and following note.com's markdown conventions. |
| `law` | Produces lawyer-level legal analysis and drafting by jurisdiction (JP/US/EU); not formal legal advice. |
| `stock` | Proposes concrete buy/sell strategies for JP/US equities with entry, take-profit, and stop-loss levels; not investment advice. |
| `recipe` | Plans nutritionally balanced daily/weekly meals with sourced nutritional data. |
| `book-writing` | Writes long-form (~80,000-word) novels without quality collapse across chapters. |
| `brainstorming` | Turns a vague idea into a concrete, decision-ready design through structured questioning. |
| `art` | Applies design judgment (color, typography, layout, UI/UX) so output doesn't look "AI-made". |
| `cad` | Builds parametric 3D CAD models with CadQuery, exporting to STEP/STL/OBJ/AMF/SVG/DXF. |
| `html-game` | Builds single-file, production-quality HTML5 games. |
| `meeting` | Analyzes meeting transcripts for behavioral patterns (speaking ratio, filler words, conflict avoidance). |
| `tailored-resume` | Tailors a resume to a specific job posting by matching required keywords and experience. |
| `target-company` | Finds and scores B2B sales prospects and proposes an outreach strategy. |
| `video-downloader` | Downloads videos (via `yt-dlp`) or extracts video URLs from pages (via `--browser`). |
| `x-post` | Rewrites X (Twitter) posts for reach/engagement based on the public ranking-algorithm source. |
| `use-gpts` | Delegates sub-tasks to external LLM web apps (ChatGPT, Claude.ai, Gemini, Perplexity) via `--browser` mode. |
| `skill-maker` | Meta-skill that guides designing, authoring, testing, and publishing new SKILL.md-format skills. |

### Directory layout

Create a `skill/` directory at your project (workspace) root. Each sub-directory is one skill, identified by its folder name:

```
skill/
  └── pr-review/
        └── SKILL.md
```

Here `pr-review` is the skill name. A `SKILL.md` file has YAML frontmatter and a Markdown body:

```markdown
---
name: pr-review
description: Use this skill when the user asks to review a pull request or check code quality before merging.
---

# PR Review Skill

1. Read the diff with `git(operation=diff)`.
2. Check for ...
3. Summarize findings ...
```

The `description` field is shown to the model in the system prompt so it can decide when a skill is relevant. The body is the full instruction set the model follows once the skill is activated.

### Three ways to use a skill

1. **Auto-invoke (default).** The system prompt lists every installed skill with its description. When the user's task matches, the model reads `skill/<name>/SKILL.md` with the built-in `read` tool and follows the instructions — no command needed.

2. **Explicit slash command.** Type `/<skill_name>` in the prompt. The skill content is loaded into the system prompt for the rest of the session. Append a prompt to run it immediately: `/pr-review review the latest commit`.

3. **On-demand fetch.** If `/<skill_name>` refers to a skill not present locally, the agent downloads it automatically from the `Tema_Q-Agent-skill` repo `https://github.com/ek15072809/Tema_Q-Agent-skill` within Python, before any LLM call, and installs it into `skill/<skill_name>/`.

### Claude directory skills

Skill file groups downloaded from `https://claude.ai/directory/skills/` can be imported directly — drop the folder into `skill/` and it works, as long as the skill does not require Claude account authentication.

### `/skills` command

Typing `/skills` lists all installed skills (name, description, path) and shows how many are active in the current session.

## Security Mode

Passing `--security` registers an additional `security_search` tool backed by a user-editable, plain-Markdown knowledge base (`~/.temaq/security.md`). Unlike a generic secure-coding guide, this file is meant to document what a general-purpose LLM typically lacks context on:

1. The structure of real malware, so the agent can recognize and strip virus-like patterns from code it generates or reviews.
2. The structure of phishing pages and scam sites, so the agent can detect and refuse to generate them.
3. The deep technical mechanism behind vulnerability classes, so the agent understands *why* a pattern is exploitable rather than following a simple denylist.

The system prompt instructs the agent to consult this knowledge base before writing or modifying code. The file is freely editable — add real cases, environment-specific notes, or preferred code examples, and the built-in indexer will pick them up automatically (it splits content by Markdown headers and fenced code blocks).

## Testing

```bash
pip install pytest
pytest tests/
```

`tests/mock_llama_server.py` provides a lightweight mock of the llama.cpp OpenAI-compatible endpoint for running tests without a real model server.

## Contributing

Issues and pull requests are welcome. Please open an issue first to discuss significant changes.

## Citation

If you use Tema_Q-Agent in your research or projects, please cite it as:

```bibtex
@software{temaq_agent2026,
  author  = {ek15072809},
  title   = {Tema_Q-Agent: Agent for Avant-Garde searching, writing, coding and so on},
  year    = {2026},
  url     = {https://github.com/ek15072809/Tema_Q-Agent},
  version = {15.5.1}
}
```

## License

This project is licensed under the [MIT License](LICENSE).

## Disclaimer

Tema_Q-Agent grants a locally running LLM the ability to read, write, and execute commands on your machine. Review the [permission engine](temaq_agent/permissions.py) and [sandbox filters](temaq_agent/sandbox.py) before use, run it in an isolated environment when possible, and always inspect model-generated shell commands before approving them.

## Author

**ek15072809**
