lcode-cli 0.39.0__py3-none-any.whl → 0.40.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.39.0"
6
+ __version__ = "0.40.0"
7
7
 
8
8
  API = ("Session", "Result", "Options", "SetupError")
9
9
 
lcode/agent.py CHANGED
@@ -306,6 +306,8 @@ class Settings:
306
306
  context: int
307
307
  mode: str = "code" # what lcode makes: code, image or video (lcode.modes)
308
308
  comfyui_url: str = "http://127.0.0.1:8188"
309
+ comfyui_path: str | None = None # a ComfyUI install lcode doesn't find by itself (lcode.comfy)
310
+ media_dir: str = ".lcode/media" # where image and video mode save their files (lcode.media)
309
311
  num_batch: int | None = None
310
312
  keep_alive: str = "30m"
311
313
  think: bool = True
@@ -370,6 +372,8 @@ class Agent:
370
372
  self.session_name = ""
371
373
  self.session_title = ""
372
374
  self.interactive = True # False for `lcode -p`: no end-of-session questions
375
+ self.comfy_process = None # the ComfyUI lcode started for image and video mode, stopped when it exits
376
+ self.no_coding_model = "" # why there's no coding model, when lcode started in image or video mode without
373
377
  self.reflected = 0 # messages before this index were already checked for notes to remember
374
378
  self._memory: memory_notes.Memory | None = None
375
379
  self._agent_types: tuple[Path, dict[str, subagents.AgentType], list[str]] | None = None
lcode/api.py CHANGED
@@ -15,6 +15,7 @@ A session is one conversation: each `run` continues it. `stream` yields the same
15
15
 
16
16
  from __future__ import annotations
17
17
 
18
+ import contextlib
18
19
  import io
19
20
  import queue
20
21
  import threading
@@ -130,6 +131,24 @@ def switch(wanted: bool | None, configured: str, default_on: str) -> str:
130
131
  return configured if configured != "off" else default_on
131
132
 
132
133
 
134
+ def coding_model(ollama, options: Options, cfg: dict, requested: int | None, hw: Hardware, console: Console):
135
+ """The coding model to use, its catalog entry and the context window; SetupError when there's none."""
136
+ from lcode import cli
137
+
138
+ check_server(ollama, hw)
139
+ try:
140
+ model, spec = cli.resolve_model(ollama, options.model or cfg["model"])
141
+ except cli.NotInstalled as e:
142
+ first_run = not options.model and cfg["model"] == config.DEFAULT_MODEL and not config.CONFIG_PATH.exists()
143
+ if first_run and not backends.is_openai(ollama):
144
+ raise SetupError("lcode isn't set up yet. Run: lcode setup") from e
145
+ raise SetupError(str(e)) from e
146
+ context, note = cli.choose_context(ollama, model, spec, requested, hw)
147
+ if note:
148
+ console.print(f"[yellow]Context {config.format_tokens(context)}: {note}[/]")
149
+ return model, spec, context
150
+
151
+
133
152
  def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | None = None) -> Agent:
134
153
  """An agent set up the way `lcode` sets up a session: model, context, hooks, language servers, MCP."""
135
154
  from lcode import catalog, cli, extensions, hooks
@@ -153,17 +172,14 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
153
172
  except OllamaError as e:
154
173
  raise SetupError(str(e)) from e
155
174
  hw = hw or detect()
156
- check_server(ollama, hw)
175
+ no_coding_model = "" # why, when image or video mode starts without one
157
176
  try:
158
- model, spec = cli.resolve_model(ollama, options.model or cfg["model"])
159
- except cli.NotInstalled as e:
160
- first_run = not options.model and cfg["model"] == config.DEFAULT_MODEL and not config.CONFIG_PATH.exists()
161
- if first_run and not backends.is_openai(ollama):
162
- raise SetupError("lcode isn't set up yet. Run: lcode setup") from e
163
- raise SetupError(str(e)) from e
164
- context, note = cli.choose_context(ollama, model, spec, requested, hw)
165
- if note:
166
- console.print(f"[yellow]Context {config.format_tokens(context)}: {note}[/]")
177
+ model, spec, context = coding_model(ollama, options, cfg, requested, hw, console)
178
+ except SetupError as e:
179
+ if (options.mode or cfg["mode"]) == "code":
180
+ raise
181
+ # Image and video mode don't need the coding model: start without it, and say so on /mode code.
182
+ model, spec, context, no_coding_model = options.model or cfg["model"], None, requested or 32768, str(e)
167
183
  num_batch = cfg["num_batch"]
168
184
  if num_batch is None and spec and spec.num_batch:
169
185
  if model == spec.local_name:
@@ -182,6 +198,8 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
182
198
  permission_mode=options.permission_mode or cfg["permission_mode"],
183
199
  mode=options.mode or cfg["mode"],
184
200
  comfyui_url=cfg["comfyui_url"],
201
+ comfyui_path=cfg["comfyui_path"],
202
+ media_dir=cfg["media_dir"],
185
203
  web=switch(options.web, cfg["web"], "on"),
186
204
  search_backend=cfg["search_backend"],
187
205
  searxng_url=cfg["searxng_url"],
@@ -211,6 +229,7 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
211
229
  )
212
230
  agent = Agent(ollama, settings, cwd, console=console)
213
231
  agent.hardware = hw
232
+ agent.no_coding_model = no_coding_model
214
233
  agent.autosave = True
215
234
  agent.interactive = options.interactive
216
235
  if options.max_steps:
@@ -250,15 +269,25 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
250
269
 
251
270
 
252
271
  def close_agent(agent: Agent) -> None:
272
+ """Stop what lcode started (background jobs, servers, the sandbox, ComfyUI), then say so: the terminal may be
273
+ gone already (closed), and saying it then fails."""
274
+ from lcode import media
275
+
276
+ said = []
253
277
  stopped = agent.jobs.stop_all()
254
278
  if stopped:
255
- agent.console.print(f"[dim]Stopped {stopped} background job(s).[/]")
279
+ said.append(f"Stopped {stopped} background job(s).")
280
+ if media.stop_engine(agent):
281
+ said.append("Stopped ComfyUI.")
256
282
  if agent.lsp is not None:
257
283
  agent.lsp.close()
258
284
  if agent.mcp:
259
285
  agent.mcp.close()
260
286
  if agent.sandbox:
261
287
  agent.sandbox.stop()
288
+ for line in said:
289
+ with contextlib.suppress(OSError):
290
+ agent.console.print(f"[dim]{line}[/]")
262
291
 
263
292
 
264
293
  # ----------------------------------------------------------------------------- running
lcode/cli.py CHANGED
@@ -3,9 +3,11 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import argparse
6
+ import contextlib
6
7
  import platform
7
8
  import re
8
9
  import shutil
10
+ import signal
9
11
  import sys
10
12
  import tempfile
11
13
  import time
@@ -466,6 +468,7 @@ def cmd_doctor(args) -> None:
466
468
  except ValueError as e:
467
469
  line("MCP", str(e), False)
468
470
  ok = False
471
+ line("ComfyUI", *comfyui_status(cfg))
469
472
  if cfg["sandbox"] == "off":
470
473
  line("Sandbox", "off (lcode config set sandbox docker)", True)
471
474
  else:
@@ -733,17 +736,10 @@ def cmd_chat(args) -> None:
733
736
  print(json.dumps({"type": "result", "status": "error", "error": str(e)}), flush=True)
734
737
  sys.exit(1)
735
738
  fail(str(e))
739
+ exit_on_hangup()
736
740
  exit_code = 0
737
741
  if args.prompt and agent.settings.mode != "code":
738
- from lcode import modes
739
-
740
- message = modes.COMING[agent.settings.mode]
741
- if quiet:
742
- print(json.dumps({"type": "result", "status": "error", "error": message}), flush=True)
743
- else:
744
- out.print(f"[yellow]{escape(message)}[/]")
745
- api.close_agent(agent)
746
- sys.exit(2)
742
+ media_request(agent, args.prompt, out, quiet) # makes the image or video, then exits
747
743
  if args.escalate and args.prompt:
748
744
  agent.escalate_approved = True # the flag is the user's OK for this run
749
745
  try:
@@ -765,6 +761,83 @@ def cmd_chat(args) -> None:
765
761
  sys.exit(exit_code)
766
762
 
767
763
 
764
+ def exit_on_hangup() -> None:
765
+ """A closed terminal (SIGHUP) or a plain kill (SIGTERM) ends lcode the usual way: it saves the session and stops
766
+ what it started (ComfyUI, MCP servers, background jobs) instead of leaving them running."""
767
+
768
+ def leave(signum, frame):
769
+ raise SystemExit(128 + signum)
770
+
771
+ for name in ("SIGHUP", "SIGTERM"):
772
+ sig = getattr(signal, name, None)
773
+ if sig is not None:
774
+ with contextlib.suppress(ValueError, OSError): # only the main thread can
775
+ signal.signal(sig, leave)
776
+
777
+
778
+ def comfyui_status(cfg: dict) -> tuple[str, bool | None]:
779
+ """lcode doctor's ComfyUI line: running or found, and whether the image model is there."""
780
+ from lcode import comfy, media
781
+
782
+ workflow = comfy.load_workflow(media.IMAGE_WORKFLOW)
783
+ server = comfy.Server(cfg["comfyui_url"])
784
+ stats = server.stats()
785
+ install = None if stats else comfy.find_install(cfg["comfyui_path"])
786
+ if not stats and install is None:
787
+ return "not found: image mode offers to install it (or lcode config set comfyui_path <folder>)", None
788
+ if stats:
789
+ where = f"{(stats.get('system') or {}).get('comfyui_version', '?')} running at {server.url}"
790
+ installed = {folder: set(server.models(folder)) for folder in workflow.models}
791
+ else:
792
+ where = f"{install.path} (lcode starts it in image mode)"
793
+ installed = {folder: set(comfy.local_models(install, folder)) for folder in workflow.models}
794
+ missing = [f"{f}/{names[0]}" for f, names in workflow.models.items() if not installed[f] & set(names)]
795
+ if missing:
796
+ return f"{where} · {workflow.name} not installed (missing {', '.join(missing)})", None
797
+ return f"{where} · image model: {workflow.name}", True
798
+
799
+
800
+ def media_request(agent, prompt: str, out: Console, quiet: bool) -> None:
801
+ """`lcode --mode image -p "…"`: make the image, say where it went (or, with --output json, a result object)."""
802
+ import json
803
+
804
+ from lcode import api, media, modes
805
+
806
+ if agent.settings.mode == "video":
807
+ message = modes.COMING["video"]
808
+ if quiet:
809
+ print(json.dumps({"type": "result", "status": "error", "error": message}), flush=True)
810
+ else:
811
+ out.print(f"[yellow]{escape(message)}[/]")
812
+ api.close_agent(agent)
813
+ sys.exit(2)
814
+ try:
815
+ made = media.generate_image(agent, prompt)
816
+ except (media.MediaError, KeyboardInterrupt) as e:
817
+ message = str(e) or "Cancelled."
818
+ if quiet:
819
+ print(json.dumps({"type": "result", "status": "error", "error": message}), flush=True)
820
+ else:
821
+ out.print(f"[red]{escape(message)}[/]")
822
+ api.close_agent(agent)
823
+ sys.exit(1)
824
+ if quiet:
825
+ result = {
826
+ "type": "result",
827
+ "status": "success",
828
+ "mode": "image",
829
+ "files": [str(path) for path in made.files],
830
+ "model": made.model,
831
+ "seed": made.seed,
832
+ "width": made.width,
833
+ "height": made.height,
834
+ "seconds": round(made.seconds, 1),
835
+ }
836
+ print(json.dumps(result, ensure_ascii=False), flush=True)
837
+ api.close_agent(agent)
838
+ sys.exit(0)
839
+
840
+
768
841
  def compact_tokens(value: str) -> int:
769
842
  """`--compact-at`: a token count such as 64k, or 0."""
770
843
  try: