Update 2026-11-23 13:04:16

multimodal
Jörn Fischer 2026-11-23 13:04:17 +01:00
parent 2f7116b954
commit 9580c6bb76
2 changed files with 171 additions and 65 deletions

218
jcode.py
View File

@ -14,7 +14,9 @@ import shutil
import signal import signal
import subprocess import subprocess
import sys import sys
import tempfile
import time import time
import traceback
import ssl import ssl
import urllib.request import urllib.request
@ -31,7 +33,7 @@ from openai import OpenAI
# --------------------------------------------------------------- Configuration # --------------------------------------------------------------- Configuration
APP_NAME = "jcode" APP_NAME = "jcode"
APP_VERSION = "1.0" APP_VERSION = "1.01"
DEFAULT_MODEL = "qwen3.8-27b-splash" #"qwen3.6-35b-a3b-uncensored-hauhaucs-aggressive" DEFAULT_MODEL = "qwen3.8-27b-splash" #"qwen3.6-35b-a3b-uncensored-hauhaucs-aggressive"
MODEL = DEFAULT_MODEL MODEL = DEFAULT_MODEL
@ -64,7 +66,9 @@ SETTINGS_FILE = Path("settings.json")
def _load_settings() -> dict: def _load_settings() -> dict:
"""Reads settings.json: providers (OpenAI/Anthropic/Gemini via OpenAI-compatible endpoints) for '/backend <name>', """Reads settings.json: providers (OpenAI/Anthropic/Gemini via OpenAI-compatible endpoints) for '/backend <name>',
plus Claude-Code-style "autoCompactEnabled" (bool) and "autoCompactWindow" (context window plus Claude-Code-style "autoCompactEnabled" (bool) and "autoCompactWindow" (context window
of the model, e.g. "256k"; the history is compacted at 80% of it).""" of the model, e.g. "256k"; the history is compacted at 80% of it; the same key inside a
provider entry overrides it for that provider's model), "sandbox" (false = no OS
sandbox for run_command) and "sandboxWritable" (extra writable paths inside it, e.g. ["~/go"])."""
try: try:
return json.loads(SETTINGS_FILE.read_text(encoding="utf-8")) if SETTINGS_FILE.is_file() else {} return json.loads(SETTINGS_FILE.read_text(encoding="utf-8")) if SETTINGS_FILE.is_file() else {}
except Exception as e: # noqa: BLE001 except Exception as e: # noqa: BLE001
@ -101,7 +105,8 @@ def _switch_backend(name: str) -> None:
print(f"{RED}\u2717 API key for '{name}' missing (set env {prov.get('api_key_env')}).{RESET}"); return print(f"{RED}\u2717 API key for '{name}' missing (set env {prov.get('api_key_env')}).{RESET}"); return
BASE_URL, _API_KEY, BACKEND, MODEL = prov["base_url"], key, name, prov.get("model", MODEL) BASE_URL, _API_KEY, BACKEND, MODEL = prov["base_url"], key, name, prov.get("model", MODEL)
client = OpenAI(base_url=BASE_URL, api_key=_API_KEY, timeout=REQUEST_TIMEOUT, max_retries=0) client = OpenAI(base_url=BASE_URL, api_key=_API_KEY, timeout=REQUEST_TIMEOUT, max_retries=0)
print(f"{DIM}Backend: {BACKEND} ({BASE_URL}) | Model: {MODEL}{RESET}"); return _set_context(prov.get("autoCompactWindow"))
print(f"{DIM}Backend: {BACKEND} ({BASE_URL}) | Model: {MODEL} | Context: {CONTEXT_LIMIT:,}{RESET}"); return
url = _OLLAMA_URL if "ollama" in name.lower() else _LM_STUDIO_URL url = _OLLAMA_URL if "ollama" in name.lower() else _LM_STUDIO_URL
key, bname = ("ollama", "Ollama") if url == _OLLAMA_URL else ("lm-studio", "LM Studio") key, bname = ("ollama", "Ollama") if url == _OLLAMA_URL else ("lm-studio", "LM Studio")
models = _fetch_models(url) models = _fetch_models(url)
@ -109,6 +114,7 @@ def _switch_backend(name: str) -> None:
MODEL = _pick_model(models) MODEL = _pick_model(models)
BASE_URL, _API_KEY, BACKEND = url, key, bname BASE_URL, _API_KEY, BACKEND = url, key, bname
client = OpenAI(base_url=BASE_URL, api_key=_API_KEY, timeout=REQUEST_TIMEOUT, max_retries=0) client = OpenAI(base_url=BASE_URL, api_key=_API_KEY, timeout=REQUEST_TIMEOUT, max_retries=0)
_set_context()
print(f"{DIM}Backend: {BACKEND} ({BASE_URL}) | Model: {MODEL}{RESET}") print(f"{DIM}Backend: {BACKEND} ({BASE_URL}) | Model: {MODEL}{RESET}")
SANDBOX = Path("code").resolve() SANDBOX = Path("code").resolve()
@ -116,12 +122,16 @@ MAX_STEPS = 200
MAX_REPEATS = 3 # identical tool calls (within REPEAT_WINDOW) or same-error failures before a reflection step; twice = stop MAX_REPEATS = 3 # identical tool calls (within REPEAT_WINDOW) or same-error failures before a reflection step; twice = stop
REPEAT_WINDOW = 10 # how many recent tool calls an identical call is compared against (catches A-B-A-B cycles) REPEAT_WINDOW = 10 # how many recent tool calls an identical call is compared against (catches A-B-A-B cycles)
CMD_TIMEOUT = 60 # seconds per command (compiling C/C++/Java takes time) CMD_TIMEOUT = 60 # seconds per command (compiling C/C++/Java takes time)
CONTEXT_LIMIT = _parse_tokens(SETTINGS.get("autoCompactWindow"), 256_000) # context window of the model (tokens) def _set_context(window=None) -> None:
COMPACT_THRESHOLD = CONTEXT_LIMIT * 8 // 10 # history is compacted from here on (80%: headroom for the next response) """Context window (tokens): the provider's "autoCompactWindow", else the global one; compaction starts at 80%."""
global CONTEXT_LIMIT, COMPACT_THRESHOLD
CONTEXT_LIMIT = _parse_tokens(window or SETTINGS.get("autoCompactWindow"), 256_000)
COMPACT_THRESHOLD = CONTEXT_LIMIT * 8 // 10 # headroom for the next response
_set_context()
AUTO_COMPACT = bool(SETTINGS.get("autoCompactEnabled", True)) # false = never compact AUTO_COMPACT = bool(SETTINGS.get("autoCompactEnabled", True)) # false = never compact
INLINE_SKILLS = bool(SETTINGS.get("inlineSkills", False)) # true = full SKILL.md texts in the system prompt (models that ignore the catalog) INLINE_SKILLS = bool(SETTINGS.get("inlineSkills", False)) # true = full SKILL.md texts in the system prompt (models that ignore the catalog)
KEEP_RECENT = 8 # most recent messages kept uncompressed KEEP_RECENT = 8 # most recent messages kept uncompressed
REQUEST_TIMEOUT = 11600 # seconds per LLM request (local models are slow) REQUEST_TIMEOUT = 3600 # seconds per LLM request (local models are slow)
RETRY_WAITS = (5, 15, 30, 60) # wait times between retry attempts RETRY_WAITS = (5, 15, 30, 60) # wait times between retry attempts
REASONING_EFFORT = "medium" # "high"|"medium"|"low"|"max"|"none" (Ollama /v1); None = backend default ('/reasoning default') REASONING_EFFORT = "medium" # "high"|"medium"|"low"|"max"|"none" (Ollama /v1); None = backend default ('/reasoning default')
TEMPERATURE = 0.3 # sampling temperature for the agent loop; 0.7 made small models "try another file name" instead of reading the error TEMPERATURE = 0.3 # sampling temperature for the agent loop; 0.7 made small models "try another file name" instead of reading the error
@ -144,13 +154,10 @@ def _log(header: str, body: str = "") -> None:
def _load_agents_md() -> str: def _load_agents_md() -> str:
"""Reads AGENTS.md from the project (sandbox) directory, if present.""" """Reads AGENTS.md from the project (sandbox) directory, if present."""
agents_file = SANDBOX / "AGENTS.md" try:
if agents_file.is_file(): return (SANDBOX / "AGENTS.md").read_text(encoding="utf-8").strip()
try: except OSError: # missing or unreadable
return agents_file.read_text(encoding="utf-8").strip() return ""
except OSError:
return ""
return ""
client = OpenAI( client = OpenAI(
base_url=BASE_URL, base_url=BASE_URL,
@ -221,8 +228,8 @@ def _resolve(path: str, write: bool = False) -> Path:
while parts and parts[0] == SANDBOX.name: while parts and parts[0] == SANDBOX.name:
parts.pop(0) parts.pop(0)
p = SANDBOX.joinpath(*parts) p = SANDBOX.joinpath(*parts)
elif not _inside(p.resolve(), SANDBOX) and _garbled_sandbox_tail(parts) is not None: elif not _inside(p.resolve(), SANDBOX) and (tail := _garbled_sandbox_tail(parts)) is not None:
p = SANDBOX.joinpath(*_garbled_sandbox_tail(parts)) p = SANDBOX.joinpath(*tail)
p = p.resolve() p = p.resolve()
if _inside(p, SANDBOX): if _inside(p, SANDBOX):
return p return p
@ -259,15 +266,13 @@ MAX_READ_LINES = 2000 # read_file returns at most this many lines per call
def _walk(base: Path): def _walk(base: Path):
"""Files and dirs under base, skipping SKIP_DIRS; yields (path, skipped_dir_entry_count).""" """Files and dirs under base, skipping SKIP_DIRS; yields (path, skipped_dir_entry_count)."""
for p in sorted(base.rglob("*")): found = []
rel = p.relative_to(base).parts for root, dirs, files in os.walk(base):
if any(part in SKIP_DIRS for part in rel[:-1]): skipped = [d for d in dirs if d in SKIP_DIRS]
continue # inside a skipped folder dirs[:] = [d for d in dirs if d not in SKIP_DIRS] # pruned: os.walk does not descend into them
if p.name in SKIP_DIRS: found += [(Path(root, n), None) for n in dirs + files if n not in SKIP_DIRS]
if p.is_dir(): found += [(Path(root, d), sum(len(ds) + len(fs) for _, ds, fs in os.walk(Path(root, d)))) for d in skipped]
yield p, sum(1 for _ in p.rglob("*")) return sorted(found, key=lambda t: t[0])
continue
yield p, None
def list_files(subdir: str = ".") -> str: def list_files(subdir: str = ".") -> str:
base = _resolve(subdir) base = _resolve(subdir)
@ -626,8 +631,72 @@ def delete_lines(path: str, start_line: int, end_line: int) -> str:
_print_diff(old, new, path) _print_diff(old, new, path)
return f"Lines {start_line}..{end_line} deleted from '{path}'. File now has {len(new.splitlines())} lines." return f"Lines {start_line}..{end_line} deleted from '{path}'. File now has {len(new.splitlines())} lines."
# Patterns for destructive commands that are never executed. Everything else # ------------------------------------------------------------------ OS sandbox
# (tests, compilers, package installation via pip/npm/...) is considered safe. # run_command is confined by the operating system where possible: bubblewrap
# (Linux) or sandbox-exec (macOS). Inside, the file system is read-only except
# for the project, the temp directories, jcode's own venv ('pip install' is
# redirected into it) and "sandboxWritable" paths from settings.json; well-known
# credential stores are unreadable. The network stays open (pip/npm, local test
# servers). Without such a tool - or with "sandbox": false in settings.json -
# only the _DANGEROUS blacklist below applies.
_SECRET_ENV = re.compile(r"(?i)key|token|secret|passw|credential|^SSH_AUTH_SOCK$")
_SECRET_PATHS = (".ssh", ".gnupg", ".aws", ".azure", ".kube", ".docker", ".config/gcloud",
".config/gh", ".netrc", ".git-credentials", ".npmrc", ".pypirc",
"Library/Keychains") # relative to the home directory
_SANDBOX_CMD: list[str] | None = None # command prefix that confines a shell command (set in main)
ISOLATION = "none (command blacklist only)"
def _sandbox_paths() -> tuple[list[Path], list[Path]]:
"""(writable, hidden) paths for the OS sandbox - existing ones only, symlinks resolved."""
writable = [SANDBOX, Path("/tmp"), Path(tempfile.gettempdir()),
*(Path(p).expanduser() for p in SETTINGS.get("sandboxWritable", []))]
if sys.prefix != sys.base_prefix:
writable.append(Path(sys.prefix))
hidden = [Path.home() / p for p in _SECRET_PATHS] + [SETTINGS_FILE] # settings.json may hold API keys
real = lambda paths: list(dict.fromkeys(p.resolve() for p in paths if p.exists()))
return real(writable), real(hidden)
def _init_sandbox() -> None:
"""Builds the sandbox command prefix and keeps it only if a test command runs with it
(bubblewrap needs unprivileged user namespaces, which some systems disable)."""
global _SANDBOX_CMD, ISOLATION
if not SETTINGS.get("sandbox", True):
ISOLATION = "off (settings.json) - command blacklist only"; return
writable, hidden = _sandbox_paths()
if sys.platform == "darwin" and (exe := shutil.which("sandbox-exec")):
sub = lambda paths: " ".join(f"(subpath {json.dumps(str(p), ensure_ascii=False)})" for p in paths)
profile = ("(version 1)(allow default)(deny file-write*)" # the last matching rule wins
f'(allow file-write* (subpath "/dev") {sub(writable)})'
+ (f"(deny file-read* {sub(hidden)})" if hidden else ""))
cmd, name = [exe, "-p", profile], "sandbox-exec"
elif sys.platform.startswith("linux") and (exe := shutil.which("bwrap")):
cmd, name = [exe, "--ro-bind", "/", "/", "--dev", "/dev"], "bubblewrap"
for p in writable:
cmd += ["--bind", str(p), str(p)]
for p in hidden: # mounted last, so they win over a writable parent
cmd += ["--tmpfs", str(p)] if p.is_dir() else ["--ro-bind", "/dev/null", str(p)]
cmd += ["--chdir", str(SANDBOX), "--"]
else:
return
try:
ok = subprocess.run(cmd + ["true"], capture_output=True, timeout=10).returncode == 0
except (OSError, subprocess.SubprocessError):
ok = False
if ok:
_SANDBOX_CMD, ISOLATION = cmd, f"{name} (writes only in project, temp dirs" + (
", venv)" if sys.prefix != sys.base_prefix else ")")
else:
ISOLATION = f"none - {name} is not usable here (command blacklist only)"
def _child_env() -> dict[str, str]:
"""Environment for commands: without API keys/tokens; npm's cache moves out of the read-only home."""
env = {k: v for k, v in os.environ.items() if not _SECRET_ENV.search(k)}
if _SANDBOX_CMD:
env["npm_config_cache"] = str(Path(tempfile.gettempdir()) / "jcode-npm-cache")
return env
# Fallback without an OS sandbox: patterns for destructive commands that are never
# executed. Everything else (tests, compilers, pip/npm installs, ...) is considered safe.
_DANGEROUS = re.compile(r"""(?xi) _DANGEROUS = re.compile(r"""(?xi)
\brm\s+(?:[^;&|>\n]*\s)?['"]?(/|~|\.\.|\$\{?HOME) # rm with any absolute/home/parent argument \brm\s+(?:[^;&|>\n]*\s)?['"]?(/|~|\.\.|\$\{?HOME) # rm with any absolute/home/parent argument
| \b(sudo|doas)\b | (^|[;&|]\s*)su\b # privilege escalation | \b(sudo|doas)\b | (^|[;&|]\s*)su\b # privilege escalation
@ -650,15 +719,16 @@ _SKILL_WRITE = re.compile(r"""(?x) \bsed\s+-i | open\([^)]*['"][wa] | \b(mv|rm|t
_SHELL = shutil.which("bash") if os.name != "nt" else None _SHELL = shutil.which("bash") if os.name != "nt" else None
def run_command(command: str, timeout: int = CMD_TIMEOUT) -> str: def run_command(command: str, timeout: int = CMD_TIMEOUT) -> str:
"""Runs a safe shell command with working directory = sandbox. """Runs a shell command with working directory = sandbox.
Any harmless command is allowed, including installing libraries The command runs inside the OS sandbox (see _init_sandbox) if one is
afterwards (e.g. 'pip install requests', 'npm install lodash'). available; otherwise destructive commands (rm -rf /, sudo, dd, mkfs,
Destructive commands (rm -rf /, sudo, dd, mkfs, shutdown, ...) are shutdown, ...) are blocked by the _DANGEROUS blacklist. API keys are
blocked. Leading 'pip'/'pip3' calls are redirected to the running removed from its environment in both cases. Leading 'pip'/'pip3' calls
Python interpreter so the library lands in jcode's environment. are redirected to the running Python interpreter so the library lands
in jcode's environment.
""" """
if (m := _DANGEROUS.search(command)) is not None: if not _SANDBOX_CMD and (m := _DANGEROUS.search(command)) is not None:
return ("ERROR: command blocked - dangerous pattern " return ("ERROR: command blocked - dangerous pattern "
f"{m.group(0).strip()!r}. Only safe commands are allowed.") f"{m.group(0).strip()!r}. Only safe commands are allowed.")
# judged per simple command, so 'cp <skill-dir>/x . && chmod +x x' passes; with a 'cd' the whole line counts # judged per simple command, so 'cp <skill-dir>/x . && chmod +x x' passes; with a 'cd' the whole line counts
@ -672,8 +742,12 @@ def run_command(command: str, timeout: int = CMD_TIMEOUT) -> str:
if _SHELL and "|" in command: if _SHELL and "|" in command:
# 'node test.js | head' must report test.js's exit code, not head's # 'node test.js | head' must report test.js's exit code, not head's
command = "set -o pipefail; " + command command = "set -o pipefail; " + command
if _SANDBOX_CMD:
popen_args = {"args": _SANDBOX_CMD + [_SHELL or "/bin/sh", "-c", command]}
else:
popen_args = {"args": command, "shell": True, "executable": _SHELL}
proc = subprocess.Popen( proc = subprocess.Popen(
command, shell=True, executable=_SHELL, cwd=SANDBOX, text=True, **popen_args, cwd=SANDBOX, env=_child_env(), text=True,
stdin=subprocess.DEVNULL, # commands waiting for input get EOF instead of blocking until the timeout stdin=subprocess.DEVNULL, # commands waiting for input get EOF instead of blocking until the timeout
stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
start_new_session=True, # own process group: a timeout kills the whole tree (node, chrome, ...) start_new_session=True, # own process group: a timeout kills the whole tree (node, chrome, ...)
@ -694,6 +768,9 @@ def run_command(command: str, timeout: int = CMD_TIMEOUT) -> str:
out = (f"stdout:\n{stdout}\nstderr:\n{stderr}" if stdout and stderr else stdout or stderr or "(no output)") out = (f"stdout:\n{stdout}\nstderr:\n{stderr}" if stdout and stderr else stdout or stderr or "(no output)")
if len(out) > 4000: # save context if len(out) > 4000: # save context
out = out[:2000] + "\n...[truncated]...\n" + out[-2000:] out = out[:2000] + "\n...[truncated]...\n" + out[-2000:]
if _SANDBOX_CMD and re.search(r"Read-only file system|Operation not permitted", out):
out += ("\n[OS sandbox: commands can write only inside the project directory and "
"the temp directory; credential files are not readable]")
if timed_out: if timed_out:
return (f"TIMEOUT after {timeout}s: {shown!r} - process tree killed. " return (f"TIMEOUT after {timeout}s: {shown!r} - process tree killed. "
f"Output until then:\n{out}") f"Output until then:\n{out}")
@ -980,7 +1057,7 @@ def _load_skills() -> dict[str, dict]:
for f in sorted(SKILLS_DIR.glob("*/SKILL.md")): for f in sorted(SKILLS_DIR.glob("*/SKILL.md")):
try: try:
meta, _ = _parse_frontmatter(f.read_text(encoding="utf-8")) meta, _ = _parse_frontmatter(f.read_text(encoding="utf-8"))
except OSError: except (OSError, UnicodeDecodeError):
continue continue
skills[meta.get("name") or f.parent.name] = {"description": meta.get("description", ""), "dir": f.parent} skills[meta.get("name") or f.parent.name] = {"description": meta.get("description", ""), "dir": f.parent}
return skills return skills
@ -1100,8 +1177,8 @@ _TOOL_META = {
"exit_code, stdout and stderr. For smoke tests/tests (e.g. " "exit_code, stdout and stderr. For smoke tests/tests (e.g. "
"'python -m pytest -q') AND for installing missing libraries " "'python -m pytest -q') AND for installing missing libraries "
"(e.g. 'pip install requests', 'npm install lodash'). " "(e.g. 'pip install requests', 'npm install lodash'). "
"Destructive commands (rm -rf /, sudo, dd, mkfs, shutdown, ...) " "Commands are confined: writing outside the project and temp "
"are blocked. Background processes (servers, GUIs) MUST redirect " "directories fails or is blocked. Background processes (servers, GUIs) MUST redirect "
"their output and be detached ('cmd > x.log 2>&1 &'), otherwise " "their output and be detached ('cmd > x.log 2>&1 &'), otherwise "
"the call blocks until the timeout." "the call blocks until the timeout."
), ),
@ -1208,6 +1285,7 @@ def splash_screen() -> None:
print(f" Model : {MODEL}") print(f" Model : {MODEL}")
print(f" Backend : {BACKEND} ({BASE_URL})") print(f" Backend : {BACKEND} ({BASE_URL})")
print(f" Sandbox : {SANDBOX}") print(f" Sandbox : {SANDBOX}")
print(f" Isolation : {ISOLATION}")
print(f" Max steps : {MAX_STEPS}") print(f" Max steps : {MAX_STEPS}")
print(" " + "\u2500" * 50) print(" " + "\u2500" * 50)
print(" Describe a task: Enter submits, Ctrl+J starts a new line, Ctrl+C aborts") print(" Describe a task: Enter submits, Ctrl+J starts a new line, Ctrl+C aborts")
@ -1318,9 +1396,7 @@ def _chat(**kwargs):
for attempt in range(1, attempts + 1): for attempt in range(1, attempts + 1):
try: try:
return client.chat.completions.create(**kwargs) return client.chat.completions.create(**kwargs)
except KeyboardInterrupt: except Exception as e: # noqa: BLE001 (Ctrl+C is not an Exception and passes through)
raise # never swallow Ctrl+C
except Exception as e: # noqa: BLE001
status = getattr(e, "status_code", None) status = getattr(e, "status_code", None)
if status and 400 <= status < 500 and status not in (408, 409, 429): if status and 400 <= status < 500 and status not in (408, 409, 429):
_log("### Request rejected", str(e)) _log("### Request rejected", str(e))
@ -1553,7 +1629,8 @@ def _pick_skills(task: str) -> list[str]:
return [] return []
catalog = "\n".join(f"- {n}: {s['description']}" for n, s in SKILLS.items()) catalog = "\n".join(f"- {n}: {s['description']}" for n, s in SKILLS.items())
try: try:
resp = _chat(model=MODEL, temperature=0, messages=[ effort = {"reasoning_effort": "none" if REASONING_EFFORT == "none" else "low"} if REASONING_EFFORT else {}
resp = _chat(model=MODEL, temperature=0, **effort, messages=[
{"role": "system", "content": "You select skills for a coding agent. Reply ONLY with the " {"role": "system", "content": "You select skills for a coding agent. Reply ONLY with the "
"comma-separated names of the skills whose description matches the task, or 'none'."}, "comma-separated names of the skills whose description matches the task, or 'none'."},
{"role": "user", "content": f"Skills:\n{catalog}\n\nTask:\n{task[:3000]}"}]) {"role": "user", "content": f"Skills:\n{catalog}\n\nTask:\n{task[:3000]}"}])
@ -1591,6 +1668,7 @@ def run(task: str, messages: list, auto_skills: bool = True) -> list:
# arguments (seen in logs: write_file with 20 different file names in a wrong directory). # arguments (seen in logs: write_file with 20 different file names in a wrong directory).
fail_key, fail_streak, fail_nudged = None, 0, False fail_key, fail_streak, fail_nudged = None, 0, False
rejected_once = False # one recovery attempt (strip images / compact) per request rejected_once = False # one recovery attempt (strip images / compact) per request
empty = clean = 0 # empty responses in a row / tool calls in a row without repeat or failure
for step in range(1, MAX_STEPS + 1): for step in range(1, MAX_STEPS + 1):
# Check the context: prefer the real usage values of the last # Check the context: prefer the real usage values of the last
# response, otherwise the character heuristic. Compact on overflow. # response, otherwise the character heuristic. Compact on overflow.
@ -1644,13 +1722,9 @@ def run(task: str, messages: list, auto_skills: bool = True) -> list:
LAST_USAGE_TOKENS = usage.total_tokens LAST_USAGE_TOKENS = usage.total_tokens
msg = resp.choices[0].message msg = resp.choices[0].message
messages.append( messages.append({"role": "assistant", "content": msg.content or ""})
{ if msg.tool_calls: # no key otherwise: strict endpoints reject "tool_calls": null
"role": "assistant", messages[-1]["tool_calls"] = [tc.model_dump() for tc in msg.tool_calls]
"content": msg.content or "",
"tool_calls": [tc.model_dump() for tc in (msg.tool_calls or [])] or None,
}
)
# Show the model's planning/thinking text (its "what am I doing"). # Show the model's planning/thinking text (its "what am I doing").
plan = (msg.content or "").strip() plan = (msg.content or "").strip()
@ -1663,7 +1737,12 @@ def run(task: str, messages: list, auto_skills: bool = True) -> list:
if not msg.tool_calls: if not msg.tool_calls:
if plan: if plan:
return messages return messages
if (empty := empty + 1) >= MAX_REPEATS:
print(f"{RED}\u2717 Task stopped: {empty} empty responses in a row. The session is preserved.{RESET}")
_log("### Error", f"{empty} empty responses in a row - task stopped")
return messages
print(f"{DIM} (empty response) - task probably still open, sending 'continue'...{RESET}"); messages.append({"role": "user", "content": "continue"}); continue print(f"{DIM} (empty response) - task probably still open, sending 'continue'...{RESET}"); messages.append({"role": "user", "content": "continue"}); continue
empty = 0
print(f"\n\u250c\u2500 Step {step}") print(f"\n\u250c\u2500 Step {step}")
for tc in msg.tool_calls: for tc in msg.tool_calls:
@ -1714,6 +1793,9 @@ def run(task: str, messages: list, auto_skills: bool = True) -> list:
key = _error_key(name, str(result)) key = _error_key(name, str(result))
fail_streak = fail_streak + 1 if (key and key == fail_key) else (1 if key else 0) fail_streak = fail_streak + 1 if (key and key == fail_key) else (1 if key else 0)
fail_key = key fail_key = key
clean = 0 if (repeats or key) else clean + 1
if clean >= REPEAT_WINDOW: # working normally again: a later loop gets a new warning first
nudged = fail_nudged = False
if fail_streak >= MAX_REPEATS and fail_streak % MAX_REPEATS == 0 and not fail_nudged: if fail_streak >= MAX_REPEATS and fail_streak % MAX_REPEATS == 0 and not fail_nudged:
result = (f"WARNING: this is failure #{fail_streak} of {name} in a row with the same " result = (f"WARNING: this is failure #{fail_streak} of {name} in a row with the same "
f"kind of error. Changing the arguments slightly will not help.\n{result}") f"kind of error. Changing the arguments slightly will not help.\n{result}")
@ -1761,10 +1843,11 @@ def _discard_incomplete(messages: list) -> None:
def main() -> None: def main() -> None:
global LAST_USAGE_TOKENS, MODEL, MAX_STEPS, REASONING_EFFORT global LAST_USAGE_TOKENS, MODEL, MAX_STEPS, REASONING_EFFORT
SANDBOX.mkdir(exist_ok=True) SANDBOX.mkdir(exist_ok=True)
_init_sandbox()
if (d := SETTINGS.get("default_provider")): _switch_backend(d) if (d := SETTINGS.get("default_provider")): _switch_backend(d)
if len(sys.argv) > 1: if len(sys.argv) > 1:
# Direct call with a task: compact header instead of full-screen splash. # Direct call with a task: compact header instead of full-screen splash.
print(f"{APP_NAME} v{APP_VERSION} | Backend: {BACKEND} | Model: {MODEL} | Sandbox: {SANDBOX}\n") print(f"{APP_NAME} v{APP_VERSION} | Backend: {BACKEND} | Model: {MODEL} | Sandbox: {SANDBOX} | Isolation: {ISOLATION}\n")
run(" ".join(sys.argv[1:]), new_session()) run(" ".join(sys.argv[1:]), new_session())
else: else:
splash_screen() splash_screen()
@ -1780,34 +1863,47 @@ def main() -> None:
break break
if not task: if not task:
continue continue
if task.lower() in ("/neu", "/new", "/reset"): cmd = task.split()[0].lower() if task.startswith("/") else "" # '/model x' -> '/model'
arg = task[len(cmd):].strip()
if cmd in ("/neu", "/new", "/reset"):
session = new_session() session = new_session()
LAST_USAGE_TOKENS = 0 LAST_USAGE_TOKENS = 0
print(f"{DIM}\u267b\ufe0f Session reset - the history was cleared.{RESET}") print(f"{DIM}\u267b\ufe0f Session reset - the history was cleared.{RESET}")
continue continue
if task.lower() == "/status": if cmd == "/status":
print_status(session) print_status(session)
continue continue
if task.lower() == "/skills": if cmd == "/skills":
print("\n".join(f" {n}: {s['description']}" for n, s in SKILLS.items()) or " (no skills in skills/)"); continue print("\n".join(f" {n}: {s['description']}" for n, s in SKILLS.items()) or " (no skills in skills/)"); continue
manual_skill = task.startswith("/") and (sk := task[1:].split(maxsplit=1))[0] in SKILLS manual_skill = task.startswith("/") and (sk := task[1:].split(maxsplit=1))[0] in SKILLS
if manual_skill: # '/<skill> task' - inject the skill instructions directly into the task if manual_skill: # '/<skill> task' - inject the skill instructions directly into the task
task = load_skill(sk[0]) + "\n\nTask: " + (sk[1] if len(sk) > 1 else "Follow the skill instructions.") task = load_skill(sk[0]) + "\n\nTask: " + (sk[1] if len(sk) > 1 else "Follow the skill instructions.")
if task.lower() == "/models": if cmd == "/models":
print("\n".join(f" {m}" for m in (_fetch_models(BASE_URL, _API_KEY) or ["(no models found)"]))); continue print("\n".join(f" {m}" for m in (_fetch_models(BASE_URL, _API_KEY) or ["(no models found)"]))); continue
if task.lower().startswith("/backend"): if cmd == "/backend":
_switch_backend(task[8:].strip()); continue _switch_backend(arg); continue
if task.lower().startswith("/model"): if cmd == "/model":
MODEL = task[6:].strip() or MODEL; print(f"{DIM}Current model: {MODEL}{RESET}"); continue MODEL = arg or MODEL; print(f"{DIM}Current model: {MODEL}{RESET}"); continue
if task.lower().startswith("/reasoning"): if cmd == "/reasoning":
r = task[10:].strip().lower(); REASONING_EFFORT = r if r in ("high", "medium", "low", "max", "none") else (None if r in ("", "default") else REASONING_EFFORT); print(f"{DIM}Reasoning effort: {REASONING_EFFORT or 'default'}{RESET}" if r in ("high", "medium", "low", "max", "none", "", "default") else f"{RED}\u2717 Use: /reasoning high|medium|low|max|none{RESET}"); continue if arg.lower() in ("high", "medium", "low", "max", "none", "", "default"):
if task.lower().startswith("/max-turns"): REASONING_EFFORT = None if arg.lower() in ("", "default") else arg.lower()
MAX_STEPS = int(n) if (n := task[10:].strip()).isdigit() else MAX_STEPS; print(f"{DIM}Max steps: {MAX_STEPS}{RESET}"); continue print(f"{DIM}Reasoning effort: {REASONING_EFFORT or 'default'}{RESET}")
else:
print(f"{RED}\u2717 Use: /reasoning high|medium|low|max|none|default{RESET}")
continue
if cmd == "/max-turns":
MAX_STEPS = int(arg) if arg.isdigit() and int(arg) else MAX_STEPS; print(f"{DIM}Max steps: {MAX_STEPS}{RESET}"); continue
if cmd and not manual_skill and "/" not in cmd[1:]: # a typo like '/staus' is not a task ('/tmp/x.py ...' is)
print(f"{RED}\u2717 Unknown command '{cmd}'.{RESET}"); continue
try: try:
session = run(task, session, auto_skills=not manual_skill) session = run(task, session, auto_skills=not manual_skill)
except KeyboardInterrupt: except KeyboardInterrupt:
_discard_incomplete(session) _discard_incomplete(session)
print(f"\n{RED}\u2717 Task aborted (Ctrl+C) - the session is preserved.{RESET}") print(f"\n{RED}\u2717 Task aborted (Ctrl+C) - the session is preserved.{RESET}")
except Exception as e: # noqa: BLE001 - e.g. a malformed server response
_discard_incomplete(session)
_log("### Error", traceback.format_exc())
print(f"\n{RED}\u2717 Task failed ({type(e).__name__}: {e}) - the session is preserved, details in {LOG_FILE}.{RESET}")
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,32 +1,42 @@
{ {
"autoCompactEnabled": true, "autoCompactEnabled": true,
"autoCompactWindow": "256k", "autoCompactWindow": "256k",
"default_provider": "", "default_provider": "strata",
"providers": { "providers": {
"openai": { "openai": {
"base_url": "https://api.openai.com/v1", "base_url": "https://api.openai.com/v1",
"api_key_env": "OPENAI_API_KEY", "api_key_env": "OPENAI_API_KEY",
"model": "gpt-4.1" "model": "gpt-4.1",
"autoCompactWindow": "1m"
}, },
"anthropic": { "anthropic": {
"base_url": "https://api.anthropic.com/v1/", "base_url": "https://api.anthropic.com/v1/",
"api_key_env": "ANTHROPIC_API_KEY", "api_key_env": "ANTHROPIC_API_KEY",
"model": "claude-sonnet-4-5" "model": "claude-sonnet-4-5",
"autoCompactWindow": "200k"
}, },
"gemini": { "gemini": {
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai/", "base_url": "https://generativelanguage.googleapis.com/v1beta/openai/",
"api_key_env": "GEMINI_API_KEY", "api_key_env": "GEMINI_API_KEY",
"model": "gemini-2.5-pro" "model": "gemini-2.5-pro",
"autoCompactWindow": "1m"
}, },
"qwen": { "qwen": {
"base_url": "https://api.scaleway.ai/6bfec461-302a-4568-84c6-c141c7836828/v1", "base_url": "https://api.scaleway.ai/6bfec461-302a-4568-84c6-c141c7836828/v1",
"api_key_env": "QWEN_API_KEY", "api_key_env": "QWEN_API_KEY",
"model": "qwen3.8-27b" "model": "qwen3.8-27b"
}, },
"strata": {
"base_url": "http://127.0.0.1:8080/v1",
"api_key_env": "STRATA_LOCAL",
"model": "qwen3.8-flash-next-iq3_xxs",
"autoCompactWindow": "128k"
},
"openrouter": { "openrouter": {
"base_url": "https://openrouter.ai/api/v1", "base_url": "https://openrouter.ai/api/v1",
"api_key_env": "OPENROUTER_API_KEY", "api_key_env": "OPENROUTER_API_KEY",
"model": "qwen/qwen3.8-27b:free" "model": "qwen/qwen3.8-27b:free"
} }
} }
} }