Metadata-Version: 2.4
Name: smerkil
Version: 0.11.2
Summary: SMERKIL Agent — a production harness for building, evaluating and operating autonomous AI agents.
Author: SMERKIL Technologies
License: Apache-2.0
Keywords: agents,ai,harness,llm,tool-loop
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# SMERKIL Agent

A production harness for building, evaluating and operating autonomous AI agents.
Zero dependencies — stdlib only. Model-agnostic (any OpenAI-compatible endpoint).

## Install

**PyPI (any OS, Python 3.9+)**
```bash
pip install smerkil
# or isolated:  uvx smerkil   /   pipx install smerkil
```

**Linux / macOS / WSL**
```bash
curl -fsSL https://smerkil-technologies.vercel.app/install.sh | bash
```

**Windows (PowerShell)**
```powershell
irm https://smerkil-technologies.vercel.app/install.ps1 | iex
```

> In `cmd.exe` there is no `bash` of its own — `curl ... | bash` there runs your
> WSL/Git-Bash Linux, and the result lives inside that Linux, not in Windows.
> Use PowerShell for a native Windows install.

**Any platform, manual**
```bash
pip install --user https://smerkil-technologies.vercel.app/smerkil-0.11.2.tar.gz
# or isolated:  uv tool install <tarball>   /   pipx install <tarball>
```
Requires Python 3.10+. The installers verify the tarball's sha256 first.

```bash
# first run: pick a provider, paste your key, any base URL you like.
# the wizard probes the endpoint and sends one live message before it says "ok"
smerkil init

# ...or answer it all in one line (no prompts)
smerkil init work --base-url https://generativelanguage.googleapis.com/v1beta \
                 --model gemini-2.5-flash --key "$GEMINI_API_KEY"

# just run it — no arguments = the chat UI
smerkil

# scaffold an agent with a role preset
smerkil new my-agent --role coder   # general|coder|researcher|reviewer|writer

# edit agent.yaml (model, tools, guardrails), export a key...
export SMERKIL_API_KEY=sk-...
export SMERKIL_BASE_URL=https://api.openai.com/v1   # or any compatible endpoint

# run it
smerkil run my-agent --goal "Summarize ./notes/ and write brief.md"

# interactive session — streaming text AND tool-call args, persistent history
smerkil chat my-agent

# expose the agent as an HTTP API
smerkil serve my-agent --token $SERVE_TOKEN

# check environment, key, model reachability, workspace health
smerkil doctor my-agent

# check behavior before you ship
smerkil eval my-agent

# replay any run
smerkil trace list
smerkil trace my-agent --show <run-id>
```

## Providers and base URLs

Any endpoint that speaks `POST {base_url}/chat/completions` works. `smerkil init`
writes both `base_url` and `api_key_env` into `agent.yaml`; you can also pass
`--base-url` / `--model` on the command line for a single run, or set
`SMERKIL_BASE_URL`.

| Provider | base_url | key env |
|---|---|---|
| Google AI Studio (Gemini) | `https://generativelanguage.googleapis.com/v1beta/openai` | `GEMINI_API_KEY` |
| OpenAI | `https://api.openai.com/v1` | `OPENAI_API_KEY` |
| OpenRouter | `https://openrouter.ai/api/v1` | `OPENROUTER_API_KEY` |
| DeepSeek | `https://api.deepseek.com/v1` | `DEEPSEEK_API_KEY` |
| Groq | `https://api.groq.com/openai/v1` | `GROQ_API_KEY` |
| Mistral | `https://api.mistral.ai/v1` | `MISTRAL_API_KEY` |
| Ollama (local) | `http://localhost:11434/v1` | — |
| anything else | your own URL | any name you pick |

A URL is normalised for you: a bare host gets `https://`, a trailing
`/chat/completions` is dropped, and `generativelanguage.googleapis.com`
gets the `/v1beta/openai` compatibility path appended. If `base_url` is missing
but `api_key_env` is a known provider key (`GEMINI_API_KEY`, `GROQ_API_KEY`, …),
the endpoint is inferred from the key — that is why a Google key no longer
fails against the OpenAI default.

Keys are stored in `~/.smerkil/credentials.env` (mode 0600) and never printed
back in full.

## What's inside

- **Tool loop runtime** — deterministic loop, parallel tool execution (a thread pool runs all tool calls from one model turn concurrently, results appended in deterministic order), token & turn budgets, hard stop on runaway loops.
- **Multi-turn chat** — `Agent.run(goal, history=[...])` records user, assistant and tool turns incrementally; context compaction can never tear a session apart. `smerkil chat` is a streaming REPL (`/reset`, `/tokens`, `/exit`).
- **Role presets** — `--role coder|researcher|reviewer|writer|general` scaffolds a tuned system prompt and tool set (coder/reviewer get the shell).
- **HTTP API** — `smerkil serve` exposes the agent over a stdlib HTTP server: `POST /v1/chat` (multi-turn, per-session history + shared session budget), `GET /sessions`, `GET /health`, `GET /live`; optional bearer-token auth.
- **Live status** — `smerkil status` finds a running server via its heartbeat file (`~/.smerkil/serve.json`) and reports which sessions are actually executing right now; `--json` for scripting.
- **Usage report** — `smerkil report` aggregates every agent's on-disk traces into one document (runs, turns, tool calls, tokens, cost, stop reasons, top tools); `smerkil push` sends it to a dashboard, opt-in.
- **Subagents** — the `subagent` tool spawns isolated child agents with their own context and goal; the child's final answer returns as a tool result. Children cannot spawn further subagents (bounded depth).
- **Context compaction** — when the transcript exceeds a token budget, older messages are summarized (system prompt and recent window kept verbatim). Summarizers are pluggable (`smerkil.compaction.Summarizer` protocol); the default `TruncatingSummarizer` needs no model, `ModelSummarizer` uses the chat model when `SMERKIL_MODEL_SUMMARIZER=1`.
- **Streaming** — SSE streaming from any OpenAI-compatible endpoint over stdlib `http.client`: text deltas (`on_token`) and live tool-call argument fragments (`on_tool_delta`); automatic non-streaming fallback when the endpoint doesn't support SSE.
- **Sticky model failover** — `fallback_models` tried in order; once a fallback serves, later turns skip the dead primary. Each trace step records the model that actually answered.
- **Failover-aware budget** — cost priced per the model that actually served each turn; chat and serve sessions share one session budget (visible via `/tokens` or `GET /sessions`, enforced mid-session).
- **Retries & backoff** — exponential backoff with jitter on connection errors and 429/5xx, honoring `Retry-After`.
- **Structured planning** — `plan_add` / `plan_list` / `plan_update` tools backed by `workspace/plan.md` with `todo` / `in_progress` / `done` statuses.
- **Human-in-the-loop confirmations** — `confirm.yaml` flags tools (or arg regexes) that pause the run and ask the human; non-interactive runs fail closed
- **Durable memory** — `memory_save` / `memory_search` / `memory_forget` persist across sessions in `.smerkil/memory.jsonl`; recent notes are auto-injected into every run's system prompt
- **More tools** — `web_fetch` (stdlib, size/time-limited, text extraction), `python_exec` (snippet in a sandboxed subprocess with timeout), `git_status` / `git_log` / `git_diff` (read-only), `git_commit` / `git_branch` (write), plus the sandboxed file tools and opt-in whitelisted shell.
- **Memory & state** — per-agent working memory, durable notes (`memory.md`), carried across runs.
- **Evals** — scenario suites (`evals.yaml`) with grounded-expectation checks; non-zero exit on regression. Ships role-aware scenarios covering planning and parallel tool calls.
- **Traces** — every run saved as JSONL (`workspace/traces/runs.jsonl`) plus per-run JSON with metadata: run id, per-step serving model, timestamps, token totals, compaction count. Pretty-print with `smerkil trace <name> --show <id>`.

## The terminal UI

`smerkil` with no arguments opens the chat UI: a banner with the active
endpoint/model/workspace, streamed answers, a rail for every tool call
(`⚙ name key=value` → `✓` or `✗ error`), a live status line after each turn
(model · tokens in/out · dollars · elapsed), and a spinner while the model is
thinking. Colour and box-drawing appear only on a TTY: pipe the output or pass
`--plain` and you get one flat header line plus plain text, no escapes.

```
smerkil                 # chat UI on the default agent
smerkil init            # provider / base URL / key / model wizard
smerkil doctor          # does this URL+key+model actually answer?
smerkil --plain         # monochrome, no box drawing
smerkil --base-url https://api.groq.com/openai/v1 --model llama-3.3-70b-versatile
```

Inside the UI:

| command | what it does |
|---|---|
| `/help` | list commands |
| `/model [name]` | show or switch model (persisted to agent.yaml) |
| `/endpoint [url]` | show or change the base URL — any OpenAI-compatible one |
| `/setup` | re-run the provider wizard |
| `/tools` | tools this agent may call |
| `/tokens` | token + dollar usage for the session, with a budget bar |
| `/status` | endpoint, model, workspace, where the key came from |
| `/verbose` | toggle full tool results |
| `/clear` | forget the conversation, keep durable memory |
| `/exit` | leave |

## CLI reference

| Command | Purpose |
|---|---|
| `smerkil new <name> [--role R]` | Scaffold an agent dir with a role preset |
| `smerkil run <name> --goal "..."` | Run one goal; exit 0 only on completed run |
| `smerkil chat <name>` | Streaming REPL: live text + tool args, session budget, `/reset`, `/tokens`, `/exit` |
| `smerkil serve <name>` | HTTP API: `POST /v1/chat`, `GET /sessions`, `GET /health`, `GET /live`; `--host`, `--port`, `--token` |
| `smerkil login` | sign in to a dashboard; stores the session token in `~/.smerkil/dashboard.json` (0600) |
| `smerkil status` | live status of a running server — active runs, sessions, budgets; `--url`, `--token`, `--json`, `--max-age` |
| `smerkil push` | upload `smerkil report --json` to a dashboard; `--url`, `--token-file` (opt-in) |
| `smerkil eval <name> [-v]` | Run eval scenarios; non-zero exit on regression |
| `smerkil trace <name> [--show <id>]` | List runs or pretty-print one trace |
| `smerkil doctor [name]` | Check API key env, endpoint/model reachability, workspace health |
| `smerkil --version` | Print version |

Output is ANSI-colored on TTYs, plain when piped.

## HTTP API (`smerkil serve`)

```bash
smerkil serve my-agent --host 127.0.0.1 --port 8317 --token "$SERVE_TOKEN"

# health
curl http://127.0.0.1:8317/health

# chat (multi-turn within a session id)
curl -X POST http://127.0.0.1:8317/v1/chat \
  -H "Authorization: Bearer $SERVE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"message": "Summarize ./notes/", "session": "job-42"}'

# per-session token/cost accounting
curl -H "Authorization: Bearer $SERVE_TOKEN" http://127.0.0.1:8317/sessions
```

Each `session` id carries its own conversation history and session budget
(guardrails from `agent.yaml`); runs inside one session are serialized,
different sessions run concurrently.

### Live status

`smerkil serve` writes a heartbeat to `$SMERKIL_HOME/serve.json` every 5s, so
`smerkil status` can find it without knowing the port:

```bash
$ smerkil status
smerkil status  stub · stub-1
  pid 619248 · http://127.0.0.1:39567 · up since 2026-10-25T21:13:01+00:00
  1 running · 3 session(s)

  ○ idle     job-A                runs   1  0p/0c  $0.0  completed
  ○ idle     job-B                runs   1  0p/0c  $0.0  completed
  ● running  watch-me             runs   0  0p/0c  $0.0  —
```

`GET /live` returns the same data as JSON: per-session `in_flight`, `runs`,
`last_stop_reason` and budget, plus server-wide `active_runs`. Exits non-zero
when nothing is serving, and `--json` is there for scripts:

```bash
smerkil status --json | jq '.active_runs'
```

A heartbeat older than `--max-age` (default 20s), or one whose pid is gone, is
treated as "not running" — a crashed server can't masquerade as live.

### Seeing it from a hosted dashboard

Your machine is behind NAT; a hosted page can't open a socket to it. So the
direction is inverted — the harness pushes its status *up*, and the dashboard
just reads it:

```bash
smerkil login --url https://smerkil-web.vercel.app      # once, password not echoed
smerkil serve coder --publish-live                       # then every ~5s
```

`POST /api/live` carries the same snapshot `GET /live` returns. A snapshot
older than 45s means the server stopped pushing, so the dashboard reports it
as offline rather than showing a stale "running". Everything is opt-in:
without `--publish-live` nothing leaves the machine. `smerkil push` and
`smerkil status` reuse the token from `login`, so it only has to be typed once.

### Git workflow tools

The coder role ships with a full read/write git toolset — the agent can
inspect, stage, commit and branch without shell access:

```yaml
tools: [git_status, git_log, git_diff, git_commit, git_branch]
```

- `git_status` — porcelain status of the repo containing the workspace
- `git_log` — recent commits (`{max_count}`)
- `git_diff` — uncommitted worktree/staged diff, or `{commit: "HEAD~1"}` for a specific commit; untracked files are shown too
- `git_commit` — stage and commit in one call: `{message, add: ["."]} `; refuses to run with an empty message or nothing staged
- `git_branch` — `{action: list|create|switch, name}`; names are validated against git ref rules

Reviewer gets the read-only subset (`git_diff` included) — it can see exactly
what changed, but cannot mutate history.

### Human-in-the-loop confirmations

Flag tools or argument patterns in `<workspace>/confirm.yaml`:

```yaml
confirm:
  tools:
    - run_shell          # always confirm shell commands
    - git_commit
  patterns:              # confirm only matching args
    - tool: web_fetch
      match: "https?://internal\\."
  ask_once_per_run: true # identical repeat calls re-use the approval
```

The run pauses and prompts on the terminal: `⚠ confirm run_shell({...}) —
allow? [y/N/a]`. The decision is made by the human, not the model — it can't
be skipped, faked, or talked out of. Denial returns a structured error to the
LLM ("denied by human: do not retry"). Non-interactive environments (CI,
subagents) **fail closed**: the call is denied, not silently allowed.
Environment switches: `SMERKIL_CONFIRM=1` (all shell), `SMERKIL_CONFIRM_ALL=1`
(every tool). Inspect what the agent remembers with `smerkil memory <name>`.

### Durable memory across sessions

The agent keeps notes in `<workspace>/.smerkil/memory.jsonl` (survives
restarts and reinstalls). Three tools, added automatically to every agent:

- `memory_save` — `{text, tags?}`: persist a self-contained fact (capped at 2000 chars)
- `memory_search` — `{query, limit?}`: keyword retrieval with tag weighting and a recency boost
- `memory_forget` — `{id}` or `{query}`: delete stale notes

The **8 most recent notes are auto-injected** into every run's system prompt
(char-capped), so context survives even if the model never calls
`memory_search`. Old-style `memory.md` keeps working alongside.

## Configuration (agent.yaml)

```yaml
name: my-agent
model: gpt-4o-mini
# tried in order when the primary fails definitively; once a fallback serves,
# later turns prefer it (sticky) until it too fails
fallback_models: [gpt-4o-mini, claude-haiku-4.5]
base_url: https://api.openai.com/v1     # any OpenAI-compatible endpoint
api_key_env: SMERKIL_API_KEY
system: You are my-agent. Plan, act with tools, verify, answer.
tools: [read_file, write_file, list_dir, memory_note,
        plan_add, plan_list, plan_update,
        python_exec, web_fetch, git_status, git_log, git_diff,
        git_commit, git_branch, subagent]
guardrails:
  max_turns: 40
  budget:
    tokens: 200000
    usd: 1.00          # priced by the model that actually served each turn
  sandbox: strict
  allow_shell: false
```

Existing 0.2.x `agent.yaml` and `evals.yaml` files work unchanged; new tools are opt-in via the `tools:` list (unknown tool names are skipped with a warning rather than crashing the run).

## Available tools

`read_file`, `write_file`, `list_dir`, `run_shell` (whitelisted, opt-in), `memory_note`, `web_fetch`, `python_exec`, `git_status`, `git_log`, `git_diff`, `git_commit`, `git_branch`, `plan_add`, `plan_list`, `plan_update` (alias: `todo`), `grep`, `glob`, `checkpoint`, `subagent`.

MIT-grade boring infrastructure for probabilistic workers.

© 2026 SMERKIL Technologies
