lcode-cli 0.51.0__py3-none-any.whl → 0.53.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.51.0"
6
+ __version__ = "0.53.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
@@ -35,11 +36,13 @@ from lcode import (
35
36
  manual,
36
37
  notify,
37
38
  planning,
39
+ repoid,
38
40
  repomap,
39
41
  residency,
40
42
  review,
41
43
  sessions,
42
44
  subagents,
45
+ traces,
43
46
  vision,
44
47
  web,
45
48
  )
@@ -76,6 +79,9 @@ from lcode.tools import (
76
79
  )
77
80
  from lcode.unreachable import NOTE_AT, Sites
78
81
 
82
+ if TYPE_CHECKING:
83
+ from lcode.replay import ReplayServer
84
+
79
85
  GPU_MEMORY_ERRORS = (
80
86
  "out of memory",
81
87
  "illegal memory access",
@@ -329,6 +335,7 @@ class Settings:
329
335
  sandbox_network: bool = False
330
336
  vision_model: str = "auto" # auto, off or an Ollama model that can see images
331
337
  memory: str = "off" # off, ask or auto: notes that carry over to later sessions (lcode.memory)
338
+ memory_check: bool = False # ask the model what's worth remembering when a conversation ends
332
339
  subagents: bool = False # the agent tool (lcode.subagents)
333
340
  trust_project: bool = False # use the repository's own commands, skills and agents (lcode.extensions)
334
341
  skills: str = "off" # all, lcode (only lcode's own skill folders) or off
@@ -347,6 +354,7 @@ class Settings:
347
354
  escalate_model: str | None = None # a stronger model to ask when stuck (lcode.escalate): provider/model
348
355
  escalate_url: str | None = None # its server, when not the provider's usual one
349
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)
350
358
 
351
359
 
352
360
  class Agent:
@@ -431,8 +439,11 @@ class Agent:
431
439
  self.reply_trouble = "" # what went wrong with the last reply: "circles", "cut_off" or ""
432
440
  self.response = None # the streaming response, so another thread can abort it
433
441
  self.ctx_used = 0
442
+ self._repo: tuple[Path, repoid.Repo | None] | None = None # the workspace's repository, for saved sessions
434
443
  self.last_speed = 0.0
435
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)
436
447
  self.messages: list[dict] = []
437
448
  self.reset()
438
449
 
@@ -701,8 +712,12 @@ class Agent:
701
712
  self.session_title = self.session_title or sessions.title_from(self.messages)
702
713
  f = self.session_file()
703
714
  f.parent.mkdir(parents=True, exist_ok=True)
715
+ repo = self.workspace_repo()
704
716
  data = {
705
717
  "cwd": str(self.workspace), # where `lcode -c` there finds it, wherever the shell moved
718
+ # /resume lists it under "this folder" in any checkout of the same repository, wherever it moves
719
+ **({"repo": repo.to_json()} if repo else {}),
720
+ "context": {"used": self.next_request_tokens(), "window": self.settings.context},
706
721
  "model": self.settings.model,
707
722
  "mode": self.settings.mode,
708
723
  "image_model": self.settings.image_model,
@@ -721,6 +736,12 @@ class Agent:
721
736
  partial.write_text(json.dumps(data))
722
737
  os.replace(partial, f)
723
738
 
739
+ def workspace_repo(self) -> repoid.Repo | None:
740
+ """The repository the workspace is in, looked up again when the workspace changes or gets its first commit."""
741
+ if self._repo is None or self._repo[0] != self.workspace or (self._repo[1] and not self._repo[1].first):
742
+ self._repo = (self.workspace, repoid.find(self.workspace))
743
+ return self._repo[1]
744
+
724
745
  def new_session(self) -> None:
725
746
  self.reset()
726
747
  self.skills_loaded.clear()
@@ -770,15 +791,18 @@ class Agent:
770
791
  self.tools.notes = [str(n) for n in data.get("notes") or []]
771
792
  self.tools.changed = dict.fromkeys(str(f) for f in data.get("changed") or [])
772
793
  self.reflected = len(self.messages) # checked for notes to remember when that session ended
773
- self.ctx_used = sum(len(json.dumps(m)) for m in self.messages) // 3
774
- self.counted_chars = None
794
+ saved = (data.get("context") or {}).get("used") if isinstance(data.get("context"), dict) else None
795
+ if isinstance(saved, int) and saved > 0: # what the model counted, plus what came after
796
+ self.ctx_used, self.counted_chars = saved, conversation_chars(self.messages)
797
+ else: # saved by a version before 0.52
798
+ self.ctx_used, self.counted_chars = sessions.estimate_tokens(self.messages), None
775
799
  return note
776
800
 
777
- def load_latest(self) -> bool:
778
- latest = sessions.list_sessions(self.workspace, limit=1)
779
- if latest:
780
- self.load(latest[0])
781
- return bool(latest)
801
+ def load_latest(self) -> str | None:
802
+ """Continue the latest conversation in this folder (or its repository). Returns a note about the working
803
+ directory ("" if it stayed), or None when there's nothing to continue."""
804
+ latest = sessions.latest(self.workspace)
805
+ return self.load(latest) if latest else None
782
806
 
783
807
  # -- model calls
784
808
  def options(self) -> dict:
@@ -965,7 +989,10 @@ class Agent:
965
989
  added = "\n".join(f"- {note}" for note in self.turn_requests[1:])
966
990
  request += f"\n\nWhat the user added while you worked:\n{added}"
967
991
  try:
968
- 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
+ ):
969
996
  problems = review.run(self, request, answer, diff)
970
997
  except OllamaError as e:
971
998
  self.say(f"The review didn't run: {e}", warning=True)
@@ -1027,8 +1054,12 @@ class Agent:
1027
1054
  def run_check(self, check: checks.Check, round_: int) -> str | None:
1028
1055
  """Run the checks after a change. Returns what to tell the model when they fail, else None."""
1029
1056
  self.say(f"Checking the work: {check.command} (from {check.source})")
1030
- 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})
1031
1060
  code = checks.exit_code(result)
1061
+ if self.trace is not None:
1062
+ self.trace.check(check.command, result, code)
1032
1063
  self.check_results.append({"command": check.command, "exit_code": code, "by": "lcode"})
1033
1064
  if code is None:
1034
1065
  self.say(f"The checks didn't run: {result.splitlines()[0][:200]}", warning=True)
@@ -1137,9 +1168,20 @@ class Agent:
1137
1168
  def run_turn(self, user_text: str) -> None:
1138
1169
  self.turn_started = time.monotonic()
1139
1170
  self.checkpoints.begin_turn(self.session_id, user_text, len(self.messages))
1171
+ lane = traces.start(self, user_text)
1172
+ status, error = "error", ""
1140
1173
  try:
1141
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
1142
1182
  finally:
1183
+ if lane is not None:
1184
+ traces.finish(self, lane, status, error)
1143
1185
  self.checkpoints.end_turn()
1144
1186
  if self.hooks.hooks and self.allowed_tools is None:
1145
1187
  payload = {"request": user_text[:2000], "cwd": str(self.cwd), "session": self.session_id}
@@ -1173,6 +1215,8 @@ class Agent:
1173
1215
 
1174
1216
  def sandbox_root(self) -> Path | None:
1175
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)
1176
1220
  if not self.sandbox:
1177
1221
  return None
1178
1222
  try:
@@ -1274,7 +1318,7 @@ class Agent:
1274
1318
  why = "its replies went round in circles or ended without an answer, twice in this request"
1275
1319
  if not escalated and self.can_escalate():
1276
1320
  escalated = True
1277
- advice = escalate.run(self, why)
1321
+ advice = self.ask_stronger(why)
1278
1322
  if advice:
1279
1323
  self.messages.append({"role": "user", "content": advice})
1280
1324
  stalls = 0
@@ -1318,7 +1362,7 @@ class Agent:
1318
1362
  if check_rounds >= checks.MAX_ROUNDS and not escalated and self.can_escalate():
1319
1363
  escalated = True
1320
1364
  why = f"the project's checks (`{check.command}`) failed {check_rounds} times in a row"
1321
- advice = escalate.run(self, why, failure=feedback)
1365
+ advice = self.ask_stronger(why, failure=feedback)
1322
1366
  if advice:
1323
1367
  self.messages.append({"role": "user", "content": advice})
1324
1368
  check_rounds -= 1 # the checks run once more after the advice
@@ -1360,8 +1404,11 @@ class Agent:
1360
1404
  self.on_tool(name, args)
1361
1405
  if name not in ("bash", "todo_write", "web_search", "web_fetch", "agent"): # those print their own
1362
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()
1363
1410
  try:
1364
- 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)
1365
1412
  except KeyboardInterrupt:
1366
1413
  for rest in calls[i:]:
1367
1414
  self.messages.append(
@@ -1409,6 +1456,8 @@ class Agent:
1409
1456
  changed, verified = True, False
1410
1457
  elif name == "bash" and changed and self.model_ran_checks(str(args.get("command", "")), result):
1411
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)
1412
1461
  tool_msg = {"role": "tool", "tool_name": name, "content": result}
1413
1462
  if call.get("id"):
1414
1463
  tool_msg["tool_call_id"] = call["id"]
@@ -1435,7 +1484,7 @@ class Agent:
1435
1484
  break
1436
1485
  if looping and not escalated and self.can_escalate():
1437
1486
  escalated = True
1438
- 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}")
1439
1488
  if advice:
1440
1489
  self.messages.append({"role": "user", "content": advice})
1441
1490
  self.repeats.reset()
@@ -1470,6 +1519,24 @@ class Agent:
1470
1519
  self.turn_status = "success"
1471
1520
  self.print_stats()
1472
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
+
1473
1540
  def keep_dropped(self, reply: dict) -> str:
1474
1541
  """Save a reply lcode dropped (its thinking too), so the user can see what went round in circles."""
1475
1542
  text = "\n\n".join(part for part in (reply.get("thinking"), reply.get("content")) if part)
@@ -1649,7 +1716,8 @@ class Agent:
1649
1716
  if len(self.messages) <= 2:
1650
1717
  return
1651
1718
  if self.interactive:
1652
- 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
1653
1721
  instructions = (
1654
1722
  "Summarize this conversation so the work can continue in a fresh context. Include: the user's goals "
1655
1723
  "and requests, key facts learned about the codebase (files, functions, paths with line numbers), "
@@ -1659,7 +1727,7 @@ class Agent:
1659
1727
  if focus:
1660
1728
  instructions += f" Focus especially on: {focus}"
1661
1729
  summary = ""
1662
- with self.console.status("[cyan]Compacting…[/]"):
1730
+ with self.console.status("[cyan]Compacting…[/]"), traces.purpose(self, "summary"):
1663
1731
  for chunk in self.chat([*self.messages, {"role": "user", "content": instructions}], None, False):
1664
1732
  summary += chunk.get("message", {}).get("content", "")
1665
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:
@@ -214,6 +254,7 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
214
254
  sandbox_network=cfg["sandbox_network"],
215
255
  vision_model=cfg["vision_model"],
216
256
  memory=switch(options.memory, cfg["memory"], "ask"),
257
+ memory_check=cfg["memory_check"],
217
258
  subagents=cfg["subagents"],
218
259
  max_parallel_agents=cfg["max_parallel_agents"],
219
260
  trust_project=trust_project,
@@ -231,6 +272,7 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
231
272
  escalate_url=cfg["escalate_url"],
232
273
  escalate_price=cfg["escalate_price"],
233
274
  compact_at=cfg["compact_at"],
275
+ trace=cfg["trace"],
234
276
  )
235
277
  agent = Agent(ollama, settings, cwd, console=console)
236
278
  agent.hardware = hw
lcode/cli.py CHANGED
@@ -20,7 +20,7 @@ from rich.progress import BarColumn, DownloadColumn, Progress, TextColumn, TimeR
20
20
  from rich.prompt import Confirm
21
21
  from rich.table import Table
22
22
 
23
- from lcode import __version__, backends, catalog, config, limits, web
23
+ from lcode import __version__, backends, catalog, config, limits, sessions, web
24
24
  from lcode.agent import Settings
25
25
  from lcode.catalog import ModelSpec
26
26
  from lcode.cloud import is_cloud, signin_command
@@ -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"])
@@ -553,6 +551,7 @@ def cmd_doctor(args) -> None:
553
551
 
554
552
  project, user = Memory(Path.cwd()).counts()
555
553
  line("Memory", f"{cfg['memory']} · {project} note(s) for this repository, {user} for every repository", True)
554
+ line("Sessions", sessions_status(Path.cwd()), True)
556
555
  node = shutil.which("npx")
557
556
  line("Node.js", "found" if node else "not found (some MCP servers need npx)", True if node else None)
558
557
  sys.exit(0 if ok else 1)
@@ -775,6 +774,14 @@ def exit_on_hangup() -> None:
775
774
  signal.signal(sig, leave)
776
775
 
777
776
 
777
+ def sessions_status(cwd: Path) -> str:
778
+ """How many conversations are saved, and where: a terminal with another LCODE_HOME or XDG_STATE_HOME has
779
+ other ones."""
780
+ listing = sessions.grouped(cwd, everything=True)
781
+ saved = len(listing.here) + len(listing.elsewhere)
782
+ return f"{saved} saved, {len(listing.here)} for this folder · in {sessions.sessions_dir()}"
783
+
784
+
778
785
  def comfyui_status(cfg: dict) -> tuple[str, bool | None]:
779
786
  """lcode doctor's ComfyUI line: running or found, and whether the image model is there."""
780
787
  from lcode import comfy
@@ -850,7 +857,7 @@ def build_parser() -> argparse.ArgumentParser:
850
857
  parser = argparse.ArgumentParser(
851
858
  prog="lcode",
852
859
  description="A local-first terminal coding agent powered by open-weight models via Ollama.",
853
- epilog="Subcommands: lcode setup | models | doctor | config | bench | mcp | index | update "
860
+ epilog="Subcommands: lcode setup | models | doctor | config | bench | trace | mcp | index | update "
854
861
  "(lcode <subcommand> --help). "
855
862
  "Docs: https://nasser1941.github.io/lcode/",
856
863
  )
@@ -972,6 +979,25 @@ def build_subparsers() -> dict[str, argparse.ArgumentParser]:
972
979
  help="summarize at this many tokens, e.g. 64k (default: the compact_at setting; 0: only at 85%%)",
973
980
  )
974
981
  subs["bench"] = p
982
+ p = argparse.ArgumentParser(
983
+ prog="lcode trace",
984
+ description="Requests recorded on this machine (the trace setting): list them, show one step by step, "
985
+ "export one for a bug report with secrets and personal details masked, or replay one with the recorded "
986
+ "answers instead of a model and see where the tool results now differ.",
987
+ )
988
+ p.add_argument("action", nargs="?", default="list", help="list (default), show, export, replay or path")
989
+ p.add_argument("trace", nargs="?", help="a number from the list (1: the newest), a trace id or a trace file")
990
+ p.add_argument("-n", "--limit", type=int, default=20, help="list: how many (default: 20)")
991
+ p.add_argument("-v", "--verbose", action="store_true", help="show: also the model's answers and results")
992
+ p.add_argument(
993
+ "-o", "--output", help="export: the file to write (default: lcode-trace-<id>.jsonl here; - prints it)"
994
+ )
995
+ p.add_argument("--repo", help="replay: in a copy of this folder (default: the recorded folder, at its commit)")
996
+ p.add_argument(
997
+ "--commands", action="store_true", help="replay: run shell commands and the checks again too (in the copy)"
998
+ )
999
+ p.add_argument("--keep", action="store_true", help="replay: keep the copy it ran in")
1000
+ subs["trace"] = p
975
1001
  p = argparse.ArgumentParser(
976
1002
  prog="lcode index",
977
1003
  description="Build or refresh the semantic code search index of the repository (an Ollama embedding model).",
@@ -1130,6 +1156,12 @@ def cmd_media(args) -> None:
1130
1156
  console.print("[dim]Install one: lcode media install <model> · choose in image mode: /model <model>[/]")
1131
1157
 
1132
1158
 
1159
+ def cmd_trace(args) -> None:
1160
+ from lcode import traces
1161
+
1162
+ sys.exit(traces.command(args, console))
1163
+
1164
+
1133
1165
  def cmd_mcp(args) -> None:
1134
1166
  from lcode.mcp.commands import run
1135
1167
 
@@ -1143,6 +1175,7 @@ COMMANDS = {
1143
1175
  "media": cmd_media,
1144
1176
  "config": cmd_config,
1145
1177
  "bench": cmd_bench,
1178
+ "trace": cmd_trace,
1146
1179
  "mcp": cmd_mcp,
1147
1180
  "index": cmd_index,
1148
1181
  "action": cmd_action,
lcode/config.py CHANGED
@@ -61,6 +61,11 @@ SETTINGS: dict[str, tuple[object, type, str]] = {
61
61
  "vision_model": ("auto", str, "model that looks at images: auto | off | an Ollama model with vision"),
62
62
  "mcp_tools": ("auto", str, "how MCP tools reach the model: auto | direct | search (on demand, saves context)"),
63
63
  "memory": ("ask", str, "notes that carry over to later sessions: off | ask (confirm each) | auto"),
64
+ "memory_check": (
65
+ False,
66
+ bool,
67
+ "when a conversation ends (quit, /clear, or before it's summarized), ask the model what's worth remembering",
68
+ ),
64
69
  "skills": ("all", str, "skills to offer the model: all (also other agents' folders) | lcode | off"),
65
70
  "repo_map": (True, bool, "give the model a ranked map of the repository's symbols"),
66
71
  "embed_model": ("auto", str, "embedding model for semantic code search (lcode index): auto | off | a model"),
@@ -83,6 +88,7 @@ SETTINGS: dict[str, tuple[object, type, str]] = {
83
88
  "secret_check": (True, bool, "before git commit and git push, look for passwords, keys and tokens they'd add"),
84
89
  "compact_at": (65536, int, "summarize at this many tokens even when the window is larger (0: only at 85%)"),
85
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"),
86
92
  }
87
93
  ENV_OVERRIDES = {
88
94
  "LCODE_MODEL": "model",
@@ -42,6 +42,7 @@ lcode config path # print the file location
42
42
  | `vision_model` | `auto` | The model that [looks at images](usage.md#images): `auto`, `off` or an Ollama model that can see |
43
43
  | `mcp_tools` | `auto` | How [MCP](mcp.md#context) tool definitions reach the model: `auto`, `direct` or `search` (on demand) |
44
44
  | `memory` | `ask` | [Notes that carry over](memory.md) to later sessions: `ask` (confirm each), `auto` or `off` |
45
+ | `memory_check` | `false` | When a conversation ends, [ask the model what's worth remembering](memory.md#a-check-when-a-session-ends) (a model call before you can leave) |
45
46
  | `skills` | `all` | Which [skills](commands.md#skills) the model is offered: `all` (lcode's folders and the ones other agents share), `lcode` (only `.lcode/skills/` and `~/.config/lcode/skills/`) or `off` |
46
47
  | `repo_map` | `true` | Give the model a ranked [map of the repository](search.md) |
47
48
  | `embed_model` | `auto` | Embedding model for [semantic code search](search.md#semantic-code-search): `auto`, `off` or a model name |
@@ -60,6 +61,7 @@ lcode config path # print the file location
60
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) |
61
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)) |
62
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) |
63
65
 
64
66
  Besides these settings, `config.toml` can hold [hooks](hooks.md) (`[[hooks]]`) and
65
67
  [permission rules](hooks.md#permission-rules) (`[permissions]`); a repository can have its own in
@@ -93,20 +95,20 @@ Environment variables override the file, which is useful for one-off runs and CI
93
95
  | `LCODE_SANDBOX` | `sandbox` |
94
96
  | `LCODE_MEMORY` | `memory` |
95
97
  | `OLLAMA_API_KEY`, `BRAVE_API_KEY`, `TAVILY_API_KEY` | API key for that [search provider](usage.md#web-search) (never stored in the config file) |
96
- | `LCODE_HOME` | where sessions and prompt history are stored |
98
+ | `LCODE_HOME` | where sessions, notes and prompt history are stored, instead of `~/.local/state/lcode` |
97
99
 
98
100
  ## Files lcode creates
99
101
 
100
102
  | Path | Contents |
101
103
  |---|---|
102
104
  | `~/.config/lcode/config.toml` | Settings |
103
- | `~/.local/state/lcode/sessions/` | Saved conversations (for `lcode -c`) |
105
+ | `~/.local/state/lcode/sessions/` | Saved conversations (for `/resume` and `lcode -c`), one JSON file each |
104
106
  | `~/.local/state/lcode/history` | Prompt history (++up++ in the prompt) |
105
107
  | `~/.config/lcode/mcp.json` | [MCP servers](mcp.md) (readable only by you; may contain tokens) |
106
108
  | `~/.local/state/lcode/mcp-auth/` | Sign-in tokens for remote MCP servers (readable only by you) |
107
109
  | `~/.local/state/lcode/mcp-logs/` | Error output of local MCP servers |
108
110
  | `~/.local/state/lcode/checkpoints/` | Checkpoints for `/undo` (copies of your project's files; deleted after 14 days) |
109
- | `~/.local/state/lcode/memory/` | [Memory](memory.md) notes: `user/` for every repository, `projects/<repository>/` for each one |
111
+ | `~/.local/state/lcode/memory/` | [Memory](memory.md) notes: `user/` for every repository, `projects/<repository>/` for each one (`/memory path` shows this repository's) |
110
112
  | `~/.config/lcode/commands/`, `~/.config/lcode/skills/` | Your [commands and skills](commands.md) (a repository's go in `.lcode/`) |
111
113
  | `~/.local/state/lcode/extensions-approved.json` | Repositories whose commands, skills and agents you approved |
112
114
  | `~/.config/lcode/agents/` | Your [custom agents](agents.md#custom-agents) (a repository's go in `.lcode/agents/`) |
@@ -114,9 +116,10 @@ Environment variables override the file, which is useful for one-off runs and CI
114
116
  | `~/.local/state/lcode/lsp-logs/` | Language servers' own output |
115
117
  | `~/.local/state/lcode/index/` | [Code search](search.md#semantic-code-search) indexes, one per repository (`lcode index`) |
116
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) |
117
120
  | `~/.local/state/lcode/limits.json` | Context sizes that ran out of GPU memory on this machine (safe to delete) |
118
121
 
119
- 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.
120
123
 
121
124
  ## Tuning for speed and memory
122
125
 
@@ -197,7 +197,8 @@ the Ollama server you configure, it only contacts the web when the model searche
197
197
  | `extensions.py` | Custom commands and skills, and approving a repository's own |
198
198
  | `frontmatter.py` | The `---` headers of notes, agents, commands and skills |
199
199
  | `planning.py` | Plan mode: what it allows, presenting a plan and approving it |
200
- | `memory.py` | Notes that carry over between sessions, and the end-of-session check |
200
+ | `memory.py` | Notes that carry over between sessions, and the optional end-of-session check |
201
+ | `sessions.py`, `repoid.py` | Saved conversations: listing them for this folder and elsewhere; which repository a folder is in, by its first commit |
201
202
  | `sandbox.py` | The optional container for shell commands |
202
203
  | `checkpoints.py` | Snapshots before the model changes files, for `/undo` and `/rewind` |
203
204
  | `catalog.py`, `models.toml` | Model catalog and memory estimates |
lcode/docs/memory.md CHANGED
@@ -49,29 +49,37 @@ instead ("staging credentials are in 1Password, vault Dev").
49
49
  `-g` saves it for every repository. Start with `feedback:`, `reference:` or `user:` to set the
50
50
  type (the default is `project`).
51
51
 
52
- - **At the end of a session**, because local models rarely save anything on their own, lcode
53
- asks the model one short question: is anything from this session worth remembering? It happens
54
- when you quit, on `/clear`, and before the conversation is compacted (the summary leaves details
55
- out). The model proposes at most three notes:
52
+ ## A check when a session ends
56
53
 
57
- ```text
58
- ╭─ Worth remembering? ────────────────────────────────────────────────────────╮
59
- │ 1 [feedback] Use pnpm, not npm (this repository) │
60
- │ 2 [project] Integration tests need `docker compose up db` first (this │
61
- │ repository) │
62
- ╰───────────────────────────────────────────────────────────────────────────────╯
63
- Save them? [y]es / numbers to keep, e.g. 1,3 / [n]o: 1
64
- ```
54
+ Local models rarely save notes on their own. With `memory_check` on, lcode asks the model one short
55
+ question when a conversation ends: is anything from it worth remembering? It happens when you
56
+ quit, on `/clear`, and before the conversation is summarized (the summary leaves details out). The
57
+ model proposes at most three notes:
58
+
59
+ ```text
60
+ ╭─ Worth remembering? ────────────────────────────────────────────────────────╮
61
+ │ 1 [feedback] Use pnpm, not npm (this repository) │
62
+ │ 2 [project] Integration tests need `docker compose up db` first (this │
63
+ │ repository) │
64
+ ╰───────────────────────────────────────────────────────────────────────────────╯
65
+ Save them? [y]es / numbers to keep, e.g. 1,3 / [n]o: 1
66
+ ```
65
67
 
66
- The question is quick: it reuses the conversation Ollama already has in memory, so the model
67
- only writes a few lines. Short sessions (one request and little work) are skipped, and Ctrl+C
68
- skips it too.
68
+ It's off by default, because it's a model call you wait for before you can leave. Turn it on with:
69
+
70
+ ```bash
71
+ lcode config set memory_check true
72
+ ```
73
+
74
+ The question reuses the conversation Ollama already has in memory, so the model only writes a few
75
+ lines. Short sessions (one request and little work) are skipped, and Ctrl+C skips it too. The
76
+ conversation itself is always saved, with or without the check.
69
77
 
70
78
  ## Asking first: the `memory` setting
71
79
 
72
80
  | `memory` | |
73
81
  |---|---|
74
- | `ask` (default) | Every note the model saves, and the end-of-session proposals, need your OK. Answer `a` once to allow the model's notes for the rest of the session. This holds in `yolo` mode too. |
82
+ | `ask` (default) | Every note the model saves, and the [end-of-session](#a-check-when-a-session-ends) proposals, need your OK. Answer `a` once to allow the model's notes for the rest of the session. This holds in `yolo` mode too. |
75
83
  | `auto` | Notes are saved without asking; lcode prints each one. |
76
84
  | `off` | No notes are loaded or saved, and the model has no `memory` tool. |
77
85
 
@@ -116,6 +124,13 @@ The dev dependencies are in a uv dependency group, which plain pytest doesn't se
116
124
 
117
125
  Each folder also has a `MEMORY.md` listing its notes, for reading; lcode regenerates it, so edit
118
126
  the notes rather than that file. A folder that isn't in a git repository gets its own notes.
127
+ `/memory path` shows where this repository's are.
128
+
129
+ A repository's notes follow it when you move or rename it, or clone it again: its folder has a
130
+ `repo.json` naming the repository's first commit, which every clone shares. Notes saved before
131
+ lcode 0.52 get that file the first time lcode runs in their repository. Notes of a repository
132
+ that moved before then are in a folder named after its old name; copy them into the new one
133
+ (`/memory path`) to keep them.
119
134
 
120
135
  At the start of a session, the model gets a one-line index of the notes (description, name, date)
121
136
  in its instructions. The index is capped at about 2,000 tokens, or 5% of a small context window;
lcode/docs/quickstart.md CHANGED
@@ -12,7 +12,7 @@ lcode
12
12
 
13
13
  ```text
14
14
  ╭──────────────────────────────────────────────╮
15
- │ lcode v0.51.0 — local coding agent │
15
+ │ lcode v0.53.0 — local coding agent │
16
16
  │ │
17
17
  │ model lcode-qwen3.6-35b │
18
18
  │ context 256K tokens │