lcode-cli 0.49.0__py3-none-any.whl → 0.49.1__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.49.0"
6
+ __version__ = "0.49.1"
7
7
 
8
8
  API = ("Session", "Result", "Options", "SetupError")
9
9
 
lcode/hardware.py CHANGED
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import platform
6
6
  import subprocess
7
7
  from dataclasses import dataclass
8
+ from pathlib import Path
8
9
 
9
10
  GIB = 1024**3
10
11
 
@@ -46,6 +47,54 @@ def _run(cmd: list[str]) -> str:
46
47
  return ""
47
48
 
48
49
 
50
+ def gpu_used_gib() -> float | None:
51
+ """GPU memory in use on the NVIDIA GPUs, in GiB; None without nvidia-smi."""
52
+ out = _run(["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"])
53
+ try:
54
+ return sum(float(v) for v in out.split()) / 1024 if out else None
55
+ except ValueError:
56
+ return None
57
+
58
+
59
+ def gpu_users() -> list[tuple[str, float]]:
60
+ """The programs holding NVIDIA GPU memory, largest first: (a short name, GiB). Empty without nvidia-smi."""
61
+ out = _run(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader,nounits"])
62
+ users: dict[str, float] = {}
63
+ for line in out.splitlines():
64
+ parts = [p.strip() for p in line.split(",")]
65
+ if len(parts) != 3:
66
+ continue
67
+ try:
68
+ gib = float(parts[2]) / 1024
69
+ except ValueError:
70
+ continue
71
+ name = program_name(parts[0], parts[1])
72
+ users[name] = users.get(name, 0.0) + gib
73
+ return sorted(users.items(), key=lambda item: -item[1])
74
+
75
+
76
+ def program_name(pid: str, process: str) -> str:
77
+ """A GPU program's short name, from its command line (/proc) or else nvidia-smi's process name."""
78
+ try:
79
+ argv = [a.decode(errors="replace") for a in Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0") if a]
80
+ except OSError:
81
+ argv = []
82
+ return name_from(argv or [process], process)
83
+
84
+
85
+ def name_from(argv: list[str], process: str = "") -> str:
86
+ """'render.py' for `python3 render.py`, 'ComfyUI' for its main.py, 'Ollama', else the program."""
87
+ program = Path(argv[0]).name if argv else process
88
+ if program.startswith("python") and len(argv) > 1:
89
+ script = next((a for a in argv[1:] if not a.startswith("-")), argv[1])
90
+ if Path(script).name == "main.py" and "comfyui" in " ".join(argv[:2]).lower():
91
+ return "ComfyUI"
92
+ return Path(script).name
93
+ if program in ("llama-server", "ollama") or "/ollama/" in (argv[0] if argv else ""):
94
+ return "Ollama"
95
+ return program or process
96
+
97
+
49
98
  def _linux_ram_gib() -> float:
50
99
  try:
51
100
  with open("/proc/meminfo") as f:
lcode/media.py CHANGED
@@ -23,13 +23,18 @@ from typing import TYPE_CHECKING
23
23
  import requests
24
24
  from rich.text import Text
25
25
 
26
- from lcode import assistant, comfy, edits, imageopts, media_cloud, preview
26
+ from lcode import assistant, comfy, edits, hardware, imageopts, media_cloud, preview, residency
27
27
  from lcode import media_catalog as catalog
28
28
 
29
29
  if TYPE_CHECKING:
30
30
  from lcode.agent import Agent
31
31
 
32
32
  SOON: dict[str, str] = {}
33
+ LOAD_WAIT = 180 # seconds to wait for the coding model to finish loading before a job (it then unloads itself)
34
+ MIN_FREE_GB = 1.0 # disk space a job needs, where its results are saved
35
+ # how PyTorch and ComfyUI say the GPU is full
36
+ OUT_OF_MEMORY = ("out of memory", "outofmemory", "vram grow failed", "would exceed allowed memory",
37
+ "cudaerrormemoryallocation", "alloc_failed") # fmt: skip
33
38
  IGNORED = "# lcode's images and videos: not part of the project unless you add them\n*\n"
34
39
 
35
40
 
@@ -135,20 +140,24 @@ def stop_engine(agent: Agent) -> bool:
135
140
 
136
141
 
137
142
  def free_gpu(agent: Agent) -> None:
138
- """Unload lcode's coding model if Ollama still has it: the image or video model needs the GPU."""
143
+ """Unload lcode's coding model if Ollama still has it, and wait until its GPU memory is free: the image or video
144
+ model needs the GPU, and a job sent while Ollama is still letting go of it runs out of memory."""
139
145
  if getattr(agent.ollama, "kind", "ollama") != "ollama":
140
146
  return
147
+ if agent.load_state == "loading": # started in code mode: the load gives the GPU back when it's done
148
+ with agent.console.status(f"Waiting for {agent.settings.model} to finish loading, to unload it…"):
149
+ deadline = time.monotonic() + LOAD_WAIT
150
+ while agent.load_state == "loading" and time.monotonic() < deadline:
151
+ time.sleep(0.2)
141
152
  try:
142
- loaded = {name for m in agent.ollama.running() for name in (m.get("name"), m.get("model"))}
153
+ if not residency.placement(agent.ollama, agent.settings.model):
154
+ return
155
+ with agent.console.status(f"Unloading {agent.settings.model} to free the GPU…"):
156
+ freed = residency.release(agent.ollama, agent.settings.model)
143
157
  except Exception:
144
158
  return
145
- model = agent.settings.model
146
- if loaded & {model, f"{model}:latest"}:
147
- try:
148
- agent.ollama.unload(model)
149
- agent.say(f"Unloaded {model} to free the GPU.")
150
- except Exception:
151
- pass
159
+ if freed:
160
+ agent.say(f"Unloaded {agent.settings.model} to free the GPU.")
152
161
 
153
162
 
154
163
  # ----------------------------------------------------------------------------- where the files go
@@ -926,8 +935,9 @@ def describe_job(model, workflow, prompt, text, seed, values, options, files) ->
926
935
 
927
936
  def run_plan(agent: Agent, server: comfy.Server, plan: Plan, cancelled, label: str) -> Made:
928
937
  """Queue the plan, follow it, save what it made, number it, show it."""
929
- free_gpu(agent)
930
938
  out = folder(agent)
939
+ check_disk(agent, out)
940
+ free_gpu(agent)
931
941
  stem = plan.stem or f"{time.strftime('%Y%m%d-%H%M%S')}-{comfy.slug(plan.prompt)}"
932
942
  hint = "Esc or Ctrl+C cancels" if agent.interactive else ""
933
943
  line = Line(f"{plan.model.name} ({label})" if label else plan.model.name, hint)
@@ -958,7 +968,7 @@ def run_plan(agent: Agent, server: comfy.Server, plan: Plan, cancelled, label: s
958
968
  except comfy.ComfyError as e:
959
969
  if job["id"]:
960
970
  comfy.forget(job["id"])
961
- raise MediaError(str(e)) from e
971
+ raise MediaError(explain(agent, str(e))) from e
962
972
  try:
963
973
  saved = comfy.save(server, outputs, out, stem, {**plan.meta, "comfyui_prompt_id": prompt_id})
964
974
  except (comfy.ComfyError, OSError) as e:
@@ -981,6 +991,55 @@ def run_plan(agent: Agent, server: comfy.Server, plan: Plan, cancelled, label: s
981
991
  return made
982
992
 
983
993
 
994
+ def check_disk(agent: Agent, out: Path) -> None:
995
+ """Refuse a job when the disk it saves to is nearly full: ComfyUI fails at the end of it otherwise."""
996
+ places = [out]
997
+ install = comfy.find_install(agent.settings.comfyui_path) if agent.comfy_process is not None else None
998
+ if install is not None:
999
+ places.append(install.path) # ComfyUI writes there first
1000
+ for place in places:
1001
+ try:
1002
+ free = shutil.disk_usage(place).free / 1e9
1003
+ except OSError:
1004
+ continue
1005
+ if free < MIN_FREE_GB:
1006
+ raise MediaError(
1007
+ f"The disk is nearly full ({free:.1f} GB free at {place}): images and videos need room. Free some "
1008
+ "space, then try again."
1009
+ )
1010
+
1011
+
1012
+ def explain(agent: Agent, error: str) -> str:
1013
+ """ComfyUI's error, said so it can be acted on: running out of GPU memory or disk space, or a crash."""
1014
+ low = error.lower()
1015
+ if any(words in low for words in OUT_OF_MEMORY):
1016
+ step = error.split(" failed:", 1)[0] if " failed:" in error else "a step"
1017
+ others = [(name, gib) for name, gib in hardware.gpu_users() if name != "ComfyUI" and gib >= 0.1]
1018
+ held = ", ".join(f"{name} ({gib:.1f} GB)" for name, gib in others)
1019
+ message = f"The GPU ran out of memory ({step})."
1020
+ if held:
1021
+ message += f" Other programs hold GPU memory: {held}. Close what you can, or try"
1022
+ else:
1023
+ message += " Try"
1024
+ message += " --quality fast or a smaller model (/models)."
1025
+ if stop_engine(agent): # after running out of memory ComfyUI can crash on its next job: start it afresh
1026
+ message += " lcode restarts ComfyUI with your next request."
1027
+ else:
1028
+ message += " Restart your ComfyUI if it keeps failing."
1029
+ return message
1030
+ if "no space left on device" in low:
1031
+ return "ComfyUI couldn't save what it made: the disk is full. Free some space, then try again."
1032
+ if "closed the websocket" in low or "connection" in low:
1033
+ proc = agent.comfy_process
1034
+ if proc is not None and proc.poll() is not None:
1035
+ agent.comfy_process = None
1036
+ return (
1037
+ f"ComfyUI stopped while it worked (it crashed; its log: {comfy.log_path()}). lcode starts it again "
1038
+ "with your next request."
1039
+ )
1040
+ return error
1041
+
1042
+
984
1043
  # ----------------------------------------------------------------------------- results: numbered, shown, opened
985
1044
 
986
1045
 
lcode/repl.py CHANGED
@@ -1737,6 +1737,8 @@ def preload(agent: Agent, session: PromptSession | None = None) -> None:
1737
1737
  refresh()
1738
1738
  try:
1739
1739
  agent.ollama.load(agent.settings.model, agent.options(), agent.settings.keep_alive)
1740
+ if agent.settings.mode != "code": # switched to image or video mode while it loaded: give the GPU back
1741
+ residency.release(agent.ollama, agent.settings.model)
1740
1742
  except OllamaError:
1741
1743
  pass
1742
1744
  finally:
lcode/residency.py CHANGED
@@ -19,6 +19,7 @@ from lcode.cloud import is_cloud
19
19
  from lcode.ollama import OllamaError
20
20
 
21
21
  GB = 1e9
22
+ RELEASE_WAIT = 15.0 # seconds to wait for Ollama to give an unloaded model's GPU memory back
22
23
  SPLIT_WARNING = 0.95 # a dense model with less than this on the GPU runs much slower
23
24
  SHORTFALL = 0.25 # this much less on the GPU than expected: something else is using GPU memory
24
25
 
@@ -69,6 +70,38 @@ def loaded(ollama, model: str | None = None) -> list[Placement]:
69
70
  return found
70
71
 
71
72
 
73
+ def release(ollama, model: str, wait: float | None = None) -> bool:
74
+ """Unload a model and wait until its GPU memory is free again; whether it was loaded.
75
+
76
+ Ollama answers the unload at once and frees the memory a moment later: a program that starts on the GPU in
77
+ that moment finds it still full. So this waits until Ollama no longer lists the model and, on NVIDIA GPUs, until
78
+ most of what it held shows as free.
79
+ """
80
+ from lcode import hardware
81
+
82
+ held = loaded(ollama, model)
83
+ if not held:
84
+ return False
85
+ before = hardware.gpu_used_gib()
86
+ ollama.unload(model)
87
+ deadline = time.monotonic() + (RELEASE_WAIT if wait is None else wait)
88
+ while loaded(ollama, model) and time.monotonic() < deadline:
89
+ time.sleep(0.2)
90
+ if before is not None: # NVIDIA: until most of it is free, or the memory stops going down for a second
91
+ target = before - 0.75 * sum(p.vram for p in held) / 2**30
92
+ last, steady = before, time.monotonic()
93
+ while time.monotonic() < deadline:
94
+ used = hardware.gpu_used_gib()
95
+ if used is None or used <= target:
96
+ break
97
+ if abs(used - last) > 0.1:
98
+ last, steady = used, time.monotonic()
99
+ elif time.monotonic() - steady >= 1.0 and used < before - 0.1:
100
+ break
101
+ time.sleep(0.2)
102
+ return True
103
+
104
+
72
105
  def placement(ollama, model: str) -> Placement | None:
73
106
  found = loaded(ollama, model)
74
107
  return found[0] if found else None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lcode-cli
3
- Version: 0.49.0
3
+ Version: 0.49.1
4
4
  Summary: A local-first terminal coding agent powered by open-weight models on your own GPU or Mac, via Ollama.
5
5
  Project-URL: Homepage, https://nasser1941.github.io/lcode/
6
6
  Project-URL: Documentation, https://nasser1941.github.io/lcode/
@@ -1,4 +1,4 @@
1
- lcode/__init__.py,sha256=5SUb93PBl_wFyfEHT79DszzpqhY-EhjUYBO5DPImasU,473
1
+ lcode/__init__.py,sha256=E_r27bB43mx6yBYRfgRUKLFIF-vd3VyGvpgQw_5IEUs,473
2
2
  lcode/__main__.py,sha256=s5N5pryX2FAu93GGZ3FxUrIXHWGzxz66lKUoaV_h8Ws,35
3
3
  lcode/acp.py,sha256=d97VV3sbqXdWKhPQQNbYRaDTm8WrUk0mGbDLiOyX7jE,29058
4
4
  lcode/action.py,sha256=wuT5F9EJCdEligPeytzmEi8FpahWBhXer528tpuTj_k,16711
@@ -25,14 +25,14 @@ lcode/extensions.py,sha256=W0HFDl0BvROzr7i_qtabHdIbacBgP5o5qIJLzoM2oNE,16806
25
25
  lcode/film.py,sha256=nfffI6oMWeherp8AOU_yM7-Cok0JKoQMVeuVtVHKXo0,14455
26
26
  lcode/frontmatter.py,sha256=Bx0n4vLPhp7ZCWx-g7xqzqNy5VoKBxyeeikh5UFB_gA,2441
27
27
  lcode/gitflow.py,sha256=6j_nnCBZXkX1qhTI7K4CyZ5D0NAZLpH96weFEo64AkQ,27913
28
- lcode/hardware.py,sha256=2VbknZCxTZJwJUD8YWdQ7ryEQo_LcjtoOBOHOU9Y0fw,3085
28
+ lcode/hardware.py,sha256=9j_gxSUYLAVtnSLIEL8FVU2q-jEEjHtMs2SVAax7yU8,5154
29
29
  lcode/hooks.py,sha256=K0itOiAuH4rxndJ9gne_uCrqby6oWAzFPRrfB3tCq-E,9324
30
30
  lcode/imageopts.py,sha256=fSVWOiYVeKXfYCdfoBedT2DB_UnZnh66xzp-uFh7N1M,9587
31
31
  lcode/jobs.py,sha256=P1P3FqI6EqL4LgdMX9YGZwCW0Bh5BRXFA_FnQxpHNjE,5618
32
32
  lcode/limits.py,sha256=oJzVQoMyTZ0_Fkpu5t3qxrf9v7Hv9S8U8BRQR5M1aKA,1237
33
33
  lcode/lsp.py,sha256=NtSW7xapv7fg2HAQLuYK1nwIqT7nG0LK1hiTpOmla_4,26086
34
34
  lcode/matching.py,sha256=2N3_qwKJ5gd8el2m_y_egKkFM9rsF1eUhYJcRCVIp98,14015
35
- lcode/media.py,sha256=HF4xzZHBtTFQW2zao0iCEZAzN36KJkakrRmlzFv1QdI,49760
35
+ lcode/media.py,sha256=IKLNDzY3fjjtdUz5NJP0XXzqXxLIoV1Zvy5Nbf4ISi0,53097
36
36
  lcode/media.toml,sha256=cvXxmTEmdwQokadYRVCjmTNIXwk3EoV82XGVj_oCFB8,11297
37
37
  lcode/media_catalog.py,sha256=hp68dG6MtS8rqgcp3coeA5tS1EAA6ATXZEMbsJhWvsk,15730
38
38
  lcode/media_cloud.py,sha256=lu9WccP7QmT6FodZaob8ZUtt0-mdKIcZrNI_vanqb7o,21237
@@ -46,9 +46,9 @@ lcode/planning.py,sha256=Q2upaoZPnXDMQT2F-ETxX1lk_wDntTzhSKNVYIQSoQA,6540
46
46
  lcode/preview.py,sha256=ATzEs6yaI1__bfo2_juWznrTDXUD4QTc_aQMPRCytgA,6253
47
47
  lcode/render.py,sha256=gMvf4W3qkLUJ4Vot3az_hP_zRDAItJC9pP-68dHFkfA,1375
48
48
  lcode/repeats.py,sha256=OTrPdb6BKArDLQEgHaXmJZ-tIFsY_1bk4P0wzzANKLY,5964
49
- lcode/repl.py,sha256=fqUFsMjFnBhCqKSwaYrhQVTSj0wLWimc8d3XdxNGmJA,79213
49
+ lcode/repl.py,sha256=rjd16rqZLyxA3Eor-k2_L5eu9ABb7dhVwyr7k2124VU,79399
50
50
  lcode/repomap.py,sha256=1GRJgEUjBl9XHSXsF7tSGXBCEgsY-3CzwMohaTudZ_M,13969
51
- lcode/residency.py,sha256=B9pwqG6yx5aQD2M5xyQ-bMnYmhD7fv3wCVw_X6VIeAo,7012
51
+ lcode/residency.py,sha256=7a2NYGyHpTm8y4yrcCrDkrtn43vOnE_wg79k9e8dNqY,8484
52
52
  lcode/review.py,sha256=0QBIS-R1B2b3zqx5TcC1qZptpKBbrDhYvMKSNCaDAUo,4686
53
53
  lcode/sandbox.py,sha256=u_pkrVRXhCGhh-wFDPwuZ3jGG7UeXxXRAeBNsm37ZvE,8608
54
54
  lcode/screenshots.py,sha256=pmrw_tp8eXzNyCZa5uot5rTgsxqsi3AdmkGn-XF9saY,57056
@@ -89,8 +89,8 @@ lcode/workflows/wan21-vace.json,sha256=vJsiRvLCXCjKIibOO0SGM3fT6bedAGxF8N2sN2vcP
89
89
  lcode/workflows/wan22-fun-inp-5b.json,sha256=4HbKEezik8MHvxTMP6PjQUPQPfCeSu10U9FrC-DHKYw,3327
90
90
  lcode/workflows/wan22-ti2v-5b.json,sha256=RcTehoC2pNizzlb7Ed3keJ56DiE7V5lhXmsvR2Y0smQ,3371
91
91
  lcode/workflows/z-image-turbo-t2i.json,sha256=sHsL7xnnuULOuWGYlQrDl4jOTySdAmb2T82c_cChv0s,1585
92
- lcode_cli-0.49.0.dist-info/METADATA,sha256=x9blNxg_Gq8qVvwX00ayj0xMEpWufF8yfF4t8qzJFQs,13532
93
- lcode_cli-0.49.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
94
- lcode_cli-0.49.0.dist-info/entry_points.txt,sha256=Hxsn_itbnbgft3U0FwxWdmEt0yoAV2LB-nJDnL9WT20,172
95
- lcode_cli-0.49.0.dist-info/licenses/LICENSE,sha256=JWjmoL7nNIC1XUa-dZm2hwLUgjUQMFo6k8APb0idNzs,1074
96
- lcode_cli-0.49.0.dist-info/RECORD,,
92
+ lcode_cli-0.49.1.dist-info/METADATA,sha256=mRkBbVyZpm8aBXzgPxONy-DJlivb1iaJE0VAN9ZUgHs,13532
93
+ lcode_cli-0.49.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
94
+ lcode_cli-0.49.1.dist-info/entry_points.txt,sha256=Hxsn_itbnbgft3U0FwxWdmEt0yoAV2LB-nJDnL9WT20,172
95
+ lcode_cli-0.49.1.dist-info/licenses/LICENSE,sha256=JWjmoL7nNIC1XUa-dZm2hwLUgjUQMFo6k8APb0idNzs,1074
96
+ lcode_cli-0.49.1.dist-info/RECORD,,