lcode-cli 0.60.0__py3-none-any.whl → 0.61.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 +1 -1
- lcode/agent.py +49 -12
- lcode/agent_base.py +2 -1
- lcode/agent_checks.py +20 -0
- lcode/agent_model.py +28 -3
- lcode/api.py +6 -1
- lcode/catalog.py +10 -0
- lcode/checks.py +73 -1
- lcode/cli.py +4 -1
- lcode/docs/how-it-works.md +14 -7
- lcode/docs/installation.md +1 -0
- lcode/docs/models.md +19 -0
- lcode/docs/quickstart.md +1 -1
- lcode/docs/traces.md +3 -1
- lcode/docs/troubleshooting.md +33 -0
- lcode/docs/usage.md +29 -4
- lcode/doctor.py +6 -1
- lcode/hardware.py +31 -8
- lcode/jobs.py +70 -25
- lcode/repl.py +1 -1
- lcode/replay.py +1 -1
- lcode/residency.py +135 -0
- lcode/tool_schemas.py +8 -1
- lcode/tools_base.py +1 -0
- lcode/tools_edit.py +1 -0
- lcode/tools_shell.py +49 -19
- lcode/traces.py +2 -0
- {lcode_cli-0.60.0.dist-info → lcode_cli-0.61.0.dist-info}/METADATA +1 -1
- {lcode_cli-0.60.0.dist-info → lcode_cli-0.61.0.dist-info}/RECORD +32 -32
- {lcode_cli-0.60.0.dist-info → lcode_cli-0.61.0.dist-info}/WHEEL +0 -0
- {lcode_cli-0.60.0.dist-info → lcode_cli-0.61.0.dist-info}/entry_points.txt +0 -0
- {lcode_cli-0.60.0.dist-info → lcode_cli-0.61.0.dist-info}/licenses/LICENSE +0 -0
lcode/__init__.py
CHANGED
lcode/agent.py
CHANGED
|
@@ -42,7 +42,8 @@ from lcode.tool_helpers import ToolError, is_binary, tree
|
|
|
42
42
|
if TYPE_CHECKING:
|
|
43
43
|
pass
|
|
44
44
|
|
|
45
|
-
MAX_STALLS = 2 # replies that go round in circles or say nothing,
|
|
45
|
+
MAX_STALLS = 2 # replies in a row that go round in circles or say nothing, before lcode stops the request
|
|
46
|
+
MAX_STALLS_PER_REQUEST = 4 # such replies in one request, even with work in between
|
|
46
47
|
STALLED = {
|
|
47
48
|
"circles": "the reply went round in circles, so lcode stopped it",
|
|
48
49
|
"cut_off": "the reply filled the context before it said anything",
|
|
@@ -50,15 +51,16 @@ STALLED = {
|
|
|
50
51
|
}
|
|
51
52
|
|
|
52
53
|
|
|
53
|
-
def stall_note(trouble: str) -> str:
|
|
54
|
+
def stall_note(trouble: str, thinking_off: bool = False) -> str:
|
|
54
55
|
"""What the model is told after a reply that went round in circles or ended without a word."""
|
|
55
56
|
first = {
|
|
56
57
|
"circles": "Your last reply went round in circles (the same thoughts over and over), so lcode stopped it.",
|
|
57
58
|
"cut_off": "Your last reply filled the rest of the context before you said anything.",
|
|
58
59
|
"": "Your last reply was empty.",
|
|
59
60
|
}[trouble]
|
|
61
|
+
off = ": thinking is off for this reply" if thinking_off else ""
|
|
60
62
|
return (
|
|
61
|
-
f"[lcode] {first} Don't deliberate at length now. Either make your next tool call, or, if you're stuck, "
|
|
63
|
+
f"[lcode] {first} Don't deliberate at length now{off}. Either make your next tool call, or, if you're stuck, "
|
|
62
64
|
"tell the user in a few lines what you did, what fails, and what they could do. If you were about to check "
|
|
63
65
|
"something by running it, run it now instead of reasoning about it: for a window, take a screenshot (with "
|
|
64
66
|
"actions for clicks or keys)."
|
|
@@ -280,9 +282,13 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
|
|
|
280
282
|
malformed = 0
|
|
281
283
|
looping = "" # the call the model kept repeating, when lcode stopped the request for it
|
|
282
284
|
blocked = None # the site that couldn't be reached, when lcode stopped the request for it
|
|
283
|
-
stalls = 0 # replies that went round in circles or ended without a word
|
|
285
|
+
stalls = 0 # replies in a row that went round in circles or ended without a word
|
|
286
|
+
stalled = 0 # such replies in this request
|
|
284
287
|
commands: list[str] = [] # shell commands run in this request
|
|
285
288
|
scripts_noted = False # the model was told about scripts it wrote and never ran
|
|
289
|
+
untested: dict[str, None] = {} # code files the model wrote in this request and hasn't run since (#242)
|
|
290
|
+
untested_noted = False # the model was told about them
|
|
291
|
+
missing: dict[str, None] = {} # programs a command in this request found missing
|
|
286
292
|
tools_used: set[str] = set() # tools called in this request
|
|
287
293
|
windows_noted = False # the model was told about windows it changed and never looked at
|
|
288
294
|
for step in range(self.max_steps):
|
|
@@ -294,7 +300,8 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
|
|
|
294
300
|
self.save() # a crash or a closed terminal loses at most this step
|
|
295
301
|
self.maybe_compact()
|
|
296
302
|
try:
|
|
297
|
-
reply
|
|
303
|
+
# After a reply that went nowhere, the next one runs without thinking, so the model acts.
|
|
304
|
+
reply = self.assistant_step(think=not (stalls and self.can_skip_thinking()))
|
|
298
305
|
calls = reply.get("tool_calls") or []
|
|
299
306
|
for i, call in enumerate(calls):
|
|
300
307
|
call.setdefault("id", f"call_{step}_{i}") # so a tool result can name its call
|
|
@@ -336,15 +343,22 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
|
|
|
336
343
|
continue
|
|
337
344
|
if not calls and (self.reply_trouble == "circles" or not (reply.get("content") or "").strip()):
|
|
338
345
|
stalls += 1
|
|
346
|
+
stalled += 1
|
|
339
347
|
dropped = self.messages.pop() # no answer, and circles would only fill the context
|
|
340
348
|
kept = self.keep_dropped(dropped)
|
|
341
|
-
if stalls < MAX_STALLS:
|
|
349
|
+
if stalls < MAX_STALLS and stalled < MAX_STALLS_PER_REQUEST:
|
|
350
|
+
# The next reply runs with thinking off: asked again with it on, the model mostly started
|
|
351
|
+
# the same deliberation over (all 6 polyglot-rust-c attempts on the dev slice, #241).
|
|
352
|
+
pause = self.settings.think and self.can_skip_thinking()
|
|
353
|
+
off = ", with thinking off" if pause else ""
|
|
342
354
|
self.console.print(
|
|
343
|
-
Text(f" ⎿ {STALLED[self.reply_trouble]}: asking for a short answer{kept}", style="yellow")
|
|
355
|
+
Text(f" ⎿ {STALLED[self.reply_trouble]}: asking for a short answer{off}{kept}", style="yellow")
|
|
344
356
|
)
|
|
345
|
-
|
|
357
|
+
note = stall_note(self.reply_trouble, thinking_off=pause)
|
|
358
|
+
self.messages.append({"role": "user", "content": note})
|
|
346
359
|
continue
|
|
347
|
-
|
|
360
|
+
times = "twice in a row" if stalls >= MAX_STALLS else f"{stalled} times in this request"
|
|
361
|
+
why = f"its replies went round in circles or ended without an answer, {times}"
|
|
348
362
|
if not escalated and self.can_escalate():
|
|
349
363
|
escalated = True
|
|
350
364
|
advice = self.ask_stronger(why)
|
|
@@ -355,12 +369,13 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
|
|
|
355
369
|
self.turn_status = "loop"
|
|
356
370
|
self.console.print(
|
|
357
371
|
Text(
|
|
358
|
-
"Stopped: the model's replies went round in circles or ended without an answer,
|
|
359
|
-
f"
|
|
372
|
+
f"Stopped: the model's replies went round in circles or ended without an answer, {times}"
|
|
373
|
+
f"{kept}. Try again with a smaller step, or tell it what to do differently.",
|
|
360
374
|
style="yellow",
|
|
361
375
|
)
|
|
362
376
|
)
|
|
363
377
|
return
|
|
378
|
+
stalls = 0 # it acted or answered: a later reply that goes nowhere starts the count again
|
|
364
379
|
if not calls:
|
|
365
380
|
if self.reply_trouble == "cut_off":
|
|
366
381
|
self.say(
|
|
@@ -383,6 +398,19 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
|
|
|
383
398
|
)
|
|
384
399
|
self.messages.append({"role": "user", "content": checks.unseen_note(unseen)})
|
|
385
400
|
continue
|
|
401
|
+
untried = [] if untested_noted else self.untested_code(untested)
|
|
402
|
+
if untried:
|
|
403
|
+
untested_noted = True
|
|
404
|
+
it = "it" if len(untried) == 1 else "them"
|
|
405
|
+
self.console.print(
|
|
406
|
+
Text(
|
|
407
|
+
f" ⎿ never ran {', '.join(untried)} after writing {it}: asking the model to",
|
|
408
|
+
style="yellow",
|
|
409
|
+
)
|
|
410
|
+
)
|
|
411
|
+
note = checks.untested_note(untried, list(missing), checks.uv_available())
|
|
412
|
+
self.messages.append({"role": "user", "content": note})
|
|
413
|
+
continue
|
|
386
414
|
check = self.project_check() if changed and not verified else None
|
|
387
415
|
if check is not None and check_rounds < checks.MAX_ROUNDS:
|
|
388
416
|
check_rounds += 1
|
|
@@ -436,6 +464,7 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
|
|
|
436
464
|
began = time.monotonic()
|
|
437
465
|
if self.trace is not None:
|
|
438
466
|
self.trace.tool_begin()
|
|
467
|
+
self.tools.wrote = []
|
|
439
468
|
try:
|
|
440
469
|
result = done[i] if i in done else self.run_tool(name, args)
|
|
441
470
|
except KeyboardInterrupt:
|
|
@@ -479,8 +508,16 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
|
|
|
479
508
|
if out_of_reach.stop:
|
|
480
509
|
blocked = out_of_reach
|
|
481
510
|
tools_used.add(name)
|
|
511
|
+
for rel in self.tools.wrote:
|
|
512
|
+
if self.tools.before.get(rel, "") is None and checks.is_code(rel):
|
|
513
|
+
untested[rel] = None # new in this request: it should run before the model says it works
|
|
482
514
|
if name == "bash":
|
|
483
|
-
|
|
515
|
+
command = str(args.get("command", ""))
|
|
516
|
+
commands.append(command)
|
|
517
|
+
if not result.startswith(REFUSED): # a command that wasn't allowed, or failed to start, ran nothing
|
|
518
|
+
for rel in checks.exercised(command, result, untested):
|
|
519
|
+
del untested[rel]
|
|
520
|
+
missing.update(dict.fromkeys(checks.not_found(result)))
|
|
484
521
|
if name in ("edit_file", "write_file", "apply_patch") and not result.startswith(REFUSED):
|
|
485
522
|
changed, verified = True, False
|
|
486
523
|
elif name == "bash" and changed and self.model_ran_checks(str(args.get("command", "")), result):
|
lcode/agent_base.py
CHANGED
|
@@ -18,6 +18,7 @@ from lcode import (
|
|
|
18
18
|
extensions,
|
|
19
19
|
repoid,
|
|
20
20
|
repomap,
|
|
21
|
+
residency,
|
|
21
22
|
subagents,
|
|
22
23
|
traces,
|
|
23
24
|
)
|
|
@@ -34,7 +35,6 @@ from lcode.tools import Toolbox
|
|
|
34
35
|
from lcode.unreachable import NOTE_AT, Sites
|
|
35
36
|
|
|
36
37
|
if TYPE_CHECKING:
|
|
37
|
-
from lcode import residency
|
|
38
38
|
from lcode.agent import Agent
|
|
39
39
|
from lcode.agent_model import Progress
|
|
40
40
|
from lcode.hardware import Hardware
|
|
@@ -196,6 +196,7 @@ class AgentBase:
|
|
|
196
196
|
self.ctx_used = 0
|
|
197
197
|
self._repo: tuple[Path, repoid.Repo | None] | None = None # the workspace's repository, for saved sessions
|
|
198
198
|
self.last_speed = 0.0
|
|
199
|
+
self.reply_speeds = residency.SpeedWatch() # to say why, when replies get far slower (lcode.residency)
|
|
199
200
|
self.usage = {"requests": 0, "prompt_tokens": 0, "prompt_ns": 0, "output_tokens": 0, "output_ns": 0}
|
|
200
201
|
self.trace: traces.Lane | None = None # the request's trace while it's recorded (lcode.traces)
|
|
201
202
|
self.replay: ReplayServer | None = None # in a replay: the recorded results of tools and checks (lcode.replay)
|
lcode/agent_checks.py
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
from collections.abc import Iterable
|
|
5
6
|
from typing import TYPE_CHECKING, cast
|
|
6
7
|
|
|
7
8
|
from lcode import (
|
|
@@ -77,6 +78,25 @@ class Checks(AgentBase):
|
|
|
77
78
|
return []
|
|
78
79
|
return checks.unrun_scripts(project_root_or_cwd(self.cwd), list(self.tools.before), commands)
|
|
79
80
|
|
|
81
|
+
def untested_code(self, written: Iterable[str]) -> list[str]:
|
|
82
|
+
"""Code files the model wrote in this request and hasn't run since their last change (#242): only where the
|
|
83
|
+
checks would run, and when the project has no checks of its own (lcode runs those instead). Window code has
|
|
84
|
+
its own check: a screenshot shows it."""
|
|
85
|
+
if self.allowed_tools is not None or self.planning() or self.no_changes or self.settings.checks == "off":
|
|
86
|
+
return []
|
|
87
|
+
if self.project_check() is not None:
|
|
88
|
+
return []
|
|
89
|
+
root = project_root_or_cwd(self.cwd)
|
|
90
|
+
found = []
|
|
91
|
+
for rel in written:
|
|
92
|
+
path = root / rel
|
|
93
|
+
try:
|
|
94
|
+
if path.is_file() and not checks.GUI_IMPORT.search(path.read_text(errors="replace")):
|
|
95
|
+
found.append(rel)
|
|
96
|
+
except OSError:
|
|
97
|
+
continue
|
|
98
|
+
return found
|
|
99
|
+
|
|
80
100
|
def unseen_windows(self, tools_used: set[str]) -> dict[str, str]:
|
|
81
101
|
"""Window code the model changed in this request and never looked at (only where the checks would run)."""
|
|
82
102
|
if self.allowed_tools is not None or self.planning() or self.no_changes or self.settings.checks == "off":
|
lcode/agent_model.py
CHANGED
|
@@ -214,13 +214,22 @@ class ModelCalls(AgentBase):
|
|
|
214
214
|
) from e
|
|
215
215
|
raise
|
|
216
216
|
|
|
217
|
+
def can_skip_thinking(self) -> bool:
|
|
218
|
+
"""Whether one reply can be asked for without thinking while thinking is on: Ollama's API has a switch for
|
|
219
|
+
it. Other servers take a chat template argument instead (vLLM, llama.cpp), which hosted APIs refuse, so
|
|
220
|
+
lcode doesn't send it unless thinking is off in the settings."""
|
|
221
|
+
return getattr(self.ollama, "kind", "ollama") == "ollama"
|
|
222
|
+
|
|
217
223
|
def _opened(self, response) -> None:
|
|
218
224
|
self.response = response
|
|
219
225
|
if self.cancel is not None and self.cancel.is_set():
|
|
220
226
|
subagents.abort(response)
|
|
221
227
|
|
|
222
|
-
def assistant_step(self) -> dict:
|
|
223
|
-
"""Stream one model response, rendering thinking/content live. Returns the assistant message.
|
|
228
|
+
def assistant_step(self, think: bool = True) -> dict:
|
|
229
|
+
"""Stream one model response, rendering thinking/content live. Returns the assistant message.
|
|
230
|
+
|
|
231
|
+
`think=False` asks for this reply without thinking, even when thinking is on: after a reply that went
|
|
232
|
+
round in circles, so the model acts instead of starting the same deliberation over."""
|
|
224
233
|
content, thinking, tool_calls, final = "", "", [], {}
|
|
225
234
|
md = MarkdownStreamer(self.console)
|
|
226
235
|
progress = Progress(steering=self.steering)
|
|
@@ -243,7 +252,7 @@ class ModelCalls(AgentBase):
|
|
|
243
252
|
start_spinner()
|
|
244
253
|
circles = Circles()
|
|
245
254
|
self.reply_trouble = ""
|
|
246
|
-
stream = self.chat(self.messages, self.tool_schemas(), self.settings.think)
|
|
255
|
+
stream = self.chat(self.messages, self.tool_schemas(), self.settings.think and think)
|
|
247
256
|
try:
|
|
248
257
|
for chunk in stream:
|
|
249
258
|
if self.cancel is not None and self.cancel.is_set():
|
|
@@ -315,4 +324,20 @@ class ModelCalls(AgentBase):
|
|
|
315
324
|
self.sent_chars = self.counted_chars = conversation_chars(self.messages)
|
|
316
325
|
seconds = final.get("eval_duration", 0) / 1e9
|
|
317
326
|
self.last_speed = final.get("eval_count", 0) / seconds if seconds else 0.0
|
|
327
|
+
self.explain_slowdown(final.get("eval_count", 0), seconds)
|
|
318
328
|
return message
|
|
329
|
+
|
|
330
|
+
def explain_slowdown(self, tokens: int, seconds: float) -> None:
|
|
331
|
+
"""When replies fall far below this session's earlier speed and RAM is short, say that's likely why, once."""
|
|
332
|
+
context, spec = self.settings.context, catalog.find(self.settings.model)
|
|
333
|
+
if spec is None or self.hardware is None or self.reply_speeds.explained:
|
|
334
|
+
return
|
|
335
|
+
slowed = self.reply_speeds.add(self.settings.model, context, tokens, seconds)
|
|
336
|
+
fit = residency.ram_fit(self.ollama, spec, context, self.hardware) if slowed else None
|
|
337
|
+
if slowed and fit and fit.short:
|
|
338
|
+
self.reply_speeds.explained = True
|
|
339
|
+
self.say(
|
|
340
|
+
f"Replies slowed from {slowed[0]:.0f} to {slowed[1]:.0f} tokens a second, most likely because RAM is "
|
|
341
|
+
f"short: {fit.describe()}. {fit.advice(residency.SESSION_COMMANDS)}",
|
|
342
|
+
warning=True,
|
|
343
|
+
)
|
lcode/api.py
CHANGED
|
@@ -317,13 +317,18 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
|
|
|
317
317
|
|
|
318
318
|
def close_agent(agent: Agent) -> None:
|
|
319
319
|
"""Stop what lcode started (background jobs, servers, the sandbox, ComfyUI), then say so: the terminal may be
|
|
320
|
-
gone already (closed), and saying it then fails."""
|
|
320
|
+
gone already (closed), and saying it then fails. Kept jobs, services the user asked for, keep running."""
|
|
321
321
|
from lcode import media
|
|
322
322
|
|
|
323
323
|
said = []
|
|
324
324
|
stopped = agent.jobs.stop_all()
|
|
325
325
|
if stopped:
|
|
326
326
|
said.append(f"Stopped {stopped} background job(s).")
|
|
327
|
+
for job in agent.jobs.kept():
|
|
328
|
+
said.append(
|
|
329
|
+
f"Left job {job.id} running, as asked: {job.command} (process group {job.proc.pid}: "
|
|
330
|
+
f"`kill -- -{job.proc.pid}` stops it; its output is in {job.log})"
|
|
331
|
+
)
|
|
327
332
|
if media.stop_engine(agent):
|
|
328
333
|
said.append("Stopped ComfyUI.")
|
|
329
334
|
if agent.lsp is not None:
|
lcode/catalog.py
CHANGED
|
@@ -16,6 +16,7 @@ else: # pragma: no cover
|
|
|
16
16
|
|
|
17
17
|
OVERHEAD_GIB = 1.0 # compute buffers and runtime; measured <1 GiB for qwen3.6-35b and qwen3.5-9b on CUDA
|
|
18
18
|
HEADROOM_GIB = 0.5 # keep a little memory free so estimates at the edge don't run out
|
|
19
|
+
OLLAMA_RAM_GIB = 10.0 # Ollama's server in a long session: its prompt cache (8 GiB by default) and 1-2 GiB of its own
|
|
19
20
|
CONTEXT_STEPS = [1048576, 524288, 262144, 131072, 65536, 32768]
|
|
20
21
|
MIN_USEFUL_CONTEXT = 32768
|
|
21
22
|
|
|
@@ -45,6 +46,15 @@ class ModelSpec:
|
|
|
45
46
|
def memory_gib(self, context: int) -> float:
|
|
46
47
|
return self.size_gb * 1e9 / GIB + self.kv_kib_per_token * 1024 * context / GIB + OVERHEAD_GIB
|
|
47
48
|
|
|
49
|
+
def in_ram_gib(self, context: int, hw: Hardware) -> float:
|
|
50
|
+
"""The part of the model that doesn't fit in GPU memory and stays in system RAM. Ollama's /api/ps leaves out
|
|
51
|
+
an MoE model's: its experts stay mapped from the model's file, so they have to stay in the page cache."""
|
|
52
|
+
return max(0.0, self.memory_gib(context) - hw.vram_gib)
|
|
53
|
+
|
|
54
|
+
def ram_needed_gib(self, context: int, hw: Hardware) -> float:
|
|
55
|
+
"""System RAM a long session needs: the part of the model outside GPU memory, and Ollama's prompt cache."""
|
|
56
|
+
return self.in_ram_gib(context, hw) + OLLAMA_RAM_GIB
|
|
57
|
+
|
|
48
58
|
def best_context(self, budget_gib: float) -> int | None:
|
|
49
59
|
"""Largest standard context window whose estimated memory fits the budget."""
|
|
50
60
|
for ctx in CONTEXT_STEPS:
|
lcode/checks.py
CHANGED
|
@@ -15,9 +15,12 @@ from __future__ import annotations
|
|
|
15
15
|
import json
|
|
16
16
|
import re
|
|
17
17
|
import shutil
|
|
18
|
+
from collections.abc import Iterable
|
|
18
19
|
from dataclasses import dataclass
|
|
19
20
|
from pathlib import Path
|
|
20
21
|
|
|
22
|
+
from lcode.permissions import is_read_only
|
|
23
|
+
|
|
21
24
|
MAX_ROUNDS = 2 # times the model gets failing checks back before lcode stops asking
|
|
22
25
|
TIMEOUT = 600 # seconds a check may run
|
|
23
26
|
OUTPUT_TAIL = 6000 # characters of a failing check's output the model gets back
|
|
@@ -121,7 +124,9 @@ def detect(root: Path) -> Check | None:
|
|
|
121
124
|
if list(root.glob("test_*.py")) or list(root.glob("*_test.py")):
|
|
122
125
|
return Check(f"{py} -m unittest", "test files")
|
|
123
126
|
if (root / "tests").is_dir():
|
|
124
|
-
|
|
127
|
+
# `-t .` lets a package of tests use relative imports. Without __init__.py, it doesn't start at all.
|
|
128
|
+
top = " -t ." if (root / "tests" / "__init__.py").is_file() else ""
|
|
129
|
+
return Check(f"{py} -m unittest discover -s tests{top}", "tests/")
|
|
125
130
|
package = text(root / "package.json")
|
|
126
131
|
if package:
|
|
127
132
|
try:
|
|
@@ -260,6 +265,73 @@ def unrun_note(scripts: list[str]) -> str:
|
|
|
260
265
|
)
|
|
261
266
|
|
|
262
267
|
|
|
268
|
+
# ----------------------------------------------------------------------------- code written, never run
|
|
269
|
+
|
|
270
|
+
CODE_SUFFIXES = frozenset(
|
|
271
|
+
{".py", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".rs", ".go", ".c", ".cc", ".cpp", ".java", ".kt", ".rb",
|
|
272
|
+
".php", ".pl", ".lua", ".jl", ".r", ".scala", ".swift", ".cs"}
|
|
273
|
+
) # fmt: skip
|
|
274
|
+
# Checks that read the code without running it (syntax, lint, types): they don't show that it works.
|
|
275
|
+
STATIC_ONLY = re.compile(
|
|
276
|
+
r"\bast\.parse\b|\bpy_compile\b|\bcompileall\b|(?:^|\s)-fsyntax-only\b|\b(?:node|deno)\s+(?:-c|--check)\b"
|
|
277
|
+
r"|\bphp\s+-l\b|\b(?:ruby|perl)\s+-c\b"
|
|
278
|
+
r"|\b(?:pyflakes|flake8|pylint|mypy|pyright|basedpyright|ruff|eslint|tsc)\b|\bcargo\s+check\b|\bgo\s+vet\b"
|
|
279
|
+
)
|
|
280
|
+
# A test runner runs the code it tests, whether or not the command names a file.
|
|
281
|
+
TEST_RUNNER = re.compile(
|
|
282
|
+
r"\b(?:pytest|py\.test|unittest|tox|nox|jest|vitest|mocha|ctest|phpunit|rspec)\b"
|
|
283
|
+
r"|\b(?:cargo|go|npm|pnpm|yarn|bun|deno|mvn|gradle|dotnet|swift|mix|make)\s+(?:run\s+)?test\b"
|
|
284
|
+
)
|
|
285
|
+
# The program, or a module the code needs, isn't installed: the code didn't run.
|
|
286
|
+
NOT_INSTALLED = re.compile(r"command not found|^\S+: not found$|No module named|Cannot find module", re.I | re.M)
|
|
287
|
+
NOT_FOUND = re.compile(r"(?:^|:\s)([\w.+-]+): (?:command )?not found\s*$", re.M)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def is_code(rel: str) -> bool:
|
|
291
|
+
"""Whether a file is a program or module in a language that runs (shell scripts have their own check)."""
|
|
292
|
+
return Path(rel).suffix.lower() in CODE_SUFFIXES
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def exercised(command: str, result: str, files: Iterable[str]) -> list[str]:
|
|
296
|
+
"""The files among `files` that a shell command ran: it names them, or their module, or runs tests, and its
|
|
297
|
+
program was there. Syntax, lint and type checks, and commands that only look, don't count."""
|
|
298
|
+
if is_read_only(command) or STATIC_ONLY.search(command):
|
|
299
|
+
return []
|
|
300
|
+
if exit_code(result) == 127 or any(NOT_INSTALLED.search(line) for line in result.splitlines()[:20]):
|
|
301
|
+
return []
|
|
302
|
+
if TEST_RUNNER.search(command):
|
|
303
|
+
return list(files)
|
|
304
|
+
return [rel for rel in files if re.search(rf"(?<![\w-]){re.escape(Path(rel).stem)}(?![\w-])", command)]
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def not_found(result: str) -> list[str]:
|
|
308
|
+
"""The programs a shell command's output says aren't installed (`bash: line 1: python3: command not found`)."""
|
|
309
|
+
return list(dict.fromkeys(NOT_FOUND.findall(result)))
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def uv_available() -> bool:
|
|
313
|
+
return shutil.which("uv") is not None
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def untested_note(files: list[str], missing: list[str], uv: bool) -> str:
|
|
317
|
+
names = ", ".join(files)
|
|
318
|
+
it = "it" if len(files) == 1 else "them"
|
|
319
|
+
note = (
|
|
320
|
+
f"[lcode] You wrote {names} in this request but haven't run {it} since your last change. Run {it} now and fix "
|
|
321
|
+
f"what fails, so you know {it} works before you say so: for a module, import it and call what you wrote; "
|
|
322
|
+
"for a server or anything else that keeps running, start it in the background and try it. A syntax check "
|
|
323
|
+
"doesn't show that it works."
|
|
324
|
+
)
|
|
325
|
+
if missing:
|
|
326
|
+
note += f" {', '.join(f'`{m}`' for m in missing)} isn't installed here."
|
|
327
|
+
if uv and any(f.endswith(".py") for f in files):
|
|
328
|
+
note += (
|
|
329
|
+
" To run Python code without changing this machine's Python, `uv run --with PACKAGE python FILE` fetches "
|
|
330
|
+
"Python and the packages it needs into a throwaway environment."
|
|
331
|
+
)
|
|
332
|
+
return note + f" If you can't run {it}, say plainly in your answer that {it} is untested, and why."
|
|
333
|
+
|
|
334
|
+
|
|
263
335
|
# ----------------------------------------------------------------------------- windows it never looked at
|
|
264
336
|
|
|
265
337
|
GUI_IMPORT = re.compile(r"^\s*(?:from|import)\s+(PyQt[56]|PySide[26]|tkinter|kivy|wx|gi\.repository)\b", re.M)
|
lcode/cli.py
CHANGED
|
@@ -26,7 +26,7 @@ from rich.progress import (
|
|
|
26
26
|
from rich.prompt import Confirm
|
|
27
27
|
from rich.table import Table
|
|
28
28
|
|
|
29
|
-
from lcode import backends, catalog, config, limits
|
|
29
|
+
from lcode import backends, catalog, config, limits, residency
|
|
30
30
|
from lcode.agent import Settings
|
|
31
31
|
from lcode.catalog import ModelSpec
|
|
32
32
|
from lcode.cli_args import build_parser, build_subparsers
|
|
@@ -313,6 +313,9 @@ def cmd_setup(args) -> None:
|
|
|
313
313
|
)
|
|
314
314
|
if spec.memory_gib(ctx) > hw.budget_gib:
|
|
315
315
|
console.print("[yellow]warning:[/] this probably doesn't fit in memory; pick a smaller --context or model.")
|
|
316
|
+
elif (fit := residency.ram_fit(ollama, spec, ctx, hw)) and fit.short:
|
|
317
|
+
commands = (f"lcode setup {spec.key} --context {{}}", "lcode setup {}", "lcode models")
|
|
318
|
+
console.print(f"[yellow]warning:[/] RAM is short: {fit.describe()}. {fit.why()} {fit.advice(commands)}")
|
|
316
319
|
if not spec.tested:
|
|
317
320
|
console.print(
|
|
318
321
|
"[yellow]note:[/] this model hasn't been verified with lcode yet — please report how it goes."
|
lcode/docs/how-it-works.md
CHANGED
|
@@ -86,12 +86,13 @@ aren't tracked.
|
|
|
86
86
|
Small models sometimes think in circles: a few paragraphs, over and over, until the context is full.
|
|
87
87
|
That takes minutes behind the spinner and ends without an answer. lcode watches the thinking as it
|
|
88
88
|
streams, and when its sentences keep repeating, it stops the model, drops that reply and asks for a
|
|
89
|
-
short one: the next tool call, or what's blocking it.
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
89
|
+
short one: the next tool call, or what's blocking it. With Ollama, that reply runs with thinking off,
|
|
90
|
+
so the model acts instead of starting the same deliberation over. The dropped reply is saved, and the
|
|
91
|
+
message says where, so you can read what went round in circles. An empty reply, or one that filled the
|
|
92
|
+
context before it said anything, gets the same second chance. When two replies in a row go nowhere, or
|
|
93
|
+
four in one request, lcode stops it (status `loop`), offering the
|
|
94
|
+
[stronger model](usage.md#a-stronger-model-when-stuck) first when one is set. An answer the context
|
|
95
|
+
cut off midway is kept, with a warning to `/compact` or use a larger `/context`.
|
|
95
96
|
|
|
96
97
|
## Subagents
|
|
97
98
|
|
|
@@ -157,6 +158,12 @@ Nemotron (Mamba layers) keep a cache in only a few layers, which is why they can
|
|
|
157
158
|
tokens on consumer hardware. The budget is GPU memory plus spare RAM on Linux, and the GPU share
|
|
158
159
|
of unified memory on Apple Silicon. See [Models & context windows](models.md#how-memory-is-estimated).
|
|
159
160
|
|
|
161
|
+
That budget says whether a model loads, not whether it keeps its speed. An MoE model's experts stay mapped
|
|
162
|
+
from its file, and Ollama's server keeps a prompt cache of up to 8 GB in RAM. When they don't fit in the RAM
|
|
163
|
+
that's available, Linux keeps dropping the experts and reading them back from disk, at a third of the speed.
|
|
164
|
+
`lcode doctor` and `lcode setup` compare the two with what's available now, and a session says so when replies
|
|
165
|
+
slow down that far. See [RAM in a long session](models.md#ram-in-a-long-session).
|
|
166
|
+
|
|
160
167
|
Two lessons from tuning the default model on a 12 GB GPU shaped the defaults:
|
|
161
168
|
|
|
162
169
|
- **Vision projectors cost ~1 GB of VRAM** that Ollama under-counts on small GPUs, causing
|
|
@@ -202,7 +209,7 @@ the Ollama server you configure, it only contacts the web when the model searche
|
|
|
202
209
|
| `sandbox.py` | The optional container for shell commands |
|
|
203
210
|
| `checkpoints.py` | Snapshots before the model changes files, for `/undo` and `/rewind` |
|
|
204
211
|
| `catalog.py`, `models.toml` | Model catalog and memory estimates |
|
|
205
|
-
| `hardware.py` | NVIDIA / Apple Silicon detection |
|
|
212
|
+
| `hardware.py` | NVIDIA / Apple Silicon detection, and the RAM available now |
|
|
206
213
|
| `ollama.py` | Ollama HTTP client |
|
|
207
214
|
| `config.py` | Settings file and environment variables |
|
|
208
215
|
| `traces.py`, `trace_view.py`, `trace_export.py` | Recording requests; listing and showing traces; exporting them with secrets masked |
|
lcode/docs/installation.md
CHANGED
|
@@ -121,6 +121,7 @@ lcode doctor
|
|
|
121
121
|
✓ Ollama http://localhost:11434 · version 0.32.15
|
|
122
122
|
✓ Model qwen3.6-35b → lcode-qwen3.6-35b
|
|
123
123
|
✓ Context 256K tokens · ~28 GB needed, ~35 GB available
|
|
124
|
+
✓ RAM ~27 GB available now, ~26 GB needed in a long session: ~16 GB of the model that doesn't fit on the GPU, up to 10 GB for Ollama's server and prompt cache
|
|
124
125
|
✓ ripgrep found
|
|
125
126
|
✓ git found
|
|
126
127
|
```
|
lcode/docs/models.md
CHANGED
|
@@ -247,6 +247,25 @@ The **memory available** for a model is:
|
|
|
247
247
|
lets the GPU use by default.
|
|
248
248
|
- **Linux with NVIDIA:** GPU memory plus system RAM minus ~8 GB for the OS and your apps.
|
|
249
249
|
|
|
250
|
+
### RAM in a long session
|
|
251
|
+
|
|
252
|
+
The estimate above says whether a model loads. Whether it keeps its speed depends on the RAM that's
|
|
253
|
+
available now, next to your other programs:
|
|
254
|
+
|
|
255
|
+
```
|
|
256
|
+
RAM needed ≈ memory − GPU memory + ~10 GB for Ollama's server and prompt cache
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
- **The part of the model that doesn't fit on the GPU.** A Mixture-of-Experts model's experts stay
|
|
260
|
+
mapped from the model's file, so they have to stay in Linux's page cache. `ollama ps` leaves them out:
|
|
261
|
+
it shows `qwen3.6-35b` at 32K as 10.5 GB, with ~12 GB more in RAM.
|
|
262
|
+
- **Ollama's prompt cache**, which grows to 8 GB in a long session, next to 1–2 GB of the server's own.
|
|
263
|
+
|
|
264
|
+
On a 12 GB GPU, `qwen3.6-35b` needs ~21 GB of RAM at 32K, ~23 GB at 128K and ~26 GB at 256K. On Linux,
|
|
265
|
+
when Ollama runs on the same machine, `lcode doctor` and `lcode setup` compare that with what's available.
|
|
266
|
+
If it's short, replies fall to about a third of their speed after a while: see
|
|
267
|
+
[Troubleshooting](troubleshooting.md#it-starts-fast-then-gets-about-three-times-slower).
|
|
268
|
+
|
|
250
269
|
## Hardware guide
|
|
251
270
|
|
|
252
271
|
What `lcode setup` recommends on common machines: the tested default when it fits, otherwise the
|
lcode/docs/quickstart.md
CHANGED
lcode/docs/traces.md
CHANGED
|
@@ -22,7 +22,9 @@ lcode trace path # the folder the traces are in
|
|
|
22
22
|
the total time, and the tokens in and out. With Ollama, also how long loading the model and
|
|
23
23
|
reading the prompt took. The server counts a reply's tokens only when the reply ends, so for one
|
|
24
24
|
lcode stopped (it went round in circles, or you interrupted it) the trace has an estimate:
|
|
25
|
-
`estimated_in` and `estimated_out`, shown as "about".
|
|
25
|
+
`estimated_in` and `estimated_out`, shown as "about". A reply asked for without thinking has
|
|
26
|
+
`think: false`: thinking is turned off, or the reply before it
|
|
27
|
+
[went nowhere](how-it-works.md#when-a-reply-goes-nowhere).
|
|
26
28
|
- **Each tool call:** its arguments, the result the model got, and how long it took. A result
|
|
27
29
|
longer than 200,000 characters keeps its start and end. When lcode cut a long output for the
|
|
28
30
|
model, the result says where the full output was saved.
|
lcode/docs/troubleshooting.md
CHANGED
|
@@ -88,6 +88,39 @@ need `lcode mcp login <name>`. More in [MCP servers: Troubleshooting](mcp.md#tro
|
|
|
88
88
|
prefer the MoE models in `lcode models` on smaller GPUs.
|
|
89
89
|
- `--no-think` skips reasoning for simple requests.
|
|
90
90
|
|
|
91
|
+
### It starts fast, then gets about three times slower
|
|
92
|
+
|
|
93
|
+
The machine is short of RAM. A model that doesn't fit on the GPU keeps the rest in RAM, and Ollama's
|
|
94
|
+
server keeps a prompt cache there that grows to 8 GB in a long session. When those don't fit next to
|
|
95
|
+
your other programs, Linux drops the model from memory and keeps reading it back from disk.
|
|
96
|
+
|
|
97
|
+
Measured with `qwen3.6-35b` at 32K on an RTX 4080 Laptop GPU (12 GB) with 31 GB of RAM: generation fell
|
|
98
|
+
from about 65 to about 20 tokens/s and prompt reading from about 200 to about 55, with the GPU at 2–14%
|
|
99
|
+
and the disk reading about 1.9 GB/s. A short test right after loading doesn't show it: the slowdown
|
|
100
|
+
starts as the prompt cache fills, within about an hour.
|
|
101
|
+
|
|
102
|
+
`lcode doctor` checks this on Linux, when Ollama runs on the same machine (in Docker too):
|
|
103
|
+
|
|
104
|
+
```text
|
|
105
|
+
! RAM ~15 GB available now, ~21 GB needed in a long session: ~11 GB of the model that doesn't
|
|
106
|
+
fit on the GPU, up to 10 GB for Ollama's server and prompt cache
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`lcode setup` gives the same warning, and a session says it once when replies fall below half of their
|
|
110
|
+
earlier speed and RAM is short. `ollama ps` doesn't show any of this: for a Mixture-of-Experts model it
|
|
111
|
+
leaves out the experts mapped from the model's file, ~12 GB for `qwen3.6-35b`.
|
|
112
|
+
|
|
113
|
+
What helps:
|
|
114
|
+
|
|
115
|
+
1. Close other programs before a long session: browsers, IDEs, containers.
|
|
116
|
+
2. Use a smaller context: `/ctx 64k` in a session or `lcode config set context 64k`. This helps most when
|
|
117
|
+
the window is large: going from 256K to 32K saves ~5 GB with `qwen3.6-35b`.
|
|
118
|
+
3. Pick a smaller model that fits on the GPU: `lcode models`.
|
|
119
|
+
4. To empty the prompt cache right away, unload the model: `ollama stop <model>`. The next request
|
|
120
|
+
reloads it, and the cache fills up again over time.
|
|
121
|
+
|
|
122
|
+
On a Mac, `lcode doctor` doesn't check this yet: see [below](#on-a-mac-a-model-that-should-fit-gets-very-slow).
|
|
123
|
+
|
|
91
124
|
### The model prints tool calls as text instead of running them
|
|
92
125
|
|
|
93
126
|
The model doesn't support Ollama's tool calling well. lcode recovers common formats, but results
|
lcode/docs/usage.md
CHANGED
|
@@ -261,6 +261,17 @@ lcode sends it back once before the answer counts: run it and fix what fails, or
|
|
|
261
261
|
it's untested and why, when running it would install, deploy or delete things. Making it executable
|
|
262
262
|
or reading it doesn't count as running it. `checks = "off"` turns this off too.
|
|
263
263
|
|
|
264
|
+
**Code it never ran.** A model that writes a new module and finds no Python, or checks only its
|
|
265
|
+
syntax, tends to call it done, and the first run shows the error. When a request wrote a new code
|
|
266
|
+
file (Python, JavaScript, TypeScript, Rust, Go, C, Java and other languages that run) and no command
|
|
267
|
+
since its last change ran it, lcode sends it back once: run it (import a module and call what it
|
|
268
|
+
wrote; start a server in the background and try it) and fix what fails, or say plainly that it's
|
|
269
|
+
untested and why. A command counts when it names the file or its module, or runs tests, and its
|
|
270
|
+
program was there: a syntax, lint or type check, `python3: command not found` or a command that
|
|
271
|
+
only reads doesn't count. When `uv` is installed, the note adds that `uv run --with PACKAGE python FILE` runs
|
|
272
|
+
Python code in a throwaway environment. A project with checks of its own gets those instead, and a
|
|
273
|
+
window gets the screenshot check above. `checks = "off"` turns this off too.
|
|
274
|
+
|
|
264
275
|
## A review before the answer
|
|
265
276
|
|
|
266
277
|
Models claim more than they did: half of a two-part request done, "it works now" without having
|
|
@@ -305,8 +316,8 @@ lcode config set escalate_price 3/15 # dollars per million tokens
|
|
|
305
316
|
|
|
306
317
|
**When.** lcode offers it when the [loop breaker](how-it-works.md#when-the-model-repeats-itself)
|
|
307
318
|
would stop the request, when the model's replies [go nowhere](how-it-works.md#when-a-reply-goes-nowhere)
|
|
308
|
-
twice, and when the project's [checks](#checks-before-done)
|
|
309
|
-
fixes, at most once per request. Not for a [site this machine can't reach](how-it-works.md#when-a-site-cant-be-reached):
|
|
319
|
+
twice in a row (or four times in one request), and when the project's [checks](#checks-before-done)
|
|
320
|
+
fail twice in a row after the model's fixes, at most once per request. Not for a [site this machine can't reach](how-it-works.md#when-a-site-cant-be-reached):
|
|
310
321
|
a stronger model can't reach it either. You can also ask at any time: `/escalate`, or
|
|
311
322
|
`/escalate the window still grows` to say what's wrong.
|
|
312
323
|
|
|
@@ -351,11 +362,24 @@ since last time with `bash_output`, and stops it with `bash_stop`.
|
|
|
351
362
|
```
|
|
352
363
|
|
|
353
364
|
- `/jobs` lists the background commands; `/jobs stop 1` stops one.
|
|
354
|
-
- They
|
|
365
|
+
- They stop when the session ends, except **kept** ones. When you ask for a service that stays up
|
|
366
|
+
after lcode is done ("start the docs server and leave it running"), the model adds
|
|
367
|
+
`keep: true`. A kept command writes its output to a log in `~/.local/state/lcode/jobs/`, and at
|
|
368
|
+
the end lcode says what it left running and how to stop it:
|
|
369
|
+
|
|
370
|
+
```text
|
|
371
|
+
Left job 1 running, as asked: mkdocs serve (process group 48211: `kill -- -48211` stops it; its
|
|
372
|
+
output is in ~/.local/state/lcode/jobs/20261103-141502-3fa9c1.log)
|
|
373
|
+
```
|
|
374
|
+
|
|
355
375
|
- Anything else a command starts with `&` is stopped when that command ends. Only background
|
|
356
376
|
commands keep running, so no process outlives the session unnoticed.
|
|
357
377
|
- Background commands ask for permission like any other command, and run in the
|
|
358
|
-
[sandbox](sandbox.md) when it's on.
|
|
378
|
+
[sandbox](sandbox.md) when it's on. A command in the sandbox can't be kept: the sandbox stops
|
|
379
|
+
with lcode.
|
|
380
|
+
- A kept command always asks first, and the question says that it stays running: even a command
|
|
381
|
+
that only reads, or a program you allowed for the session. Only `yolo` mode and an allow rule
|
|
382
|
+
in your settings let it through without asking. Plan mode doesn't run it.
|
|
359
383
|
|
|
360
384
|
## What's happening under the hood
|
|
361
385
|
|
|
@@ -379,6 +403,7 @@ stays loaded:
|
|
|
379
403
|
| The model that looks at images needs the memory | `Loading the vision model … to look at bug.png; qwen3.6-35b makes room and reloads afterwards`, then `◆ qwen3.6-35b was unloaded to make room…`, and the next step says `Reloading qwen3.6-35b into memory (it made room for the vision model …)` |
|
|
380
404
|
| A tool needs the GPU to itself (an MCP server with `free_gpu`) | `◆ Unloaded qwen3.6-35b so the server can use the GPU; it reloads afterwards.` |
|
|
381
405
|
| Ollama ran out of memory | `⚠` what ran out (the prompt batch, or the context next to the model), what lcode retries with, and what it remembers for next time |
|
|
406
|
+
| Replies fell below half of their earlier speed and RAM is short (once a session, on Linux) | `⚠ Replies slowed from 65 to 20 tokens a second, most likely because RAM is short: ~15 GB available now, ~21 GB needed in a long session…`, with what to do. See [Troubleshooting](troubleshooting.md#it-starts-fast-then-gets-about-three-times-slower) |
|
|
382
407
|
|
|
383
408
|
While the model loads in the background at startup, the status bar says
|
|
384
409
|
`loading the model into memory…`. Mixture-of-Experts models, such as qwen3.6-35b, run well with
|