lcode-cli 0.21.0__py3-none-any.whl → 0.23.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.21.0"
6
+ __version__ = "0.23.0"
7
7
 
8
8
  API = ("Session", "Result", "Options", "SetupError")
9
9
 
lcode/acp.py CHANGED
@@ -48,7 +48,12 @@ KINDS = {
48
48
  "bash": "execute", "web_search": "fetch", "web_fetch": "fetch", "agent": "think", "todo_write": "think",
49
49
  "present_plan": "switch_mode", "bash_output": "read", "bash_stop": "execute",
50
50
  } # fmt: skip
51
- STOP = {"success": "end_turn", "max_steps": "max_turn_requests", "interrupted": "cancelled"}
51
+ STOP = {
52
+ "success": "end_turn",
53
+ "max_steps": "max_turn_requests",
54
+ "loop": "max_turn_requests",
55
+ "interrupted": "cancelled",
56
+ }
52
57
  MAX_INLINE = 200_000 # bytes of a file the editor attaches that go into the prompt
53
58
  METHOD_NOT_FOUND, INVALID_PARAMS, INTERNAL_ERROR, NOT_FOUND = -32601, -32602, -32603, -32002
54
59
 
lcode/action.py CHANGED
@@ -297,7 +297,7 @@ def answer(hub: GitHub, task: Task, inputs: Inputs, cwd: Path) -> None:
297
297
  )
298
298
  with open_session(inputs, cwd) as session:
299
299
  result = session.run(prompt)
300
- if result.status not in ("success", "max_steps"):
300
+ if result.status not in ("success", "max_steps", "loop"):
301
301
  raise ActionError(result.error or result.status)
302
302
  reply = result.text.strip() or "(no answer)"
303
303
  changed = git(cwd, "status", "--porcelain").strip()
@@ -336,6 +336,8 @@ def answer(hub: GitHub, task: Task, inputs: Inputs, cwd: Path) -> None:
336
336
  reply += f"\n\n{link}"
337
337
  if result.status == "max_steps":
338
338
  reply += f"\n\n(Stopped after {inputs.max_steps} steps.)"
339
+ elif result.status == "loop":
340
+ reply += "\n\n(Stopped: the model kept repeating the same call.)"
339
341
  hub.comment(task.number, reply[:MAX_COMMENT] + footer(result))
340
342
 
341
343
 
@@ -349,7 +351,7 @@ def review(hub: GitHub, task: Task, inputs: Inputs, cwd: Path) -> None:
349
351
  prompt = gitflow.review_prompt(session.agent, base)
350
352
  session.agent.no_changes = "This is a review, so nothing can be changed: report what should change instead."
351
353
  result = session.run(prompt)
352
- if result.status not in ("success", "max_steps"):
354
+ if result.status not in ("success", "max_steps", "loop"):
353
355
  raise ActionError(result.error or result.status)
354
356
  hub.comment(task.number, f"**lcode review**\n\n{result.text.strip()[:MAX_COMMENT]}{footer(result)}")
355
357
 
lcode/agent.py CHANGED
@@ -32,6 +32,7 @@ from lcode.mcp import McpManager
32
32
  from lcode.ollama import Ollama, OllamaError
33
33
  from lcode.permissions import Permissions
34
34
  from lcode.render import MarkdownStreamer
35
+ from lcode.repeats import Repeats
35
36
  from lcode.sandbox import Sandbox, SandboxError, project_root
36
37
  from lcode.tools import (
37
38
  LSP_SCHEMA,
@@ -57,7 +58,9 @@ MAX_STEPS_PER_TURN = 150
57
58
  EVENT_OUTPUT = 4000 # characters of a tool's output in an event
58
59
  # How a tool result starts when the call failed or wasn't allowed (an "error" in events and results).
59
60
  REFUSED = ("Error:", "A deny rule", "The user denied", "This needs the user's permission")
60
- MAX_MALFORMED_CALL_RETRIES = 2 # Ollama rejects tool calls whose arguments aren't valid JSON # safety cap on tool-call iterations for one request
61
+ MAX_MALFORMED_CALL_RETRIES = 2 # Ollama rejects tool calls whose arguments aren't valid JSON
62
+ # How Ollama reports a tool call it couldn't parse (Qwen3.6's calls are XML)
63
+ MALFORMED_CALL = ("error parsing tool call", "XML syntax error")
61
64
  AUTO_COMPACT_RATIO = 0.85 # summarize the history when the context is this full
62
65
  PRUNED_ENOUGH = 0.6 # after pruning old tool output, summarize only if the context is still this full
63
66
  PROJECT_FILES = ("AGENTS.md", "LCODE.md", "CLAUDE.md")
@@ -216,6 +219,7 @@ class Settings:
216
219
  notify: bool = False # desktop notifications after long requests (lcode.notify)
217
220
  notify_after: int = 30 # seconds: a request this long notifies when it's done or waits for an answer
218
221
  max_parallel_agents: int = 1
222
+ repeat_limit: int = 3 # identical calls with identical results before the model is told (lcode.repeats)
219
223
 
220
224
 
221
225
  class Agent:
@@ -267,7 +271,8 @@ class Agent:
267
271
  # Decides on a presented plan instead of asking in the terminal: "ask", "auto-edit", or why not.
268
272
  self.plan_review: Callable[[str, str], str] | None = None
269
273
  self.max_steps = MAX_STEPS_PER_TURN
270
- self.turn_status = "" # how the last request ended: success, max_steps
274
+ self.turn_status = "" # how the last request ended: success, max_steps, loop
275
+ self.repeats = Repeats(settings.repeat_limit) # notices when the model repeats itself
271
276
  self.response = None # the streaming response, so another thread can abort it
272
277
  self.ctx_used = 0
273
278
  self.last_speed = 0.0
@@ -809,7 +814,9 @@ class Agent:
809
814
  self.turn_status = "running"
810
815
  note = planning.NOTE if self.planning() and self.allowed_tools is None else ""
811
816
  self.messages.append({"role": "user", "content": self.expand_mentions(user_text) + note})
817
+ self.repeats.reset()
812
818
  malformed = 0
819
+ looping = "" # the call the model kept repeating, when lcode stopped the request for it
813
820
  for step in range(self.max_steps):
814
821
  if self.cancel is not None and self.cancel.is_set():
815
822
  raise KeyboardInterrupt
@@ -834,17 +841,22 @@ class Agent:
834
841
  }
835
842
  )
836
843
  except OllamaError as e:
837
- if "error parsing tool call" not in str(e) or malformed >= MAX_MALFORMED_CALL_RETRIES:
844
+ if not any(m in str(e) for m in MALFORMED_CALL) or malformed >= MAX_MALFORMED_CALL_RETRIES:
838
845
  raise
839
846
  malformed += 1
840
- reason = str(e).rsplit("err=", 1)[-1].strip() if "err=" in str(e) else "invalid JSON"
847
+ if "err=" in str(e):
848
+ reason = str(e).rsplit("err=", 1)[-1].strip()
849
+ elif "XML syntax error" in str(e):
850
+ reason = str(e).split("XML syntax error", 1)[1].strip(" :") or "invalid XML"
851
+ else:
852
+ reason = "invalid JSON"
841
853
  self.console.print("[yellow]The model wrote a malformed tool call; asking it to try again.[/]")
842
854
  self.messages.append(
843
855
  {
844
856
  "role": "user",
845
- "content": f"[lcode] Your last tool call could not be parsed ({reason}): its arguments "
846
- "must be one complete, valid JSON object. Make the call again. If it writes a file, "
847
- "make sure the whole content is included and properly escaped.",
857
+ "content": f"[lcode] Your last tool call could not be parsed ({reason}): it must be "
858
+ "complete and well-formed, with every argument closed. Make the call again. If it writes "
859
+ "a file, make sure the whole content is included and properly escaped.",
848
860
  }
849
861
  )
850
862
  continue
@@ -892,6 +904,15 @@ class Agent:
892
904
  self.console.print(Text(f" {result[:300]}", style="red"))
893
905
  elif name in ("read_file", "grep", "glob", "list_dir"):
894
906
  self.console.print(Text(f" ⎿ {result.count(chr(10)) + 1} line(s)", style="dim"))
907
+ verdict = self.repeats.check(name, args, result)
908
+ if verdict.note:
909
+ result += verdict.note
910
+ what = "stopping the request" if verdict.stop else "told the model"
911
+ self.console.print(
912
+ Text(f" ⎿ same call, same result, {verdict.count} times: {what}", style="yellow")
913
+ )
914
+ if verdict.stop:
915
+ looping = self.describe_call(name, args)
895
916
  tool_msg = {"role": "tool", "tool_name": name, "content": result}
896
917
  if call.get("id"):
897
918
  tool_msg["tool_call_id"] = call["id"]
@@ -905,6 +926,27 @@ class Agent:
905
926
  "output": result[:EVENT_OUTPUT] + ("…" if len(result) > EVENT_OUTPUT else ""),
906
927
  }
907
928
  )
929
+ if looping:
930
+ for rest in calls[i + 1 :]:
931
+ skipped = {
932
+ "role": "tool",
933
+ "tool_name": rest.get("function", {}).get("name", ""),
934
+ "content": "Not run: lcode stopped the request before this call.",
935
+ }
936
+ if rest.get("id"):
937
+ skipped["tool_call_id"] = rest["id"]
938
+ self.messages.append(skipped)
939
+ break
940
+ if looping:
941
+ self.turn_status = "loop"
942
+ self.console.print(
943
+ Text(
944
+ f"Stopped: the model kept making the same call with the same result: {looping}. Tell it "
945
+ "what to do differently, or try again.",
946
+ style="yellow",
947
+ )
948
+ )
949
+ return
908
950
  else:
909
951
  self.turn_status = "max_steps"
910
952
  self.console.print(f"[yellow]Stopped after {self.max_steps} steps.[/]")
lcode/api.py CHANGED
@@ -35,8 +35,8 @@ if TYPE_CHECKING:
35
35
  from lcode.hardware import Hardware
36
36
 
37
37
  SCHEMA_VERSION = 1
38
- STATUSES = ("success", "error", "max_steps", "interrupted")
39
- EXIT_CODES = {"success": 0, "error": 1, "max_steps": 3, "interrupted": 130}
38
+ STATUSES = ("success", "error", "max_steps", "loop", "interrupted")
39
+ EXIT_CODES = {"success": 0, "error": 1, "max_steps": 3, "loop": 4, "interrupted": 130}
40
40
  OLLAMA_INSTALL = {
41
41
  "linux": "curl -fsSL https://ollama.com/install.sh | sh",
42
42
  "darwin": "brew install ollama (or download it from https://ollama.com/download)",
@@ -69,7 +69,7 @@ class Options:
69
69
  class Result:
70
70
  """How a request went. `to_json()` is what `lcode -p --output json` prints."""
71
71
 
72
- status: str # success, error, max_steps or interrupted
72
+ status: str # success, error, max_steps, loop (stopped: the model kept repeating itself) or interrupted
73
73
  text: str # the model's final answer
74
74
  session_id: str
75
75
  model: str
@@ -194,6 +194,7 @@ def open_agent(cwd: Path, options: Options, console: Console, hw: Hardware | Non
194
194
  embed_model=cfg["embed_model"],
195
195
  notify=cfg["notify"],
196
196
  notify_after=cfg["notify_after"],
197
+ repeat_limit=cfg["repeat_limit"],
197
198
  )
198
199
  agent = Agent(ollama, settings, cwd, console=console)
199
200
  agent.interactive = options.interactive
@@ -272,7 +273,7 @@ def run_request(agent: Agent, prompt: str) -> Result:
272
273
 
273
274
  try:
274
275
  agent.run_turn(prompt)
275
- status = "max_steps" if agent.turn_status == "max_steps" else "success"
276
+ status = agent.turn_status if agent.turn_status in ("max_steps", "loop") else "success"
276
277
  except KeyboardInterrupt:
277
278
  status, error = "interrupted", "interrupted before the request was done"
278
279
  except ModelError as e:
lcode/config.py CHANGED
@@ -59,6 +59,7 @@ SETTINGS: dict[str, tuple[object, type, str]] = {
59
59
  "subagents": (True, bool, "let the model hand tasks to subagents that have their own context"),
60
60
  "notify": (True, bool, "desktop notification when a long request is done or waits for you"),
61
61
  "notify_after": (30, int, "seconds a request runs before it notifies (with notify on)"),
62
+ "repeat_limit": (3, int, "identical tool calls with identical results before lcode steps in (0: never)"),
62
63
  "max_parallel_agents": (1, int, "subagents that may run at the same time (more needs OLLAMA_NUM_PARALLEL)"),
63
64
  }
64
65
  ENV_OVERRIDES = {
lcode/mcp/catalog.toml CHANGED
@@ -281,3 +281,24 @@ secret = true
281
281
  var = "VALOHAI_HOST"
282
282
  prompt = "Valohai address (Enter for app.valohai.com; for a self-hosted installation, its URL)"
283
283
  optional = true
284
+
285
+ [xai]
286
+ name = "xAI Grok Imagine"
287
+ description = "Generate and edit images, and generate videos and speech, with xAI's Grok Imagine and voice API (paid, in the cloud)"
288
+ homepage = "https://nasser1941.github.io/lcode/mcp/#xai"
289
+ requires = ["uvx"]
290
+ setup = """Uses xAI's API: your prompts, and images you edit or animate, go to xAI, and every call is billed to your xAI
291
+ account (an image $0.02-0.05, video $0.02-0.08 a second, speech per character). Create an API key at https://console.x.ai.
292
+ Files are saved in generated/ in the project. lcode asks before each call; to stop asking for some tools, list them
293
+ under "allow" for this server in mcp.json. xAI has no music generation."""
294
+
295
+ [xai.server]
296
+ command = "uvx"
297
+ args = ["--isolated", "--python", "3.12", "--from", "lcode-cli", "lcode-mcp-xai"]
298
+ env = { XAI_API_KEY = "${XAI_API_KEY}" }
299
+ timeout = 900 # a video takes minutes
300
+
301
+ [[xai.inputs]]
302
+ var = "XAI_API_KEY"
303
+ prompt = "xAI API key (create one at https://console.x.ai)"
304
+ secret = true
lcode/repeats.py ADDED
@@ -0,0 +1,104 @@
1
+ """Notice when the model goes round in circles.
2
+
3
+ Small models sometimes fall into a loop: they make a tool call, get a result, and make the very same call
4
+ again, and again, until the user steps in. Within one request lcode counts the calls that repeat an earlier
5
+ one exactly: the same tool, the same arguments and the same result. At the `limit`-th one (a call that
6
+ failed: one sooner) the result gets a note that tells the model so, and if it still goes on, lcode ends the
7
+ request.
8
+
9
+ Results that change aren't repeats: a test run again after a fix, a background job read while it runs. And
10
+ a call that may have changed something (a file edit, a shell command that isn't read-only) starts the count
11
+ again for every other call, so checking a build after each edit never adds up. Its own repeats still count:
12
+ running the same failing command over and over is a loop.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import json
19
+ from dataclasses import dataclass
20
+
21
+ from lcode.permissions import is_read_only
22
+
23
+ STOP_AFTER_NOTE = 2 # repeats after the note before the request ends
24
+ FAILED = ("Error:", "A deny rule", "The user denied", "This needs the user's permission")
25
+ UNCHANGING = frozenset(
26
+ {
27
+ "read_file",
28
+ "list_dir",
29
+ "glob",
30
+ "grep",
31
+ "view_image",
32
+ "repo_map",
33
+ "search_code",
34
+ "lsp",
35
+ "web_search",
36
+ "web_fetch",
37
+ "bash_output",
38
+ "todo_write",
39
+ "skill",
40
+ "mcp_find_tools",
41
+ }
42
+ ) # tools that don't change files; anything else might
43
+
44
+
45
+ @dataclass
46
+ class Verdict:
47
+ count: int # how often this exact call got this exact result in the request
48
+ note: str = "" # to add to the tool result
49
+ stop: bool = False # end the request
50
+
51
+
52
+ class Repeats:
53
+ def __init__(self, limit: int = 3) -> None:
54
+ self.limit = limit # 0: off
55
+ self.seen: dict[str, int] = {}
56
+
57
+ def reset(self) -> None:
58
+ """A new request."""
59
+ self.seen.clear()
60
+
61
+ def check(self, name: str, args: dict, result: str) -> Verdict:
62
+ """Count this call and its result."""
63
+ if self.limit <= 0:
64
+ return Verdict(1)
65
+ key = hashlib.sha256(json.dumps([name, args, result], sort_keys=True, default=str).encode()).hexdigest()
66
+ count = self.seen.get(key, 0) + 1
67
+ if changes_things(name, args, result):
68
+ self.seen.clear()
69
+ self.seen[key] = count
70
+ failed = result.startswith(FAILED)
71
+ note_at = max(2, self.limit - 1) if failed else max(2, self.limit)
72
+ if count < note_at:
73
+ return Verdict(count)
74
+ same = "the same error" if failed else "the same result"
75
+ if count >= note_at + STOP_AFTER_NOTE:
76
+ return Verdict(
77
+ count,
78
+ f"\n\n[lcode] You made this exact call {count} times in this request and got {same} each "
79
+ "time, so lcode stopped the request here. Next time, don't repeat a call that didn't help: "
80
+ "change your approach, or tell the user what is blocking you.",
81
+ stop=True,
82
+ )
83
+ hint = (
84
+ "If it's an edit, read the file again and copy the text exactly. "
85
+ if failed and name in ("edit_file", "write_file")
86
+ else ""
87
+ )
88
+ return Verdict(
89
+ count,
90
+ f"\n\n[lcode] You made this exact call {count} times in this request and got {same} each time. "
91
+ f"Making it again won't change that. Use what it returned, or try something different. {hint}"
92
+ "If you're stuck, stop and tell the user what is blocking you.",
93
+ )
94
+
95
+
96
+ def changes_things(name: str, args: dict, result: str) -> bool:
97
+ """Whether the call may have changed files (or anything else a later call could see)."""
98
+ if name in UNCHANGING:
99
+ return False
100
+ if name in ("edit_file", "write_file"):
101
+ return not result.startswith(FAILED)
102
+ if name == "bash":
103
+ return not is_read_only(str(args.get("command", "")))
104
+ return True # other tools (MCP, subagents…) might
lcode/servers/xai.py ADDED
@@ -0,0 +1,289 @@
1
+ """An MCP server for xAI's Grok Imagine and voice APIs: images, image edits, videos and speech.
2
+
3
+ xAI has an HTTP API but no MCP server, so lcode ships this one. It needs an API key (XAI_API_KEY,
4
+ from https://console.x.ai) and saves what it makes in the project, in `generated/` unless a path is
5
+ given. The prompts, and any image it edits or animates, go to xAI, which bills per image, per
6
+ second of video and per character of speech, and applies its own usage policies.
7
+
8
+ Run: lcode-mcp-xai (lcode mcp add xai sets it up)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import base64
15
+ import mimetypes
16
+ import os
17
+ import re
18
+ import time
19
+ from pathlib import Path
20
+
21
+ import requests
22
+
23
+ from lcode import __version__
24
+ from lcode.mcp.server import Server, ToolFailure
25
+
26
+ API = "https://api.x.ai/v1"
27
+ TIMEOUT = 120
28
+ IMAGE_MODELS = ["grok-imagine-image-2.0", "grok-imagine-image-quality", "grok-imagine-image"]
29
+ VIDEO_MODELS = ["grok-imagine-video-1.5", "grok-imagine-video-1.5-lite", "grok-imagine-video"]
30
+ ASPECT_RATIOS = ["auto", "1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3", "2:1", "1:2", "21:9"]
31
+ VOICES = ["eve", "ara", "leo", "rex", "sal", "luna", "iris", "orion", "helix", "zagan", "carina", "altair", "zenith",
32
+ "perseus", "helios", "lux", "kepler", "rigel", "cosmo", "celeste", "ursa", "sirius", "lumen", "castor",
33
+ "naksh", "atlas"] # fmt: skip
34
+ AUDIO_FORMATS = {"mp3": ".mp3", "wav": ".wav"}
35
+ VIDEO_WAIT = 600 # seconds generate_video waits before handing back the request id
36
+ POLL = 5
37
+
38
+
39
+ class XAI:
40
+ def __init__(self, key: str, base: str = API, output: Path | None = None):
41
+ self.base = base.rstrip("/")
42
+ self.output = output or Path("generated")
43
+ self.session = requests.Session()
44
+ self.session.headers.update({"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
45
+
46
+ def request(self, method: str, path: str, **kwargs) -> requests.Response:
47
+ try:
48
+ r = self.session.request(method, f"{self.base}{path}", timeout=TIMEOUT, **kwargs)
49
+ except requests.RequestException as e:
50
+ raise ToolFailure(f"can't reach xAI: {e}") from e
51
+ if r.status_code in (401, 403):
52
+ raise ToolFailure(
53
+ f"xAI refused the request ({r.status_code}): {_error(r)}. Check XAI_API_KEY (console.x.ai)."
54
+ )
55
+ if r.status_code == 429:
56
+ raise ToolFailure(f"xAI's rate limit or credit limit was reached: {_error(r)}")
57
+ if r.status_code >= 400:
58
+ raise ToolFailure(f"xAI error {r.status_code}: {_error(r)}")
59
+ return r
60
+
61
+ def post(self, path: str, body: dict) -> dict:
62
+ return self.request("POST", path, json=body).json()
63
+
64
+ def download(self, url: str) -> bytes:
65
+ try:
66
+ r = requests.get(url, timeout=TIMEOUT)
67
+ r.raise_for_status()
68
+ except requests.RequestException as e:
69
+ raise ToolFailure(f"couldn't download the result from xAI: {e}") from e
70
+ return r.content
71
+
72
+ def target(self, path: str, stem: str, suffix: str) -> Path:
73
+ """Where to save: the given path, or a new file in the output folder."""
74
+ if path:
75
+ target = Path(path).expanduser()
76
+ if not target.suffix:
77
+ target = target.with_suffix(suffix)
78
+ else:
79
+ name = re.sub(r"[^a-z0-9]+", "-", stem.lower()).strip("-")[:40] or "xai"
80
+ target = self.output / f"{name}-{time.strftime('%Y%m%d-%H%M%S')}{suffix}"
81
+ target.parent.mkdir(parents=True, exist_ok=True)
82
+ n, unique = 2, target
83
+ while unique.exists():
84
+ unique = target.with_name(f"{target.stem}-{n}{target.suffix}")
85
+ n += 1
86
+ return unique
87
+
88
+
89
+ def _error(r: requests.Response) -> str:
90
+ try:
91
+ data = r.json()
92
+ except ValueError:
93
+ return r.text[:300]
94
+ error = data.get("error") if isinstance(data, dict) else None
95
+ if isinstance(error, dict):
96
+ return str(error.get("message") or error)[:300]
97
+ return str(error or data)[:300]
98
+
99
+
100
+ def data_url(path: str) -> str:
101
+ """A local image as a data: URL, for edits and image-to-video."""
102
+ file = Path(path).expanduser()
103
+ if not file.is_file():
104
+ raise ToolFailure(f"{path} doesn't exist")
105
+ mime = mimetypes.guess_type(file.name)[0] or "image/png"
106
+ if mime not in ("image/png", "image/jpeg", "image/webp"):
107
+ raise ToolFailure(f"{path} isn't a PNG, JPEG or WebP image")
108
+ return f"data:{mime};base64,{base64.b64encode(file.read_bytes()).decode()}"
109
+
110
+
111
+ def image_suffix(data: bytes) -> str:
112
+ if data[:3] == b"\xff\xd8\xff":
113
+ return ".jpg"
114
+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
115
+ return ".webp"
116
+ return ".png"
117
+
118
+
119
+ def save_images(api: XAI, reply: dict, prompt: str, path: str) -> list[Path]:
120
+ saved = []
121
+ items = reply.get("data") or []
122
+ if not items:
123
+ raise ToolFailure(f"xAI returned no image: {str(reply)[:300]}")
124
+ for i, item in enumerate(items):
125
+ data = base64.b64decode(item["b64_json"]) if item.get("b64_json") else api.download(item["url"])
126
+ many = path and len(items) > 1
127
+ target = api.target(f"{Path(path).with_suffix('')}-{i + 1}" if many else path, prompt, image_suffix(data))
128
+ target.write_bytes(data)
129
+ saved.append(target)
130
+ return saved
131
+
132
+
133
+ def build(api: XAI) -> Server:
134
+ server = Server(
135
+ "xai",
136
+ __version__,
137
+ "xAI's Grok Imagine and voice: generate and edit images, generate videos (from text or a start image) "
138
+ "and speech. Results are saved as files in the project; each call costs money on the user's xAI account. "
139
+ "xAI has no music generation.",
140
+ )
141
+ path_arg = {"type": "string", "description": "Where to save it (default: a new file in generated/)"}
142
+
143
+ @server.tool(
144
+ "generate_image",
145
+ "Generate images from a description with Grok Imagine and save them. Costs $0.02–0.05 per image.",
146
+ {
147
+ "prompt": {"type": "string", "description": "What the image shows, in detail"},
148
+ "n": {"type": "integer", "description": "How many images, 1–10 (default 1)"},
149
+ "aspect_ratio": {"type": "string", "enum": ASPECT_RATIOS, "description": "Default auto"},
150
+ "resolution": {"type": "string", "enum": ["1k", "2k"], "description": "Default 1k"},
151
+ "model": {"type": "string", "enum": IMAGE_MODELS, "description": f"Default {IMAGE_MODELS[0]}"},
152
+ "path": path_arg,
153
+ },
154
+ ["prompt"],
155
+ )
156
+ def generate_image(prompt: str, n: int = 1, aspect_ratio: str = "auto", resolution: str = "1k",
157
+ model: str = IMAGE_MODELS[0], path: str = "") -> str: # fmt: skip
158
+ body = {"model": model, "prompt": prompt, "n": max(1, min(10, int(n))), "response_format": "b64_json"}
159
+ if aspect_ratio and aspect_ratio != "auto":
160
+ body["aspect_ratio"] = aspect_ratio
161
+ if resolution and resolution != "1k":
162
+ body["resolution"] = resolution
163
+ saved = save_images(api, api.post("/images/generations", body), prompt, path)
164
+ return f"Saved {len(saved)} image(s) from {model}:\n" + "\n".join(f"- {p}" for p in saved)
165
+
166
+ @server.tool(
167
+ "edit_image",
168
+ "Change an existing image (a local file) as described, with Grok Imagine, and save the result.",
169
+ {
170
+ "image": {"type": "string", "description": "Path of the image to edit (PNG, JPEG or WebP)"},
171
+ "prompt": {"type": "string", "description": "What to change"},
172
+ "model": {"type": "string", "enum": IMAGE_MODELS, "description": f"Default {IMAGE_MODELS[0]}"},
173
+ "path": path_arg,
174
+ },
175
+ ["image", "prompt"],
176
+ )
177
+ def edit_image(image: str, prompt: str, model: str = IMAGE_MODELS[0], path: str = "") -> str:
178
+ body = {"model": model, "prompt": prompt, "image": {"url": data_url(image), "type": "image_url"},
179
+ "response_format": "b64_json"} # fmt: skip
180
+ saved = save_images(api, api.post("/images/edits", body), prompt, path)
181
+ return f"Saved the edited image: {saved[0]}"
182
+
183
+ def finish_video(request_id: str, prompt: str, path: str, wait: float) -> str:
184
+ deadline = time.monotonic() + wait
185
+ while True:
186
+ state = api.request("GET", f"/videos/{request_id}").json()
187
+ status = state.get("status")
188
+ if status == "done":
189
+ video = state.get("video") or {}
190
+ target = api.target(path, prompt or request_id, ".mp4")
191
+ target.write_bytes(api.download(video["url"]))
192
+ return f"Saved the video ({video.get('duration', '?')} s, {state.get('model', '')}): {target}"
193
+ if status in ("failed", "expired"):
194
+ raise ToolFailure(f"xAI couldn't make the video ({status}): {state.get('error') or state}")
195
+ if time.monotonic() > deadline:
196
+ return (
197
+ f"The video isn't ready yet (request {request_id}). Check later with "
198
+ f'video_status(request_id="{request_id}"), which downloads it when it\'s done.'
199
+ )
200
+ time.sleep(POLL)
201
+
202
+ @server.tool(
203
+ "generate_video",
204
+ "Generate a video with Grok Imagine, from a description and optionally a start image, and save it as "
205
+ "MP4. Takes a minute or more. Costs $0.02–0.08 per second of video.",
206
+ {
207
+ "prompt": {"type": "string", "description": "What happens in the video"},
208
+ "image": {"type": "string", "description": "A local image to start from (optional)"},
209
+ "duration": {"type": "integer", "description": "Seconds, 1–15 (default 8)"},
210
+ "aspect_ratio": {
211
+ "type": "string",
212
+ "enum": [r for r in ASPECT_RATIOS if r not in ("auto", "2:1", "1:2", "21:9")],
213
+ },
214
+ "resolution": {"type": "string", "enum": ["480p", "720p", "1080p"], "description": "Default 720p"},
215
+ "model": {"type": "string", "enum": VIDEO_MODELS, "description": f"Default {VIDEO_MODELS[0]}"},
216
+ "path": path_arg,
217
+ },
218
+ ["prompt"],
219
+ )
220
+ def generate_video(prompt: str, image: str = "", duration: int = 8, aspect_ratio: str = "16:9",
221
+ resolution: str = "720p", model: str = VIDEO_MODELS[0], path: str = "") -> str: # fmt: skip
222
+ body: dict = {"model": model, "prompt": prompt, "duration": max(1, min(15, int(duration))),
223
+ "aspect_ratio": aspect_ratio, "resolution": resolution} # fmt: skip
224
+ if image:
225
+ body["image"] = {"url": data_url(image)}
226
+ request_id = api.post("/videos/generations", body).get("request_id")
227
+ if not request_id:
228
+ raise ToolFailure("xAI didn't start the video")
229
+ return finish_video(str(request_id), prompt, path, VIDEO_WAIT)
230
+
231
+ @server.tool(
232
+ "video_status",
233
+ "Check a video that generate_video started and that wasn't ready yet; saves it when it's done.",
234
+ {"request_id": {"type": "string"}, "path": path_arg},
235
+ ["request_id"],
236
+ )
237
+ def video_status(request_id: str, path: str = "") -> str:
238
+ return finish_video(request_id, "", path, 0)
239
+
240
+ @server.tool(
241
+ "text_to_speech",
242
+ "Turn text into speech with an xAI voice and save it as an audio file. Billed per character.",
243
+ {
244
+ "text": {"type": "string", "description": "What to say (up to 60,000 characters)"},
245
+ "voice": {"type": "string", "enum": VOICES, "description": "Default eve"},
246
+ "language": {"type": "string", "description": "BCP-47 code such as en, de, fr, ja, or auto (default)"},
247
+ "format": {"type": "string", "enum": list(AUDIO_FORMATS), "description": "Default mp3"},
248
+ "speed": {"type": "number", "description": "1.0 is normal"},
249
+ "path": path_arg,
250
+ },
251
+ ["text"],
252
+ )
253
+ def text_to_speech(text: str, voice: str = "eve", language: str = "auto", format: str = "mp3",
254
+ speed: float = 1.0, path: str = "") -> str: # fmt: skip
255
+ codec = format if format in AUDIO_FORMATS else "mp3"
256
+ body = {"text": text, "voice_id": voice.lower(), "language": language or "auto",
257
+ "output_format": {"codec": codec}, "speed": float(speed or 1.0)} # fmt: skip
258
+ r = api.request("POST", "/tts", json=body)
259
+ duration = ""
260
+ if "json" in r.headers.get("Content-Type", ""):
261
+ data = r.json()
262
+ audio = base64.b64decode(data.get("audio", ""))
263
+ duration = f", {data['duration']:.1f} s" if isinstance(data.get("duration"), (int, float)) else ""
264
+ else:
265
+ audio = r.content
266
+ if not audio:
267
+ raise ToolFailure("xAI returned no audio")
268
+ target = api.target(path, text[:40], AUDIO_FORMATS[codec])
269
+ target.write_bytes(audio)
270
+ return f"Saved the speech ({voice}{duration}): {target}"
271
+
272
+ return server
273
+
274
+
275
+ def main(argv: list[str] | None = None) -> None:
276
+ parser = argparse.ArgumentParser(
277
+ prog="lcode-mcp-xai", description="MCP server for xAI's image, video and speech APIs (stdio)."
278
+ )
279
+ parser.add_argument("--output", default=os.environ.get("LCODE_XAI_OUTPUT", "generated"),
280
+ help="folder for the files it makes (default: generated/ in the project)") # fmt: skip
281
+ args = parser.parse_args(argv)
282
+ key = os.environ.get("XAI_API_KEY")
283
+ if not key:
284
+ parser.error("set XAI_API_KEY to an xAI API key (https://console.x.ai)")
285
+ build(XAI(key, os.environ.get("XAI_API_BASE", API), Path(args.output))).serve()
286
+
287
+
288
+ if __name__ == "__main__":
289
+ main()
lcode/subagents.py CHANGED
@@ -486,12 +486,17 @@ class Run:
486
486
  child._run_turn(self.task)
487
487
  last = child.messages[-1]
488
488
  if last.get("role") != "assistant" or last.get("tool_calls") or not last.get("content", "").strip():
489
- # It ran out of steps: ask for what it has so far, without tools.
489
+ # It ran out of steps, or went round in circles: ask for what it has so far, without tools.
490
+ why = (
491
+ "You kept making the same call, so lcode stopped you."
492
+ if child.turn_status == "loop"
493
+ else "You've used all your steps."
494
+ )
490
495
  child.messages.append(
491
496
  {
492
497
  "role": "user",
493
- "content": "[lcode] You've used all your steps. Stop here and write your report: what "
494
- "you found or did so far, and what's left.",
498
+ "content": f"[lcode] {why} Stop here and write your report: what you found or did so "
499
+ "far, and what's left.",
495
500
  }
496
501
  )
497
502
  child.allowed_tools = set()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lcode-cli
3
- Version: 0.21.0
3
+ Version: 0.23.0
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/
@@ -116,7 +116,8 @@ through [Ollama](https://ollama.com), and when it needs current information it c
116
116
  (`lcode mcp add atlassian`), image generation with ComfyUI, or any other MCP server. Browser sign-in (OAuth) is built in.
117
117
  - **Sees images.** Attach a screenshot or mockup with `@path` and lcode looks at it, using the
118
118
  vision part of your model. With ComfyUI (`lcode mcp add comfyui`) it can also generate and edit
119
- images with local models such as FLUX, SDXL and Qwen-Image.
119
+ images with local models such as FLUX, SDXL and Qwen-Image, or, in the cloud, images, videos
120
+ and speech with xAI's Grok Imagine (`lcode mcp add xai`).
120
121
  - **Web search when needed.** Looks up the latest versions, docs and error messages with Ollama web
121
122
  search, Brave, Tavily or your own SearXNG, and reads pages as clean text.
122
123
  - **Private.** The model runs on your machine, lcode never uploads your files and has no telemetry.
@@ -1,9 +1,9 @@
1
- lcode/__init__.py,sha256=CcNLwxNc-qPLNMDrdZMe5h6rRYH_9ISij5uyXwc5PBA,473
1
+ lcode/__init__.py,sha256=G36hAKq_BqNwKGr17AmtWXAKHe-_Nnbzm_VWmWBC-SI,473
2
2
  lcode/__main__.py,sha256=s5N5pryX2FAu93GGZ3FxUrIXHWGzxz66lKUoaV_h8Ws,35
3
- lcode/acp.py,sha256=kRD_uuDDdGXt7xwvXZ8OqePK1HprEV76wWAWkV_gcak,28987
4
- lcode/action.py,sha256=1r3abjheYFYQ-EUArvotls8pLmE3YjNMGHAy_iF0Z70,16198
5
- lcode/agent.py,sha256=FgZJpGD1a46qaa1nixZYXS3rPaFaJgnGpfoUi7ikhGY,51106
6
- lcode/api.py,sha256=rOpcA2-axzUj_DppH3EelanVnwd-2O4MgN91OXGJePY,15250
3
+ lcode/acp.py,sha256=Tpc8lsvffZSYbTRI4t7X4E2chahqZIPcKeYIcL5bV3Y,29035
4
+ lcode/action.py,sha256=W-QqdGt4VAVLq7mcIdvL9UrEOwDEWvkZ26gNDv8k1kg,16330
5
+ lcode/agent.py,sha256=Br-L-7sLnGBG_Hw2lwi19peFZldCh4Ve7PgtVPURjTU,53254
6
+ lcode/api.py,sha256=FQ6aVLB936Cu2XEBmuOoq0u1DfOiExmgap0Y3WxJ2mQ,15376
7
7
  lcode/backends.py,sha256=dtJHrC6ys73bRDg64z0tQz1PavmeAkiODZu1fOO9ExQ,20635
8
8
  lcode/bench.py,sha256=XVdk0hDxmRcjgROOCgwwOsExcUhIxgh0B2vnxtGnA3o,40742
9
9
  lcode/bench_backend.py,sha256=X2fo-zRX92Xp3KMxSsFlWioc2vRupBTtowj5kLME8mw,14287
@@ -11,7 +11,7 @@ lcode/catalog.py,sha256=pZ1azX9OH2r4JE2c6E5OfwywpgS39-W2oXzoCHJhmtM,4141
11
11
  lcode/checkpoints.py,sha256=eqPtmPe44-aweWqc2H21ROogwzIt3NpvcUobsaCHoGY,18354
12
12
  lcode/cli.py,sha256=ue5wsoFxraXXVu7X32S4tbKPLKYhgeI6zpK2i5nXXlU,40180
13
13
  lcode/codesearch.py,sha256=Io8leN1nb_Y-Dvlm9xaGtwUWYXX-ooswuznJV6dGU1s,10766
14
- lcode/config.py,sha256=eDEvOAA1plsSjvihzHEwGjNVgvcz3Pb-AR5DY5JmXnM,10255
14
+ lcode/config.py,sha256=fGjK4fM_YRY0qDQmbIVT3FAfL2I2UxLfYEFxnAI-Xu4,10365
15
15
  lcode/context.py,sha256=qJymLE3eYeaF6qVOzlUwDURqlky__8cskl_6vXeU3AA,10701
16
16
  lcode/extensions.py,sha256=W0HFDl0BvROzr7i_qtabHdIbacBgP5o5qIJLzoM2oNE,16806
17
17
  lcode/frontmatter.py,sha256=Bx0n4vLPhp7ZCWx-g7xqzqNy5VoKBxyeeikh5UFB_gA,2441
@@ -28,11 +28,12 @@ lcode/ollama.py,sha256=u5tnvL28cfaFS4GhmiEsHhTQe6w3Ng_Tej05UUzLQTQ,7715
28
28
  lcode/permissions.py,sha256=i04YLtqYCxwApgawomPp4d35uk9HAJtpKY__gfw8j9s,6347
29
29
  lcode/planning.py,sha256=Q2upaoZPnXDMQT2F-ETxX1lk_wDntTzhSKNVYIQSoQA,6540
30
30
  lcode/render.py,sha256=gMvf4W3qkLUJ4Vot3az_hP_zRDAItJC9pP-68dHFkfA,1375
31
+ lcode/repeats.py,sha256=uzyAewX03nJf5dKwYFH4y9ZDnh0Lvy2k0qC2vdntM5Y,4061
31
32
  lcode/repl.py,sha256=pQAPePNsBxJfcuif2Cvyxr0FSeO_DVGv_T5cL9BrWu4,48470
32
33
  lcode/repomap.py,sha256=1GRJgEUjBl9XHSXsF7tSGXBCEgsY-3CzwMohaTudZ_M,13969
33
34
  lcode/sandbox.py,sha256=u_pkrVRXhCGhh-wFDPwuZ3jGG7UeXxXRAeBNsm37ZvE,8608
34
35
  lcode/sessions.py,sha256=wOR-J0EHgJxLSPboKPHnvBcp5VTUYTj3tZWgpsa6-K4,4013
35
- lcode/subagents.py,sha256=rD7lnIioodirh8eVnXvRWdZx79J_rscPLssD2Gt7KIo,28914
36
+ lcode/subagents.py,sha256=Z2RHp7an16dhOGReucVIEOAnXjxM8jx7sHvWd_Fp2V4,29142
36
37
  lcode/tools.py,sha256=pOdA4ihQHSs8yWUzfxhiLw3GajF5Dr1edxVX0Akr6CU,47257
37
38
  lcode/update.py,sha256=i92bnW252VneYh0vD6djxmXsDOa5MXP20bjlLZUue_c,25236
38
39
  lcode/vision.py,sha256=w33QPmdGwP33wM4mvmAH4amFDZ1xzeXhEsSLJ-STSHY,4243
@@ -40,7 +41,7 @@ lcode/web.py,sha256=vyxKbSRJTl1Lj3hj7Yd_NwTgbv0Xi6dup2YfUXjqp-Y,14579
40
41
  lcode/mcp/__init__.py,sha256=XujtAmRoXW9S0uq1XPf_CAeCkHh_UvA8FCmoAKP9j1Y,171
41
42
  lcode/mcp/auth.py,sha256=vyH3oolgIBNJLYabr2h5Soui99NTY1QxjQEgtczfF6A,16655
42
43
  lcode/mcp/catalog.py,sha256=I_O10N7cBl0ZW6O7x2kwKn89pvEXUXODUh8FsPXnB-E,3790
43
- lcode/mcp/catalog.toml,sha256=9uIcH8z2hAzaPzRNuVeSZs239uhIjroGNd76SkmK_NA,11662
44
+ lcode/mcp/catalog.toml,sha256=N8MKyyS_FeCo-RbV3RVZ3ZODro2yk55yqUlymXsWdcQ,12641
44
45
  lcode/mcp/client.py,sha256=3Gen7zRvWehngXn_dAMOAdKqFkFkQZIQW96hQcW4N4k,7119
45
46
  lcode/mcp/commands.py,sha256=mnp0G-GW5ZsARi2tkHuT3hl883sBGFUVRAV3AapA5oU,16478
46
47
  lcode/mcp/config.py,sha256=Ej6WX2b_55a84H5WdAwSk9DzERKoq5ifUBQ9uDgSG_o,8780
@@ -52,8 +53,9 @@ lcode/mcp/stdio.py,sha256=kC6KHwzMMDjBr-yCZLmyVKS7PZXU299WpZdYRoX5eRQ,6292
52
53
  lcode/servers/__init__.py,sha256=qrIhxEodEB8cjKEQ4Cicc0GsQhE2OH-9qlVHzr3-tq8,77
53
54
  lcode/servers/encord.py,sha256=WSauawL1UKYZCUAG1oalcKL_An3DVof-JM6xIgFyQSE,12769
54
55
  lcode/servers/valohai.py,sha256=e5xZGIoa4cja4f5i85q1GpL9c7cglUjV8jN2co1CFMY,14430
55
- lcode_cli-0.21.0.dist-info/METADATA,sha256=5G93iKQq-92dbzpKJxamXKr9giXtXiVm0AsqhcJf4NU,12527
56
- lcode_cli-0.21.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
57
- lcode_cli-0.21.0.dist-info/entry_points.txt,sha256=pMz2Byj2QRyt-ZZQYZvmWUtmKPCeE7f8iCvu-sjZPIo,133
58
- lcode_cli-0.21.0.dist-info/licenses/LICENSE,sha256=JWjmoL7nNIC1XUa-dZm2hwLUgjUQMFo6k8APb0idNzs,1074
59
- lcode_cli-0.21.0.dist-info/RECORD,,
56
+ lcode/servers/xai.py,sha256=h2emAvHSnkuB9WmJInlynsDhvxJwNVD2AHFX7vqMXNc,13627
57
+ lcode_cli-0.23.0.dist-info/METADATA,sha256=r2mvuIagBxzC4y5i14mZ7tYHnhy-Osy50M-wTYhkk-4,12620
58
+ lcode_cli-0.23.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
59
+ lcode_cli-0.23.0.dist-info/entry_points.txt,sha256=Hxsn_itbnbgft3U0FwxWdmEt0yoAV2LB-nJDnL9WT20,172
60
+ lcode_cli-0.23.0.dist-info/licenses/LICENSE,sha256=JWjmoL7nNIC1XUa-dZm2hwLUgjUQMFo6k8APb0idNzs,1074
61
+ lcode_cli-0.23.0.dist-info/RECORD,,
@@ -2,3 +2,4 @@
2
2
  lcode = lcode.cli:main
3
3
  lcode-mcp-encord = lcode.servers.encord:main
4
4
  lcode-mcp-valohai = lcode.servers.valohai:main
5
+ lcode-mcp-xai = lcode.servers.xai:main