lcode-cli 0.52.0__py3-none-any.whl → 0.54.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lcode/__init__.py CHANGED
@@ -3,7 +3,7 @@
3
3
  From a program: `from lcode import Session` (see lcode.api).
4
4
  """
5
5
 
6
- __version__ = "0.52.0"
6
+ __version__ = "0.54.0"
7
7
 
8
8
  API = ("Session", "Result", "Options", "SetupError")
9
9
 
lcode/agent.py CHANGED
@@ -18,6 +18,7 @@ import uuid
18
18
  from collections.abc import Callable
19
19
  from dataclasses import dataclass
20
20
  from pathlib import Path
21
+ from typing import TYPE_CHECKING
21
22
 
22
23
  from rich.console import Console
23
24
  from rich.markdown import Markdown
@@ -41,6 +42,7 @@ from lcode import (
41
42
  review,
42
43
  sessions,
43
44
  subagents,
45
+ traces,
44
46
  vision,
45
47
  web,
46
48
  )
@@ -77,6 +79,9 @@ from lcode.tools import (
77
79
  )
78
80
  from lcode.unreachable import NOTE_AT, Sites
79
81
 
82
+ if TYPE_CHECKING:
83
+ from lcode.replay import ReplayServer
84
+
80
85
  GPU_MEMORY_ERRORS = (
81
86
  "out of memory",
82
87
  "illegal memory access",
@@ -349,6 +354,7 @@ class Settings:
349
354
  escalate_model: str | None = None # a stronger model to ask when stuck (lcode.escalate): provider/model
350
355
  escalate_url: str | None = None # its server, when not the provider's usual one
351
356
  escalate_price: str | None = None # dollars per million tokens in/out, e.g. "3/15", for the cost estimate
357
+ trace: bool = False # record each request on this machine (lcode.traces)
352
358
 
353
359
 
354
360
  class Agent:
@@ -436,6 +442,8 @@ class Agent:
436
442
  self._repo: tuple[Path, repoid.Repo | None] | None = None # the workspace's repository, for saved sessions
437
443
  self.last_speed = 0.0
438
444
  self.usage = {"requests": 0, "prompt_tokens": 0, "prompt_ns": 0, "output_tokens": 0, "output_ns": 0}
445
+ self.trace: traces.Lane | None = None # the request's trace while it's recorded (lcode.traces)
446
+ self.replay: ReplayServer | None = None # in a replay: the recorded results of tools and checks (lcode.replay)
439
447
  self.messages: list[dict] = []
440
448
  self.reset()
441
449
 
@@ -981,7 +989,10 @@ class Agent:
981
989
  added = "\n".join(f"- {note}" for note in self.turn_requests[1:])
982
990
  request += f"\n\nWhat the user added while you worked:\n{added}"
983
991
  try:
984
- with self.console.status("Reviewing the change against your request…", spinner="dots"):
992
+ with (
993
+ self.console.status("Reviewing the change against your request…", spinner="dots"),
994
+ traces.purpose(self, "review"),
995
+ ):
985
996
  problems = review.run(self, request, answer, diff)
986
997
  except OllamaError as e:
987
998
  self.say(f"The review didn't run: {e}", warning=True)
@@ -1043,8 +1054,12 @@ class Agent:
1043
1054
  def run_check(self, check: checks.Check, round_: int) -> str | None:
1044
1055
  """Run the checks after a change. Returns what to tell the model when they fail, else None."""
1045
1056
  self.say(f"Checking the work: {check.command} (from {check.source})")
1046
- result = self.tools.run("bash", {"command": check.command, "timeout": checks.TIMEOUT})
1057
+ result = self.replay.check_result(check.command) if self.replay is not None else None
1058
+ if result is None:
1059
+ result = self.tools.run("bash", {"command": check.command, "timeout": checks.TIMEOUT})
1047
1060
  code = checks.exit_code(result)
1061
+ if self.trace is not None:
1062
+ self.trace.check(check.command, result, code)
1048
1063
  self.check_results.append({"command": check.command, "exit_code": code, "by": "lcode"})
1049
1064
  if code is None:
1050
1065
  self.say(f"The checks didn't run: {result.splitlines()[0][:200]}", warning=True)
@@ -1153,9 +1168,20 @@ class Agent:
1153
1168
  def run_turn(self, user_text: str) -> None:
1154
1169
  self.turn_started = time.monotonic()
1155
1170
  self.checkpoints.begin_turn(self.session_id, user_text, len(self.messages))
1171
+ lane = traces.start(self, user_text)
1172
+ status, error = "error", ""
1156
1173
  try:
1157
1174
  self._run_turn(user_text)
1175
+ status = self.turn_status
1176
+ except KeyboardInterrupt:
1177
+ status = "interrupted"
1178
+ raise
1179
+ except Exception as e:
1180
+ error = str(e) if isinstance(e, OllamaError) else f"{type(e).__name__}: {e}"
1181
+ raise
1158
1182
  finally:
1183
+ if lane is not None:
1184
+ traces.finish(self, lane, status, error)
1159
1185
  self.checkpoints.end_turn()
1160
1186
  if self.hooks.hooks and self.allowed_tools is None:
1161
1187
  payload = {"request": user_text[:2000], "cwd": str(self.cwd), "session": self.session_id}
@@ -1189,6 +1215,8 @@ class Agent:
1189
1215
 
1190
1216
  def sandbox_root(self) -> Path | None:
1191
1217
  """The folder the model is limited to while the sandbox is on (None when it's off)."""
1218
+ if self.replay is not None:
1219
+ return self.replay.root # a replay changes nothing outside its copy of the folder (lcode.traces)
1192
1220
  if not self.sandbox:
1193
1221
  return None
1194
1222
  try:
@@ -1290,7 +1318,7 @@ class Agent:
1290
1318
  why = "its replies went round in circles or ended without an answer, twice in this request"
1291
1319
  if not escalated and self.can_escalate():
1292
1320
  escalated = True
1293
- advice = escalate.run(self, why)
1321
+ advice = self.ask_stronger(why)
1294
1322
  if advice:
1295
1323
  self.messages.append({"role": "user", "content": advice})
1296
1324
  stalls = 0
@@ -1334,7 +1362,7 @@ class Agent:
1334
1362
  if check_rounds >= checks.MAX_ROUNDS and not escalated and self.can_escalate():
1335
1363
  escalated = True
1336
1364
  why = f"the project's checks (`{check.command}`) failed {check_rounds} times in a row"
1337
- advice = escalate.run(self, why, failure=feedback)
1365
+ advice = self.ask_stronger(why, failure=feedback)
1338
1366
  if advice:
1339
1367
  self.messages.append({"role": "user", "content": advice})
1340
1368
  check_rounds -= 1 # the checks run once more after the advice
@@ -1376,8 +1404,11 @@ class Agent:
1376
1404
  self.on_tool(name, args)
1377
1405
  if name not in ("bash", "todo_write", "web_search", "web_fetch", "agent"): # those print their own
1378
1406
  self.console.print(Text(f"● {self.describe_call(name, args)}", style="bold magenta"))
1407
+ began = time.monotonic()
1408
+ if self.trace is not None:
1409
+ self.trace.tool_begin()
1379
1410
  try:
1380
- result = done[i] if i in done else self.tools.run(name, args)
1411
+ result = done[i] if i in done else self.run_tool(name, args)
1381
1412
  except KeyboardInterrupt:
1382
1413
  for rest in calls[i:]:
1383
1414
  self.messages.append(
@@ -1425,6 +1456,8 @@ class Agent:
1425
1456
  changed, verified = True, False
1426
1457
  elif name == "bash" and changed and self.model_ran_checks(str(args.get("command", "")), result):
1427
1458
  verified = True # the model ran the checks itself, after its last change
1459
+ if self.trace is not None:
1460
+ self.trace.tool(call.get("id", ""), name, args, result, time.monotonic() - began)
1428
1461
  tool_msg = {"role": "tool", "tool_name": name, "content": result}
1429
1462
  if call.get("id"):
1430
1463
  tool_msg["tool_call_id"] = call["id"]
@@ -1451,7 +1484,7 @@ class Agent:
1451
1484
  break
1452
1485
  if looping and not escalated and self.can_escalate():
1453
1486
  escalated = True
1454
- advice = escalate.run(self, f"it kept making the same call with the same result: {looping}")
1487
+ advice = self.ask_stronger(f"it kept making the same call with the same result: {looping}")
1455
1488
  if advice:
1456
1489
  self.messages.append({"role": "user", "content": advice})
1457
1490
  self.repeats.reset()
@@ -1486,6 +1519,24 @@ class Agent:
1486
1519
  self.turn_status = "success"
1487
1520
  self.print_stats()
1488
1521
 
1522
+ def run_tool(self, name: str, args: dict) -> str:
1523
+ if self.replay is not None: # a replay gives some tools their recorded results (lcode.traces)
1524
+ served = self.replay.tool_result(name, args)
1525
+ if served is not None:
1526
+ return served
1527
+ args = self.replay.moved(args) # the recorded folder's paths point into the replay's copy
1528
+ return self.tools.run(name, args)
1529
+
1530
+ def ask_stronger(self, why: str, failure: str = "") -> str | None:
1531
+ """The stronger model's advice for the local model, if one is set and the user agrees (lcode.escalate)."""
1532
+ if self.replay is not None:
1533
+ return self.replay.escalation(why)
1534
+ with traces.inside(self, "escalate"):
1535
+ advice = escalate.run(self, why, failure)
1536
+ if self.trace is not None:
1537
+ self.trace.escalation(why, advice)
1538
+ return advice
1539
+
1489
1540
  def keep_dropped(self, reply: dict) -> str:
1490
1541
  """Save a reply lcode dropped (its thinking too), so the user can see what went round in circles."""
1491
1542
  text = "\n\n".join(part for part in (reply.get("thinking"), reply.get("content")) if part)
@@ -1665,7 +1716,8 @@ class Agent:
1665
1716
  if len(self.messages) <= 2:
1666
1717
  return
1667
1718
  if self.interactive:
1668
- memory_notes.reflect(self) # what the summary leaves out is gone for good
1719
+ with traces.inside(self, "memory"):
1720
+ memory_notes.reflect(self) # what the summary leaves out is gone for good
1669
1721
  instructions = (
1670
1722
  "Summarize this conversation so the work can continue in a fresh context. Include: the user's goals "
1671
1723
  "and requests, key facts learned about the codebase (files, functions, paths with line numbers), "
@@ -1675,7 +1727,7 @@ class Agent:
1675
1727
  if focus:
1676
1728
  instructions += f" Focus especially on: {focus}"
1677
1729
  summary = ""
1678
- with self.console.status("[cyan]Compacting…[/]"):
1730
+ with self.console.status("[cyan]Compacting…[/]"), traces.purpose(self, "summary"):
1679
1731
  for chunk in self.chat([*self.messages, {"role": "user", "content": instructions}], None, False):
1680
1732
  summary += chunk.get("message", {}).get("content", "")
1681
1733
  requests = context_tools.user_requests(self.messages)
lcode/api.py CHANGED
@@ -18,12 +18,14 @@ from __future__ import annotations
18
18
  import contextlib
19
19
  import io
20
20
  import queue
21
+ import shlex
21
22
  import threading
22
23
  import time
23
24
  from collections.abc import Callable, Iterator
24
25
  from dataclasses import asdict, dataclass, field
25
26
  from pathlib import Path
26
27
  from typing import TYPE_CHECKING, Any
28
+ from urllib.parse import urlsplit
27
29
 
28
30
  from rich.console import Console
29
31
 
@@ -40,8 +42,9 @@ STATUSES = ("success", "error", "max_steps", "loop", "interrupted")
40
42
  EXIT_CODES = {"success": 0, "error": 1, "max_steps": 3, "loop": 4, "interrupted": 130}
41
43
  OLLAMA_INSTALL = {
42
44
  "linux": "curl -fsSL https://ollama.com/install.sh | sh",
43
- "darwin": "brew install ollama (or download it from https://ollama.com/download)",
45
+ "macos": "brew install ollama && brew services start ollama (or download the app from https://ollama.com/download)",
44
46
  }
47
+ DOCKER_TIMEOUT = 10 # seconds for Docker to list its containers, when Ollama doesn't answer
45
48
 
46
49
 
47
50
  class SetupError(Exception):
@@ -114,14 +117,51 @@ def check_server(ollama, hw: Hardware | None = None) -> str:
114
117
  except OllamaError as e:
115
118
  from lcode.hardware import detect
116
119
 
117
- hint = OLLAMA_INSTALL.get((hw or detect()).os, OLLAMA_INSTALL["linux"])
118
- raise SetupError(f"{e}\n\nIs Ollama installed and running? Install it with:\n {hint}") from e
120
+ raise SetupError(f"{e}\n\n{ollama_down(ollama.host, (hw or detect()).os)}") from e
119
121
  if version_tuple(version) < MIN_VERSION:
120
122
  needed = ".".join(map(str, MIN_VERSION))
121
123
  raise SetupError(f"Ollama {version} is too old; lcode needs {needed} or newer. Update Ollama.")
122
124
  return version
123
125
 
124
126
 
127
+ def ollama_down(host: str, os_name: str) -> str:
128
+ """What to do when Ollama doesn't answer at `host`: start the Docker container it runs in, or install it."""
129
+ from lcode import update
130
+
131
+ docker = urlsplit(host).hostname in update.LOCAL_HOSTS and update.docker_installed()
132
+ containers, trouble = [], ""
133
+ try:
134
+ containers = update.ollama_containers(host, stopped=True, timeout=DOCKER_TIMEOUT) if docker else []
135
+ except (update.UpdateError, ValueError) as e: # Docker isn't running, or doesn't let this user in
136
+ trouble = str(e).removeprefix("docker ps failed: ")
137
+ if len(containers) == 1:
138
+ container = containers[0]
139
+ if container.running:
140
+ return (
141
+ f"Ollama runs in Docker, in the container {container.name}, but doesn't answer. If it has just "
142
+ f"started, try again in a moment; if not, see why:\n docker logs --tail 20 {container.name}"
143
+ )
144
+ compose = container.compose
145
+ if compose and compose["files"] and all(Path(f).is_file() for f in compose["files"]):
146
+ start = shlex.join(update.compose_up(compose)[0])
147
+ else:
148
+ start = f"docker start {container.name}"
149
+ return f"Ollama runs in Docker, in the container {container.name}, which is stopped. Start it with:\n {start}"
150
+ if containers:
151
+ names = ", ".join(c.name for c in containers)
152
+ return f"Ollama runs in Docker here, in one of these containers: {names}. Start it with:\n docker start <name>"
153
+ install = OLLAMA_INSTALL.get(os_name, OLLAMA_INSTALL["linux"])
154
+ hint = f"Is Ollama installed and running? Install it with:\n {install}"
155
+ if trouble:
156
+ hint += f"\nIf you run Ollama in Docker, start Docker first. It says: {trouble}"
157
+ elif docker:
158
+ hint += (
159
+ "\nIf you ran Ollama in Docker, its container is gone: create it again (with Docker Compose: "
160
+ "docker compose up -d, in the folder of its compose file)."
161
+ )
162
+ return hint
163
+
164
+
125
165
  def switch(wanted: bool | None, configured: str, default_on: str) -> str:
126
166
  """A setting that's "off" or some mode: None keeps the config's, False turns it off, True on."""
127
167
  if wanted is None:
@@ -232,6 +272,7 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
232
272
  escalate_url=cfg["escalate_url"],
233
273
  escalate_price=cfg["escalate_price"],
234
274
  compact_at=cfg["compact_at"],
275
+ trace=cfg["trace"],
235
276
  )
236
277
  agent = Agent(ollama, settings, cwd, console=console)
237
278
  agent.hardware = hw
lcode/cli.py CHANGED
@@ -30,11 +30,6 @@ from lcode.ollama import MIN_VERSION, Ollama, OllamaError, redact, version_tuple
30
30
 
31
31
  console = Console(highlight=False)
32
32
 
33
- OLLAMA_INSTALL = {
34
- "linux": "curl -fsSL https://ollama.com/install.sh | sh",
35
- "macos": "brew install ollama && brew services start ollama (or download the app from https://ollama.com)",
36
- }
37
-
38
33
 
39
34
  class NotInstalled(Exception):
40
35
  pass
@@ -382,7 +377,10 @@ def cmd_doctor(args) -> None:
382
377
  if openai:
383
378
  line("", f"start {ollama.name}'s server, or set its address: lcode config set base_url <url>", None)
384
379
  else:
385
- line("", f"install: {OLLAMA_INSTALL.get(hw.os, OLLAMA_INSTALL['linux'])}", None)
380
+ from lcode import api
381
+
382
+ for text in api.ollama_down(ollama.host, hw.os).splitlines():
383
+ line("", escape(text.strip()), None)
386
384
  sys.exit(1)
387
385
  try:
388
386
  model, spec = resolve_model(ollama, cfg["model"])
@@ -596,6 +594,10 @@ def cmd_config(args) -> None:
596
594
  def cmd_bench(args) -> None:
597
595
  from lcode import bench
598
596
 
597
+ if args.harbor:
598
+ from lcode import harbor_bench
599
+
600
+ sys.exit(harbor_bench.command(args, console))
599
601
  if args.list:
600
602
  bench.print_tasks(console)
601
603
  return
@@ -859,7 +861,7 @@ def build_parser() -> argparse.ArgumentParser:
859
861
  parser = argparse.ArgumentParser(
860
862
  prog="lcode",
861
863
  description="A local-first terminal coding agent powered by open-weight models via Ollama.",
862
- epilog="Subcommands: lcode setup | models | doctor | config | bench | mcp | index | update "
864
+ epilog="Subcommands: lcode setup | models | doctor | config | bench | trace | mcp | index | update "
863
865
  "(lcode <subcommand> --help). "
864
866
  "Docs: https://nasser1941.github.io/lcode/",
865
867
  )
@@ -944,6 +946,17 @@ def build_subparsers() -> dict[str, argparse.ArgumentParser]:
944
946
  p.add_argument("--keep", action="store_true", help="keep each task's folder and transcript for inspection")
945
947
  p.add_argument("-v", "--verbose", action="store_true", help="show the model working, like a normal session")
946
948
  p.add_argument("--list", action="store_true", help="list the tasks and exit")
949
+ p.add_argument(
950
+ "--harbor",
951
+ choices=["dev", "held-out"],
952
+ help="public benchmarks instead: a slice of Terminal-Bench 2.0 and SWE-bench Verified, run with Harbor",
953
+ )
954
+ p.add_argument("--attempts", type=int, default=3, help="with --harbor: attempts per task (default: 3, for pass^3)")
955
+ p.add_argument(
956
+ "--docker-bridge",
957
+ action="store_true",
958
+ help="with --harbor: run the tasks on Docker's default network (when Docker can't make networks)",
959
+ )
947
960
  p.add_argument(
948
961
  "--session",
949
962
  action="store_true",
@@ -981,6 +994,25 @@ def build_subparsers() -> dict[str, argparse.ArgumentParser]:
981
994
  help="summarize at this many tokens, e.g. 64k (default: the compact_at setting; 0: only at 85%%)",
982
995
  )
983
996
  subs["bench"] = p
997
+ p = argparse.ArgumentParser(
998
+ prog="lcode trace",
999
+ description="Requests recorded on this machine (the trace setting): list them, show one step by step, "
1000
+ "export one for a bug report with secrets and personal details masked, or replay one with the recorded "
1001
+ "answers instead of a model and see where the tool results now differ.",
1002
+ )
1003
+ p.add_argument("action", nargs="?", default="list", help="list (default), show, export, replay or path")
1004
+ p.add_argument("trace", nargs="?", help="a number from the list (1: the newest), a trace id or a trace file")
1005
+ p.add_argument("-n", "--limit", type=int, default=20, help="list: how many (default: 20)")
1006
+ p.add_argument("-v", "--verbose", action="store_true", help="show: also the model's answers and results")
1007
+ p.add_argument(
1008
+ "-o", "--output", help="export: the file to write (default: lcode-trace-<id>.jsonl here; - prints it)"
1009
+ )
1010
+ p.add_argument("--repo", help="replay: in a copy of this folder (default: the recorded folder, at its commit)")
1011
+ p.add_argument(
1012
+ "--commands", action="store_true", help="replay: run shell commands and the checks again too (in the copy)"
1013
+ )
1014
+ p.add_argument("--keep", action="store_true", help="replay: keep the copy it ran in")
1015
+ subs["trace"] = p
984
1016
  p = argparse.ArgumentParser(
985
1017
  prog="lcode index",
986
1018
  description="Build or refresh the semantic code search index of the repository (an Ollama embedding model).",
@@ -1139,6 +1171,12 @@ def cmd_media(args) -> None:
1139
1171
  console.print("[dim]Install one: lcode media install <model> · choose in image mode: /model <model>[/]")
1140
1172
 
1141
1173
 
1174
+ def cmd_trace(args) -> None:
1175
+ from lcode import traces
1176
+
1177
+ sys.exit(traces.command(args, console))
1178
+
1179
+
1142
1180
  def cmd_mcp(args) -> None:
1143
1181
  from lcode.mcp.commands import run
1144
1182
 
@@ -1152,6 +1190,7 @@ COMMANDS = {
1152
1190
  "media": cmd_media,
1153
1191
  "config": cmd_config,
1154
1192
  "bench": cmd_bench,
1193
+ "trace": cmd_trace,
1155
1194
  "mcp": cmd_mcp,
1156
1195
  "index": cmd_index,
1157
1196
  "action": cmd_action,
@@ -1161,7 +1200,11 @@ COMMANDS = {
1161
1200
 
1162
1201
 
1163
1202
  def main(argv: list[str] | None = None) -> None:
1203
+ from lcode import update
1204
+
1164
1205
  argv = sys.argv[1:] if argv is None else argv
1206
+ with contextlib.suppress(Exception): # a convenience: it must never stop lcode from starting
1207
+ update.leave_own_environment() # with uvx, `python` in commands and checks is yours, not lcode's
1165
1208
  try:
1166
1209
  if argv and argv[0] in COMMANDS:
1167
1210
  parser = build_subparsers()[argv[0]]
lcode/config.py CHANGED
@@ -88,6 +88,7 @@ SETTINGS: dict[str, tuple[object, type, str]] = {
88
88
  "secret_check": (True, bool, "before git commit and git push, look for passwords, keys and tokens they'd add"),
89
89
  "compact_at": (65536, int, "summarize at this many tokens even when the window is larger (0: only at 85%)"),
90
90
  "max_parallel_agents": (1, int, "subagents that may run at the same time (more needs OLLAMA_NUM_PARALLEL)"),
91
+ "trace": (True, bool, "record each request's steps, timings and tokens on this machine, for lcode trace"),
91
92
  }
92
93
  ENV_OVERRIDES = {
93
94
  "LCODE_MODEL": "model",
lcode/docs/bench.md CHANGED
@@ -4,6 +4,9 @@
4
4
  coding on my machine?* It runs a fixed set of small coding tasks against one or more models and
5
5
  reports how many they solved, how fast they ran and how much memory they used.
6
6
 
7
+ To compare with other agents on public benchmarks (Terminal-Bench 2.0 and SWE-bench Verified),
8
+ see [Public benchmarks](public-benchmarks.md).
9
+
7
10
  ```bash
8
11
  lcode bench # the configured model
9
12
  lcode bench qwen3.6-35b qwen3.5-9b # compare models
@@ -61,6 +61,7 @@ lcode config path # print the file location
61
61
  | `repeat_limit` | `3` | Identical tool calls with identical results before lcode [steps in](how-it-works.md#when-the-model-repeats-itself); `0` turns it off, along with the checks for [unreachable sites](how-it-works.md#when-a-site-cant-be-reached) and [thinking in circles](how-it-works.md#when-a-reply-goes-nowhere) |
62
62
  | `secret_check` | `true` | Before `git commit` and `git push`, look for passwords, keys and tokens they'd add ([details](usage.md#secrets-in-commits)) |
63
63
  | `checkpoints` | `true` | Save a checkpoint before the model changes files, so [`/undo`](usage.md#undo-and-checkpoints) can restore them |
64
+ | `trace` | `true` | Record each request's model calls, tool calls, times and tokens on this machine, for [`lcode trace`](traces.md) (kept 30 days) |
64
65
 
65
66
  Besides these settings, `config.toml` can hold [hooks](hooks.md) (`[[hooks]]`) and
66
67
  [permission rules](hooks.md#permission-rules) (`[permissions]`); a repository can have its own in
@@ -115,9 +116,10 @@ Environment variables override the file, which is useful for one-off runs and CI
115
116
  | `~/.local/state/lcode/lsp-logs/` | Language servers' own output |
116
117
  | `~/.local/state/lcode/index/` | [Code search](search.md#semantic-code-search) indexes, one per repository (`lcode index`) |
117
118
  | `~/.local/state/lcode/outputs/` | The full text of long command output that was cut short for the model (kept a week) |
119
+ | `~/.local/state/lcode/traces/` | [Run traces](traces.md): each request's steps, times and tokens, one file per request (kept 30 days, 200 MB at most) |
118
120
  | `~/.local/state/lcode/limits.json` | Context sizes that ran out of GPU memory on this machine (safe to delete) |
119
121
 
120
- Sessions contain everything the model read, including file contents. Delete the folder to clear them.
122
+ Sessions and traces contain everything the model read, including file contents. Delete the folders to clear them.
121
123
 
122
124
  ## Tuning for speed and memory
123
125
 
@@ -0,0 +1,128 @@
1
+ # Public benchmarks
2
+
3
+ `lcode bench` has eight small tasks of its own, and good models solve all of them. To see progress
4
+ past that, and to compare with other agents, lcode runs on two public benchmarks that anyone can
5
+ rerun:
6
+
7
+ - [Terminal-Bench 2.0](https://www.tbench.ai/): tasks in a terminal, from fixing a git repository
8
+ to building software, recovering data or setting up servers.
9
+ - [SWE-bench Verified](https://www.swebench.com/): real bug fixes in Python projects such as Django,
10
+ SymPy and matplotlib, checked by the project's own tests.
11
+
12
+ Both run on [Harbor](https://github.com/harbor-framework/harbor). Harbor starts each task in a
13
+ fresh Docker container. lcode is installed in that container and works on the task as one request
14
+ (`lcode -p "<the task>" --yolo`), with the model on your machine. Afterwards the task's tests decide
15
+ whether it passed.
16
+
17
+ ## What you need
18
+
19
+ - **Docker**, running.
20
+ - **uv**: lcode runs Harbor with `uvx`, so there's nothing else to install.
21
+ - **Disk space** for the tasks' images: about 20 GB for the dev slice. Each SWE-bench task has an
22
+ image of its own, 1–3 GB.
23
+ - **A model server the containers can reach.** lcode in a container finds your machine by itself:
24
+ as `host.docker.internal` with Docker Desktop (macOS, Windows), or as the container's gateway on
25
+ Linux. Ollama has to listen on more than `127.0.0.1` for that:
26
+ - Ollama in Docker with its port published (`-p 11434:11434`) already does.
27
+ - Ollama installed on Linux listens only on `127.0.0.1`. Run `sudo systemctl edit ollama`, add
28
+ `Environment="OLLAMA_HOST=0.0.0.0"` under `[Service]`, and restart it. That also opens it to
29
+ your network, so keep port 11434 closed in your firewall.
30
+
31
+ ## Running it
32
+
33
+ ```bash
34
+ lcode bench --harbor dev # the dev slice with your model, 3 attempts per task
35
+ lcode bench --harbor dev qwen3.6-35b --context 64k
36
+ lcode bench --harbor dev --tasks cobol-modernization,django__django-11555 --attempts 1
37
+ lcode bench --harbor dev --list # the slice's tasks
38
+ ```
39
+
40
+ Tasks run one at a time, since they share your GPU. The context is your configured one unless you
41
+ give `--context`. A container can't see your GPU, so lcode there doesn't choose a context itself.
42
+
43
+ lcode in the container is the same version as yours: from PyPI, or a wheel built from your checkout
44
+ when you run lcode from one, so a change can be measured before it's released.
45
+
46
+ ## The slices
47
+
48
+ | Slice | Terminal-Bench 2.0 | SWE-bench Verified | For |
49
+ |---|---|---|---|
50
+ | `dev` | 15 | 10 | everyday checks of a change |
51
+ | `held-out` | 14 | 11 | confirming a change helps beyond the tasks it was tuned on |
52
+
53
+ Both were drawn once, at random and by difficulty, from the tasks a local model can try in a night:
54
+
55
+ - Terminal-Bench without its model-training tasks, and with at most 30 minutes per task: 2 easy,
56
+ 10 medium and 3 hard tasks in the dev slice.
57
+ - SWE-bench Verified's two common difficulties: five fixes estimated under 15 minutes and five of
58
+ 15 minutes to an hour.
59
+
60
+ Don't tune lcode on the held-out set: once a change is chosen because it does well there, the set
61
+ no longer tells you whether changes generalize.
62
+
63
+ ## What's reported
64
+
65
+ Two tasks, one attempt each, with qwen3.6-35b at 32K on a 12 GB laptop GPU:
66
+
67
+ ```text
68
+ $ lcode bench --harbor dev --tasks prove-plus-comm,django__django-11555 --attempts 1
69
+ …
70
+ Task Benchmark Passed Time Tokens in Tokens out
71
+ prove-plus-comm terminal-bench 1/1 0.6 min 27,827 1,494
72
+ django__django-11555 swebench-verified 0/1 19.9 min 2,370,217 38,508
73
+ pass@1 50% · pass^1 50%
74
+ ```
75
+
76
+ With three attempts, the last line also gives each run's pass rate and the spread between them.
77
+
78
+ - **pass@1**: the share of attempts that passed, averaged over the tasks. It's the number to compare
79
+ with leaderboards.
80
+ - **pass^3**: the share of tasks whose three attempts all passed. That shows how dependable lcode is,
81
+ not just how often it gets lucky.
82
+ - **runs and spread**: the pass rate of each task's first attempt, its second and its third. Single
83
+ runs of the same setup differ by several points, so differences smaller than the spread are noise.
84
+ - **Time and tokens** per attempt, from lcode's own record of the request (its
85
+ [trace](traces.md)).
86
+
87
+ Attempts whose container didn't start (a failed image download, say) count neither as passed nor
88
+ as failed. The report shows how many there were.
89
+
90
+ Everything is saved in `~/.local/state/lcode/bench/<slice>-<time>/`:
91
+
92
+ - `lcode-bench.json`: the results, with the lcode and Harbor versions, the model, the context, the
93
+ machine, the date and the command that reproduces them. `--json FILE` saves a copy.
94
+ - Harbor's own results: each attempt's log, the task's test output, and lcode's trace and session.
95
+ `uvx --from harbor harbor view <folder>` browses them.
96
+
97
+ ## With Harbor directly
98
+
99
+ `lcode.harbor:Lcode` is an ordinary Harbor agent, so every Harbor dataset and option works:
100
+
101
+ ```bash
102
+ uvx --python 3.13 --from harbor==0.25.0 --with lcode-cli harbor run \
103
+ -d terminal-bench@2.0 -a lcode.harbor:Lcode -m qwen3.6-35b --ak context=32768
104
+ ```
105
+
106
+ Its options, each given with `--ak name=value`:
107
+
108
+ | Option | What it does |
109
+ |---|---|
110
+ | `context` | the context window, e.g. `32768` |
111
+ | `host` | Ollama's address as the container sees it, e.g. `http://192.168.1.20:11434` |
112
+ | `version` | the lcode version to install (default: the one Harbor runs with) |
113
+ | `wheel` | an lcode wheel on your machine to install instead |
114
+
115
+ Other model servers work as in lcode itself: `--ae LCODE_BACKEND=openai --ae LCODE_BASE_URL=…`.
116
+
117
+ ## When Docker can't make networks
118
+
119
+ Harbor gives each task a network of its own. When Docker says *all predefined address pools have
120
+ been fully subnetted*, every address range it could use overlaps a route on your machine. A VPN that
121
+ sends all traffic through itself does that. Add `--docker-bridge`, and the tasks run on Docker's
122
+ default network instead. With Harbor directly, pass `--extra-docker-compose` with a file holding:
123
+
124
+ ```yaml
125
+ services:
126
+ main:
127
+ network_mode: bridge
128
+ ```
lcode/docs/quickstart.md CHANGED
@@ -12,7 +12,7 @@ lcode
12
12
 
13
13
  ```text
14
14
  ╭──────────────────────────────────────────────╮
15
- │ lcode v0.52.0 — local coding agent │
15
+ │ lcode v0.54.0 — local coding agent │
16
16
  │ │
17
17
  │ model lcode-qwen3.6-35b │
18
18
  │ context 256K tokens │