Skip to main content
Glama

id: README

BoteX: Execution Harness for AI Coding Agents

License: Apache-2.0 Python 3.13+ CI BoteX MCP server – quality and maintenance score on Glama

Giving an LLM direct, unrestricted access to your repository usually ends the same way: it hallucinates line numbers, corrupts indentation, writes broken syntax, eats your token budget reading thousands of irrelevant lines, or gets stuck in an infinite fix-break loop.

BoteX is a guardrail harness designed specifically for autonomous code-editing agents. It sits between an MCP client (such as Devin, Antigravity, Claude Desktop, or Cursor) and your codebase, enforcing deterministic safeguards before any code ever touches your disk.


Related MCP server: MultiAgents-MCP

Why BoteX?

Instead of trusting the model to behave, BoteX wraps every action in safety gates:

  • Outline-first inspection: Agents inspect symbol skeletons (get_outline) before asking for specific line ranges. This prevents dumping massive files into context and slashes token waste.

  • Prompt Injection & Untrusted Data Isolation (OWASP LLM01: Prompt Injection): External content retrieved by tools (file contents, web pages, memory notes) is automatically wrapped in XML-like untrusted data boundary tags (<untrusted_file_content>, <untrusted_web_content>, <untrusted_memory_content>). System prompt rules instruct the LLM to treat bounded content strictly as data, significantly reducing prompt injection risks.

  • Sensitive Information Disclosure & Secret Guardrails (OWASP LLM02: Sensitive Information Disclosure): Prevents accidental leaks by blocking access to environment files (.env*), SSH keys, credentials, and local configurations (botex.config.local.json). Automatically redacts API keys, Bearer tokens, private keys, and provider secrets in tool outputs and logs.

  • Read-before-write gate: Models cannot patch a file they haven't inspected in the current session. No blind edits, no guessing.

  • Pre-write syntax validation: Code modifications are validated in memory (e.g. ast.parse for Python) before saving. If the patch breaks syntax, it gets rejected on the spot.

  • Multi-tier fuzzy patching: Patches are whitespace- and newline-resilient (CRLF/LF agnostic with indentation detection), so minor formatting mismatches don't break execution.

  • Unbounded Consumption Protection (OWASP LLM06: Unbounded Consumption): Prevents "Denial of Wallet" and infinite loop resource exhaustion. BoteX evaluates USD spend dynamically mid-loop to enforce the budget cap instantly, and aborts with an automatic rollback if the agent falls into a mutation streak or stagnation loop.

  • Misinformation Protection (OWASP LLM07: Misinformation): Generated code undergoes rigorous in-memory AST and syntax validation (including ruff for Python and bash -n for shell scripts) to reject hallucinated or invalid code before touching disk. Post-write verify_command acts as a mandatory final test gate.

  • Improper Output Handling (OWASP LLM10: Improper Output Handling): Strict Read-Before-Write gates ensure no blind writes occur, and every touched file is backed by a pre-mutation snapshot. If an agent hits an error, the automatic snapshot rollback reverts the workspace cleanly.

  • Hard budget & pricing caps: Pre-flight checks verify model pricing against live provider catalogs. If a task exceeds its budget or a model is overpriced, BoteX aborts before spending a cent.

  • Strict privacy & Zero Data Retention (ZDR): Enforces provider.data_collection: deny on OpenRouter calls, blocks .env/secrets, masks API keys in logs, and prevents path traversal attacks. Free (:free) models that cannot guarantee ZDR are rejected locally. Opt out explicitly per run (allow_non_zdr) or via the openrouter-free provider preset.

  • Proactive Rate Limiting & Cooldown Tracking: Token-bucket rate limiter tracks RPM and TPM limits per provider with burst buffers and debt queues. When providers return rate-limit headers or 429 status codes, BoteX enters a cooldown window instead of repeatedly burning retries.

  • In-Flight State Checkpointing & Provider Fallbacks: Failed model runs take a snapshot of planned steps, observations, and read files before rolling back workspace changes. The next model or fallback provider receives this context directly, avoiding redundant exploration.

  • Memory Vault with hedged recall cascade: Persistent two-tier memory (plus an optional read-only swarm scope) with a [[wikilink]] graph. recall_memory answers a natural-language query in one call: a local Bielik model synthesizes first, and NVIDIA/Gemini/:free fallbacks hedge in only after a configurable idle window. Every response reports recall_status, per-tier attempts, and the workspace searched.

  • Enhanced Permission Controls (OWASP LLM03: Excessive Agency): BoteX protects against Excessive Agency via a centralized Agency Middleware. Tools are strictly defined with Risk Levels (LOW, MEDIUM, HIGH) and required scopes. High-risk destructive actions automatically require explicit interactive operator approval (or pre-authorized task scopes in headless mode), limiting the potential damage of prompt injections or hallucinations.


Quickstart

1. Installation

Requires Python 3.13+:

pip install -r requirements.txt

(Optional: install globally via pip install . to get the botex CLI command).

2. Add your API key

BoteX handles provider keys internally, so calling MCP clients don't need to pass credentials on every request. Create a .env file next to server.py:

OPENROUTER_API_KEY=sk-or-v1-...
# GEMINI_API_KEY=AIza...        # only for provider "google" (GOOGLE_API_KEY works as fallback)
# GROQ_API_KEY=gsk_...          # only for provider "groq"
# CLOUDFLARE_API_TOKEN=...      # only for provider "cloudflare" (Workers AI)
# CLOUDFLARE_ACCOUNT_ID=...     # account id for the cloudflare provider (or providers.cloudflare.account_id)

Key lookup order: OPENROUTER_API_KEY env var → local .env → custom paths.env_file → botex.config.local.json (gitignored). For provider google, the key resolves via GEMINI_API_KEY → GOOGLE_API_KEY → secrets.google_api_key in config; cloudflare resolves via CLOUDFLARE_API_TOKEN → CF_API_TOKEN → secrets.cloudflare_api_key.

3. Connect to your MCP client

You can run BoteX as a local stdio process or as a remote service over SSE.

Option A: Local Process (stdio)

Register BoteX using the included zero-install launchers (bin/botex.cmd on Windows, bin/botex.sh on Linux/macOS) or directly with Python:

{
  "mcpServers": {
    "botex": {
      "command": "C:/path/to/harness/bin/botex.cmd"
    }
  }
}

Option B: Remote MCP (Cloud or VPS)

Start the gateway with botex cloud and connect via StreamableHTTP (/mcp/http) or legacy SSE (/mcp/sse):

{
  "mcpServers": {
    "botex-cloud": {
      "url": "http://127.0.0.1:8000/mcp/http",
      "headers": {
        "Authorization": "Bearer <your_token>"
      }
    }
  }
}

How It Works

Every delegated task goes through an explicit contract-driven lifecycle:

Delegated Task
     │
     ▼
[Pre-flight check] ──► Validate budget, model capabilities & price cap
     │
     ▼
[Tool Loop]        ──► Symbol outline ─► Target read ─► In-memory patch ─► Syntax check
     │
     ├─► Success   ──► Verify contract (file exists, syntax valid, verify_command passed) ─► DONE
     │
     └─► Failure   ──► Rollback snapshots ─► Try next candidate (model_fallbacks) or abort

A task returns ok: true only when its completion is verified on disk, not just because an LLM said "I'm done". For background tasks (start_task / get_task_status), status reports the execution lifecycle (QUEUED, RUNNING, DONE, FAILED, CANCELLED); lifecycle DONE means the run finished, not success. Success requires result_data.ok == true and result_data.status == "DONE".


MCP Tools Reference

BoteX exposes a focused set of MCP tools:

Task Execution

  • run_subagent(task, ...): Runs a full coding task synchronously and blocks until finished. Returns both human-readable text and detailed structured metadata.

  • start_task(task, ...): Launches a task asynchronously in the background and returns a task_id.

  • get_task_status(task_id): Polls progress, logs, and results for a background task.

Context Inclusion Layer (Swarm Relay)

BoteX provides an in-process, deterministic Context Inclusion Layer (botex/core/context_inclusion.py) for multi-agent swarm collaboration (Antigravity, Devin, ZCode, BoteX):

  • OutputNormalizer: Zero-LLM deterministic parser that extracts statuses, summaries, mutated files, memory keys, and blocking reasons from heterogeneous agent outputs (Devin JSON, ZCode Markdown, BoteX receipts, plain text), converting all Windows paths to POSIX repo-relative paths (/).

  • DeterministicSignalGate:

    • collapse_passed_tests: Collapses consecutive passed tests into concise milestone summaries.

    • pinpoint_failure_trace: Isolates exception headers and innermost stack frames, pruning verbose tracebacks.

    • prune_diff_to_ast_manifest: Prunes multi-thousand line diffs into a compact manifest of modified AST symbols.

    • deduplicate_observations: Eliminates repetitive observation turns using Jaccard word-similarity thresholding (>0.80).

  • ContextKnapsack: Enforces strict byte budgets (default 4096B) for inter-agent context forwarding. Overflow is safely offloaded to .botex/scratchpad/<scratch_id>.log with secret masking and traversal guards.

Two-Tier Memory Vault

  • save_memory(title, content, workspace_dir, kind, tags, memory_id, scope, confidence, project, origin): Saves persistent notes, decisions, handoffs, beliefs, heuristics, or lessons (confidence from 0.0 to 1.0). Scope can be "local" (<workspace_dir>/.botex/memory/) or "global" (~/.botex/memory/). Use project="swarm" with scope="global" on BoteX Cloud for shared multi-host swarm knowledge; origin (<agent>@<host>) is recorded explicitly or inherited from X-Agent-Id/X-Host SSE headers. Ephemeral local handoffs (tags=["temp-handoff"], expires: YYYY-MM-DD) are pruned automatically by the Curator.

  • read_memory(memory_id, workspace_dir, scope) / search_memory(workspace_dir, query, tag, kind, scope, since, until, min_confidence, status, project): Retrieves saved memory across local, global, or swarm storage (scope="all" searches all configured roots). Supports temporal range filters (since, until in ISO 8601), confidence thresholds (min_confidence), lifecycle filtering (status, default "active"; pass "all" for a full scan), project partitioning (project), and spreading activation across linked notes combined with FTS5 via Reciprocal Rank Fusion (RRF).

  • patch_memory_section(memory_id, section, new_content, workspace_dir, scope, append): Replaces or appends one Markdown section in a memory note without touching frontmatter, other sections, or the Timeline trail.

  • delete_memory(memory_id, workspace_dir, scope): Deletes a specific memory note from local or global storage.

  • get_backlinks(memory_id, workspace_dir, scope): Lists memories that link to the given note through [[wikilinks]].

  • find_graph_health(workspace_dir, scope): Audits the vault's wikilink graph — reports broken links, orphan notes, and cycles.

  • init_obsidian_vault(workspace_dir, scope, override_existing, export_index): Writes .obsidian/ config (per-kind graph colors) and optionally regenerates _GRAPH_INDEX.md.

  • recall_memory(query, workspace_dir, topic, scope): One-shot natural language memory recall. Expands search hits via 1-hop graph traversal (wikilinks + backlinks) and synthesizes facts with cited sources via a server-side curator cascade (local-ollama -> nvidia -> gemini -> openrouter-free -> deterministic), cutting context bloat by up to 98%.

  • reflect_memory(workspace_dir, topic, scope, min_confidence, limit): Clusters and synthesizes related memories, beliefs, and heuristics into higher-order architectural takeaways and patterns without external database engines.

  • read_scratchpad(memory_id, workspace_dir): Reads an execution or terminal log offloaded to .botex/scratchpad/<memory_id>.log.

Diagnostics & Utility

  • get_outline(path, workspace_dir): Returns a high-level symbol outline of a file without reading all lines.

  • get_stats(period): Generates token usage and cost reports from the local analytics ledger.

  • check_health(): Checks readiness of providers, models, keys, and budget limits.

  • clean_snapshots(max_age_days, max_total_mb): Prunes old workspace backup snapshots.

  • recommend_models(task_type, limit, include_free, provider, profile, tier): Queries /api/v1/models with authenticated headers, classifies models into high / standard / budget tiers, filters for tool-calling support (require_tools=true) and interactive endpoints (excluding :batch), and ranks models by task aptitude and token cost. include_free=true admits :free variants.

  • fetch_url(url, max_bytes): Safe, caller-side URL fetching with strict host and size filters.


Task Delegation & Parameters

run_subagent and start_task expose the exact same caller parameters, including approval_policy. Example payload:

{
  "task": "Add email validation to auth/validators.py and cover it with unit tests",
  "files": ["auth/validators.py"],
  "workspace_dir": "./my-project",
  "profile": "coding"
}

Key Parameters

Parameter

Default

Description

task

(required)

Clear description of what needs to be implemented or fixed.

files

[]

List of primary target files to nudge the agent toward (target hints, not a security allowlist; workspace_dir is the hard boundary).

workspace_dir

""

Root directory the agent is restricted to. Empty = engine.default_workspace from config, else the server's current directory. For Remote SSE (botex cloud), workspace_dir is on the BoteX host.

provider

""

API provider from botex.config.json (openrouter, nvidia, google, openrouter-free, ollama, groq, cloudflare; empty = configured default or BOTEX_PROVIDER).

model

""

Explicit provider model ID; overrides profile.

profile

""

Model profile from botex.config.json (default, coding, auto-beta, review, fast). Empty = picked per mode via engine.mode_profiles.

api_key

""

Provider API key per-request (keep empty in examples; do not pass secrets in task or memory).

mode

"edit"

Capability preset: readonly, edit, destructive, full. readonly is hard read-only (no local write, delete/move, or exec; flags cannot widen it).

recipe

""

Specialized workflow persona (planner, code-explorer, reviewer, security-reviewer, security-taint-hardener, build-resolver, tdd, architecture-adr, ui-craftsman).

max_turns

0

Max tool-loop iterations (0 uses engine.max_turns, 45 in the shipped config, overridable per mode via engine.mode_max_turns).

max_tokens

0

Per-turn completion cap (0 = config value; reasoning models need ~8000+).

max_duration_s

0

Total wall-clock limit in seconds (0 = config value).

budget_limit_usd

-1

Hard spend limit for this task (-1 uses global config, 0 = unlimited).

allow_destructive

false

Explicit opt-in for delete_file and move_file.

allow_exec

false

Explicit opt-in for run_command (requires exec.enabled: true in config).

allow_net

false

Explicit opt-in for web access via read_url.

net_allowed_hosts

[]

Per-run host authorization for read_url (interacts with net.policy).

net_allowed_urls

[]

Per-run URL authorization; a trailing / authorizes that subtree.

allow_non_zdr

false

Per-run consent to relax the ZDR gate; required for :free models (provider may log/train on prompts). The result carries zdr_enforced: false.

output_path

""

File-output contract: enforce that this exact file must be written and non-empty for DONE status. Requires mutating mode (edit, destructive, full); MUST NOT be used with readonly (readonly reports in summary).

approval_policy

"high_risk"

Human-in-the-Loop policy: none, high_risk, mutations, all_risky. Shared by run_subagent and start_task.

verify_command

""

Verification command (e.g. pytest tests/test_auth.py) that must pass before completion. Requires exec.enabled: true and exec authorization.


Recipes & System Prompts

BoteX builds the API System Prompt dynamically for each run. It fuses a hardcoded operational core (tool rules, syntax validation checks, output formats) with an optional Recipe (a markdown file). This means that providing a --recipe <name> (or the "recipe": "<name>" JSON parameter) acts as an injection mechanism for your custom System Prompts, giving the agent specialized personas or specific constraints.

Recipes live in the botex/skills/recipes/ directory.

Examples of custom System Prompts for Modding and Analysis

If you are using BoteX as an MCP Server to analyze game mods or reverse-engineer engine behavior, you can create custom recipes like botex/skills/recipes/ue4.md or botex/skills/recipes/lua_audit.md.

  • Unreal Engine 4 Modding (--recipe ue4)

    You are an expert C++ and UE4 Blueprint reverse engineer. Your primary goal is to identify memory leaks in object instantiation and unsafe cast operations. Always prioritize stability over performance optimizations. Adhere strictly to Epic Games naming conventions.
  • Security Audit (--recipe lua_audit)

    You are a strict security auditor analyzing game mods. Review this Lua codebase for potential sandbox escapes, arbitrary file read/write vulnerabilities, and networking exploits. Do not attempt to fix logic bugs; focus only on security vulnerabilities.
  • Code Refactoring & Optimization (--recipe optimize)

    You are an optimization expert. The target codebase runs in a heavily restricted environment. Identify inefficient loops, excessive global variable usage, and unnecessary memory allocations. Suggest changes using only standard libraries.

When provided, BoteX automatically appends your recipe to the system instructions before starting the LLM loop.


Safety & Capability Modes

Permissions follow the principle of least privilege. Modes are presets over core capabilities:

Mode

Allowed Operations

Typical Use Case

readonly

Outline inspection, ranged file reads, memory search.

Architecture reviews, exploratory passes.

edit (default)

Read tools + apply_patch + create_file.

Standard feature work and bug fixing.

destructive

Edit tools + delete_file + move_file.

Refactoring, renaming, file reorganizations.

full

Destructive tools + gated run_command execution.

Full autonomous loop (edit → test → fix).

NOTE

readonly and chat are hard read-only modes: no local writes, deletions, moves, or command execution. Capability flags cannot widen readonly to write or exec; allow_net adds only read-only network access (read_url). Chat is a separate CLI/REST interface (botex chat, /api/chat), not the normal task delegation API. Network access (allow_net) is never enabled by default in any preset. It must be explicitly enabled per request or configured via net.allowed_hosts.

Command Execution (run_command) Safety

BoteX is not a full OS sandbox. When allow_exec is granted, processes run under the operator's account. However, BoteX guards execution with multiple layers:

  1. Disabled by default: Requires exec.enabled: true in configuration.

  2. Binary allowlist: Only pre-approved executables (pytest, python, ruff, git, etc.) can be called.

  3. Deny rules: Blocks dangerous arguments (python -c, git push, rm, shell piping, network downloads).

  4. Isolated environment: Executes directly (shell=False), workspace set as cwd, secret environment variables stripped, and execution timeouts strictly enforced.

Human-in-the-Loop (HITL) Approvals

BoteX integrates an interactive approval manager for high-risk operations. Configure the policy in botex.config.json under approval.policy:

  • NONE: Auto-approves operations permitted by the capability mode.

  • HIGH_RISK (default): Blocks destructive actions (delete_file, move_file) and shell execution (run_command) until an operator approves.

  • MUTATIONS: Requires operator approval for any file modifications (create_file, apply_patch).

  • ALL_RISKY: Intercepts all mutating tools and system execution commands.

In REPL mode, BoteX prompts for interactive confirmation. In Cloud Gateway mode, actions enter a pending approval queue and can be approved or rejected via REST API (POST /api/approvals/{id}/decide).


Model Fallbacks & OpenRouter Live Routing

If a model refuses a task, burns its token limit without output, or hits provider rate limits, BoteX falls back to alternative models defined in botex.config.json:

"model_fallbacks": {
  "default": ["anthropic/claude-sonnet-4", "qwen/qwen3-coder", "deepseek/deepseek-v3.2"],
  "auto-beta": ["anthropic/claude-sonnet-4", "qwen/qwen3-coder", "deepseek/deepseek-v3.2"],
  "coding": ["anthropic/claude-sonnet-4", "qwen/qwen3-coder", "deepseek/deepseek-v3.2"],
  "review": ["openai/gpt-5.4", "google/gemini-2.5-pro", "deepseek/deepseek-r1"],
  "fast": ["qwen/qwen3-coder-flash", "openai/gpt-4o-mini", "deepseek/deepseek-v3.2"]
}

BoteX uses two complementary failover layers:

  1. In-Payload OpenRouter Failovers (extra_body.models): Before sending the first turn to OpenRouter, BoteX runs each fallback candidate through all five safety gates (Denylist, Decisions, ZDR, Price, Tools) and passes up to three validated slugs in extra_body["models"]. If the primary endpoint is overloaded on the initial request, OpenRouter switches to the next validated model on the wire without an extra client round-trip. Meta-routers (openrouter/auto, openrouter/pareto-code, openrouter/free) are excluded from models: [...], and once a run modifies any file (files_touched) or executes a command (exec_ran), BoteX strips models from subsequent turns so a different model never takes over a mutated workspace mid-task.

  2. Engine-Level Rollback & Retry: If an attempt fails mid-run, BoteX verifies that all partial file changes from the failed attempt were rolled back before starting the next candidate model. A fallback model never inherits a dirty workspace.

Before a candidate can fail at all, a shared retry layer (botex/providers/retry.py, configured per provider via providers.<name>.retry) waits out unbilled transient rejections: HTTP 429 and connection errors (Google additionally retries 503 "overloaded"), honoring server wait hints (Retry-After header, retryDelay/quotaResetDelay body fields). Timeouts and other 5xx are never retried — the request may already have executed, so a retry could double-bill it — and daily-quota errors skip the wait entirely so the run falls back immediately. While the layer is enabled, SDK-internal retries are disabled (max_retries=0) so exactly one layer owns the backoff policy; setting "retry": false on a provider hands control back to the SDK. Config keys: enabled (default true), max_waits (2), max_wait_s (60.0), base_delay_s (1.0), jitter_s (1.5). A persistent 429 surfaces as failure_kind: "provider_rate_limited", which is eligible for the model_fallbacks chain.

For OpenRouter runs, BoteX also sets extra_body.provider (data_collection: "deny" when ZDR is active, require_parameters: true when tools or response_format are present, allow_fallbacks: true, and sort: "throughput"), automatically stripping reasoning parameters for non-reasoning model slugs so require_parameters: true never triggers HTTP 404 rejections. On DONE, BoteX queries GET /api/v1/generation?id=... in parallel (with a short 404 retry) to record official billing (total_cost), queue latency (queue_time_ms), inference time (generation_time_ms), and prompt cache read/write tokens in .agent_analytics.jsonl and .botex/memory/ task receipts.


Self-Improvement Loop

BoteX feeds run telemetry back through deterministic checks. Across all layers, learning stays local and evidence-gated: promotion into live behavior requires verified confirmation counts or a human-reviewed PR.

Telemetry & Attribution

analytics.log_run (botex/providers/analytics.py) appends every run to the append-only ledger .agent_analytics.jsonl (a legacy .agent_analytics.json is folded in once; monthly rollups rotate to analytics-archive/). Beyond cost/token/duration fields, each entry carries masked attribution fields when non-empty:

  • origin, recipe, routed_tier, taxonomy: provenance and task class. taxonomy is assigned by classify_task_taxonomy (botex/core/meta_harness.py) into bugfix, refactor, test, infra, analysis, feature, or general; routed_tier/routed_profile appear when the opt-in engine.task_size_routing block assigns a tier profile.

  • applied_skills, applied_lessons: the Skill Vault entries and meta-lesson ids actually injected into the run (max 8 each).

  • syntax_rejections, rollback_count: contrastive quality counters.

  • shadow_recommended_model: the Layer C advisory pick, when one exists.

Attribution strings are CR/LF-flattened, mask_secrets-masked, and capped at 64 characters, keeping a consistent ledger schema across runs.

Contrastive Episodic Learning

When a task recovers after a failure, BoteX writes structured traces:

  • Contrastive handoffs: InFlightTaskState (botex/core/state.py) keeps two bounded ring buffers (syntax_rejections, last 5 {file, error} pairs, and rollback_reasons, last 5), masked and capped at 200 chars per field. On model/provider fallback they ride the checkpoint into the next candidate's prompt ("Rejected Edits (do NOT repeat these)" plus rollback context), so a different model does not repeat the same mistakes.

  • Lesson extraction: when a task recovers after a model failure, extract_meta_lesson (botex/core/meta_harness.py) persists a kind="lesson" note as status="candidate" with confidence=0.4, written resolution-first and tagged path:<dir> for the touched directories. The is_infra_failure gate keeps provider-side noise (rate limits, timeouts, quota/auth/budget/config errors, HTTP 429 text) out of the vault, so infrastructure failures never become lessons and never penalize confidence.

  • Bounded recall: get_relevant_meta_lessons surfaces only status="active" lessons at confidence >= 0.6; lessons bound to matching path:<dir> prefixes rank ahead of generic taxonomy matches. pack_lessons_within_budget caps the injected block at 800 bytes via ContextKnapsack; overflow lessons are dropped rather than replaced by a pointer.

  • Deterministic feedback: update_lesson_confidence (botex/memory/memory.py) nudges injected lesson ids with no LLM call: +0.1 on DONE with zero rollbacks, -0.15 on quality failures (any rollback, VERIFICATION_FAILED, STAGNANT_ROLLBACK, or INCOMPLETE), and never on infra failures or ABORTED. Confidence is clamped to [0, 1]; crossing below 0.2 marks the note deprecated with a Timeline audit line.

  • Curator promotion: CuratorService.promote_candidate_lessons (step 6d of botex/ops/curator/curator_service.py) flips candidate -> active only when confidence >= 0.8 and at least 2 distinct DONE, zero-rollback ledger runs cite the lesson in applied_lessons. origin="human", human-curated, and frozen notes are never mutated. The opt-in promote_to_global=True additionally copies verified lessons into scope="global", project="swarm", skipping notes that contain secret patterns or duplicate existing swarm content.

  • API origin hardening: POST /api/memory ignores the client-supplied origin field. Provenance comes from sanitized X-Agent-Id/X-Host headers (NFKC-folded, [a-zA-Z0-9_.-] allowlist, 32 chars per part); claims of reserved agents (human, human-curated, operator, curator) are rejected server-side.

Layer B: PR-Only Skill Crystallization

CuratorService.crystallize_skill_proposals (step 6e) clusters recurring active lessons (min_cluster_size >= 5 sharing a path: or domain tag, or untagged lessons with at least 2 co-occurring significant tokens) and drafts learned-<taxonomy>-<topic> SKILL.md + recipe.md proposals via write_skill_proposal_draft (botex/skills/skills.py).

Drafts land solely under <workspace>/.botex/proposals/skills/ and .botex/proposals/recipes/ after passing size (128 KB), secret (mask_secrets), prompt-injection (has_injection_pattern), and SkillSpector (audit_skill_content, skills.audit.risk_threshold = 30) gates. Frontmatter is stamped proposal_only: true, author: botex-curator, and records the audit verdict. Live skills/ and botex/skills/recipes/ are never touched; a human-reviewed PR is required to promote a draft.

Layer C: Shadow Meta-Routing (Advisory Only)

recommend_shadow_model / get_shadow_routing_advice (botex/providers/analytics.py) score models per (recipe, taxonomy) bucket from the ledger once >= 10 matching samples exist: a smoothed success rate, a quality penalty from rollbacks and syntax rejections (capped at 0.25), and a small cost bonus where _SHADOW_COST_FLOOR_USD ($0.0001) keeps :free model costs finite. The engine evaluates the advice off the event loop (asyncio.to_thread), emits a shadow_routing event (EventKind.SHADOW_ROUTING) carrying recommended_model/actual_model/diverged/sample_count, and records shadow_recommended_model in the ledger. Guarantees: shadow_only / actual_override: false, hard_banned_models stays empty, and active routing is never overridden. Divergence data provides empirical evidence before changing live routing defaults.


Free Models (Non-ZDR Opt-in)

ZDR is on by default and :free slugs are rejected pre-flight with ZDR_VIOLATION. Operators without a paid subscription (or anyone who accepts that free endpoints may log/train on prompts) can opt in two ways; both leave an audit trail (zdr_enforced: false in the result and a stderr warning):

# Persistent: switch to the bundled free-tier provider preset
# (all profiles resolve to tool-capable :free models)
botex config provider openrouter-free          # or BOTEX_PROVIDER=openrouter-free

# or relax ZDR on the current provider (keeps paid models, widens routing)
botex config zdr off                            # 'on' restores enforcement

# Per-run only, no config change:
botex run "task" --provider openrouter-free
botex run "task" --model qwen/qwen3.8-27b:free --allow-non-zdr
{"task": "...", "provider": "openrouter-free"}
{"task": "...", "model": "qwen/qwen3.8-27b:free", "allow_non_zdr": true}
NOTE

:free variants also require the OpenRouter account-level free-model opt-in (privacy settings); without it requests surface as provider_policy_denied. Free models carry per-day rate limits. The model_fallbacks chains in the preset stay entirely on :free slugs.


Configuration

Settings are resolved hierarchically (lowest to highest priority):

  1. botex.config.json: committed defaults (provider profiles, engine limits, security lists).

  2. botex.config.local.json: machine-local overrides (gitignored; place custom keys or limits here).

  3. BOTEX_* environment variables.

Config files are re-read automatically when they change (file mtime check on every access), so edits to botex.config.local.json - manual or via botex config ... - take effect on the next call, including in a running MCP server; no restart is needed. Environment variables are read from the server process environment, so changing them requires a restart.

Example botex.config.local.json:

{
  "engine": {
    "budget_limit_usd": 1.0,
    "max_turns": 20,
    "default_workspace": "C:/projects/my-project"
  },
  "pricing": {
    "max_input_per_mtok": 3.0,
    "max_output_per_mtok": 6.0
  }
}

Standalone CLI & REPL

BoteX can be run directly from your terminal without any MCP client:

Interactive REPL

botex repl -w ./my-project --profile coding

Prompts for [y/N] confirmation whenever the agent wants to delete or move files.

The startup banner shows the resolved absolute workspace and where it came from (explicit, default_workspace or cwd), and warns when it is the BoteX repository itself. Inside the REPL, workspace (or cd) prints the current workspace, and workspace <DIR> / cd <DIR> switches the target project for the rest of the session (relative paths are resolved against the current workspace; the directory must exist).

Set a persistent default so that running botex without -w never targets the harness itself:

botex config workspace C:/projects/my-project   # writes engine.default_workspace
botex config workspace none                      # clear it (falls back to cwd)

Workspace resolution: explicit -w / workspace_dir > engine.default_workspace > current directory. BOTEX_DEFAULT_WORKSPACE overrides the config value.

Headless One-Shot Tasks

# Run a specific task
botex run "Add --verbose flag to cli.py" -w ./my-project --profile coding

# Fix a bug with a tight turn budget
botex run "Fix the failing auth test" --files tests/test_auth.py --max-turns 15

# Refactoring with destructive permissions
botex run "Clean up legacy modules" -w ./my-project --allow-destructive

Conversational Chat Mode

Multi-turn discussion with token streaming, read-only tools, and automatic context pruning:

# Start interactive chat in the terminal
botex chat --model openrouter/auto

# With a custom system prompt and temperature
botex chat --system "Focus on security analysis" --temp 0.2

In-chat commands: /clear (reset session), /history (review transcript), /help, /exit.

Cloud Gateway & Remote MCP (FastAPI)

Run BoteX as a background cloud daemon with SSE transport, WebSocket chat, and REST endpoints:

# Start cloud server on default port 8000
botex cloud --host 0.0.0.0 --port 8000

Zero-Friction Local mode runs unauthenticated when BOTEX_ACCESS_TOKEN is unset. Set BOTEX_ACCESS_TOKEN in .env to enforce Bearer token verification on all protected endpoints.

REST surface (all under /api/): health, wallet, key/status, analytics (+POST analytics/digest), models, models/recommended, recipes, skills (+/{name}), tasks (+/{id}, /{id}/cancel, /{id}/events SSE), approvals (+/{id}/decide), memory (+/graph, /backlinks), curator/status, curator/run, rate_limits, chat (+/abort, /sessions, /sessions/{id}, /sessions/{id}/save_to_memory), and WebSocket /api/chat/ws. /api/health and the PWA shell stay public; all other /api/* routes require Bearer authentication.

Maintenance & Observability

botex health               # Verify API keys, provider connectivity, and model pricing
botex wallet               # Check OpenRouter balance, key limits, and daily query caps
botex config               # Inspect or modify local configuration defaults
botex --stats              # View weekly token consumption and spend per model
botex --stats --month      # Monthly cost report
botex --history <task_id>  # Inspect exact prompts, tool calls, and diffs for a run
botex --snapshots          # Check disk usage of backup snapshots
botex --clean-snapshots    # Prune old snapshot backups
botex models [--refresh]   # List configured provider models (refresh catalog)
botex memory <sub>         # Memory vault CLI (save, search, list, ...)
botex serve                # Force MCP stdio server mode explicitly

Project Structure

server.py              MCP server entry point & CLI dispatcher
bin/                   Zero-install launchers (`botex.cmd`, `botex.sh`, `botex-edge.*`)
pyproject.toml         Package configuration (exposes `botex` CLI command)
requirements.txt       Runtime dependencies (loose ">=" floor for dev/CI installs)
requirements.lock      Pinned deploy lockfile — regenerate via
                       `uv pip compile pyproject.toml --universal --python-version 3.13 -o requirements.lock`
botex.config.json      Committed defaults (providers, engine limits, exec/net policy)
ROADMAP.md             Deferred features & technical rationale
botex/                 Domain subpackages (legacy flat imports like `botex.engine`
                       still resolve via the alias graft in `botex/__init__.py`;
                       see docs/IMPORT_MAP.md)
  core/
    engine.py            Autonomous execution loop, 5-gate in-payload failovers,
                         in-flight checkpointing, provider fallbacks & rollback triggers
    state.py             InFlightTaskState checkpoints + contrastive ring buffers
    contracts.py         Task completion verification & status taxonomy
    events.py            Engine event emitter taxonomy (EventKind)
    capabilities.py      Permission presets & agency middleware
    approval.py          Human-in-the-loop approval manager
    context_guard.py     Context compaction & verification output pruning
    context_inclusion.py Deterministic swarm context relay (ContextKnapsack)
    meta_harness.py      Task taxonomy, episodic lesson extraction/recall,
                         infra-failure gate, lesson budget packing
    tracing.py           OTel-style span helpers
  providers/
    providers.py         Provider registry & adapters + request normalizer
    analytics.py         Cost/token ledger, run attribution, shadow meta-routing
    benchmarks.py        recommend_models & task-tier estimation
    catalog.py           Dynamic model catalog with TTL caching
    denylist.py          Hierarchical model denylist (exact/glob/regex)
    pricing.py           Live model price guardrail
    rate_limiter.py      Token-bucket RPM/TPM limiter & cooldowns
    retry.py             Shared transient-failure backoff & circuit breaker
    wallet.py            Credit balance & key budget status
    http_pool.py         Pooled httpx clients
    prompt_cache.py      Prompt-cache policy gating
  tools/
    file_tools.py        Outline-first reads, create/move/delete
    patch_engine.py      Fuzzy patching, in-memory syntax checks & snapshots
    exec_tools.py        run_command policy & argument filtering
    net_tools.py         SSRF-safe read_url / fetch_url
    security.py          Path traversal defense, secret masking & .gitignore
    vision.py            Vision input triage
  memory/
    memory.py            Two-tier Memory Vault, wikilink graph, lifecycle
                         statuses & confidence, scratchpad offload
    curator.py           Facade re-exporting botex.ops.curator service API
    embeddings.py        Local embedding helpers for memory/graph features
    obsidian.py          Obsidian PKM vault export & _GRAPH_INDEX.md
  ops/
    curator/             Nightly Knowledge-Graph curator (CuratorService):
                         lesson promotion, PR-only skill crystallization into
                         .botex/proposals/, recall cascade, Telegram dispatch
    maintenance.py       Maintenance jobs (WAL checkpoints, index sync)
    migrate_projects.py  Vault migration tooling
  skills/
    skills.py            Server-side Skill Vault, safe install/update, L0 triage
                         & PR-only write_skill_proposal_draft
    skillspector_gate.py SkillSpector pre-flight audit gate
    recipes.py           Recipe loader & system-prompt injection
    recipes/             Bundled persona prompts (planner, reviewer, tdd,
                         code-explorer, build-resolver, security-reviewer,
                         security-taint-hardener, architecture-adr, ui-craftsman)
  server/
    server_cloud.py      FastAPI Cloud Gateway, Remote MCP SSE/HTTP, REST API
                         & memory-origin hardening
    chat.py              Conversational chat sessions & read-only sandbox
    config.py            Layered config loader & workspace containment
    plugins.py           ZeroTrust subprocess plugin runner
    i18n.py / ui.py      CLI localization & ANSI styling
web/                   Vue 3 + Vite + Pinia + Tailwind CSS PWA frontend
skills/                Caller-side SKILL.md (botex) + server-side skill packs
tests/                 Comprehensive test suite (1344 tests across 67 files)
deploy/oracle-vps/     systemd units & one-click installer for Oracle A1.Flex ARM64
docs/
  TUTORIAL.md          Architecture deep dive and technical walkthrough
  IMPORT_MAP.md        Canonical vs legacy import paths (v2.1.0 modularization)
  TELEGRAM_NOTIFICATIONS.md  Curator alert setup guide

Testing

Run the full local test suite (no API key required):

python -m pytest tests/

All unit, approval, chat, memory, and cloud gateway tests run hermetically in offline mode.


License & Trademark

BoteX is licensed under the Apache License 2.0. See LICENSE for details. Derivative works must retain attribution notices as specified in NOTICE.

The BoteX name and logo are trademarks of Jakub Grzesiak (jg-webtech.pl). You are free to fork and modify the code under Apache-2.0, but forks or derived distributions should not use the name "BoteX" or suggest official endorsement without prior written consent.

Available Tools

25 tools
bot_consultB

Single-hop (ttl_hops=1) consult of a registered Tethered Bot: returns its identity, bounded instructions excerpt, active brief, and a recall over the shared Memory Vault restricted to ACTIVE notes only. Bots unknown to both the Cloud Soul store and the local fast-cache get BOT_NOT_FOUND.

Args: bot_id: Registered bot slug (alphanumeric/-/_ only). query: Natural-language question for the vault recall.

Inputs: query (required), bot_id (required). Returns: object

botex_get_rap_sheetA

Queries the isolated BlackBox penal ledger for an agent/model or workspace rap sheet. Returned evidence snippets are wrapped as untrusted data to block prompt injection.

When to call: at cross-review start or when taking over a local or Edge workspace ('edge://<device_id>/<workspace_id>') from another agent to check recurring mistakes.

Args: actor_agent: Optional offender filter (empty = all actors in workspace). workspace_dir: Target workspace path or 'edge://<device_id>/<workspace_id>' URI. limit: Max incidents to return (clamped to 1..200). window_days: Trailing lookback window in days (clamped to 1..365).

Inputs: limit, actor_agent, window_days, workspace_dir. Returns: object

botex_report_violationA

Records a swarm agent/model rule violation into the isolated BlackBox penal ledger (.botex/penal_vault.db), completely separated from the Memory Vault.

When to call: during cross-review or handoff verification when you observe a verified contract breach (SEC_01 secrets/workspace breach, SKILL_01 skipped tests or test theater, SCOPE_01 diff explosion, HAL_01 hallucinated tools/paths, LOOP_01 3+ identical failures). Never log violations or penalties into save_memory.

Args: offender: Target agent or model identifier (e.g. 'zcode-headless', 'botex:glm-5.3-flash'). violation_code: Canonical code ('SEC_01', 'SKILL_01', 'SCOPE_01', 'HAL_01', 'LOOP_01'). severity: Incident severity ('WARN', 'REJECT', 'CRITICAL'). Default 'REJECT'. skill_recipe: Optional skill/recipe active during the infraction. evidence_snippet: Concise log/diff excerpt (automatically secret-masked). workspace_dir: Target workspace path or 'edge://<device_id>/<workspace_id>' URI. enforcement_action: Action label ('PENALTY_LOGGED', 'HANDOFF_REJECTED', 'ESCALATED'). origin: Optional provenance identifier '@' of the reporting agent.

Inputs: offender (required), violation_code (required), origin, severity, +4 more. Returns: object

bot_report_activityA

Reports a bot's lease/heartbeat on a scope path into the Cloud Soul host_leases table. host_id is bound to the real MCP session provenance (X-Agent-Id@X-Host) — caller-supplied values are never used. A fenced-out write (stale fencing token) returns the rejection payload unchanged and does NOT refresh the local fast-cache.

Args: bot_id: Registered bot slug. scope_path: Lease scope (workspace path or identifier). summary: Short activity note (secret-masked before storage). fencing_token: Monotonic fencing token; higher wins on a live lease.

Inputs: bot_id (required), summary (required), scope_path (required), fencing_token. Returns: object

check_healthA

Checks BoteX environment readiness (provider keys, snapshot dir, disk).

Inputs: no named parameters. Returns: result

clean_snapshotsC

Purges old or excess backup snapshots from disk.

Inputs: max_age_days, max_total_mb. Returns: result

delete_memoryA

Deletes a specific memory entry by ID from the workspace or global Memory Vault and removes its index/graph links.

Args: memory_id: The ID of the memory entry to delete (e.g. 'mem_a1b2c3d4'). workspace_dir: Workspace root directory. Empty = engine.default_workspace from the config, else the server's current directory. scope: Lookup scope ('local', 'global', or 'all'). Default is 'local'.

Inputs: memory_id (required), scope, workspace_dir. Returns: object

fetch_urlA

Fetch one public http(s) text document for caller-side research.

This tool is intentionally separate from BoteX's internal read_url: the orchestrating agent chooses the URL, so arbitrary public hosts do not have to be configured in net.allowed_hosts. SSRF protections, redirect revalidation, content-type checks, byte limits, and secret masking still apply. In net.policy='allowlist', only configured hosts may be fetched.

Inputs: url (required), max_bytes. Returns: object

find_graph_healthB

Audits Memory Vault knowledge graph integrity: reports broken links, orphan notes, and cycles.

Args: workspace_dir: Workspace root directory. scope: Lookup scope ('local', 'global', or 'all').

Inputs: scope, workspace_dir. Returns: object

get_outlineB

Returns a lightweight file skeleton (classes, methods, functions, headers, line numbers) without reading the whole file. Saves ~90% of tokens.

Inputs: path (required), workspace_dir. Returns: object

get_statsA

Returns an analytics summary of executed BoteX tasks (USD costs, token usage, code-line balance). Args: period: 'week' (last 7 days) or 'month' (last 30 days).

Inputs: period. Returns: result

get_task_statusA

Return status and result for a task started with start_task.

status is the task lifecycle (QUEUED | RUNNING | DONE | FAILED | CANCELLED) — DONE here means "finished", not "succeeded"; check result_data.status / result_data.ok for the engine outcome. result is the pretty-text report; result_data is the structured engine result (status, failure_kind, ok, files_touched, exec_ran, rollback_verified, attempts[], cost_usd, ...).

Inputs: task_id (required). Returns: object

init_obsidian_vaultA

Initializes or syncs Obsidian PKM vault configuration (.obsidian/graph.json, app.json) with preset color profiles for #decision, #lesson, #handoff, #context.

Args: workspace_dir: Workspace root directory. scope: Target scope ('local' or 'global'). override_existing: Whether to overwrite existing .obsidian config files. export_index: Also generate dynamic _GRAPH_INDEX.md note.

Inputs: scope, export_index, workspace_dir, override_existing. Returns: object

patch_memory_sectionA

Surgically updates a Markdown section (e.g. '## Compiled Truth') in a memory note without modifying frontmatter, other sections, or the Timeline audit trail.

Args: memory_id: Target memory ID to patch. section: Section heading to replace or create (default 'Compiled Truth'). new_content: New Markdown text for the section. workspace_dir: Workspace root directory. scope: Lookup scope ('local' or 'global'). append: Whether to append to existing section content instead of replacing. origin: Optional provenance identifier '@'. Falls back to X-Agent-Id@X-Host session header or 'botex'.

Inputs: memory_id (required), scope, append, origin, +3 more. Returns: object

read_memoryA

Reads the full content and metadata of a specific memory entry by ID from the Memory Vault.

Args: memory_id: The ID of the memory entry to retrieve (e.g. 'mem_a1b2c3d4'). workspace_dir: Workspace root directory. Empty = engine.default_workspace from the config, else the server's current directory. scope: Lookup scope ('local', 'global', or 'all'). Default is 'local'.

Inputs: memory_id (required), scope, workspace_dir. Returns: object

read_scratchpadB

Reads the full execution or terminal log offloaded to the scratchpad (.botex/scratchpad/<memory_id>.log).

Args: memory_id: The ID of the scratchpad entry (e.g. 'mem_exec_a1b2c3d4'). workspace_dir: Workspace root directory. Empty = engine.default_workspace from the config, else the server's current directory.

Inputs: memory_id (required), workspace_dir. Returns: object

recall_memoryA

One-shot recall: ask the Memory Vault a natural-language question and get a synthesized answer with sources in a single call. BoteX gathers the top search hits plus their 1-hop graph neighbourhood (wikilinks + backlinks), then a server-side curator model (Ollama -> NVIDIA -> Gemini -> OpenRouter free) answers strictly from those notes. Falls back to a deterministic digest when no model is available. Use read_memory on a returned source only when you need the full raw note.

Args: query: Natural-language question or topic. workspace_dir: Workspace root directory. Empty = engine.default_workspace from the config, else the server's current directory. topic: Optional tag restricting the search to a thematic bucket. scope: 'local', 'global', or 'all'. Default is 'all'. project: Optional project slug filter restricting initial search hits.

Returns: {ok, answer, sources, confidence (HIGH|MEDIUM|LOW|NOT_FOUND), tier_used, context_nodes, truncated}

Inputs: query (required), scope, topic, project, +1 more. Returns: object

recommend_modelsB

[EN] Fetches the most cost-effective and capable models from OpenRouter based on live benchmarks. USE THIS TOOL BEFORE calling run_subagent if you are unsure which model ID to use or want to optimize for cost/quality. include_free=True also admits ':free' variants (non-ZDR — prompts may be logged/trained on); they require allow_non_zdr or the openrouter-free provider to actually run.

[PL] Pobiera rekomendacje modeli z OpenRouter na podstawie benchmarków. Użyj tego narzędzia ZANIM wywołasz run_subagent, jeśli nie znasz dokładnego ID modelu. include_free=True dopuszcza warianty ':free' (non-ZDR — prompty mogą być logowane/trenowane); do uruchomienia wymagają allow_non_zdr albo providera openrouter-free.

Inputs: tier, limit, recipe, profile, +3 more. Returns: result

reflect_memoryA

Synthesizes gathered facts, decisions, beliefs, and heuristics from the Memory Vault into an ordered reasoning digest (Hindsight-style reflection). Entries are grouped by kind (decisions, beliefs, heuristics, lessons, handoffs, context) and ranked by confidence and recency — fully deterministic and local, with no LLM calls.

Args: query: Free-text query steering which memories to reflect on. workspace_dir: Workspace root directory. Empty = engine.default_workspace from the config, else the server's current directory. topic: Optional tag restricting the reflection to a thematic bucket. min_confidence: Minimum certainty threshold in [0.0, 1.0]. Default 0.5. scope: Reflection scope ('local', 'global', or 'all'). Default is 'all'. project: Optional project slug filter.

Inputs: query (required), scope, topic, project, +2 more. Returns: object

run_subagentA

Runs BoteX — an autonomous code execution engine (agent-agnostic harness). BoteX performs multi-step tasks on local files inside workspace_dir.

TIP: If the user didn't specify a model, DO NOT guess. Use the recommend_models tool first to find the best model for this task!

Key engine features:

  • Outline-First and Context Pruning: ~90% token savings.

  • Pre-write Syntax Check: in-memory code validation before touching disk.

  • Multi-tier Fuzzy Patching: tolerant of CRLF/LF and indentation drift.

  • Hard Zero-Retention on OpenRouter (provider: data_collection=deny) and DLP secret censoring.

  • Automatic Snapshot Rollback on loops or critical failures.

Args: task: Precise description of the coding or refactoring task. files: Optional list of primary files affected by the task. workspace_dir: Project directory path. Empty = engine.default_workspace from the config, else the server's current directory. model: Any model from the provider's catalog. Empty = model from config (see 'profile' and botex.config.json). profile: Model profile from botex.config.json (e.g. 'default', 'coding', 'auto-beta', 'fast'). When both 'model' and 'profile' are empty, the capability mode picks the tier via engine.mode_profiles (readonly -> 'fast', destructive/full -> 'coding'). Ignored when 'model' is given explicitly. provider: API provider from the 'providers' section of botex.config.json ('openrouter', 'nvidia', 'google', 'openrouter-free', 'ollama'). Empty = provider marked 'default: true' in the configuration. mode: Capability preset: 'readonly' (read only — the contract is an analysis report, DONE requires non-empty findings), 'edit' (read + edit — default), 'destructive' (+delete/move), 'full' (+run_command). Empty = engine.default_mode from config. Explicit allow_* flags may widen ordinary presets, but 'readonly' and 'chat' are hard read-only modes and cannot gain local writes, destructive operations, or command execution. In headless mode this is pre-authorization — grant it consciously. max_turns: Maximum tool-loop steps (0 = config value). max_tokens: Per-turn completion cap (0 = config value; reasoning models need ~8000+ since thinking shares this budget). max_duration_s: Total wall-clock limit in seconds (0 = config value, 0 disables only when config is also 0). Checked between turns. budget_limit_usd: Daily spend limit in USD (negative = config value, 0 = no limit). allow_destructive: Authorize destructive operations (delete_file/ move_file) for this task. Headless mode cannot confirm mid-run — grant ONLY with the user's consent. allow_exec: Authorize run_command for this task (also requires exec.enabled=true in config). WARNING: this is NOT a sandbox — commands run with operator privileges. Grant only for trusted workspaces with the user's consent. api_key: Optional provider API key passed per-request (highest priority — overrides env/.env/config). Empty = resolved internally by the harness. output_path: Optional required output file (workspace-relative). Sets the file_output contract: DONE is accepted only when the file exists on disk, is non-empty, and passes the syntax gate; a DONE response carrying the payload as text is salvaged to disk. Requires a mutating mode. allow_net: Explicitly authorizes the read-only public web tool for this run. It is never enabled by a capability mode. net_allowed_hosts: Optional per-run host authorization. In net.policy='caller' these replace config defaults; in 'public' they narrow public access; in 'allowlist' they must stay inside net.allowed_hosts. net_allowed_urls: Optional per-run URL authorization rules. A URL ending in '/' authorizes that subtree; otherwise it authorizes the exact URL including its query string. verify_command: Optional allowlisted command that must pass before DONE is accepted — it runs against the workspace as it stands, including when the task made no writes (a passing verifier validates a legitimate no-change result). Requires exec.enabled=true in config and exec authorization. recipe: Optional operational persona / workflow prompt (e.g. 'planner', 'code-explorer', 'reviewer', 'security-reviewer', 'build-resolver', 'tdd'). allow_non_zdr: Per-run consent to relax the Zero Data Retention gate. Required for free (:free) models whose endpoints may log or train on prompts — it also switches the wire provider.data_collection flag to 'allow'. Grant only with the operator's consent; the result carries zdr_enforced=false. The openrouter-free provider preset is the persistent config-level alternative. approval_policy: Operator approval policy for risky operations: 'none', 'high_risk' (default), 'mutations', 'all_risky'.

Returns: A pretty-text report in the text content (unchanged format for legacy clients) plus the full engine result as structuredContent (status, failure_kind, ok, files_touched, exec_ran, rollback_verified, attempts[], cost_usd, ...). ok is true only when status == DONE — i.e. the task contract was verified, not merely claimed by the model.

Inputs: task (required), mode, files, model, +20 more. Returns: Structured result of a finished BoteX run. `status` is one of the engine status…

save_memoryA

Saves a persistent context note, architectural decision, task handoff, lesson, belief, or heuristic into the workspace or global shared Memory Vault. Masks secrets and provides directory isolation.

Args: title: Short descriptive title of the memory entry. content: Detailed markdown notes, architectural rationale, or handoff context. workspace_dir: Workspace root directory. Empty = engine.default_workspace from the config, else the server's current directory. kind: Entry category ('context' | 'decision' | 'handoff' | 'lesson' | 'belief' | 'heuristic'). tags: Optional list of keyword tags for filtering and discovery. memory_id: Optional custom identifier (alphanumeric/hyphen/underscore). Auto-generated if omitted. scope: Storage scope ('local' for workspace, 'global' for cross-workspace). Default is 'local'. confidence: Certainty score in [0.0, 1.0] for belief/heuristic-style entries. Default 1.0. project: Optional project slug (e.g. 'botex', 'tw3se', 'swarm') for logical partitioning. origin: Optional provenance identifier '@'. Falls back to X-Agent-Id@X-Host session header or 'botex'. Reserved identity claims ('human', 'human-curated', 'operator', 'curator') are rejected.

Inputs: title (required), content (required), kind, tags, +6 more. Returns: object

search_memoryA

Searches the Memory Vault by keyword query, tag, or entry kind (context, decision, handoff, lesson, belief, heuristic) across local, global, or all scopes. Directly linked notes surface via spreading activation over the wikilink graph.

Args: workspace_dir: Workspace root directory. Empty = engine.default_workspace from the config, else the server's current directory. query: Free-text search string matched against title, content, and tags. tag: Filter by specific tag. kind: Filter by entry kind ('context', 'decision', 'handoff', 'lesson', 'belief', 'heuristic'). scope: Search scope ('local', 'global', or 'all'). Default is 'local'. since: Optional ISO-8601 date/datetime lower bound on entry timestamps. until: Optional ISO-8601 date/datetime upper bound on entry timestamps. min_confidence: Optional minimum certainty threshold in [0.0, 1.0]. project: Optional project slug filter (or '_unassigned' for entries without a project).

Inputs: tag, kind, query, scope, +5 more. Returns: object

start_taskA

Start a detached BoteX task and return its task_id immediately.

Runs the same engine as run_subagent, but returns instantly with a task_id for polling via get_task_status. Concurrency is bounded by engine.max_concurrent_tasks and the queue by engine.max_queued_tasks — a full queue returns status TOO_MANY_QUEUED.

The capability/limits arguments are identical to run_subagent — same contracts, same pre-authorization semantics:

  • mode: capability preset — 'readonly' (read tools only; the contract is an analysis report), 'edit' (read + write; default), 'destructive' (+ delete/move), 'full' (+ run_command). Empty = engine.default_mode.

  • allow_destructive / allow_exec / allow_net widen ordinary presets, never narrow them. 'readonly' and 'chat' are hard read-only modes and cannot gain local writes, destructive operations, or command execution. allow_exec additionally requires exec.enabled=true in the config. None of these is a sandbox: grant them only with the user's consent.

  • output_path makes the contract file_output: DONE requires the file to exist, be non-empty, and pass the syntax gate (mutating mode).

  • verify_command is an allowlisted command that must pass before DONE is accepted — it runs even when the task made no writes. Requires exec authorization.

  • recipe: Optional operational persona / workflow prompt (e.g. 'planner', 'code-explorer', 'reviewer', 'security-reviewer', 'build-resolver', 'tdd').

  • max_turns / max_tokens / max_duration_s / budget_limit_usd: 0 (negative for budget) = config value; a non-positive max_turns is clamped to 1.

  • net_allowed_hosts / net_allowed_urls narrow or replace the net scope per run according to net.policy (see run_subagent).

  • allow_non_zdr: per-run consent to relax Zero Data Retention — needed for free (:free) models whose endpoints may log or train on prompts. Same semantics as in run_subagent.

  • approval_policy: Operator approval policy for risky operations: 'none', 'high_risk', 'mutations', or 'all_risky'.

Returns: {"task_id": str, "status": "QUEUED"} — poll with get_task_status. The finished task's result_data carries the full engine result (status, failure_kind, ok, files_touched, exec_ran, rollback_verified, attempts[], cost_usd, ...).

Inputs: task (required), mode, files, model, +20 more. Returns: object

swarm_list_botsA

Lists registered Tethered Bots with their active host leases and brief metadata. Cloud Soul store is authoritative; entries that exist only in the local edge fast-cache are merged in and marked source: local_cache.

Args: namespace: Optional exact namespace filter (empty = all namespaces).

Inputs: namespace. Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.3/5.0

    Scored across 25 tools

    Disambiguation3/5

    Most tools have distinct targets, but the memory-retrieval cluster (search_memory vs recall_memory vs reflect_memory) overlaps conceptually, and run_subagent vs start_task are the same engine exposed two ways — differentiated only by long prose rather than by name. The violation/penalty tools are explicitly fenced off from save_memory, which helps, but an agent must read carefully to pick the right retrieval verb.

    Naming Consistency4/5

    Nearly all names are snake_case verb_noun (save_memory, read_memory, patch_memory_section, get_task_status). Minor deviations exist: a botex_ prefix on the penal-ledger tools and swarm_list_bots (noun_verb_noun) break the verb-first pattern, and find_graph_health is really an audit/check rather than a 'find'.

    Tool Count3/5

    25 tools is at the heavy end of the range even for a server spanning memory vault, task engine, swarm coordination, and a penal ledger. Each of the four sub-surfaces is reasonably sized on its own, but the combined surface is broad enough that discoverability and correct selection suffer.

    Completeness3/5

    Memory CRUD is mostly covered (save/read/delete/patch/search/graph), but there is no list/enumerate-memories tool and no metadata update (tags, confidence, title) apart from section patching. The task lifecycle is notably incomplete: get_task_status reports CANCELLED but there is no cancel_task or list-tasks operation, forcing agents to poll and wait out runs.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables MCP-capable coding assistants to delegate repository investigation, bounded implementation work, and noisy command runs (tests, builds, linters) to sandboxed OpenCode agents. Each role can use an independently selected model, and only concise results are returned to the parent agent, which keeps responsibility for architecture and high-risk operations.
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables delegating tasks to agents you configure yourself through OpenAI-compatible Chat Completions backends, with automatic or explicit routing, synchronous calls, persistent asynchronous jobs, and multi-step reviewed workflows. It returns proposals and analyses only, leaving file changes, command execution, and approvals under the MCP client's control.
      20 npm
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables MCP clients to delegate work to nested subagents running on Codex and Claude Code, keeping each task's session, turn history and results durable in SQLite while the main chat continues. Supports async or blocking waits, mid-session context updates, git worktree isolation, read-only-by-default permission inheritance, and cancelling whole subagent trees.
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables an MCP client to delegate coding work to independently configured sub-agent sessions with any connected model, agents, skills, parallel execution, permission controls, and full API access, returning answers, changed files, and costs.
      15
      MIT