lcode-cli 0.61.0__py3-none-any.whl → 0.63.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.61.0"
6
+ __version__ = "0.63.0"
7
7
 
8
8
  API = ("Session", "Result", "Options", "SetupError")
9
9
 
lcode/agent.py CHANGED
@@ -44,27 +44,47 @@ if TYPE_CHECKING:
44
44
 
45
45
  MAX_STALLS = 2 # replies in a row that go round in circles or say nothing, before lcode stops the request
46
46
  MAX_STALLS_PER_REQUEST = 4 # such replies in one request, even with work in between
47
+ THOUGHT_TAIL = 1500 # characters of a stopped reply's thinking that the model gets back, so it needn't start over
47
48
  STALLED = {
48
49
  "circles": "the reply went round in circles, so lcode stopped it",
50
+ "overthought": "the reply thought at length without acting, so lcode stopped it",
49
51
  "cut_off": "the reply filled the context before it said anything",
50
52
  "": "the reply was empty",
51
53
  }
52
54
 
53
55
 
54
- def stall_note(trouble: str, thinking_off: bool = False) -> str:
55
- """What the model is told after a reply that went round in circles or ended without a word."""
56
+ def stall_note(trouble: str, thinking_off: bool = False, thought: str = "") -> str:
57
+ """What the model is told after a reply that went round in circles, thought too long or ended without a word.
58
+
59
+ `thought` is the stopped reply's thinking: for one that thought too long, its end goes back to the model, so
60
+ the next reply can act on where the reasoning got to instead of starting it over (#241)."""
56
61
  first = {
57
62
  "circles": "Your last reply went round in circles (the same thoughts over and over), so lcode stopped it.",
63
+ "overthought": "Your last reply thought at length without writing anything or making a tool call, so lcode "
64
+ "stopped it.",
58
65
  "cut_off": "Your last reply filled the rest of the context before you said anything.",
59
66
  "": "Your last reply was empty.",
60
67
  }[trouble]
61
68
  off = ": thinking is off for this reply" if thinking_off else ""
62
- return (
69
+ note = (
63
70
  f"[lcode] {first} Don't deliberate at length now{off}. Either make your next tool call, or, if you're stuck, "
64
71
  "tell the user in a few lines what you did, what fails, and what they could do. If you were about to check "
65
72
  "something by running it, run it now instead of reasoning about it: for a window, take a screenshot (with "
66
73
  "actions for clicks or keys)."
67
74
  )
75
+ if trouble == "overthought" and thought.strip():
76
+ note += f"\n\nWhere your thinking had got to (its last part):\n\n{thought_tail(thought)}"
77
+ return note
78
+
79
+
80
+ def thought_tail(thought: str) -> str:
81
+ """The end of a stopped reply's thinking, from a line or sentence start: about THOUGHT_TAIL characters."""
82
+ if len(thought) <= THOUGHT_TAIL:
83
+ return thought.strip()
84
+ tail = thought[-THOUGHT_TAIL:]
85
+ ends = [tail.find(end) + len(end) for end in ("\n", ". ", "? ", "! ", "… ") if end in tail]
86
+ starts = [i for i in ends if i < len(tail) // 2] or [tail.find(" ") + 1] # else at least a whole word
87
+ return "…" + tail[min(starts) :].strip()
68
88
 
69
89
 
70
90
  EVENT_OUTPUT = 4000 # characters of a tool's output in an event
@@ -343,7 +363,9 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
343
363
  continue
344
364
  if not calls and (self.reply_trouble == "circles" or not (reply.get("content") or "").strip()):
345
365
  stalls += 1
346
- stalled += 1
366
+ # A reply that only thought too long counts as one in a row, so one that goes nowhere after it ends
367
+ # the request, but not towards the limit per request: in a long task, hard steps think long.
368
+ stalled += self.reply_trouble != "overthought"
347
369
  dropped = self.messages.pop() # no answer, and circles would only fill the context
348
370
  kept = self.keep_dropped(dropped)
349
371
  if stalls < MAX_STALLS and stalled < MAX_STALLS_PER_REQUEST:
@@ -351,10 +373,14 @@ class Agent(PromptParts, Sessions, Checks, ContextWindow, ModelCalls):
351
373
  # the same deliberation over (all 6 polyglot-rust-c attempts on the dev slice, #241).
352
374
  pause = self.settings.think and self.can_skip_thinking()
353
375
  off = ", with thinking off" if pause else ""
354
- self.console.print(
355
- Text(f" ⎿ {STALLED[self.reply_trouble]}: asking for a short answer{off}{kept}", style="yellow")
356
- )
357
- note = stall_note(self.reply_trouble, thinking_off=pause)
376
+ what = STALLED[self.reply_trouble]
377
+ if self.reply_trouble == "overthought":
378
+ what = (
379
+ f"the reply thought for over {format_tokens(self.settings.think_budget)} tokens without "
380
+ "acting (think_budget), so lcode stopped it"
381
+ )
382
+ self.console.print(Text(f" ⎿ {what}: asking for a short answer{off}{kept}", style="yellow"))
383
+ note = stall_note(self.reply_trouble, thinking_off=pause, thought=dropped.get("thinking") or "")
358
384
  self.messages.append({"role": "user", "content": note})
359
385
  continue
360
386
  times = "twice in a row" if stalls >= MAX_STALLS else f"{stalled} times in this request"
lcode/agent_base.py CHANGED
@@ -86,6 +86,7 @@ class Settings:
86
86
  secret_check: bool = True # scan what git commit and git push would add (lcode.secretscan)
87
87
  compact_at: int = 0 # tokens: make room at this size even when the window is larger (0: only at 85%)
88
88
  repeat_limit: int = 3 # identical calls with identical results before the model is told (lcode.repeats)
89
+ think_budget: int = 7000 # tokens a reply may think before it writes or calls a tool (0: no limit)
89
90
  checks: str = "off" # the project's checks after a change (lcode.checks): auto, off or a command
90
91
  review: str = "off" # check a change against the request before the answer (lcode.review): auto or off
91
92
  escalate_model: str | None = None # a stronger model to ask when stuck (lcode.escalate): provider/model
@@ -191,7 +192,7 @@ class AgentBase:
191
192
  self.turn_status = "" # how the last request ended: success, max_steps, loop, blocked
192
193
  self.repeats = Repeats(settings.repeat_limit) # notices when the model repeats itself
193
194
  self.sites = Sites(NOTE_AT if settings.repeat_limit else 0) # notices a site this machine can't reach
194
- self.reply_trouble = "" # what went wrong with the last reply: "circles", "cut_off" or ""
195
+ self.reply_trouble = "" # what went wrong with the last reply: "circles", "overthought", "cut_off" or ""
195
196
  self.response = None # the streaming response, so another thread can abort it
196
197
  self.ctx_used = 0
197
198
  self._repo: tuple[Path, repoid.Repo | None] | None = None # the workspace's repository, for saved sessions
lcode/agent_checks.py CHANGED
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from collections.abc import Iterable
6
+ from pathlib import Path
6
7
  from typing import TYPE_CHECKING, cast
7
8
 
8
9
  from lcode import (
@@ -115,17 +116,30 @@ class Checks(AgentBase):
115
116
  def model_ran_checks(self, command: str, result: str) -> bool:
116
117
  """Whether a command the model ran was the project's checks, and they passed."""
117
118
  check = self.project_check()
118
- if check is None or not checks.covers(check, command) or checks.exit_code(result) != 0:
119
+ if check is None or not checks.covers(check, command) or not checks.run_passed(check, command, result):
119
120
  return False
120
121
  self.check_results.append({"command": check.command, "exit_code": 0, "by": "model"})
121
122
  return True
122
123
 
124
+ def check_folder(self, check: checks.Check) -> Path:
125
+ """Where the checks run: the project's root, wherever the model's last `cd` left its shell. A command from the
126
+ user's own setting runs where they started lcode."""
127
+ return self.workspace if check.source == checks.YOUR_SETTING else project_root_or_cwd(self.cwd)
128
+
129
+ def files_changed(self) -> list[str]:
130
+ """The files this request changed, with the model's file tools or with its shell commands."""
131
+ return [*self.tools.before, *self.checkpoints.changed_so_far()]
132
+
123
133
  def run_check(self, check: checks.Check, round_: int) -> str | None:
124
134
  """Run the checks after a change. Returns what to tell the model when they fail, else None."""
125
135
  self.say(f"Checking the work: {check.command} (from {check.source})")
126
136
  result = self.replay.check_result(check.command) if self.replay is not None else None
127
137
  if result is None:
128
- result = self.tools.run("bash", {"command": check.command, "timeout": checks.TIMEOUT})
138
+ here, self.cwd = self.cwd, self.check_folder(check)
139
+ try:
140
+ result = self.tools.run("bash", {"command": check.command, "timeout": checks.TIMEOUT})
141
+ finally:
142
+ self.cwd = here
129
143
  code = checks.exit_code(result)
130
144
  if self.trace is not None:
131
145
  self.trace.check(check.command, result, code)
@@ -138,15 +152,34 @@ class Checks(AgentBase):
138
152
  return None
139
153
  if checks.no_tests(check, result):
140
154
  self.say(f"The checks found no tests to run ({check.command}).")
141
- return None
142
- if checks.missing(check, result):
155
+ elif checks.missing(check, result):
143
156
  self.say(
144
157
  f"The checks couldn't run ({check.command}): {result.splitlines()[0][:160]}. Install what they need, "
145
158
  'or set the command: lcode config set checks "…" (or checks off).',
146
159
  warning=True,
147
160
  )
148
- return None
149
- if round_ >= checks.MAX_ROUNDS:
161
+ elif checks.no_test_ran(check, result) and not checks.names_any(result, self.files_changed()):
162
+ self.say(
163
+ f"The checks stopped before running a test ({check.command}): {checks.stop_reason(result)} It doesn't "
164
+ "name a file this request changed, so the model isn't asked to fix it. To get checks that run, fix "
165
+ 'that or set the command: lcode config set checks "…" (or checks off).',
166
+ warning=True,
167
+ )
168
+ else:
169
+ return self.failed_check(check, result, code, round_)
170
+ self.check_results[-1]["exit_code"] = None # no test ran: whoever reads this later shouldn't read a failure
171
+ return None
172
+
173
+ def failed_check(self, check: checks.Check, result: str, code: int, round_: int) -> str:
174
+ """Say that the checks failed, or didn't finish; what to tell the model."""
175
+ if checks.timed_out(result):
176
+ self.check_results[-1]["exit_code"] = None
177
+ self.say(
178
+ f"The checks didn't finish in {checks.TIMEOUT} seconds and were stopped ({check.command}). To use a "
179
+ 'faster command: lcode config set checks "…" (or checks off).',
180
+ warning=True,
181
+ )
182
+ elif round_ >= checks.MAX_ROUNDS:
150
183
  then = "" if self.can_escalate() else ": the model will say what's left"
151
184
  self.say(f"Checks still fail ({check.command}, exit code {code}){then}.", warning=True)
152
185
  else:
lcode/agent_model.py CHANGED
@@ -41,6 +41,8 @@ GPU_MEMORY_ERRORS = (
41
41
 
42
42
 
43
43
  SAFE_NUM_BATCH = 512 # Ollama's default prompt batch
44
+ # Characters a thinking token takes: qwen3.6's long thinking on the dev slice, as Ollama counted it (median 3.3).
45
+ THINK_CHARS_PER_TOKEN = 3.3
44
46
 
45
47
 
46
48
  class Progress:
@@ -229,7 +231,11 @@ class ModelCalls(AgentBase):
229
231
  """Stream one model response, rendering thinking/content live. Returns the assistant message.
230
232
 
231
233
  `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."""
234
+ round in circles, so the model acts instead of starting the same deliberation over.
235
+
236
+ A reply that thinks past `think_budget` tokens before it writes anything or calls a tool is stopped
237
+ (`reply_trouble` "overthought"): on the dev slice, 2 of 102 attempts that passed had one, against 42 of 110
238
+ that failed (#241)."""
233
239
  content, thinking, tool_calls, final = "", "", [], {}
234
240
  md = MarkdownStreamer(self.console)
235
241
  progress = Progress(steering=self.steering)
@@ -251,6 +257,7 @@ class ModelCalls(AgentBase):
251
257
 
252
258
  start_spinner()
253
259
  circles = Circles()
260
+ budget = self.settings.think_budget * THINK_CHARS_PER_TOKEN
254
261
  self.reply_trouble = ""
255
262
  stream = self.chat(self.messages, self.tool_schemas(), self.settings.think and think)
256
263
  try:
@@ -273,6 +280,10 @@ class ModelCalls(AgentBase):
273
280
  if self.settings.repeat_limit and circles.feed(msg["thinking"]):
274
281
  self.reply_trouble = "circles"
275
282
  break # closing the stream below stops the model
283
+ acted = content.strip() or (msg.get("content") or "").strip() or tool_calls or msg.get("tool_calls")
284
+ if budget and len(thinking) > budget and not acted:
285
+ self.reply_trouble = "overthought"
286
+ break
276
287
  if msg.get("content"):
277
288
  if printed_thinking:
278
289
  self.console.print("\n")
lcode/api.py CHANGED
@@ -266,6 +266,7 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
266
266
  notify_after=cfg["notify_after"],
267
267
  secret_check=cfg["secret_check"],
268
268
  repeat_limit=cfg["repeat_limit"],
269
+ think_budget=cfg["think_budget"],
269
270
  checks=cfg["checks"],
270
271
  review=cfg["review"],
271
272
  escalate_model=cfg["escalate_model"],
@@ -345,6 +346,12 @@ def close_agent(agent: Agent) -> None:
345
346
  # ----------------------------------------------------------------------------- running
346
347
 
347
348
 
349
+ def request_status(agent: Agent) -> str:
350
+ """How a request that ran to its end went: success, or max_steps, loop or blocked when lcode stopped it. `lcode -p`
351
+ exits with its code (EXIT_CODES), with or without --output."""
352
+ return agent.turn_status if agent.turn_status in ("max_steps", "loop", "blocked") else "success"
353
+
354
+
348
355
  def run_request(agent: Agent, prompt: str) -> Result:
349
356
  """Run one request to its end and say how it went; errors end up in the result, not raised."""
350
357
  calls: dict[str, dict] = {}
@@ -369,7 +376,7 @@ def run_request(agent: Agent, prompt: str) -> Result:
369
376
 
370
377
  try:
371
378
  agent.run_turn(prompt)
372
- status = agent.turn_status if agent.turn_status in ("max_steps", "loop", "blocked") else "success"
379
+ status = request_status(agent)
373
380
  except KeyboardInterrupt:
374
381
  status, error = "interrupted", "interrupted before the request was done"
375
382
  except ModelError as e:
lcode/backends.py CHANGED
@@ -21,7 +21,7 @@ from urllib.parse import quote
21
21
 
22
22
  import requests
23
23
 
24
- from lcode.ollama import OllamaError, redact
24
+ from lcode.ollama import OllamaError, redact, reply_lines
25
25
 
26
26
  PRESETS = { # backend setting -> (the server's name, its default address)
27
27
  "lmstudio": ("LM Studio", "http://localhost:1234/v1"),
@@ -308,7 +308,7 @@ class OpenAICompatible:
308
308
  with r:
309
309
  if r.status_code != 200:
310
310
  raise self._failed(r.status_code, r.text)
311
- for line in r.iter_lines():
311
+ for line in reply_lines(r, self.name, self.host, BackendError):
312
312
  if not line or not line.startswith(b"data:"):
313
313
  continue
314
314
  data = line[5:].strip()
lcode/bench.py CHANGED
@@ -27,12 +27,12 @@ from rich.markup import escape
27
27
  from rich.table import Table
28
28
  from rich.text import Text
29
29
 
30
- from lcode import __version__, escalate
30
+ from lcode import __version__, escalate, residency
31
31
  from lcode.agent import Agent, Settings
32
32
  from lcode.bench_checks import Check, Task
33
33
  from lcode.bench_quick import TASKS
34
34
  from lcode.config import format_tokens
35
- from lcode.hardware import Hardware
35
+ from lcode.hardware import GIB, Hardware
36
36
  from lcode.ollama import Ollama, OllamaError
37
37
 
38
38
  SCHEMA_VERSION = 1
@@ -188,8 +188,10 @@ class ModelRun:
188
188
  think: bool = True
189
189
  load_seconds: float = 0.0
190
190
  prompt_tps: float | None = None # measured with a fresh prompt; see prompt_speed()
191
- memory_gb: float | None = None
192
- gpu_percent: int | None = None
191
+ memory_gb: float | None = None # as Ollama's /api/ps counts it, which can leave part of the model out
192
+ gpu_percent: int | None = None # of memory_gb, on the GPU
193
+ estimated_memory_gib: float | None = None # all of the model by the catalog's estimate, when Ollama leaves part out
194
+ estimated_gpu_percent: int | None = None # of estimated_memory_gib, on the GPU
193
195
  usage: dict = field(default_factory=dict)
194
196
  tasks: list[TaskResult] = field(default_factory=list)
195
197
  error: str | None = None # the model couldn't run at all
@@ -219,6 +221,14 @@ class ModelRun:
219
221
  def tool_errors(self) -> int:
220
222
  return sum(t.tool_errors for t in self.tasks)
221
223
 
224
+ def note_memory(self, where: residency.Placement) -> None:
225
+ """Ollama's count keeps the names it always had, so results compare with older ones. The estimate that the line
226
+ after the load shows goes next to it."""
227
+ self.memory_gb, self.gpu_percent = round(where.size / 1e9, 1), round(100 * where.vram / where.size)
228
+ if where.estimate > where.size:
229
+ self.estimated_memory_gib = round(where.estimate / GIB, 1)
230
+ self.estimated_gpu_percent = round(100 * where.gpu_share)
231
+
222
232
  def to_json(self) -> dict:
223
233
  data = asdict(self)
224
234
  rates = self.rates()
@@ -410,13 +420,11 @@ def _read_prompt(ollama: Ollama, settings: Settings, options: dict) -> float | N
410
420
  return round(count / (ns / 1e9), 1) if ns and count >= 1000 else None
411
421
 
412
422
 
413
- def memory_use(ollama: Ollama, model: str) -> tuple[float | None, int | None]:
414
- for entry in ollama.running():
415
- if entry.get("name") in (model, f"{model}:latest") or entry.get("model") in (model, f"{model}:latest"):
416
- size, vram = entry.get("size") or 0, entry.get("size_vram") or 0
417
- if size:
418
- return round(size / 1e9, 1), round(100 * vram / size)
419
- return None, None
423
+ def memory_use(ollama: Ollama, model: str, context: int) -> residency.Placement | None:
424
+ """How the loaded model sits in memory, counted as the line after a load counts it: Ollama 0.40 leaves out the
425
+ part of a Mixture-of-Experts model that stays mapped from its file in RAM (see residency.with_estimate)."""
426
+ where = residency.placement(ollama, model) # Ollama lists lcode-qwen3.6-35b as lcode-qwen3.6-35b:latest
427
+ return residency.with_estimate(where, model, context) if where and where.size else None
420
428
 
421
429
 
422
430
  def run_model(
@@ -455,14 +463,15 @@ def run_model(
455
463
  run.interrupted = True
456
464
  return run
457
465
  run.load_seconds = round(time.monotonic() - started, 1)
458
- run.memory_gb, run.gpu_percent = memory_use(ollama, settings.model)
466
+ if placed := memory_use(ollama, settings.model, settings.context):
467
+ run.note_memory(placed)
459
468
  try:
460
469
  with console.status(Elapsed(" Measuring prompt speed")):
461
470
  run.prompt_tps = prompt_speed(ollama, settings, options)
462
471
  except KeyboardInterrupt:
463
472
  run.interrupted = True
464
473
  return run
465
- where = f" · {run.memory_gb} GB, {run.gpu_percent}% on the GPU" if run.memory_gb else ""
474
+ where = f" · {placed.describe()}" if placed else ""
466
475
  reads = f" · reads prompts at {run.prompt_tps:,.0f} tok/s" if run.prompt_tps else ""
467
476
  if getattr(ollama, "kind", "ollama") == "ollama":
468
477
  console.print(f" [dim]Loaded in {run.load_seconds:.0f}s{where}{reads}[/]")
@@ -503,8 +512,8 @@ def run_model(
503
512
  run.pruned, run.compacted = pruned + shared.pruned, compacted + shared.compacted
504
513
  if run.interrupted:
505
514
  break
506
- if run.memory_gb is None:
507
- run.memory_gb, run.gpu_percent = memory_use(ollama, settings.model)
515
+ if run.memory_gb is None and (placed := memory_use(ollama, settings.model, settings.context)):
516
+ run.note_memory(placed)
508
517
  # lcode lowers the batch size or context if the GPU runs out of memory; report what was used.
509
518
  run.context, run.num_batch, run.think = settings.context, settings.num_batch, settings.think
510
519
  return run
@@ -521,6 +530,13 @@ def percent(share: float | None) -> str:
521
530
  return "–" if share is None else f"{share * 100:.0f}%"
522
531
 
523
532
 
533
+ def memory(run: ModelRun) -> str:
534
+ """'~23 GB, 42% on GPU' by lcode's estimate, as the line after the load counts it, or else what Ollama says."""
535
+ if run.estimated_memory_gib:
536
+ return f"~{run.estimated_memory_gib:.0f} GB, {run.estimated_gpu_percent}% on GPU"
537
+ return f"{run.memory_gb} GB, {run.gpu_percent}% on GPU" if run.memory_gb else "?"
538
+
539
+
524
540
  def summary_rows(runs: list[ModelRun], tasks: list[Task]) -> list[tuple[str, list[str]]]:
525
541
  rows = []
526
542
  for task in {t.id: t for t in tasks}.values(): # a task that ran several times: one row, a mark each
@@ -554,10 +570,7 @@ def summary_rows(runs: list[ModelRun], tasks: list[Task]) -> list[tuple[str, lis
554
570
  ("Generation", [cell(r, f"{r.generation_tps:.1f} tok/s" if r.generation_tps else "?") for r in runs]),
555
571
  ("Prompt reading", [cell(r, f"{r.prompt_tps:,.0f} tok/s" if r.prompt_tps else "?") for r in runs]),
556
572
  ("Tool-call errors", [cell(r, str(r.tool_errors)) for r in runs]),
557
- (
558
- "Memory",
559
- [cell(r, f"{r.memory_gb} GB, {r.gpu_percent}% on GPU" if r.memory_gb else "?") for r in runs],
560
- ),
573
+ ("Memory", [cell(r, memory(r)) for r in runs]),
561
574
  ("Context", [cell(r, format_tokens(r.context)) for r in runs]),
562
575
  ]
563
576
  if any(r.session for r in runs):
lcode/checkpoints.py CHANGED
@@ -386,6 +386,18 @@ class Checkpoints:
386
386
  f"[dim]↶ Checkpoint {cp.n}: {count} file{'' if count == 1 else 's'} changed · /undo reverts them[/]"
387
387
  )
388
388
 
389
+ def changed_so_far(self) -> list[str]:
390
+ """The files changed so far in the running request, by shell commands too, without a nested repository's."""
391
+ cp = self._current
392
+ if cp is None:
393
+ return []
394
+ store = Store(Path(cp.worktree))
395
+ try:
396
+ changes = store.changes(cp.before, store.tree())
397
+ except CheckpointError:
398
+ return []
399
+ return [c["path"] for c in changes if not (store.worktree / c["path"]).is_dir()]
400
+
389
401
  def ref(self, n: int) -> str:
390
402
  return f"refs/lcode/{self.session_id}/{n}"
391
403