microharness
A minimalist, zero-dependency, and fully pluggable AI agent microframework in Python.
Built with zero external runtime dependencies (standard library only) to teach the core architectural boundaries of agentic systems. Compatible with modern packaging tools like uv and standard pip.
Documentation: https://kagandi.github.io/microharness/
Installation
Install directly from PyPI:
# Using pip:
pip install microharness
# Or with uv:
uv add microharness
# Or run as a standalone CLI tool without installing into your current environment:
uvx microharness "Inspect the files in this directory"
The Core Mental Model: Harness vs. Loop
| Component | Responsibility | Location in microharness |
|---|---|---|
| Agent Loop (The Engine) | Pure Thought $\to$ Action $\to$ Observation cycle. Agnostic to benchmarks, sandboxes, and models. | core/loop.py (~40 LOC) |
| Harness (The Chassis) | The outer environment: workspace directory, sandboxing, budgets, memory compaction, telemetry/tracing, and grading. | core/harness.py |
| Interactive Router | One command table (/model, /resume, /compact, /skill, ...) shared by the CLI session and the TUI, so the two frontends cannot drift. |
core/interactive.py |
Configuration, Steering, Skills, Commands & Tool Plugins
microharness supports cascading configuration at two distinct scopes:
- Global User Baseline (
~/.microharness/or--global-dir) - Project-Local Scope (
.microharness/in current workspace root)
1. Configuration Files (config.json)
Configure your baseline model, endpoint, API key, and limits globally or override them per project:
- Global Baseline:
~/.microharness/config.json - Project Override:
.microharness/config.json
{
"default_model": "smart",
"max_context_tokens": 64000,
"trigger_ratio": 0.80,
"max_tool_tokens": 8000,
"sandbox": false,
"models": {
"fast": {
"model": "gemini-2.5-flash",
"provider": "google-ai-studio",
"description": "Fast flash model"
},
"smart": {
"model": "anthropic/claude-5.5-sonnet",
"provider": "openrouter",
"description": "Frontier reasoning model"
},
"local": {
"model": "local-model",
"provider": "lmstudio",
"endpoint": "http://localhost:1234/v1",
"description": "Local offline LLM"
}
}
}
Per-model context caps: a models entry may declare max_context_tokens, and a provider profile in providers.json may declare context_tokens (entry > profile > global max_context_tokens/max_tokens/context_tokens); switching models applies the cap live.
Legacy max_context_chars/max_tool_chars keys are removed; old char budgets converted as chars//4 (e.g. 4000 chars behaved as 1000 tokens).
To preserve prior behavior, set max_tool_tokens/max_context_tokens explicitly (e.g. "max_tool_tokens": 1000 replaces a former 4000-char tool limit).
Precedence Hierarchy:
- CLI Flags (
--model,--endpoint,--api-key,--preset,--sandbox,-d) — Highest priority - Environment Variables / Local
.env(MODEL_ENDPOINT,MODEL_NAME,MODEL_API_KEY, or provider keys likeOPENROUTER_API_KEY,GEMINI_API_KEY,AI_GATEWAY_API_KEY) - Global Credential Store (
~/.microharness/auth.json) — Per-provider API keys viamicroharness auth loginor/login - Project Config (
.microharness/config.json) — Project overrides (skipped when preset setsisolated: trueorinherit_project: false) - Agent Preset (
~/.microharness/presets/<name>/or.microharness/presets/<name>/) — Optional bundled persona (agent.md+config.json) - Global Config (
~/.microharness/config.json) — Machine baseline - Hardcoded Fallbacks (
MockModel, default prompts) — Lowest priority
Provider Credentials (~/.microharness/auth.json & microharness auth)
Store API keys once per provider in ~/.microharness/auth.json instead of duplicating secrets in config.json:
# Store or update a provider API key interactively (masked prompt, written with 0600 permissions):
uv run microharness auth login openrouter
# Or pick from an interactive numbered list of known providers:
uv run microharness auth login
# Inspect configured providers and effective credential sources (secrets are masked):
uv run microharness auth list
# Remove a stored provider credential from auth.json:
uv run microharness auth logout openrouter
Pass --global-dir <dir> (or -d <project-dir>) to any microharness auth subcommand to target a custom configuration directory. Credentials are stored per canonical provider name (for example openrouter, google-ai-studio, vercel, openai, anthropic) and resolve in this order: explicit CLI/model-spec key $\to$ provider environment variables (env_keys) $\to$ ~/.microharness/auth.json $\to$ providers.json api_key (literal or env:VAR) $\to$ fallback environment variables $\to$ top-level config.json "api_key".
Amazon Bedrock
bedrock is a built-in provider that targets Bedrock's official OpenAI-compatible endpoint.
On a machine with active AWS SSO (aws sso login) it works with zero config:
uv run microharness --model "bedrock/us.openai.gpt-5.6-sol" "Refactor auth.py"
Credentials resolve from the standard chain (environment, ~/.aws/credentials, SSO
cache), and requests are SigV4-signed with the standard library; the harness never
shells out to the AWS CLI. The region resolves from config.json "region", then
AWS_REGION, then AWS_DEFAULT_REGION, then the ~/.aws/config profile region
(profile from config.json "aws_profile" or AWS_PROFILE, default default).
Without credentials or region the spec falls back to MockModel with a hint
(aws sso login). A BEDROCK_API_KEY bearer token still overrides SSO when set.
Only models whose Bedrock model card lists Chat Completions are served on this
endpoint (Claude/Nova IDs return model_not_found); the registry default is
us.openai.gpt-5.6-sol.
Auth schemes are pluggable: built-ins are none, bearer, header, and sigv4
(see core/auth.py), and extra single-file plugins can be installed as
~/.microharness/auth/<scheme>.py (global dir only, never project-local).
The shim exposes no prompt-cache or reasoning parameters, so the Bedrock profile runs with cache_strategy: "openai_breakpoint" and reasoning_format: "none": with cache_ttl on, the first system text part carries an explicit prompt_cache_breakpoint (sub-1024-token prefixes are a server-side no-op); a stale user providers.json keeps "none" and simply skips breakpoints.
2. Cascading Instructions (AGENTS.md)
You can provide personal agent preferences globally, while projects can specialize or override them:
- Global Baseline:
~/.microharness/AGENTS.md(e.g., your personal coding habits, formatting preferences). - Project Conventions:
.microharness/AGENTS.mdor./AGENTS.mdin the repo root (e.g., repo-specific test commands, architecture rules).
The harness loads both in cascading order (Global baseline first, Project local second) into the system prompt.
3. Progressive Skills Disclosure (.microharness/skills/ & Shadowing) — Agent-Facing
Define reusable task workflows for the agent in .microharness/skills/<skill_name>/SKILL.md:
- Global Skills (
~/.microharness/skills/): Available across all projects on your machine. - Project Skills (
.microharness/skills/): Project-specific tools and workflows (namespaced cleanly without polluting the project root). - Skill Shadowing: If a project defines a skill with the same name as a global skill, the project version cleanly overrides it.
- Progressive Disclosure: Full skill files are never dumped into the prompt. Instead, the harness injects a 1-line index with scope badges (
[global]or[project]). - Lazy Loading & Security: The agent reads full instructions on demand via
read_file. Global skills are authorized for reading, while all file writes remain strictly sandboxed to the project directory.
4. Custom Slash Commands (.microharness/commands/*.md) — User-Facing
Define reusable prompt templates and macros for the user in .microharness/commands/<name>.md:
# Review code changes
Review the git diff or specified files: $ARGUMENTS.
Check for:
1. Correctness and edge-case logic bugs
2. Unit test coverage
3. Adherence to conventions in AGENTS.md
- Skills vs. Commands: Skills teach the agent how to perform complex workflows; Commands give the user prompt shortcuts.
- Invocation: Type
/review src/auth.pyin interactive chat or passmicroharness "/review src/auth.py". - Argument Substitution:
$ARGUMENTSor{args}is substituted with your trailing arguments. - Dynamic Help & Shadowing:
/helplists all discovered custom commands with their descriptions and scopes ([project]or[global]). Project commands shadow global ones.
5. Subagents (.microharness/agents/*.md, Presets & Parallel Delegation)
Delegate isolated subtasks to child agents with a clean Memory (zero parent context bias) and scoped tools:
- Built-in Presets:
explore(read-onlyread_file,grep,glob,git_read),reviewer(unbiased read-only code review), andworker(full file + bash tools, excluding recursivesubagentcalls). - Custom Agent Files: Place Markdown definitions with optional YAML frontmatter in
~/.microharness/agents/*.md([global]) or.microharness/agents/*.md([project], shadowing global and built-in presets):--- name: security-reviewer description: Audits diffs and auth logic for security flaws tools: [read_file, bash] model: fast effort: high max_steps: 10 --- You are a focused security reviewer starting with a clean context...
Supports comma-separated or YAMLtoolslists (withread/write/editaliases),effort(reasoning_effort/thinkingaliases), and optionalmax_steps(max_turnsalias). - Parallel Fan-Out: Emitting multiple
subagentcalls in one turn or passingtasks: [{agent, task, ...}, ...]runs child loops concurrently and returns aggregated findings. - TUI & Interactive Discovery: Use
/agent(or/agents,/subagent) to list, inspect, or delegate to subagents, with floating Tab autocomplete and live child-step action lines in the TUI.
6. Custom Tool Plugins (.microharness/tools/*.py) — Zero-Commit Extensibility
Add new capabilities to the agent dynamically without modifying harness core code or making git commits:
- Global Tools (
~/.microharness/tools/*.py): Available across all projects on your machine (always trusted and loaded automatically). - Project Tools (
.microharness/tools/*.py): Scoped to the current repository. Requires explicit opt-in via--trust-project-tools(or"trust_project_tools": truein~/.microharness/config.json) to prevent untrusted code execution from cloned repositories. - Tool Shadowing & Overrides: A project tool with the same
nameoverrides the global version. If a custom plugin shares a name with a built-in tool (e.g.bash), it will override it and emit a warning to ensure full visibility.
Authoring Conventions
A tool plugin file can follow any of these patterns:
Option A: Standalone Tool Class (Simplest)
Any class conforming to the Tool protocol (name, description, parameters, execute):
# ~/.microharness/tools/web_fetch.py or .microharness/tools/calculator.py
class CalculatorTool:
name = "calculate"
description = "Evaluates basic math expressions safely"
parameters = {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "The math expression (e.g. '24 * 7')"}
},
"required": ["expression"],
}
def execute(self, expression: str) -> tuple[int, str]:
try:
return 0, str(eval(expression, {"__builtins__": {}}, {}))
except Exception as exc:
return 1, f"Error: {exc}"
Option B: Environment-Aware Factory (get_tools)
Use get_tools(env) if your tool needs access to the harness execution environment (e.g. env.workspace_dir):
# .microharness/tools/db_tool.py
class DatabaseTool:
name = "query_db"
description = "Queries a project SQLite database"
parameters = {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"],
}
def __init__(self, env=None):
self.workspace = env.workspace_dir if env else "."
def execute(self, query: str) -> tuple[int, str]:
# Query local database in self.workspace
return 0, "Query results..."
def get_tools(env=None):
return [DatabaseTool(env)]
Option C: Module-Level tools List
Export an explicit list of pre-instantiated tool instances:
# .microharness/tools/helpers.py
tools = [ToolOne(), ToolTwo()]
7. Bundled MCP Support (plugins/mcp.py & ToolProvider)
microharness ships a zero-dependency, lazy-loaded Model Context Protocol (MCP) plugin (plugins/mcp.py) implementing core.protocols.ToolProvider:
{
"mcp_mode": "progressive", // "progressive" (default), "direct", or "code_mode"
"mcp_servers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "env:GITHUB_TOKEN" },
"description": "GitHub issues, PRs, and repositories"
},
"remote-docs": {
"url": "https://docs.example.com/mcp",
"headers": { "Authorization": "Bearer env:DOCS_TOKEN" }
}
}
}
- Progressive & Code Mode by Design:
"progressive"injects only a 1-line-per-server index and exposesmcp_search+mcp_call.--mcp-mode code_modeexposes Pythoncode_modebacked by an authenticated loopback bridge and defersmcp_callso the model can batch/filtertools.call(...)andmcp.search(...)/mcp.call(...)calls in one script without JS/Wasm dependencies. Pass--mcp-mode direct(or"mode": "direct"per server) to registermcp__<server>__<tool>directly. - Optional & Swappable: Never imported unless
mcp_serversis configured. Disable with--no-mcp/enable_mcp=False, or pass customToolProviderinstances viaHarness(tool_providers=[...]). - Trust & Permissions: Non-global MCP servers (e.g.
.microharness/config.jsonor path presets) require--trust-project-tools(or"trust_project_tools": truein~/.microharness/config.json), remote HTTP/SSE servers respect--no-network-tools, and mutating tools (readOnlyHint != true) obeyask/read-onlypermission modes.
See docs/mcp.md for all server options, transports (stdio, Streamable HTTP, /sse), secret references (env:VAR), and Code Mode details.
8. Agent Config Presets (presets/<name>/) — Portable Agent Bundles
Bundle a full runnable agent configuration into a single directory (~/.microharness/presets/<name>/ or .microharness/presets/<name>/):
agent.md(orAGENT.md): YAML frontmatter (name,description,model,reasoning_effort,toolsallow-list,isolated,include_builtin_subagents, etc.) plus the base system prompt body.- Optional Subdirectories:
config.json,subagents/,tools/,skills/, andcommands/scoped to that preset (with per-subagentmodel/effortoverrides for heterogeneous multi-model teams). - Invocation: Pass
--preset <name-or-path>(alias--agent), inspect with--list-presets(--list-agents), or run/presetin interactive sessions. Presets outside<global_dir>/presets/still require--trust-project-toolsbefore runningtools/*.pyplugins or command hooks.
See docs/presets.md for the full manifest reference and multi-model examples.
Working on Existing Projects
By default, the agent runs directly in your current working directory (like Claude Code or Aider). It sees all your existing files, respects git, and resumes right where you left off:
# Operates directly on the current directory:
uv run microharness "Inspect the files in this directory and explain the architecture"
# Or point to any other project directory with -d:
uv run microharness -d /path/to/my-project "Fix the bug in auth.py"
If you ever want an isolated disposable scratchpad (e.g. for testing without touching real files), pass --sandbox:
uv run microharness --sandbox "Experiment with writing a new scraper"
Docker Sandboxing (via OrbStack or Docker Desktop)
For 100% containerized process, operating system, and filesystem isolation (e.g. running untrusted code, heavy test suites, or SWE benchmarks), pass --docker:
# Run educational demo inside an isolated Linux Docker container
uv run microharness --demo calculator --docker
# Run the Mini-SWE benchmark suite inside Docker
uv run microharness --benchmark mini-swe --docker
# Specify a custom Docker image (default: python:3.11)
uv run microharness --docker --docker-image python:3.11 "Run pytest and fix bugs"
- Instant Hybrid I/O: The workspace directory is mounted at
/workspace. File reading, writing, and editing occur on the host filesystem with zero container latency, while all bash commands execute inside the isolated Docker Linux container viadocker exec. - Zero Runtime Dependencies: Operates entirely via Python's standard library
subprocesswithout third-party Docker SDKs. Works out of the box with OrbStack or standard Docker Desktop. - Automatic Teardown: Containers are automatically stopped and removed upon task completion with zero orphaned background containers.
If you prefer a one-and-done batch run (e.g. for CI), pass --batch:
uv run microharness "Run pytest and fix any failures" --batch
Continuous Interactive Chat & Meta-Commands
When you chat with the agent, the harness maintains persistent memory and renders a clean context budget status line before every turn:
─── Context: 1.4k / 8k (17.8%) ───
You:
Slash Commands (No Model Call)
You can inspect or control the harness runtime directly:
/model [name|number]: Inspect available models or switch active model dynamically on the fly (e.g./model fastor/model 2). In TUI mode, Tab autocompletes configured model names. A name is matched against themodelsaliases inconfig.json, their underlying model ids, and the provider registry (openaioropenai/gpt-4oboth work). An unrecognized name is rejected with the list of valid models rather than silently constructing a client for a model that does not exist. The--modelstartup flag applies the same recognition rules but only warns on stderr, so it remains usable for endpoints whose provider is not in the registry./login [provider|number] [key]: List providers and their effective credential sources without exposing secrets, or store/update an API key for a provider in~/.microharness/auth.json(prompts with masked input when the key is omitted; Tab autocompletes providers in TUI mode)./logout [provider|number]: List providers with keys stored in~/.microharness/auth.json, or remove stored credentials for a provider./resume [id|number]: List previous sessions in~/.microharness/runs/(with workspace affinity) or resume conversation history from an earlier session in-place. Discovery reads only the newest sessions first and falls back to a full scan when your repository has no recent session, so an older session for the same repo stays reachable./agent [name|number] [task]: List built-in and discovered subagents (.microharness/agents/*.md), inspect an agent's tools/model/effort/max_steps, or delegate a task directly (with Tab autocomplete in the TUI)./preset: Display the active agent preset (if any) and list discovered presets./cache [5m|1h|off]: Inspect or switch prompt caching duration on the fly (5mstandard ephemeral,1hextended beta, oroff)./status: Displays detailed memory metrics (system, user, assistant, and tool counts + budget percentage) and prompt cache hit rates./compact: Manually triggers memory compaction to prune older tool observations and reclaim context space./new: Starts a fresh conversation context while keeping all your project files intact./help: Lists available commands./exit: Finalizes and exports the session trace.
Cancelling a Running Turn
The two cancel keys are not equivalent, and the status bar says so while a turn runs:
Ctrl+Caborts the active step immediately, including a request that is already in flight. The incomplete tool turn is dropped and the session stays usable.Escis a cooperative cancel. It takes effect at the next step boundary and while the model waits between retries (for example during a throttle backoff). The moment it is seen the UI printsCancelling… aborting the pending model requestand abandons the wait.
Esc cannot abort a request that is currently waiting on the provider, because the HTTP timeout covers time-to-first-byte and shortening it would break slow models. Use Ctrl+C for that. See SPEC.md §5.2 for the planned work to unify the two.
Quickstart with uv
1. Install & Sync Environment
uv sync
2. Run the Test Suite
uv run pytest
(930+ unit and integration tests run in ~15s. Static checks run via uv run ruff check ., uv run ruff format --check ., and uv run ty check.)
3. Interactive and TUI Sessions
# Launch interactive mode (full-screen TUI):
uv run microharness
# Resume previous interactive session:
uv run microharness --resume
# Resume a specific session by ID:
uv run microharness --resume run-2026-10-03-xxxx
4. Run Mini-SWE for Rapid Sanity Testing
Run the lightweight 5-task sanity test suite before launching heavy benchmarks:
# Run the entire Mini-SWE sanity benchmark suite:
uv run microharness --benchmark mini-swe
# Filter to a specific challenge (e.g. rate_limiter or query_builder):
uv run microharness --benchmark mini-swe --task rate_limiter
# Built-in demo tasks:
uv run microharness --demo calculator
uv run microharness --demo greeting
Mini-SWE Benchmark Suite (Sanity & Smoke Testing)
microharness includes Mini-SWE, a fast, lightweight, pure-Python benchmark designed primarily for rapid sanity testing, local iteration, and CI smoke testing:
- Sanity Testing Focus: Validates the agent's tool-calling loop, multi-turn file editing, memory compaction, and test assertion grading in seconds—without burning model quota or waiting on multi-hour containerized benchmarks.
- Pure Python & Zero Docker: Operates entirely with Python's standard library. No multi-gigabyte container downloads, instant startup.
- Anti-Cheating Evaluator (
PristineTestEvaluator): Evaluators restore pristine test files prior to running verification. An agent cannot bypass tests by deleting or rewriting assertions in the test suite. - 5 Realistic Engineering Challenges:
rate_limiter: Token Bucket rate limiter losing fractional refills under rapid polling.circular_serializer: Circular JSON serializer cycle detection & ISO-8601 formatting.auth_middleware: HTTP auth middleware case-insensitive headers & whitespace tolerance.lru_ttl_cache: LRU cache with TTL updating existing keys & refreshing MRU order.query_builder: SQL query builder AST precedence grouping & single-quote escaping.
- Automated Scorecard & JSON Telemetry: Generates a formatted summary table in the terminal and exports comprehensive JSON results to
~/.microharness/runs/benchmark_report.json.
DeepSWE-mini Benchmark Suite (Harbor Format & Docker)
microharness natively supports DeepSWE-mini (curated from Datacurve-AI DeepSWE and LocalLLaMA/deepswe-mini):
- 16 Curated Real-World Repositories: Across Python, Go, and TypeScript (e.g.
aiomonitor,bandit,ipython,narwhals,textual,prometheus,valibot,dasel). - Harbor Standard Compliance: Automatically parses
task.tomlmetadata (via Python 3.11's standard librarytomllib), pulls task ECR container images, mounts behavioral verifiers, and grades viatests/grader.py. - Zero Dependency Container Sandboxing: Spawns isolated Docker containers via OrbStack or Docker Desktop, syncs repo code at NVMe speed, and automatically captures
model.patchdiffs.
# Clone tasks once (only ~3.5MB repository metadata):
git clone --depth 1 https://github.com/datacurve-ai/deep-swe datasets/deep-swe
# Run the entire 16-task DeepSWE-mini benchmark suite in Docker:
uv run main.py --benchmark deepswe-mini --docker
# Run a specific task with custom step & timeout budgets:
uv run main.py --benchmark deepswe-mini --task aiomonitor --max-steps 500 --timeout 7200 --docker
# Run with official Datacurve Pier framework using microharness adapter:
uvx --from datacurve-pier pier run -p datasets/deep-swe/tasks/aiomonitor-task-snapshots-diff \
--agent-import-path benchmarks.pier_agent:MicroharnessAgent --env docker
Experiment Tracking (microharness experiments)
Benchmark runs automatically upsert run summaries (~/.microharness/experiments.csv) and per-task outcomes (~/.microharness/experiments_tasks.csv), recording harness_version, git_commit, active preset, subagents, scores, and token/cache telemetry:
# List recent benchmark runs
uv run microharness experiments list --limit 20
# Backfill historical *_report.json and standalone trace.json runs into CSV
uv run microharness experiments backfill
True Pluggability (Zero Code Modifications)
Because components follow minimal Python Protocols, you can plug in any Model, Tool, or Evaluator from the outside without touching a single line of harness code:
from microharness import Harness
# In-place coding agent on your repo with global and project steering:
harness = Harness(
model=my_custom_model, # Or HttpChatModel(endpoint, model, key)
workspace_dir=".", # Works directly on your project
global_dir="~/.microharness", # Global config, instructions & skills
tools=[bash_tool, my_tool], # Custom tools (dynamically documented in system prompt)
)
harness.run_tui("Help me refactor the database layer")
Key Educational Paradigms Demonstrated
-
In-Place Project Operation vs. Sandboxing (
core/environment.py)- By default, operates directly on existing project files with zero root directory pollution.
- Optional
--sandboxcreates an isolated scratchpad in~/.microharness/runs/(or--runs-dir). - Prevents path traversal outside project boundaries while permitting read access to authorized global directories (
allowed_read_dirs). - Executes bash with timeouts and combined stdout/stderr.
-
Cascading Configuration & Steering (
core/harness.py)- Loads global defaults from
~/.microharness/config.json. - Injects global user instructions (
~/.microharness/AGENTS.md) and project instructions (./AGENTS.md) in cascading order. - Discovers
skills/andcommands/globally and locally; project definitions cleanly shadow global ones. - Indexes skills lazily with scope badges to conserve context tokens.
- Loads global defaults from
-
Targeted File Editing vs. Full Rewrites (
core/tools.py)- Built-in
edit_file(path, old_str, new_str)enforces exact, unique string replacement. - Prevents token wastage and LLM hallucination bugs common when rewriting large files with
write_file.
- Built-in
-
Dynamic Tool Introspection (
core/tools.py)ToolRegistry.to_system_prompt_snippet()automatically reflects registered tools in the system prompt. Custom tools require zero prompt tweaking.
-
Large Log Handling & Spillover (
core/tools.py)- Massive command outputs are head + tail truncated.
- The full, raw output is spilled to
~/.microharness/runs/<run_id>/logs/so it never pollutes the user's project root.
-
Proactive 80% Context Compaction & Memory Optimization (
core/memory.py)- Proactively prunes older tool observations at an 80% high-water mark (
trigger_ratio = 0.80), keeping 20% reserved for output tokens and model reasoning. - Enriched Tombstones with Log Pointers: Collapsed tool outputs embed the exact spilled log file path (
Full log: <path>. Use read_file to inspect if needed.), giving the agent a deterministic bridge to inspect full outputs. - Historical Reasoning Pruning: Automatically prunes transient
<think>...</think>and<thinking>...</thinking>reasoning streams from older assistant turns to reclaim thousands of tokens for reasoning models (DeepSeek-R1, Claude Thinking, o1/o3). - Session Files Modified Ledger: Injects and maintains an active session ledger (
[Session Files Modified: file1.py, file2.py]) across compactions at the safe prefix. - Preserves system prompt, initial task, and recent working turns.
- Proactively prunes older tool observations at an 80% high-water mark (
-
Git Patch Export (
patch.diff) & Modern CLI Tracing (core/tracer.py)- Automatic git diff extraction: generates
patch.difffor coding tasks in git repositories. - Modern Developer CLI Output: Eliminates academic ReAct tags (
Thought:/Action:/Observation:) in favor of natural assistant speech,$ <command>execution,● Read/Write/Edit <path>, real-time duration headers, and clean output gutters. - Persists machine-readable
trace.jsonand human-readabletrace.mdin~/.microharness/runs/<run_id>/for every run.
- Automatic git diff extraction: generates
-
Automated Evaluation (
core/evaluator.py)- Evaluators test whether the agent actually succeeded (e.g. running test commands, asserting file contents, or Docker-based SWE-bench graders).
Project Structure
microharness/
├── pyproject.toml # Modern PEP 621 packaging for uv & hatchling
├── uv.lock # Deterministic lockfile generated by uv
├── SPEC.md # Detailed specification & design rationale
├── mkdocs.yml # MkDocs Material site configuration for GitHub Pages
├── README.md # Quickstart and overview
├── docs/ # Documentation site (served via GitHub Pages)
│ ├── index.md # Documentation home & mental model
│ ├── getting-started.md
│ ├── configuration.md
│ ├── interactive-tui.md
│ ├── subagents.md
│ ├── presets.md # Agent config presets reference
│ ├── mcp.md # MCP servers, transports & Python Code Mode guide
│ ├── architecture.md
│ ├── pluggability.md
│ └── benchmarks.md
├── AGENTS.md # Project conventions for agents
├── .microharness/ # Clean project-level configuration namespace
│ ├── skills/ # Progressive disclosure skills
│ │ └── run-tests/
│ │ └── SKILL.md
│ └── commands/ # Custom slash commands (user prompt shortcuts)
│ └── review.md
├── .env.example # Environment variable template
├── main.py # Runnable demonstration & CLI entrypoint
├── microharness/ # Top-level package exports & entrypoints (__main__.py)
├── benchmarks/ # SWE benchmark suites & runners
│ ├── mini_swe.py # 5 real-world pure-Python SWE tasks & PristineTestEvaluator
│ ├── harbor.py # Harbor / DeepSWE-mini benchmark loader & Docker verifier adapter
│ ├── experiments.py # Central CSV experiment tracking & historical backfill
│ ├── pier_agent.py # Datacurve Pier framework agent adapter (MicroharnessAgent)
│ └── runner.py # Benchmark orchestrator, scorecard table & incremental JSON report export
├── plugins/
│ └── mcp.py # Zero-dependency stdlib MCP client (stdio, Streamable HTTP & SSE)
├── core/
│ ├── types.py # Clean dataclasses (Message, ToolCall, Task, Trajectory, RunResult)
│ ├── prompts.py # System prompt templates & prompt assembly
│ ├── environment.py # Workspace & bash runner (supports in-place and sandbox)
│ ├── tools.py # Pluggable tool protocol & built-ins (bash, read_file, write_file)
│ ├── code_mode.py # Python Code Mode & authenticated loopback tool bridge
│ ├── memory.py # Context manager & 80% high-water mark compaction
│ ├── protocols.py # Model protocol, capability protocols (cache, deadline, cancel) & cancellation
│ ├── usage.py # Token normalization, per-model telemetry & run-level totals
│ ├── providers.py # Provider registry, model-spec resolution & client construction
│ ├── auth_store.py # Per-provider global credential store (~/.microharness/auth.json)
│ ├── model.py # Generic HttpChatModel & MockModel clients
│ ├── config.py # Cascading configuration, JSONC reading & setting resolution
│ ├── presets.py # Named agent preset bundles (agent.md + subagents/tools/skills)
│ ├── skills.py # Progressive-disclosure skills (discovery, summaries, activation)
│ ├── subagents.py # Subagent presets, .md discovery & isolated child delegation tool
│ ├── commands.py # Custom slash commands & slash-input resolution
│ ├── discovery.py # Hierarchical resource discovery & @file-tagging
│ ├── interactive.py # Interactive command router shared by the CLI session & the TUI
│ ├── session.py # Step driver, session index, resumption & trace reconstruction
│ ├── loop.py # Native tool-calling loop (~40 lines)
│ ├── evaluator.py # Automated graders (CommandTestEvaluator, FileContentEvaluator)
│ ├── tracer.py # Telemetry collector, modern CLI renderer & trace exporter
│ ├── tui.py # Full-screen curses TUI (markdown rendering, autocomplete)
│ ├── tui_session.py # TUI turn driver: step rendering & cooperative cancellation
│ └── harness.py # Harness orchestrator wiring the chassis together
└── tests/
├── test_auth_store.py # Global auth.json storage, permissions & masking tests
├── test_benchmarks.py # Mini-SWE baseline failure, anti-cheating & reference tests
├── test_code_mode.py # Python Code Mode bridge, auth & Docker/read-only boundary tests
├── test_mcp.py # MCP stdio/HTTP/SSE transports, search ranking & security tests
├── test_harbor.py # Harbor task parsing, Docker image validation & evaluator tests
├── test_environment.py # Path sandboxing & bash timeout tests
├── test_tools.py # Tools, truncation & disk spillover tests
├── test_memory.py # Conversation history, stats & 80% compaction tests
├── test_model.py # Endpoint normalization, serialization & mock model tests
├── test_evaluator.py # Grader assertions tests
├── test_config.py # Config cascade, JSONC parsing & tool-trust boundary tests
├── test_protocols.py # Capability protocol detection tests
├── test_usage.py # Token normalization & telemetry accounting tests
├── test_providers.py # Provider registry, model specs & available-model tests
├── test_skills.py # Skill discovery, summaries & activation tests
├── test_presets.py # Agent preset discovery, isolation, trust & CLI tests
├── test_experiments.py # Central CSV experiment tracking & backfill tests
├── test_subagents.py # Subagent parsing, isolation, overrides, parallel & TUI tests
├── test_commands.py # Slash-command discovery, expansion & resolution tests
├── test_prompts.py # Prompt assembly & AGENTS.md cascading tests
├── test_session.py # Step driver retries, deadlines & session resumption tests
├── test_interactive.py # Command router & rendering tests
├── test_tui_session.py # TUI turn rendering & cancellation tests
└── test_harness.py # End-to-end lifecycle, global config, commands & guardrails tests
Metadata
Release files for microharness 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| microharness-0.2.0.tar.gz | 546.8 kB | Without provenance | Details for microharness-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| microharness-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for microharness-0.2.0-py3-none-any.whl |
Total release size: 789.6 kB
Release files / microharness-0.2.0.tar.gz
| Download URL | microharness-0.2.0.tar.gz |
|---|---|
| Size | 546.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
583618c18eed20ad8171da23abe01cea66bc572945c2856c63f20dd6622deedb
|
|
BLAKE2b-256 checksum How to use checksums |
e5033ed0c1be4200e6cb9b70d7eee45f03630a7089a8f4d52b0149cb6308d975
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / microharness-0.2.0-py3-none-any.whl
| Download URL | microharness-0.2.0-py3-none-any.whl |
|---|---|
| Size | 242.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d2b74850f72fb2393d0eba79da5f85ad88e4ae5202e0706ce24b80a77cfa458a
|
|
BLAKE2b-256 checksum How to use checksums |
15bf228bfd427e7a8814510f63962285c8b6c82df032a6777add2d4429933ac3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for microharness 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.