lcode-cli 0.23.0__py3-none-any.whl → 0.25.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 +67 -14
- lcode/bench.py +9 -2
- lcode/bench_runtime.py +156 -0
- lcode/cli.py +4 -0
- lcode/clipboard.py +139 -0
- lcode/repl.py +22 -1
- {lcode_cli-0.23.0.dist-info → lcode_cli-0.25.0.dist-info}/METADATA +1 -1
- {lcode_cli-0.23.0.dist-info → lcode_cli-0.25.0.dist-info}/RECORD +12 -10
- {lcode_cli-0.23.0.dist-info → lcode_cli-0.25.0.dist-info}/WHEEL +0 -0
- {lcode_cli-0.23.0.dist-info → lcode_cli-0.25.0.dist-info}/entry_points.txt +0 -0
- {lcode_cli-0.23.0.dist-info → lcode_cli-0.25.0.dist-info}/licenses/LICENSE +0 -0
lcode/__init__.py
CHANGED
lcode/agent.py
CHANGED
|
@@ -11,6 +11,7 @@ import shutil
|
|
|
11
11
|
import subprocess
|
|
12
12
|
import threading
|
|
13
13
|
import time
|
|
14
|
+
import urllib.parse
|
|
14
15
|
import uuid
|
|
15
16
|
from collections.abc import Callable
|
|
16
17
|
from dataclasses import dataclass
|
|
@@ -63,6 +64,15 @@ MAX_MALFORMED_CALL_RETRIES = 2 # Ollama rejects tool calls whose arguments aren
|
|
|
63
64
|
MALFORMED_CALL = ("error parsing tool call", "XML syntax error")
|
|
64
65
|
AUTO_COMPACT_RATIO = 0.85 # summarize the history when the context is this full
|
|
65
66
|
PRUNED_ENOUGH = 0.6 # after pruning old tool output, summarize only if the context is still this full
|
|
67
|
+
# @path, @"path with spaces" or @'path'
|
|
68
|
+
MENTION = re.compile(r"""(?<!\S)@(?:"([^"\n]+)"|'([^'\n]+)'|([\w./~\-]+))""")
|
|
69
|
+
# An image path written in a message: in quotes, or without spaces (a space escaped as "\ " is fine), or as a
|
|
70
|
+
# file:// address, the way terminals paste a dragged file.
|
|
71
|
+
IMAGE_PATH = re.compile(
|
|
72
|
+
r"""(['"])((?:file://)?[^'"\n]+?\.(?:png|jpe?g|webp|gif))\1"""
|
|
73
|
+
r"""|(?<![^\s(])((?:[^\s\\'"(]|\\ )+?\.(?:png|jpe?g|webp|gif))(?=[\s,;:!?)\]]|\.(?:\s|$)|$)""",
|
|
74
|
+
re.IGNORECASE,
|
|
75
|
+
)
|
|
66
76
|
PROJECT_FILES = ("AGENTS.md", "LCODE.md", "CLAUDE.md")
|
|
67
77
|
|
|
68
78
|
SYSTEM_PROMPT = """You are lcode, an autonomous software-engineering agent running in the user's terminal on their own machine, powered by the local model {model}. You help the user understand codebases, answer questions about code, write scripts (Python by default), fix bugs, refactor, and run commands.
|
|
@@ -71,14 +81,18 @@ SYSTEM_PROMPT = """You are lcode, an autonomous software-engineering agent runni
|
|
|
71
81
|
- Use your tools to gather facts. Never guess file contents, APIs, or command output — read, search, or run them.
|
|
72
82
|
- To understand a repository: look at the layout, README/docs, entry points and config, then grep and read the relevant files. Cite code as `path:line`.
|
|
73
83
|
- Read a file before editing it. Use edit_file for targeted changes and write_file for new files or full rewrites. old_string must be copied exactly from the file (without the line-number prefixes).
|
|
74
|
-
- After writing or changing code, verify it: run the script, the tests, or at least a syntax check (e.g. `{python} -m py_compile file.py`). Fix what fails.
|
|
75
84
|
- Match the existing code style, naming and structure. Don't add unrequested features.
|
|
76
85
|
- For multi-step tasks, plan with todo_write and keep it updated.
|
|
77
86
|
- Work autonomously until the task is done. Only stop to ask the user when you are genuinely blocked or the decision is theirs.
|
|
78
87
|
- Don't run destructive or irreversible commands (rm -rf, git reset --hard, git push --force, dropping data) unless the user explicitly asked.
|
|
79
|
-
- Never claim something works without having run it. If something fails, say so and show the relevant error.
|
|
80
88
|
- If the user denies a tool call, don't retry the same thing; adjust or ask.
|
|
81
89
|
|
|
90
|
+
# Verifying your work
|
|
91
|
+
- A syntax check or an import only shows that code loads. Run what you changed the way it will be used (the script, the tests, the app) and fix what fails.
|
|
92
|
+
- To fix a bug, first reproduce each problem the user reports with a test, a command or a short script, then run the same checks to show they're gone.
|
|
93
|
+
- For what you can't see, like a GUI, a web page or a layout, check it without a screen where you can: `QT_QPA_PLATFORM=offscreen` for Qt, a headless browser, or a script that prints sizes and positions or renders to an image{look}. Measure instead of assuming.
|
|
94
|
+
- Never claim something works, mark a todo done, or call it tested unless you ran it. If you couldn't check something, say so and tell the user exactly what to look for. If something fails, say so and show the relevant error.
|
|
95
|
+
|
|
82
96
|
# Communication
|
|
83
97
|
- Be concise and direct; no filler. Use GitHub-flavored markdown.
|
|
84
98
|
- When you finish, give a short summary of what you found or changed and anything the user needs to do.
|
|
@@ -307,6 +321,7 @@ class Agent:
|
|
|
307
321
|
skills=extensions.skills_prompt(self.extensions().skills, self.settings.context),
|
|
308
322
|
code=self.code_prompt(),
|
|
309
323
|
map=self.map_prompt(),
|
|
324
|
+
look=" you look at with view_image" if self.vision_model() else "",
|
|
310
325
|
)
|
|
311
326
|
|
|
312
327
|
def repo_map(self) -> repomap.RepoMap | None:
|
|
@@ -965,30 +980,68 @@ class Agent:
|
|
|
965
980
|
)
|
|
966
981
|
|
|
967
982
|
def expand_mentions(self, text: str) -> str:
|
|
968
|
-
"""
|
|
969
|
-
|
|
970
|
-
|
|
983
|
+
"""Attach what the user's message points to: files and folders written as @path, image paths (with or
|
|
984
|
+
without @), and @name of an agent asks for that agent. An image path that doesn't exist is reported to
|
|
985
|
+
the user and the model, so the model doesn't guess what the image shows."""
|
|
986
|
+
attached: list[str] = []
|
|
987
|
+
seen: set[Path] = set()
|
|
988
|
+
question = MENTION.sub("", text)
|
|
989
|
+
|
|
990
|
+
def attach_image(p: Path) -> None:
|
|
991
|
+
try:
|
|
992
|
+
description = self.look(p, question)
|
|
993
|
+
who = f' described_by="{self.vision_model()}"'
|
|
994
|
+
except ToolError as e:
|
|
995
|
+
description, who = f"(lcode couldn't look at this image: {e})", ""
|
|
996
|
+
self.console.print(Text(f" ⎿ {e}", style="yellow"))
|
|
997
|
+
else:
|
|
998
|
+
self.console.print(Text(f" ⎿ looked at {self.tools.rel(p)}", style="dim"))
|
|
999
|
+
attached.append(f'<image path="{self.tools.rel(p)}"{who}>\n{description}\n</image>')
|
|
1000
|
+
|
|
1001
|
+
def missing_image(shown: str) -> None:
|
|
1002
|
+
self.console.print(
|
|
1003
|
+
Text(f" ⎿ {shown} doesn't exist, so the model can't see it. Paste images with Ctrl+V.", style="yellow")
|
|
1004
|
+
)
|
|
1005
|
+
attached.append(
|
|
1006
|
+
f"[lcode: the user's message mentions the image {shown}, but there's no such file, so it wasn't "
|
|
1007
|
+
"attached and you can't see it. Don't guess what it shows: ask the user to paste it again (Ctrl+V "
|
|
1008
|
+
"in lcode's prompt) or to describe it.]"
|
|
1009
|
+
)
|
|
1010
|
+
|
|
1011
|
+
for match in MENTION.finditer(text):
|
|
1012
|
+
ref = next(g for g in match.groups() if g)
|
|
971
1013
|
p = self.tools.resolve(ref)
|
|
1014
|
+
seen.add(p)
|
|
972
1015
|
name = ref.removeprefix("agent-")
|
|
973
1016
|
if not p.exists() and self.settings.subagents and name in self.agent_types():
|
|
974
1017
|
attached.append(f'[The user wants the {name} agent for this: call the agent tool with type "{name}".]')
|
|
975
1018
|
continue
|
|
976
1019
|
if p.is_file() and vision.is_image(p):
|
|
977
|
-
|
|
978
|
-
description = self.look(p, re.sub(r"(?<!\S)@[\w./~\-]+", "", text))
|
|
979
|
-
who = f' described_by="{self.vision_model()}"'
|
|
980
|
-
except ToolError as e:
|
|
981
|
-
description, who = f"(lcode couldn't look at this image: {e})", ""
|
|
982
|
-
self.console.print(Text(f" ⎿ {e}", style="yellow"))
|
|
983
|
-
else:
|
|
984
|
-
self.console.print(Text(f" ⎿ looked at {self.tools.rel(p)}", style="dim"))
|
|
985
|
-
attached.append(f'<image path="{self.tools.rel(p)}"{who}>\n{description}\n</image>')
|
|
1020
|
+
attach_image(p)
|
|
986
1021
|
elif p.is_file() and not is_binary(p) and p.stat().st_size < 200_000:
|
|
987
1022
|
attached.append(f'<file path="{self.tools.rel(p)}">\n{p.read_text(errors="replace")}\n</file>')
|
|
988
1023
|
self.tools.read_mtimes[str(p)] = p.stat().st_mtime
|
|
989
1024
|
self.console.print(Text(f" ⎿ attached {self.tools.rel(p)}", style="dim"))
|
|
990
1025
|
elif p.is_dir():
|
|
991
1026
|
attached.append(f'<directory path="{self.tools.rel(p)}">\n{tree(p, 2)}\n</directory>')
|
|
1027
|
+
elif not p.exists() and vision.is_image(p):
|
|
1028
|
+
missing_image(ref)
|
|
1029
|
+
for match in IMAGE_PATH.finditer(text):
|
|
1030
|
+
quoted, raw = bool(match.group(2)), match.group(2) or match.group(3)
|
|
1031
|
+
if raw.startswith("@") or "://" in raw.removeprefix("file://"):
|
|
1032
|
+
continue # attached above, or a web address
|
|
1033
|
+
if raw.startswith("file://"):
|
|
1034
|
+
shown = urllib.parse.unquote(raw.removeprefix("file://"))
|
|
1035
|
+
else:
|
|
1036
|
+
shown = raw.replace("\\ ", " ")
|
|
1037
|
+
p = self.tools.resolve(shown)
|
|
1038
|
+
if p in seen:
|
|
1039
|
+
continue
|
|
1040
|
+
seen.add(p)
|
|
1041
|
+
if p.is_file():
|
|
1042
|
+
attach_image(p)
|
|
1043
|
+
elif quoted or raw.startswith(("/", "~", "./", "../", "file://")):
|
|
1044
|
+
missing_image(shown) # a name without a folder may be a file to create: no warning
|
|
992
1045
|
return text + ("\n\n" + "\n\n".join(attached) if attached else "")
|
|
993
1046
|
|
|
994
1047
|
# -- context management
|
lcode/bench.py
CHANGED
|
@@ -746,7 +746,7 @@ TASKS = [
|
|
|
746
746
|
|
|
747
747
|
def extra_tasks() -> list[Task]:
|
|
748
748
|
"""Tasks that only run when asked for with --tasks (they're slower, or test optional features)."""
|
|
749
|
-
from lcode import bench_backend
|
|
749
|
+
from lcode import bench_backend, bench_runtime
|
|
750
750
|
|
|
751
751
|
return [
|
|
752
752
|
Task(
|
|
@@ -755,7 +755,14 @@ def extra_tasks() -> list[Task]:
|
|
|
755
755
|
bench_backend.PROMPT,
|
|
756
756
|
bench_backend.FILES,
|
|
757
757
|
bench_backend.check,
|
|
758
|
-
)
|
|
758
|
+
),
|
|
759
|
+
Task(
|
|
760
|
+
"runtime-bug",
|
|
761
|
+
"Fix a bug that shows only when it runs",
|
|
762
|
+
bench_runtime.PROMPT,
|
|
763
|
+
bench_runtime.FILES,
|
|
764
|
+
bench_runtime.check,
|
|
765
|
+
),
|
|
759
766
|
]
|
|
760
767
|
|
|
761
768
|
|
lcode/bench_runtime.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""A bug that only shows when the code runs, for `lcode bench --tasks runtime-bug`.
|
|
2
|
+
|
|
3
|
+
A camera wall lays out video panels in a window. While video plays, the window grows taller frame after
|
|
4
|
+
frame, past the screen, and can't be made smaller again: each panel's minimum size is taken from the
|
|
5
|
+
frame it shows, and the frame is scaled to the whole cell, status bar included. Reading the code, the
|
|
6
|
+
obvious fixes are band-aids (ignore the minimum sizes, or only fix the scaling) that fail part of the
|
|
7
|
+
hidden test. Running it, the window sizes show the ratchet. It's the kind of bug a GUI has, without
|
|
8
|
+
needing one, and rewards reproducing a problem before fixing it.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
WALL = '''\
|
|
17
|
+
"""A camera wall: a window with a grid of panels, each showing its camera's latest video frame."""
|
|
18
|
+
|
|
19
|
+
SPACING = 8 # pixels between and around the panels
|
|
20
|
+
STATUS_BAR = 20 # under its video, each panel shows the camera's name and status
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Panel:
|
|
24
|
+
def __init__(self, name):
|
|
25
|
+
self.name = name
|
|
26
|
+
self.min_width = self.min_height = 1 # the panel can't get smaller than this
|
|
27
|
+
self.video = (0, 0) # the size of the frame on screen
|
|
28
|
+
|
|
29
|
+
def show(self, frame_width, frame_height, cell_width, cell_height):
|
|
30
|
+
"""Show a frame scaled to fit the panel's cell, keeping its aspect ratio."""
|
|
31
|
+
scale = min(cell_width / frame_width, cell_height / frame_height)
|
|
32
|
+
self.video = (int(frame_width * scale), int(frame_height * scale))
|
|
33
|
+
# The video and the status bar under it must stay visible.
|
|
34
|
+
self.min_width, self.min_height = self.video[0], self.video[1] + STATUS_BAR
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Wall:
|
|
38
|
+
def __init__(self, names, rows, cols):
|
|
39
|
+
self.rows, self.cols = rows, cols
|
|
40
|
+
self.panels = [Panel(name) for name in names]
|
|
41
|
+
self.width = self.height = 0
|
|
42
|
+
|
|
43
|
+
def resize(self, width, height):
|
|
44
|
+
"""Ask for a window size. The window can't be smaller than its panels need."""
|
|
45
|
+
need_width = max(p.min_width for p in self.panels) * self.cols + SPACING * (self.cols + 1)
|
|
46
|
+
need_height = max(p.min_height for p in self.panels) * self.rows + SPACING * (self.rows + 1)
|
|
47
|
+
self.width, self.height = max(width, need_width), max(height, need_height)
|
|
48
|
+
|
|
49
|
+
def cell(self):
|
|
50
|
+
"""The size of one panel's cell."""
|
|
51
|
+
return (
|
|
52
|
+
(self.width - SPACING * (self.cols + 1)) // self.cols,
|
|
53
|
+
(self.height - SPACING * (self.rows + 1)) // self.rows,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
def new_frame(self, frame_width, frame_height):
|
|
57
|
+
"""Every camera delivered a frame: show it in each panel, then let the layout settle."""
|
|
58
|
+
cell_width, cell_height = self.cell()
|
|
59
|
+
for panel in self.panels:
|
|
60
|
+
panel.show(frame_width, frame_height, cell_width, cell_height)
|
|
61
|
+
self.resize(self.width, self.height)
|
|
62
|
+
'''
|
|
63
|
+
|
|
64
|
+
SIMULATE = '''\
|
|
65
|
+
"""Play the camera wall without a screen: python simulate.py [WIDTH HEIGHT [ROWSxCOLS]]"""
|
|
66
|
+
|
|
67
|
+
import sys
|
|
68
|
+
|
|
69
|
+
from wall import Wall
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def main():
|
|
73
|
+
width, height = (int(sys.argv[1]), int(sys.argv[2])) if len(sys.argv) > 2 else (2560, 1080)
|
|
74
|
+
rows, cols = map(int, sys.argv[3].split("x")) if len(sys.argv) > 3 else (3, 3)
|
|
75
|
+
wall = Wall([f"camera {n + 1}" for n in range(rows * cols)], rows, cols)
|
|
76
|
+
wall.resize(width * 9 // 10, height * 9 // 10)
|
|
77
|
+
print(f"{rows}x{cols} wall on a {width}x{height} screen, window {wall.width}x{wall.height}")
|
|
78
|
+
for n in range(1, 6):
|
|
79
|
+
wall.new_frame(1920, 1080)
|
|
80
|
+
print(f"after frame {n}: window {wall.width}x{wall.height}, video {wall.panels[0].video}")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
if __name__ == "__main__":
|
|
84
|
+
main()
|
|
85
|
+
'''
|
|
86
|
+
|
|
87
|
+
FILES = {"wall.py": WALL, "simulate.py": SIMULATE}
|
|
88
|
+
|
|
89
|
+
PROMPT = (
|
|
90
|
+
"Users say the camera wall in wall.py keeps growing taller while video plays, until it's bigger than "
|
|
91
|
+
"their screen, and after that it can't be made smaller again. Fix it."
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
HIDDEN_TEST = """\
|
|
95
|
+
import unittest
|
|
96
|
+
|
|
97
|
+
from wall import SPACING, STATUS_BAR, Wall
|
|
98
|
+
|
|
99
|
+
SCREENS = [(2560, 1080, 3, 3), (1920, 1080, 2, 3), (1366, 768, 3, 3), (3440, 1440, 2, 4), (1280, 1024, 2, 2)]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def play(width, height, rows, cols, frames=30, frame=(1920, 1080)):
|
|
103
|
+
wall = Wall([f"camera {n}" for n in range(rows * cols)], rows, cols)
|
|
104
|
+
wall.resize(width, height)
|
|
105
|
+
for _ in range(frames):
|
|
106
|
+
wall.new_frame(*frame)
|
|
107
|
+
return wall
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class HiddenTest(unittest.TestCase):
|
|
111
|
+
def test_keeps_its_size(self):
|
|
112
|
+
for width, height, rows, cols in SCREENS:
|
|
113
|
+
with self.subTest(screen=(width, height), grid=(rows, cols)):
|
|
114
|
+
wall = play(width * 9 // 10, height * 9 // 10, rows, cols)
|
|
115
|
+
self.assertEqual((wall.width, wall.height), (width * 9 // 10, height * 9 // 10))
|
|
116
|
+
|
|
117
|
+
def test_can_be_made_smaller(self):
|
|
118
|
+
wall = play(2304, 972, 3, 3)
|
|
119
|
+
wall.resize(1280, 720)
|
|
120
|
+
wall.new_frame(1920, 1080)
|
|
121
|
+
self.assertEqual((wall.width, wall.height), (1280, 720))
|
|
122
|
+
|
|
123
|
+
def test_video_fits_and_fills_its_cell(self):
|
|
124
|
+
for width, height, rows, cols in SCREENS:
|
|
125
|
+
for frame in [(1920, 1080), (1280, 960), (720, 1280)]:
|
|
126
|
+
with self.subTest(screen=(width, height), grid=(rows, cols), frame=frame):
|
|
127
|
+
wall = play(width * 9 // 10, height * 9 // 10, rows, cols, frames=3, frame=frame)
|
|
128
|
+
cell_width = (wall.width - SPACING * (cols + 1)) // cols
|
|
129
|
+
cell_height = (wall.height - SPACING * (rows + 1)) // rows
|
|
130
|
+
for panel in wall.panels:
|
|
131
|
+
video_width, video_height = panel.video
|
|
132
|
+
self.assertLessEqual(video_width, cell_width)
|
|
133
|
+
self.assertLessEqual(video_height + STATUS_BAR, cell_height)
|
|
134
|
+
fills = video_width >= cell_width - 2 or video_height + STATUS_BAR >= cell_height - 2
|
|
135
|
+
self.assertTrue(fills, "the video doesn't use the room it has")
|
|
136
|
+
self.assertAlmostEqual(video_width / video_height, frame[0] / frame[1], delta=0.02)
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
PROBLEMS = {
|
|
140
|
+
"test_keeps_its_size": "the window still grows",
|
|
141
|
+
"test_can_be_made_smaller": "the window can't be made smaller",
|
|
142
|
+
"test_video_fits_and_fills_its_cell": "the video doesn't fit its cell above the status bar (or doesn't fill it)",
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def check(folder: Path, answer: str):
|
|
147
|
+
from lcode.bench import Check, last_line, run_python
|
|
148
|
+
|
|
149
|
+
if not (folder / "wall.py").is_file():
|
|
150
|
+
return Check(False, "wall.py is missing")
|
|
151
|
+
(folder / "test_hidden_wall.py").write_text(HIDDEN_TEST)
|
|
152
|
+
r = run_python(folder, "-m", "unittest", "-q", "test_hidden_wall")
|
|
153
|
+
if r.returncode == 0:
|
|
154
|
+
return Check(True, "keeps its size, can be made smaller, and the video fits")
|
|
155
|
+
failed = [text for name, text in PROBLEMS.items() if re.search(rf"\b{name}\b", r.stderr)]
|
|
156
|
+
return Check(False, "; ".join(failed) or last_line(r.stderr) or last_line(r.stdout))
|
lcode/cli.py
CHANGED
|
@@ -346,6 +346,10 @@ def cmd_doctor(args) -> None:
|
|
|
346
346
|
line("Vision", "off; set vision_model to a model the server serves that can see images", None)
|
|
347
347
|
else:
|
|
348
348
|
line("Vision", "off" if cfg["vision_model"] == "off" else vision.INSTALL_HINT, None)
|
|
349
|
+
if seer:
|
|
350
|
+
from lcode import clipboard
|
|
351
|
+
|
|
352
|
+
line("Clipboard", *clipboard.status())
|
|
349
353
|
if limits.get(model):
|
|
350
354
|
line(
|
|
351
355
|
"Limit",
|
lcode/clipboard.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Paste from the clipboard with Ctrl+V, images included.
|
|
2
|
+
|
|
3
|
+
A terminal can only paste text, so a screenshot never reaches lcode that way. On Ctrl+V lcode reads the
|
|
4
|
+
clipboard itself: with wl-paste on Wayland, xclip on X11, and pngpaste or osascript on macOS. An image is
|
|
5
|
+
saved in lcode's state folder and goes into the prompt as `@path`, so it's attached like any other image;
|
|
6
|
+
anything else is pasted as text.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from lcode import config
|
|
20
|
+
|
|
21
|
+
TIMEOUT = 5 # seconds for a clipboard tool
|
|
22
|
+
IMAGE_TYPES = ("image/png", "image/jpeg", "image/webp", "image/gif")
|
|
23
|
+
SUFFIXES = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", "image/gif": ".gif"}
|
|
24
|
+
KEEP = 50 # pasted images kept; older ones are removed
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Paste:
|
|
29
|
+
image: Path | None = None # a saved image
|
|
30
|
+
text: str = "" # or text
|
|
31
|
+
problem: str = "" # why nothing could be pasted
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def run(argv: list[str]) -> bytes | None:
|
|
35
|
+
try:
|
|
36
|
+
done = subprocess.run(argv, capture_output=True, timeout=TIMEOUT, check=False)
|
|
37
|
+
except (OSError, subprocess.SubprocessError):
|
|
38
|
+
return None
|
|
39
|
+
return done.stdout if done.returncode == 0 else None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def folder() -> Path:
|
|
43
|
+
return config.STATE_DIR / "pasted"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def save(data: bytes, suffix: str) -> Path:
|
|
47
|
+
where = folder()
|
|
48
|
+
where.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
old = sorted(where.glob("pasted-*")) # the names sort by time
|
|
50
|
+
for path in old[: max(0, len(old) - KEEP + 1)]:
|
|
51
|
+
path.unlink(missing_ok=True)
|
|
52
|
+
now = time.time_ns()
|
|
53
|
+
stamp = f"{time.strftime('%Y%m%d-%H%M%S', time.localtime(now / 1e9))}-{now % 1_000_000_000:09d}"
|
|
54
|
+
path = where / f"pasted-{stamp}{suffix}"
|
|
55
|
+
n = 1
|
|
56
|
+
while path.exists():
|
|
57
|
+
n += 1
|
|
58
|
+
path = where / f"pasted-{stamp}-{n}{suffix}"
|
|
59
|
+
path.write_bytes(data)
|
|
60
|
+
return path
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def pick(types: list[str]) -> str | None:
|
|
64
|
+
return next((t for t in IMAGE_TYPES if t in types), None)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def paste() -> Paste:
|
|
68
|
+
"""Whatever is on the clipboard: an image (saved to a file) or text."""
|
|
69
|
+
if sys.platform == "darwin":
|
|
70
|
+
return paste_mac()
|
|
71
|
+
if os.environ.get("WAYLAND_DISPLAY") and shutil.which("wl-paste"):
|
|
72
|
+
return paste_with(
|
|
73
|
+
["wl-paste", "--list-types"],
|
|
74
|
+
lambda kind: ["wl-paste", "--no-newline", "--type", kind],
|
|
75
|
+
["wl-paste", "--no-newline"],
|
|
76
|
+
)
|
|
77
|
+
if os.environ.get("DISPLAY") and shutil.which("xclip"):
|
|
78
|
+
return paste_with(
|
|
79
|
+
["xclip", "-selection", "clipboard", "-t", "TARGETS", "-o"],
|
|
80
|
+
lambda kind: ["xclip", "-selection", "clipboard", "-t", kind, "-o"],
|
|
81
|
+
["xclip", "-selection", "clipboard", "-o"],
|
|
82
|
+
)
|
|
83
|
+
return Paste(problem=status()[0])
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def status() -> tuple[str, bool | None]:
|
|
87
|
+
"""Whether Ctrl+V can paste images here, and if not, what to do (for the paste and `lcode doctor`)."""
|
|
88
|
+
if sys.platform == "darwin":
|
|
89
|
+
return "Ctrl+V pastes images" + (" (with pngpaste)" if shutil.which("pngpaste") else ""), True
|
|
90
|
+
if os.environ.get("WAYLAND_DISPLAY"):
|
|
91
|
+
if shutil.which("wl-paste"):
|
|
92
|
+
return "Ctrl+V pastes images (with wl-paste)", True
|
|
93
|
+
return "To paste images with Ctrl+V, install wl-clipboard (for example `sudo apt install wl-clipboard`).", None
|
|
94
|
+
if os.environ.get("DISPLAY"):
|
|
95
|
+
if shutil.which("xclip"):
|
|
96
|
+
return "Ctrl+V pastes images (with xclip)", True
|
|
97
|
+
return "To paste images with Ctrl+V, install xclip (for example `sudo apt install xclip`).", None
|
|
98
|
+
return "There's no clipboard here (no desktop session), so give an image by its path.", None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def paste_with(list_types: list[str], get, get_text: list[str]) -> Paste:
|
|
102
|
+
types = (run(list_types) or b"").decode(errors="replace").split()
|
|
103
|
+
kind = pick(types)
|
|
104
|
+
if kind:
|
|
105
|
+
data = run(get(kind))
|
|
106
|
+
if data:
|
|
107
|
+
return Paste(image=save(data, SUFFIXES[kind]))
|
|
108
|
+
text = run(get_text)
|
|
109
|
+
if text:
|
|
110
|
+
return Paste(text=text.decode(errors="replace"))
|
|
111
|
+
return Paste(problem="The clipboard is empty.")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def paste_mac() -> Paste:
|
|
115
|
+
if shutil.which("pngpaste"):
|
|
116
|
+
data = run(["pngpaste", "-"])
|
|
117
|
+
if data:
|
|
118
|
+
return Paste(image=save(data, ".png"))
|
|
119
|
+
else:
|
|
120
|
+
target = folder() / ".clipboard.png"
|
|
121
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
122
|
+
target.unlink(missing_ok=True)
|
|
123
|
+
script = [
|
|
124
|
+
"try",
|
|
125
|
+
"set png to (the clipboard as «class PNGf»)",
|
|
126
|
+
f'set f to open for access POSIX file "{target}" with write permission',
|
|
127
|
+
"write png to f",
|
|
128
|
+
"close access f",
|
|
129
|
+
"end try",
|
|
130
|
+
]
|
|
131
|
+
run(["osascript", *[arg for line in script for arg in ("-e", line)]])
|
|
132
|
+
if target.exists() and target.stat().st_size:
|
|
133
|
+
data = target.read_bytes()
|
|
134
|
+
target.unlink(missing_ok=True)
|
|
135
|
+
return Paste(image=save(data, ".png"))
|
|
136
|
+
text = run(["pbpaste"])
|
|
137
|
+
if text:
|
|
138
|
+
return Paste(text=text.decode(errors="replace"))
|
|
139
|
+
return Paste(problem="The clipboard is empty.")
|
lcode/repl.py
CHANGED
|
@@ -14,6 +14,7 @@ import time
|
|
|
14
14
|
from pathlib import Path
|
|
15
15
|
|
|
16
16
|
from prompt_toolkit import PromptSession
|
|
17
|
+
from prompt_toolkit.application import run_in_terminal
|
|
17
18
|
from prompt_toolkit.completion import Completer, Completion
|
|
18
19
|
from prompt_toolkit.formatted_text import HTML
|
|
19
20
|
from prompt_toolkit.history import FileHistory
|
|
@@ -26,7 +27,7 @@ from rich.rule import Rule
|
|
|
26
27
|
from rich.table import Table
|
|
27
28
|
from rich.text import Text
|
|
28
29
|
|
|
29
|
-
from lcode import __version__, backends, catalog, extensions, gitflow, limits, sessions, web
|
|
30
|
+
from lcode import __version__, backends, catalog, clipboard, extensions, gitflow, limits, sessions, web
|
|
30
31
|
from lcode import context as context_tools
|
|
31
32
|
from lcode import memory as memory_notes
|
|
32
33
|
from lcode.agent import AUTO_COMPACT_RATIO, INIT_PROMPT, Agent
|
|
@@ -101,6 +102,13 @@ class InputCompleter(Completer):
|
|
|
101
102
|
yield Completion(completion, start_position=-len(fragment))
|
|
102
103
|
|
|
103
104
|
|
|
105
|
+
def mention(path: Path) -> str:
|
|
106
|
+
"""How a file goes into the prompt: @path, with ~ for the home folder, in quotes if it has spaces."""
|
|
107
|
+
home = Path.home()
|
|
108
|
+
shown = f"~/{path.relative_to(home)}" if path.is_relative_to(home) else str(path)
|
|
109
|
+
return f'@"{shown}"' if " " in shown else f"@{shown}"
|
|
110
|
+
|
|
111
|
+
|
|
104
112
|
def build_session(agent: Agent) -> PromptSession:
|
|
105
113
|
kb = KeyBindings()
|
|
106
114
|
|
|
@@ -119,6 +127,19 @@ def build_session(agent: Agent) -> PromptSession:
|
|
|
119
127
|
def _newline(event):
|
|
120
128
|
event.current_buffer.insert_text("\n")
|
|
121
129
|
|
|
130
|
+
@kb.add("c-v")
|
|
131
|
+
def _paste(event):
|
|
132
|
+
"""Paste the clipboard: an image becomes @path (terminals can't paste images), anything else is text."""
|
|
133
|
+
got = clipboard.paste()
|
|
134
|
+
buf = event.current_buffer
|
|
135
|
+
if got.image:
|
|
136
|
+
before = buf.document.char_before_cursor
|
|
137
|
+
buf.insert_text(("" if not before or before.isspace() else " ") + mention(got.image) + " ")
|
|
138
|
+
elif got.text:
|
|
139
|
+
buf.insert_text(got.text.replace("\r\n", "\n"))
|
|
140
|
+
else:
|
|
141
|
+
run_in_terminal(lambda: agent.console.print(Text(f" {got.problem}", style="yellow")))
|
|
142
|
+
|
|
122
143
|
@kb.add("s-tab")
|
|
123
144
|
def _cycle_mode(event):
|
|
124
145
|
agent.perms.cycle()
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: lcode-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.25.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/
|
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
lcode/__init__.py,sha256=
|
|
1
|
+
lcode/__init__.py,sha256=znAn1x1nESR2keV7zRFdQd7reQE9a4zKFE1_LsWuoas,473
|
|
2
2
|
lcode/__main__.py,sha256=s5N5pryX2FAu93GGZ3FxUrIXHWGzxz66lKUoaV_h8Ws,35
|
|
3
3
|
lcode/acp.py,sha256=Tpc8lsvffZSYbTRI4t7X4E2chahqZIPcKeYIcL5bV3Y,29035
|
|
4
4
|
lcode/action.py,sha256=W-QqdGt4VAVLq7mcIdvL9UrEOwDEWvkZ26gNDv8k1kg,16330
|
|
5
|
-
lcode/agent.py,sha256=
|
|
5
|
+
lcode/agent.py,sha256=naua7OJW9BXhv8mpF1QLdclnFy6RHZAjw9LYTt_dBy0,56201
|
|
6
6
|
lcode/api.py,sha256=FQ6aVLB936Cu2XEBmuOoq0u1DfOiExmgap0Y3WxJ2mQ,15376
|
|
7
7
|
lcode/backends.py,sha256=dtJHrC6ys73bRDg64z0tQz1PavmeAkiODZu1fOO9ExQ,20635
|
|
8
|
-
lcode/bench.py,sha256=
|
|
8
|
+
lcode/bench.py,sha256=7ICipu_2GXW6vE519XeZucc2GSWA44votT8JvqcNv1k,40964
|
|
9
9
|
lcode/bench_backend.py,sha256=X2fo-zRX92Xp3KMxSsFlWioc2vRupBTtowj5kLME8mw,14287
|
|
10
|
+
lcode/bench_runtime.py,sha256=EjzNgIvUkdbT8cbSy1TpmlyeIk6e-ipjlDFpM7Dnqx0,6835
|
|
10
11
|
lcode/catalog.py,sha256=pZ1azX9OH2r4JE2c6E5OfwywpgS39-W2oXzoCHJhmtM,4141
|
|
11
12
|
lcode/checkpoints.py,sha256=eqPtmPe44-aweWqc2H21ROogwzIt3NpvcUobsaCHoGY,18354
|
|
12
|
-
lcode/cli.py,sha256=
|
|
13
|
+
lcode/cli.py,sha256=cH5mcYi54Aofcv0PDNgFmFFQX8OQjhwTGdbWMUM_FG8,40289
|
|
14
|
+
lcode/clipboard.py,sha256=nTSdJyCXPdtjH947RjvB3QvRqnL5HZsS9KB8EkC42cc,5138
|
|
13
15
|
lcode/codesearch.py,sha256=Io8leN1nb_Y-Dvlm9xaGtwUWYXX-ooswuznJV6dGU1s,10766
|
|
14
16
|
lcode/config.py,sha256=fGjK4fM_YRY0qDQmbIVT3FAfL2I2UxLfYEFxnAI-Xu4,10365
|
|
15
17
|
lcode/context.py,sha256=qJymLE3eYeaF6qVOzlUwDURqlky__8cskl_6vXeU3AA,10701
|
|
@@ -29,7 +31,7 @@ lcode/permissions.py,sha256=i04YLtqYCxwApgawomPp4d35uk9HAJtpKY__gfw8j9s,6347
|
|
|
29
31
|
lcode/planning.py,sha256=Q2upaoZPnXDMQT2F-ETxX1lk_wDntTzhSKNVYIQSoQA,6540
|
|
30
32
|
lcode/render.py,sha256=gMvf4W3qkLUJ4Vot3az_hP_zRDAItJC9pP-68dHFkfA,1375
|
|
31
33
|
lcode/repeats.py,sha256=uzyAewX03nJf5dKwYFH4y9ZDnh0Lvy2k0qC2vdntM5Y,4061
|
|
32
|
-
lcode/repl.py,sha256=
|
|
34
|
+
lcode/repl.py,sha256=ZKd4l4wDGKHVaGz8bxjLGc2gRc2W-RpHPQYG9M2A_Zw,49441
|
|
33
35
|
lcode/repomap.py,sha256=1GRJgEUjBl9XHSXsF7tSGXBCEgsY-3CzwMohaTudZ_M,13969
|
|
34
36
|
lcode/sandbox.py,sha256=u_pkrVRXhCGhh-wFDPwuZ3jGG7UeXxXRAeBNsm37ZvE,8608
|
|
35
37
|
lcode/sessions.py,sha256=wOR-J0EHgJxLSPboKPHnvBcp5VTUYTj3tZWgpsa6-K4,4013
|
|
@@ -54,8 +56,8 @@ lcode/servers/__init__.py,sha256=qrIhxEodEB8cjKEQ4Cicc0GsQhE2OH-9qlVHzr3-tq8,77
|
|
|
54
56
|
lcode/servers/encord.py,sha256=WSauawL1UKYZCUAG1oalcKL_An3DVof-JM6xIgFyQSE,12769
|
|
55
57
|
lcode/servers/valohai.py,sha256=e5xZGIoa4cja4f5i85q1GpL9c7cglUjV8jN2co1CFMY,14430
|
|
56
58
|
lcode/servers/xai.py,sha256=h2emAvHSnkuB9WmJInlynsDhvxJwNVD2AHFX7vqMXNc,13627
|
|
57
|
-
lcode_cli-0.
|
|
58
|
-
lcode_cli-0.
|
|
59
|
-
lcode_cli-0.
|
|
60
|
-
lcode_cli-0.
|
|
61
|
-
lcode_cli-0.
|
|
59
|
+
lcode_cli-0.25.0.dist-info/METADATA,sha256=j0rf2PzRDAvWLYN-2RizBuLuel-tmvhfgf_m_pvTHkE,12620
|
|
60
|
+
lcode_cli-0.25.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
61
|
+
lcode_cli-0.25.0.dist-info/entry_points.txt,sha256=Hxsn_itbnbgft3U0FwxWdmEt0yoAV2LB-nJDnL9WT20,172
|
|
62
|
+
lcode_cli-0.25.0.dist-info/licenses/LICENSE,sha256=JWjmoL7nNIC1XUa-dZm2hwLUgjUQMFo6k8APb0idNzs,1074
|
|
63
|
+
lcode_cli-0.25.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|