Update 2026-11-23 13:04:16
parent
2f7116b954
commit
9580c6bb76
218
jcode.py
218
jcode.py
|
|
@ -14,7 +14,9 @@ import shutil
|
|||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
import ssl
|
||||
import urllib.request
|
||||
|
||||
|
|
@ -31,7 +33,7 @@ from openai import OpenAI
|
|||
|
||||
# --------------------------------------------------------------- Configuration
|
||||
APP_NAME = "jcode"
|
||||
APP_VERSION = "1.0"
|
||||
APP_VERSION = "1.01"
|
||||
DEFAULT_MODEL = "qwen3.8-27b-splash" #"qwen3.6-35b-a3b-uncensored-hauhaucs-aggressive"
|
||||
MODEL = DEFAULT_MODEL
|
||||
|
||||
|
|
@ -64,7 +66,9 @@ SETTINGS_FILE = Path("settings.json")
|
|||
def _load_settings() -> dict:
|
||||
"""Reads settings.json: providers (OpenAI/Anthropic/Gemini via OpenAI-compatible endpoints) for '/backend <name>',
|
||||
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:
|
||||
return json.loads(SETTINGS_FILE.read_text(encoding="utf-8")) if SETTINGS_FILE.is_file() else {}
|
||||
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
|
||||
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)
|
||||
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
|
||||
key, bname = ("ollama", "Ollama") if url == _OLLAMA_URL else ("lm-studio", "LM Studio")
|
||||
models = _fetch_models(url)
|
||||
|
|
@ -109,6 +114,7 @@ def _switch_backend(name: str) -> None:
|
|||
MODEL = _pick_model(models)
|
||||
BASE_URL, _API_KEY, BACKEND = url, key, bname
|
||||
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}")
|
||||
|
||||
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
|
||||
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)
|
||||
CONTEXT_LIMIT = _parse_tokens(SETTINGS.get("autoCompactWindow"), 256_000) # context window of the model (tokens)
|
||||
COMPACT_THRESHOLD = CONTEXT_LIMIT * 8 // 10 # history is compacted from here on (80%: headroom for the next response)
|
||||
def _set_context(window=None) -> None:
|
||||
"""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
|
||||
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
|
||||
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
|
||||
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
|
||||
|
|
@ -144,13 +154,10 @@ def _log(header: str, body: str = "") -> None:
|
|||
|
||||
def _load_agents_md() -> str:
|
||||
"""Reads AGENTS.md from the project (sandbox) directory, if present."""
|
||||
agents_file = SANDBOX / "AGENTS.md"
|
||||
if agents_file.is_file():
|
||||
try:
|
||||
return agents_file.read_text(encoding="utf-8").strip()
|
||||
except OSError:
|
||||
return ""
|
||||
return ""
|
||||
try:
|
||||
return (SANDBOX / "AGENTS.md").read_text(encoding="utf-8").strip()
|
||||
except OSError: # missing or unreadable
|
||||
return ""
|
||||
|
||||
client = OpenAI(
|
||||
base_url=BASE_URL,
|
||||
|
|
@ -221,8 +228,8 @@ def _resolve(path: str, write: bool = False) -> Path:
|
|||
while parts and parts[0] == SANDBOX.name:
|
||||
parts.pop(0)
|
||||
p = SANDBOX.joinpath(*parts)
|
||||
elif not _inside(p.resolve(), SANDBOX) and _garbled_sandbox_tail(parts) is not None:
|
||||
p = SANDBOX.joinpath(*_garbled_sandbox_tail(parts))
|
||||
elif not _inside(p.resolve(), SANDBOX) and (tail := _garbled_sandbox_tail(parts)) is not None:
|
||||
p = SANDBOX.joinpath(*tail)
|
||||
p = p.resolve()
|
||||
if _inside(p, SANDBOX):
|
||||
return p
|
||||
|
|
@ -259,15 +266,13 @@ MAX_READ_LINES = 2000 # read_file returns at most this many lines per call
|
|||
|
||||
def _walk(base: Path):
|
||||
"""Files and dirs under base, skipping SKIP_DIRS; yields (path, skipped_dir_entry_count)."""
|
||||
for p in sorted(base.rglob("*")):
|
||||
rel = p.relative_to(base).parts
|
||||
if any(part in SKIP_DIRS for part in rel[:-1]):
|
||||
continue # inside a skipped folder
|
||||
if p.name in SKIP_DIRS:
|
||||
if p.is_dir():
|
||||
yield p, sum(1 for _ in p.rglob("*"))
|
||||
continue
|
||||
yield p, None
|
||||
found = []
|
||||
for root, dirs, files in os.walk(base):
|
||||
skipped = [d for d in dirs if d in SKIP_DIRS]
|
||||
dirs[:] = [d for d in dirs if d not in SKIP_DIRS] # pruned: os.walk does not descend into them
|
||||
found += [(Path(root, n), None) for n in dirs + files if n not in SKIP_DIRS]
|
||||
found += [(Path(root, d), sum(len(ds) + len(fs) for _, ds, fs in os.walk(Path(root, d)))) for d in skipped]
|
||||
return sorted(found, key=lambda t: t[0])
|
||||
|
||||
def list_files(subdir: str = ".") -> str:
|
||||
base = _resolve(subdir)
|
||||
|
|
@ -626,8 +631,72 @@ def delete_lines(path: str, start_line: int, end_line: int) -> str:
|
|||
_print_diff(old, new, path)
|
||||
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
|
||||
# (tests, compilers, package installation via pip/npm/...) is considered safe.
|
||||
# ------------------------------------------------------------------ OS sandbox
|
||||
# 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)
|
||||
\brm\s+(?:[^;&|>\n]*\s)?['"]?(/|~|\.\.|\$\{?HOME) # rm with any absolute/home/parent argument
|
||||
| \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
|
||||
|
||||
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
|
||||
afterwards (e.g. 'pip install requests', 'npm install lodash').
|
||||
Destructive commands (rm -rf /, sudo, dd, mkfs, shutdown, ...) are
|
||||
blocked. Leading 'pip'/'pip3' calls are redirected to the running
|
||||
Python interpreter so the library lands in jcode's environment.
|
||||
The command runs inside the OS sandbox (see _init_sandbox) if one is
|
||||
available; otherwise destructive commands (rm -rf /, sudo, dd, mkfs,
|
||||
shutdown, ...) are blocked by the _DANGEROUS blacklist. API keys are
|
||||
removed from its environment in both cases. Leading 'pip'/'pip3' calls
|
||||
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 "
|
||||
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
|
||||
|
|
@ -672,8 +742,12 @@ def run_command(command: str, timeout: int = CMD_TIMEOUT) -> str:
|
|||
if _SHELL and "|" in command:
|
||||
# 'node test.js | head' must report test.js's exit code, not head's
|
||||
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(
|
||||
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
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
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)")
|
||||
if len(out) > 4000: # save context
|
||||
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:
|
||||
return (f"TIMEOUT after {timeout}s: {shown!r} - process tree killed. "
|
||||
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")):
|
||||
try:
|
||||
meta, _ = _parse_frontmatter(f.read_text(encoding="utf-8"))
|
||||
except OSError:
|
||||
except (OSError, UnicodeDecodeError):
|
||||
continue
|
||||
skills[meta.get("name") or f.parent.name] = {"description": meta.get("description", ""), "dir": f.parent}
|
||||
return skills
|
||||
|
|
@ -1100,8 +1177,8 @@ _TOOL_META = {
|
|||
"exit_code, stdout and stderr. For smoke tests/tests (e.g. "
|
||||
"'python -m pytest -q') AND for installing missing libraries "
|
||||
"(e.g. 'pip install requests', 'npm install lodash'). "
|
||||
"Destructive commands (rm -rf /, sudo, dd, mkfs, shutdown, ...) "
|
||||
"are blocked. Background processes (servers, GUIs) MUST redirect "
|
||||
"Commands are confined: writing outside the project and temp "
|
||||
"directories fails or is blocked. Background processes (servers, GUIs) MUST redirect "
|
||||
"their output and be detached ('cmd > x.log 2>&1 &'), otherwise "
|
||||
"the call blocks until the timeout."
|
||||
),
|
||||
|
|
@ -1208,6 +1285,7 @@ def splash_screen() -> None:
|
|||
print(f" Model : {MODEL}")
|
||||
print(f" Backend : {BACKEND} ({BASE_URL})")
|
||||
print(f" Sandbox : {SANDBOX}")
|
||||
print(f" Isolation : {ISOLATION}")
|
||||
print(f" Max steps : {MAX_STEPS}")
|
||||
print(" " + "\u2500" * 50)
|
||||
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):
|
||||
try:
|
||||
return client.chat.completions.create(**kwargs)
|
||||
except KeyboardInterrupt:
|
||||
raise # never swallow Ctrl+C
|
||||
except Exception as e: # noqa: BLE001
|
||||
except Exception as e: # noqa: BLE001 (Ctrl+C is not an Exception and passes through)
|
||||
status = getattr(e, "status_code", None)
|
||||
if status and 400 <= status < 500 and status not in (408, 409, 429):
|
||||
_log("### Request rejected", str(e))
|
||||
|
|
@ -1553,7 +1629,8 @@ def _pick_skills(task: str) -> list[str]:
|
|||
return []
|
||||
catalog = "\n".join(f"- {n}: {s['description']}" for n, s in SKILLS.items())
|
||||
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 "
|
||||
"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]}"}])
|
||||
|
|
@ -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).
|
||||
fail_key, fail_streak, fail_nudged = None, 0, False
|
||||
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):
|
||||
# Check the context: prefer the real usage values of the last
|
||||
# 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
|
||||
msg = resp.choices[0].message
|
||||
|
||||
messages.append(
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": msg.content or "",
|
||||
"tool_calls": [tc.model_dump() for tc in (msg.tool_calls or [])] or None,
|
||||
}
|
||||
)
|
||||
messages.append({"role": "assistant", "content": msg.content or ""})
|
||||
if msg.tool_calls: # no key otherwise: strict endpoints reject "tool_calls": null
|
||||
messages[-1]["tool_calls"] = [tc.model_dump() for tc in msg.tool_calls]
|
||||
|
||||
# Show the model's planning/thinking text (its "what am I doing").
|
||||
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 plan:
|
||||
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
|
||||
empty = 0
|
||||
|
||||
print(f"\n\u250c\u2500 Step {step}")
|
||||
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))
|
||||
fail_streak = fail_streak + 1 if (key and key == fail_key) else (1 if key else 0)
|
||||
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:
|
||||
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}")
|
||||
|
|
@ -1761,10 +1843,11 @@ def _discard_incomplete(messages: list) -> None:
|
|||
def main() -> None:
|
||||
global LAST_USAGE_TOKENS, MODEL, MAX_STEPS, REASONING_EFFORT
|
||||
SANDBOX.mkdir(exist_ok=True)
|
||||
_init_sandbox()
|
||||
if (d := SETTINGS.get("default_provider")): _switch_backend(d)
|
||||
if len(sys.argv) > 1:
|
||||
# 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())
|
||||
else:
|
||||
splash_screen()
|
||||
|
|
@ -1780,34 +1863,47 @@ def main() -> None:
|
|||
break
|
||||
if not task:
|
||||
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()
|
||||
LAST_USAGE_TOKENS = 0
|
||||
print(f"{DIM}\u267b\ufe0f Session reset - the history was cleared.{RESET}")
|
||||
continue
|
||||
if task.lower() == "/status":
|
||||
if cmd == "/status":
|
||||
print_status(session)
|
||||
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
|
||||
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
|
||||
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
|
||||
if task.lower().startswith("/backend"):
|
||||
_switch_backend(task[8:].strip()); continue
|
||||
if task.lower().startswith("/model"):
|
||||
MODEL = task[6:].strip() or MODEL; print(f"{DIM}Current model: {MODEL}{RESET}"); continue
|
||||
if task.lower().startswith("/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 task.lower().startswith("/max-turns"):
|
||||
MAX_STEPS = int(n) if (n := task[10:].strip()).isdigit() else MAX_STEPS; print(f"{DIM}Max steps: {MAX_STEPS}{RESET}"); continue
|
||||
if cmd == "/backend":
|
||||
_switch_backend(arg); continue
|
||||
if cmd == "/model":
|
||||
MODEL = arg or MODEL; print(f"{DIM}Current model: {MODEL}{RESET}"); continue
|
||||
if cmd == "/reasoning":
|
||||
if arg.lower() in ("high", "medium", "low", "max", "none", "", "default"):
|
||||
REASONING_EFFORT = None if arg.lower() in ("", "default") else arg.lower()
|
||||
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:
|
||||
session = run(task, session, auto_skills=not manual_skill)
|
||||
except KeyboardInterrupt:
|
||||
_discard_incomplete(session)
|
||||
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__":
|
||||
main()
|
||||
|
|
|
|||
|
|
@ -1,32 +1,42 @@
|
|||
{
|
||||
"autoCompactEnabled": true,
|
||||
"autoCompactWindow": "256k",
|
||||
"default_provider": "",
|
||||
"default_provider": "strata",
|
||||
"providers": {
|
||||
"openai": {
|
||||
"base_url": "https://api.openai.com/v1",
|
||||
"api_key_env": "OPENAI_API_KEY",
|
||||
"model": "gpt-4.1"
|
||||
"model": "gpt-4.1",
|
||||
"autoCompactWindow": "1m"
|
||||
},
|
||||
"anthropic": {
|
||||
"base_url": "https://api.anthropic.com/v1/",
|
||||
"api_key_env": "ANTHROPIC_API_KEY",
|
||||
"model": "claude-sonnet-4-5"
|
||||
"model": "claude-sonnet-4-5",
|
||||
"autoCompactWindow": "200k"
|
||||
},
|
||||
"gemini": {
|
||||
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai/",
|
||||
"api_key_env": "GEMINI_API_KEY",
|
||||
"model": "gemini-2.5-pro"
|
||||
"model": "gemini-2.5-pro",
|
||||
"autoCompactWindow": "1m"
|
||||
},
|
||||
"qwen": {
|
||||
"base_url": "https://api.scaleway.ai/6bfec461-302a-4568-84c6-c141c7836828/v1",
|
||||
"api_key_env": "QWEN_API_KEY",
|
||||
"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": {
|
||||
"base_url": "https://openrouter.ai/api/v1",
|
||||
"api_key_env": "OPENROUTER_API_KEY",
|
||||
"model": "qwen/qwen3.8-27b:free"
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue