jcode/README.md

9.4 KiB

jcode

A minimal, single-file coding agent (~1,200 lines of Python) for local LLMs — with optional cloud fallback.

jcode connects to a local LM Studio or Ollama server (or, via settings.json, to OpenAI, Anthropic, or Gemini), takes a task in plain language, and works autonomously inside a sandboxed ./code directory: it reads, writes, and edits files, runs commands, searches the web, looks at images/screenshots/PDF pages, writes its own smoke tests, and keeps fixing the code until the tests pass.

   _               _
  (_) ___ ___   __| |  ___
  | |/ __/ _ \ / _  | / _ \
  | | (_| (_) | (_| ||  __/
 _/ |\___\___/ \____| \___|
|__/

Features

  • Autonomous test-fix loop — the agent writes a test for every change, runs it, analyzes failures, fixes the code, and repeats until green (up to MAX_STEPS, default 200).
  • Sandboxed — all file operations are confined to ./code; path-escape attempts (../, absolute paths) are blocked. Destructive shell commands (rm -rf /, sudo, dd, mkfs, shutdown, fork bombs, curl | sh, …) are refused.
  • Zero-config local backends — auto-detects LM Studio (port 1234) first, then Ollama (port 11434).
  • Cloud providers via settings.json — switch to OpenAI, Anthropic, or Gemini at runtime with /backend <name>; all are used through their OpenAI-compatible endpoints, so the single openai client dependency covers everything.
  • Project guidelines via AGENTS.md — project-specific rules (coding style, per-language test conventions) are loaded from code/AGENTS.md and injected as binding instructions.
  • Vision — the agent can look at images, screenshots and PDF pages (see the view_image/take_screenshot/view_pdf_page tools below) to visually check its own work, e.g. a generated plot or a running GUI.
  • Session-wide context management — token usage is tracked (server-reported or estimated); when the context nears its limit, older history is compacted into an LLM-written summary so long sessions keep working.
  • Adjustable reasoning effort — /reasoning high|medium|low|max|none controls the model's thinking effort at runtime (backend-dependent; none turns it off).
  • Robust against flaky servers — visible retries with backoff; if the backend goes down, the session is preserved and the task can simply be resubmitted.
  • Transparent — every request, tool call, and result is logged to logFile.md; file changes are shown as colored unified diffs in the terminal.
  • Tools available to the model:
    • list_files, read_file (optionally with line numbers), search_files (regex grep over the sandbox, hits as file:line: content)
    • write_file, edit_file (search/replace), insert_lines, delete_lines
    • run_command (blocks known-destructive patterns; pip/pip3 calls are redirected to jcode's own Python interpreter)
    • web_search (DuckDuckGo) and fetch_url (fetches a page and extracts its text)
    • view_image (png/jpg/gif/webp/bmp/svg), take_screenshot (whole screen, e.g. of a GUI app under test), view_pdf_page (renders one PDF page) — images are delivered to the model as an inline image right after the tool result

Requirements

  • Python 3.10+
  • pip install openai prompt_toolkit ddgs
  • One of:
    • LM Studio with the local server running (default http://localhost:1234), or
    • Ollama (http://localhost:11434), or
    • an API key for OpenAI / Anthropic / Gemini (see settings.json below)
  • Optional, only needed for the vision tools (the agent will tell you what's missing and how to install it when it tries to use one):
    • Pillow — view_image, take_screenshot, view_pdf_page
    • cairosvg — view_image on .svg files
    • pymupdf — view_pdf_page
    • certifi — CA bundle for fetch_url; falls back to the system default if not installed. Set JCODE_INSECURE_SSL=1 to disable TLS verification (e.g. behind a re-signing corporate proxy) — use with care.

Usage

# One-shot task
python jcode.py "Write fib.py with fib(n) and a smoke test that checks fib(10)==55."

# Interactive mode (multiline input; history is kept across tasks)
python jcode.py

All generated files land in ./code, which is created automatically.

Interactive commands

Command Effect
/status Show context usage, message counts, model, sandbox
/new, /neu, /reset Clear the session history
/models List models available on the current backend
/model <name> Switch model
/backend <name> Switch to lm-studio, ollama, or a provider from settings.json (e.g. openai, anthropic, gemini)
/reasoning <level> Set reasoning effort: high, medium, low, max, or none (off); no argument resets to the backend default
/max-turns N Set the step limit per task
Ctrl+C Abort the current input or running task (session is preserved)
Ctrl+D, or Ctrl+C on an empty prompt Quit

Configuration

settings.json (optional)

Placed next to jcode.py. Defines cloud providers and, optionally, the backend to start on. API keys are read from environment variables — don't put literal keys in the file.

{
  "default_provider": "",
  "providers": {
    "openai": {
      "base_url": "https://api.openai.com/v1",
      "api_key_env": "OPENAI_API_KEY",
      "model": "gpt-4.1"
    },
    "anthropic": {
      "base_url": "https://api.anthropic.com/v1/",
      "api_key_env": "ANTHROPIC_API_KEY",
      "model": "claude-sonnet-4-5"
    },
    "gemini": {
      "base_url": "https://generativelanguage.googleapis.com/v1beta/openai/",
      "api_key_env": "GEMINI_API_KEY",
      "model": "gemini-2.5-pro"
    }
  }
}
  • default_provider: name of a provider to activate at startup; leave "" to use the auto-detected local backend.
  • Each provider needs base_url (an OpenAI-compatible endpoint), api_key_env (environment variable holding the key), and optionally model.
  • If the file is missing or malformed, jcode prints a warning and runs purely locally.
export ANTHROPIC_API_KEY=sk-ant-...
python jcode.py
Task> /backend anthropic

AGENTS.md (optional)

If code/AGENTS.md exists, it is loaded at session start and treated as binding project guidelines — e.g. "simplicity first", surgical changes only, and the per-language verification conventions (how to compile/test C, C++, Java, PHP, Python, HTML, CSS). Keeping language-specific rules here rather than in the system prompt keeps every request lean and lets you adapt conventions per project without touching code.

Constants in jcode.py

Constant Default Meaning
MODEL (auto) Model name; auto-corrected to the closest available model
MAX_STEPS 200 Tool-use steps per task
CMD_TIMEOUT 60 s Default timeout per shell command (overridable per call via the timeout argument)
CONTEXT_LIMIT 256 000 Model context window (tokens)
COMPACT_THRESHOLD 250 000 History compaction kicks in above this
KEEP_RECENT 8 Most recent messages kept uncompressed when compacting
REQUEST_TIMEOUT 11 600 s Timeout per LLM request (local models are slow)
REASONING_EFFORT (backend default) Reasoning effort sent to the backend; set at runtime with /reasoning
MAX_IMAGE_SIDE 1280 px Longest edge images are scaled to before being sent to the model
MAX_IMAGES_IN_CONTEXT 4 Older images beyond this are replaced by a text stub to save context

How it works

  1. The task is appended to the session history and sent to the model together with the tool schemas (derived automatically from the Python type annotations — no schema drift).
  2. The model plans, calls tools (read → edit → run test), and gets each result back.
  3. Failing tests loop back into analysis and fixes; only when the tests are green does the model answer with a summary and the turn ends.
  4. Near the context limit, the older history is summarized by the model itself and replaced, so the session can continue indefinitely.

Safety notes

jcode blocks known-destructive command patterns and confines file access to the sandbox, but run_command still executes shell commands on your machine with your user's permissions. Review logFile.md when in doubt, and treat web content fetched by the agent as untrusted data.

License

MIT License — Copyright (c) 2026 Prof. Dr. Joern Fischer

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.