codehaven 0.14.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.
- codehaven-0.14.0.dist-info/METADATA +686 -0
- codehaven-0.14.0.dist-info/RECORD +57 -0
- codehaven-0.14.0.dist-info/WHEEL +5 -0
- codehaven-0.14.0.dist-info/entry_points.txt +3 -0
- codehaven-0.14.0.dist-info/licenses/LICENSE +21 -0
- codehaven-0.14.0.dist-info/top_level.txt +1 -0
- offline_agent/__init__.py +2 -0
- offline_agent/__main__.py +4 -0
- offline_agent/agent.py +815 -0
- offline_agent/answers.py +438 -0
- offline_agent/arabic.py +106 -0
- offline_agent/changes.py +228 -0
- offline_agent/chats.py +121 -0
- offline_agent/cli.py +379 -0
- offline_agent/coder.py +199 -0
- offline_agent/dependencies.py +132 -0
- offline_agent/doctor.py +190 -0
- offline_agent/documents.py +189 -0
- offline_agent/edits.py +204 -0
- offline_agent/errors.py +41 -0
- offline_agent/evaluation.py +284 -0
- offline_agent/evidence.py +187 -0
- offline_agent/exclusions.py +95 -0
- offline_agent/export.py +27 -0
- offline_agent/gui.css +237 -0
- offline_agent/gui.html +177 -0
- offline_agent/gui.js +1213 -0
- offline_agent/gui.py +967 -0
- offline_agent/gui_arabic.js +226 -0
- offline_agent/guides.py +203 -0
- offline_agent/history.py +126 -0
- offline_agent/index_cache.py +78 -0
- offline_agent/insights.py +333 -0
- offline_agent/javascript.py +200 -0
- offline_agent/knowledge.py +569 -0
- offline_agent/languages.py +396 -0
- offline_agent/memory.py +192 -0
- offline_agent/messages.py +51 -0
- offline_agent/model.py +498 -0
- offline_agent/more_languages.py +253 -0
- offline_agent/ocr.py +204 -0
- offline_agent/prompts.py +130 -0
- offline_agent/references/langgraph-approvals.md +38 -0
- offline_agent/references/langgraph-checkpoints.md +37 -0
- offline_agent/references/langgraph-graphs.md +42 -0
- offline_agent/references/langgraph.md +49 -0
- offline_agent/review.py +205 -0
- offline_agent/scans.py +325 -0
- offline_agent/semantic.py +264 -0
- offline_agent/slash.py +53 -0
- offline_agent/study.py +210 -0
- offline_agent/symbols.py +201 -0
- offline_agent/tasks.py +164 -0
- offline_agent/test_runner.py +264 -0
- offline_agent/trace.py +239 -0
- offline_agent/tracebacks.py +98 -0
- offline_agent/workspace.py +419 -0
offline_agent/cli.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
"""The codehaven command: one task, an interactive session, or the browser GUI."""
|
|
2
|
+
import argparse
|
|
3
|
+
import contextlib
|
|
4
|
+
import sys
|
|
5
|
+
import time
|
|
6
|
+
from functools import partial
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import coder, doctor, edits, errors, export, index_cache, ocr, slash
|
|
10
|
+
from .agent import Session, run
|
|
11
|
+
from .chats import Chats
|
|
12
|
+
from .knowledge import KnowledgeBase
|
|
13
|
+
from .memory import Memory
|
|
14
|
+
from .model import MODEL, Ollama
|
|
15
|
+
from .semantic import Semantic, choose_model
|
|
16
|
+
from .test_runner import DEFAULT_IMAGE
|
|
17
|
+
from .workspace import Workspace, combined
|
|
18
|
+
|
|
19
|
+
SEMANTIC_WAIT = 60 # Seconds a command waits for meaning search before answering with what is ready.
|
|
20
|
+
EXIT_WORDS = {"exit", "quit", "/exit", "/quit"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def write_stream(text):
|
|
24
|
+
"""Print a piece of the streamed answer at once, without waiting for the end of the line."""
|
|
25
|
+
sys.stdout.write(text)
|
|
26
|
+
sys.stdout.flush()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def interactive(session, first_task=None, prompt=input):
|
|
30
|
+
"""Read tasks until exit. One failed or interrupted task does not end the session."""
|
|
31
|
+
with contextlib.suppress(ImportError):
|
|
32
|
+
import readline # noqa: F401 (gives input() line editing and arrow-key history, where Python has it)
|
|
33
|
+
print("Interactive session. Type a task, /reset to forget earlier answers, /export [file] to save the answers as "
|
|
34
|
+
"Markdown, or exit to quit.", flush=True)
|
|
35
|
+
task = first_task
|
|
36
|
+
answered = [] # (question, answer, issues) of this session, for /export.
|
|
37
|
+
while True:
|
|
38
|
+
if task is None:
|
|
39
|
+
try:
|
|
40
|
+
task = prompt("\ncodehaven> ").strip()
|
|
41
|
+
except EOFError:
|
|
42
|
+
print()
|
|
43
|
+
return 0
|
|
44
|
+
if task.lower() in EXIT_WORDS:
|
|
45
|
+
return 0
|
|
46
|
+
if task == "/reset":
|
|
47
|
+
session.reset()
|
|
48
|
+
print("Session history cleared.", flush=True)
|
|
49
|
+
elif task == "/undo":
|
|
50
|
+
editor = getattr(session, "options", {}).get("editor")
|
|
51
|
+
if editor is None:
|
|
52
|
+
print("Nothing to undo: changing code is off. Start with --allow-edits to turn it on.", flush=True)
|
|
53
|
+
else:
|
|
54
|
+
try:
|
|
55
|
+
print(f"Undid: {edits.undo(session.workspace, editor.journal)}", flush=True)
|
|
56
|
+
except (edits.EditError, OSError) as exc:
|
|
57
|
+
print(f"Error: {exc}", file=sys.stderr, flush=True)
|
|
58
|
+
elif task == "/export" or task.startswith("/export "):
|
|
59
|
+
if not answered:
|
|
60
|
+
print("Nothing to export yet: ask a question first.", flush=True)
|
|
61
|
+
else:
|
|
62
|
+
try:
|
|
63
|
+
written = export.write(task[len("/export"):].strip() or ".",
|
|
64
|
+
export.markdown(answered, str(getattr(session.workspace, "root", "")),
|
|
65
|
+
getattr(session.model, "model", "")))
|
|
66
|
+
print(f"Saved {len(answered)} answer{'s' if len(answered) != 1 else ''} to {written}.", flush=True)
|
|
67
|
+
except FileExistsError:
|
|
68
|
+
print("That file already exists; CodeHaven does not overwrite it. Give another name.", file=sys.stderr, flush=True)
|
|
69
|
+
except OSError as exc:
|
|
70
|
+
print(f"Error: could not save the answers ({exc}).", file=sys.stderr, flush=True)
|
|
71
|
+
elif task.startswith("/") and task.split()[0] not in ("/reset", "/undo", "/export"):
|
|
72
|
+
try:
|
|
73
|
+
expanded = slash.expand(task)
|
|
74
|
+
except ValueError as exc:
|
|
75
|
+
print(exc, file=sys.stderr, flush=True)
|
|
76
|
+
else:
|
|
77
|
+
if expanded is None:
|
|
78
|
+
print(slash.help_text(["/reset: forget earlier answers", "/export [file]: save the answers as Markdown",
|
|
79
|
+
"/undo: undo the last change (with --allow-edits)", "exit: quit"]), flush=True)
|
|
80
|
+
else:
|
|
81
|
+
task = expanded
|
|
82
|
+
continue # Asked below, as if it had been typed in full.
|
|
83
|
+
elif task:
|
|
84
|
+
try:
|
|
85
|
+
session.ask(task)
|
|
86
|
+
state = getattr(session, "last_state", None) or {}
|
|
87
|
+
if state.get("final_text"):
|
|
88
|
+
answered.append((task, state["final_text"], state.get("issues", [])))
|
|
89
|
+
except (ValueError, OSError) as exc:
|
|
90
|
+
print(f"Error: {exc}", file=sys.stderr, flush=True)
|
|
91
|
+
except KeyboardInterrupt:
|
|
92
|
+
print("\nStopped this task.", file=sys.stderr, flush=True)
|
|
93
|
+
except Exception as exc: # An unexpected problem ends this task, not the session.
|
|
94
|
+
errors.report(exc)
|
|
95
|
+
print(f"Error: {errors.friendly(exc)}", file=sys.stderr, flush=True)
|
|
96
|
+
task = None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def read_picture(picture, out=None):
|
|
100
|
+
"""Write the code in a picture to a new file beside it. Needs Tesseract, not the model."""
|
|
101
|
+
try:
|
|
102
|
+
source = Path(picture).expanduser()
|
|
103
|
+
if source.stat().st_size > ocr.IMAGE_BYTES:
|
|
104
|
+
raise ValueError(f"Only pictures up to {ocr.IMAGE_BYTES // 1_000_000} MB can be read.")
|
|
105
|
+
target = Path(out).expanduser() if out else None
|
|
106
|
+
found = ocr.read_code(source.name, source.read_bytes(), target.name if target else None)
|
|
107
|
+
target = target or source.with_name(found["name"])
|
|
108
|
+
try:
|
|
109
|
+
with open(target, "x", encoding="utf-8") as handle: # "x" refuses to replace a file that is there.
|
|
110
|
+
handle.write(found["text"])
|
|
111
|
+
except FileExistsError:
|
|
112
|
+
raise ValueError(f"{target} already exists, and CodeHaven never changes your files. "
|
|
113
|
+
"Choose a new name with --out.") from None
|
|
114
|
+
except (ValueError, OSError) as exc:
|
|
115
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
116
|
+
return 1
|
|
117
|
+
print(f"Read {found['lines']} lines from {source.name} into {target}.\n"
|
|
118
|
+
"Reading a picture can get characters wrong, so check the text before you run it.")
|
|
119
|
+
if found["check"]:
|
|
120
|
+
print("Compare with the picture: line " + ", ".join(map(str, found["check"])) + ".")
|
|
121
|
+
if found["syntax"]:
|
|
122
|
+
print(f"Not valid Python yet ({found['syntax']}).")
|
|
123
|
+
elif target.suffix == ".py":
|
|
124
|
+
print("It is valid Python.")
|
|
125
|
+
return 0
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def main(argv=None):
|
|
129
|
+
"""Parse the command line and run the chosen mode. Returns the exit code."""
|
|
130
|
+
parser = argparse.ArgumentParser(description=f"CodeHaven — Your code. Your machine. No API fees. A read-only assistant for "
|
|
131
|
+
f"understanding code with a local model ({MODEL} by default). "
|
|
132
|
+
"It never changes your files.")
|
|
133
|
+
parser.add_argument("task", nargs="?", help="Question about the code, in plain English or Arabic")
|
|
134
|
+
parser.add_argument("--workspace", help="Project folder; defaults to the current folder (with --gui, none)")
|
|
135
|
+
parser.add_argument("--also", action="append", default=[], metavar="FOLDER",
|
|
136
|
+
help="Another repository to open with --workspace, so questions are answered across both; repeatable")
|
|
137
|
+
parser.add_argument("--exclude", action="append", default=[], metavar="PATTERN",
|
|
138
|
+
help="Additional Git-style exclusion; repeat for multiple patterns")
|
|
139
|
+
parser.add_argument("--knowledge-base", help="Local reference directory; defaults to workspace/knowledge")
|
|
140
|
+
parser.add_argument("--retrieval-budget", type=int, default=4000, metavar="BYTES",
|
|
141
|
+
help="Retrieval JSON budget in UTF-8 bytes (2000..16000; default 4000)")
|
|
142
|
+
parser.add_argument("--max-output-tokens", type=int, default=1024,
|
|
143
|
+
help="Maximum response tokens per action (256..8192; default 1024)")
|
|
144
|
+
parser.add_argument("--prompt-budget", type=int, default=12000, metavar="BYTES",
|
|
145
|
+
help="Conversation content budget (8000..64000 UTF-8 bytes; default 12000)")
|
|
146
|
+
parser.add_argument("--test-runner", choices=("unittest", "pytest"), default="unittest")
|
|
147
|
+
parser.add_argument("--test-image", default=DEFAULT_IMAGE, help="Prepared local Docker image for isolated tests")
|
|
148
|
+
parser.add_argument("--allow-python", action="store_true",
|
|
149
|
+
help="Let the agent ask to run a short Python snippet, shown to you for approval first, in the same "
|
|
150
|
+
"Docker sandbox as the tests (no network, read-only copy of the project)")
|
|
151
|
+
parser.add_argument("--test-docker-socket", help="Absolute local Unix Docker socket; remote daemons are unsupported")
|
|
152
|
+
parser.add_argument("--endpoint", default="http://127.0.0.1:11434")
|
|
153
|
+
parser.add_argument("--model", default=MODEL, help=f"Installed local Ollama model (default {MODEL}, the tested one)")
|
|
154
|
+
parser.add_argument("--max-steps", type=int, default=12, choices=range(1, 31), metavar="1..30")
|
|
155
|
+
parser.add_argument("--doctor", action="store_true",
|
|
156
|
+
help="Check the local server, the model, and the optional tools, and say how to get what is missing")
|
|
157
|
+
parser.add_argument("--setup", action="store_true",
|
|
158
|
+
help="Guided first run: check Ollama, suggest a model for this computer's memory, and download it "
|
|
159
|
+
"with ollama pull only if you say yes (the only step that uses the internet)")
|
|
160
|
+
parser.add_argument("--start-ollama", action="store_true",
|
|
161
|
+
help="If no Ollama server is running, start one for this run on 127.0.0.1 with cloud features "
|
|
162
|
+
"off, and stop it on exit")
|
|
163
|
+
parser.add_argument("-i", "--interactive", action="store_true",
|
|
164
|
+
help="Ask several tasks in one session; follow-ups see earlier answers")
|
|
165
|
+
parser.add_argument("--no-retry", action="store_true",
|
|
166
|
+
help="Do not ask the model to correct an answer that fails its checks (one extra step, on by default)")
|
|
167
|
+
parser.add_argument("--allow-edits", action="store_true",
|
|
168
|
+
help="Let CodeHaven change code when you ask it to (fix, write tests, add docstrings, rename, write "
|
|
169
|
+
"docs). Each change is shown as a diff and applied only if you answer y; --undo puts it back")
|
|
170
|
+
parser.add_argument("--undo", action="store_true", help="Undo the last change CodeHaven made in this workspace, then exit")
|
|
171
|
+
parser.add_argument("--export", metavar="FILE",
|
|
172
|
+
help="Also save the question and its answer, with citations, as Markdown to FILE (a new file; "
|
|
173
|
+
"an existing one is never replaced). In --interactive, type /export [FILE] instead")
|
|
174
|
+
parser.add_argument("--no-stream", action="store_true", help="Print the final answer only once it is complete")
|
|
175
|
+
parser.add_argument("--gui", action="store_true", help="Open a local page in your browser to pick a repository and chat")
|
|
176
|
+
parser.add_argument("--port", type=int, default=0, help="Port for --gui on 127.0.0.1 (default: any free port)")
|
|
177
|
+
parser.add_argument("--no-browser", action="store_true", help="With --gui, print the link instead of opening it")
|
|
178
|
+
parser.add_argument("--allow-clone", action="store_true",
|
|
179
|
+
help="With --gui, allow downloading GitHub repositories you ask for (the only network use; "
|
|
180
|
+
"off by default, nothing is uploaded)")
|
|
181
|
+
parser.add_argument("--clone-dir", metavar="FOLDER",
|
|
182
|
+
help="With --allow-clone, where downloaded repositories are kept (default ~/CodeHaven/repos)")
|
|
183
|
+
parser.add_argument("--remember", action=argparse.BooleanOptionalAction, default=True,
|
|
184
|
+
help="Keep checked answers about this repository on this computer and recall them in later "
|
|
185
|
+
"sessions while the files they cite are unchanged (on by default; --no-remember saves "
|
|
186
|
+
"nothing to disk)")
|
|
187
|
+
parser.add_argument("--memory-dir", metavar="FOLDER",
|
|
188
|
+
help="Where saved answers are kept (default ~/CodeHaven/memory)")
|
|
189
|
+
parser.add_argument("--chats-dir", metavar="FOLDER",
|
|
190
|
+
help="Where the browser page keeps saved chats (default ~/CodeHaven/chats; nothing is kept "
|
|
191
|
+
"with --no-remember)")
|
|
192
|
+
parser.add_argument("--forget", action="store_true",
|
|
193
|
+
help="Delete the answers saved for this workspace, then exit")
|
|
194
|
+
parser.add_argument("--semantic", action=argparse.BooleanOptionalAction, default=True,
|
|
195
|
+
help="Also search by meaning with a local Ollama embedding model, when one is installed "
|
|
196
|
+
"(on by default; --no-semantic uses key words only)")
|
|
197
|
+
parser.add_argument("--embed-model", metavar="NAME",
|
|
198
|
+
help="Installed local embedding model for --semantic (default: the first found of "
|
|
199
|
+
"nomic-embed-text, embeddinggemma, mxbai-embed-large, ...)")
|
|
200
|
+
parser.add_argument("--index-dir", metavar="FOLDER",
|
|
201
|
+
help="Where the keyword index and meaning-search vectors are kept (default ~/CodeHaven/index; nothing is kept "
|
|
202
|
+
"with --no-remember)")
|
|
203
|
+
parser.add_argument("--ocr", metavar="PICTURE",
|
|
204
|
+
help="Read the code in a PNG or JPEG picture, such as a screenshot, into a new file beside it, "
|
|
205
|
+
"then exit. Offline; needs Tesseract installed on this computer")
|
|
206
|
+
parser.add_argument("--out", metavar="FILE", help="With --ocr, the file to write (default: the picture's name with .py)")
|
|
207
|
+
args = parser.parse_args(argv)
|
|
208
|
+
# --ocr and --forget do not use the model, so they are handled before Ollama is contacted.
|
|
209
|
+
if args.ocr:
|
|
210
|
+
return read_picture(args.ocr, args.out)
|
|
211
|
+
if args.undo:
|
|
212
|
+
try:
|
|
213
|
+
workspace = Workspace(args.workspace or ".", excludes=args.exclude)
|
|
214
|
+
print(f"Undid: {edits.undo(workspace, edits.journal_path(workspace))}")
|
|
215
|
+
return 0
|
|
216
|
+
except (ValueError, OSError) as exc:
|
|
217
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
218
|
+
return 1
|
|
219
|
+
if args.forget:
|
|
220
|
+
try:
|
|
221
|
+
memory = Memory(Workspace(args.workspace or ".", excludes=args.exclude), args.memory_dir)
|
|
222
|
+
count = len(memory.notes)
|
|
223
|
+
memory.forget()
|
|
224
|
+
chats = Chats(memory.workspace, args.chats_dir)
|
|
225
|
+
saved_chats = len(chats.chats)
|
|
226
|
+
chats.forget()
|
|
227
|
+
index_cache.forget(index_cache.path(memory.workspace, args.index_dir))
|
|
228
|
+
except (ValueError, OSError) as exc:
|
|
229
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
230
|
+
return 1
|
|
231
|
+
print(f"Forgot {count} saved answer{'s' if count != 1 else ''} and {saved_chats} saved "
|
|
232
|
+
f"chat{'s' if saved_chats != 1 else ''} for {memory.workspace.root}.")
|
|
233
|
+
return 0
|
|
234
|
+
if not 2000 <= args.retrieval_budget <= 16000:
|
|
235
|
+
parser.error("--retrieval-budget must be between 2000 and 16000 bytes")
|
|
236
|
+
if args.setup:
|
|
237
|
+
try:
|
|
238
|
+
return doctor.setup(Ollama(model=args.model, endpoint=args.endpoint), output=partial(print, flush=True))
|
|
239
|
+
except (ValueError, OSError) as exc:
|
|
240
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
241
|
+
return 1
|
|
242
|
+
if not args.doctor and not args.interactive and not args.gui and not args.task: # --undo returned above.
|
|
243
|
+
# Typed at a terminal with nothing to ask yet, the likely wish is to start asking.
|
|
244
|
+
if not sys.stdin.isatty():
|
|
245
|
+
parser.error("a task is required unless --doctor, --interactive, --gui, or --forget is used")
|
|
246
|
+
args.interactive = True
|
|
247
|
+
if not 0 <= args.port <= 65535:
|
|
248
|
+
parser.error("--port must be between 0 and 65535")
|
|
249
|
+
server = model = None
|
|
250
|
+
try:
|
|
251
|
+
model = Ollama(model=args.model, endpoint=args.endpoint, max_output_tokens=args.max_output_tokens,
|
|
252
|
+
prompt_budget=args.prompt_budget)
|
|
253
|
+
if args.start_ollama:
|
|
254
|
+
server = doctor.start_ollama(model, partial(print, flush=True))
|
|
255
|
+
try:
|
|
256
|
+
model.check_model()
|
|
257
|
+
except ValueError as exc:
|
|
258
|
+
# The GUI can start with another installed model, which the page lets the user change.
|
|
259
|
+
try:
|
|
260
|
+
available = [m["name"] for m in model.local_models()] if args.gui else []
|
|
261
|
+
except ValueError:
|
|
262
|
+
available = []
|
|
263
|
+
if not available:
|
|
264
|
+
# Say what is missing and the command that fixes it, not only that the request failed.
|
|
265
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
266
|
+
for line in doctor.missing_server(model):
|
|
267
|
+
print(" " + line, file=sys.stderr)
|
|
268
|
+
return 1
|
|
269
|
+
model.use(available[0])
|
|
270
|
+
print(f"{args.model} is not available; starting with {available[0]}. Choose another model in the page.")
|
|
271
|
+
embed_model = choose_model(model, args.embed_model) if args.semantic else None
|
|
272
|
+
if embed_model and hasattr(model, "companions"):
|
|
273
|
+
model.companions.add(embed_model) # Ours, so not reported as another program's model.
|
|
274
|
+
others = model.other_loaded_models()
|
|
275
|
+
if others:
|
|
276
|
+
print("Warning: Ollama also has " + ", ".join(others) + " loaded. If both models do not fit in memory, Ollama "
|
|
277
|
+
"reloads them in turn, which can add a minute or more to every step. Check with `ollama ps`.")
|
|
278
|
+
if args.doctor:
|
|
279
|
+
print(f"Local Ollama is ready: {model.model}")
|
|
280
|
+
print(f"Meaning search: {embed_model}" if embed_model else "Meaning search: off (--no-semantic)" if not args.semantic
|
|
281
|
+
else "Meaning search: off, no embedding model is installed. To turn it on, run once while online: "
|
|
282
|
+
"ollama pull nomic-embed-text")
|
|
283
|
+
suggestion, why = doctor.suggested_model()
|
|
284
|
+
print(f"Suggested model for this computer: {suggestion} ({why})." if suggestion != model.model else
|
|
285
|
+
f"The model in use is the one suggested for this computer ({why}).")
|
|
286
|
+
for line in doctor.extras(args.test_image) + [doctor.default_model_hint(model)]:
|
|
287
|
+
if line:
|
|
288
|
+
print(line)
|
|
289
|
+
return 0
|
|
290
|
+
if args.gui:
|
|
291
|
+
# Imported only here, so the web server is loaded only when --gui asks for it.
|
|
292
|
+
from .gui import serve
|
|
293
|
+
return serve(model, port=args.port, open_browser=not args.no_browser, repository=args.workspace,
|
|
294
|
+
max_steps=args.max_steps, retrieval_budget=args.retrieval_budget, excludes=args.exclude,
|
|
295
|
+
allow_clone=args.allow_clone, clone_folder=args.clone_dir,
|
|
296
|
+
remember=args.remember, memory_folder=args.memory_dir,
|
|
297
|
+
embed_model=embed_model, index_folder=args.index_dir, chats_folder=args.chats_dir,
|
|
298
|
+
allow_edits=args.allow_edits)
|
|
299
|
+
workspace = (combined([args.workspace or ".", *args.also], excludes=args.exclude) if args.also
|
|
300
|
+
else Workspace(args.workspace or ".", excludes=args.exclude))
|
|
301
|
+
if workspace.scopes:
|
|
302
|
+
print("Opened together: " + ", ".join(workspace.scopes) + f" (paths are shown from {workspace.root}).")
|
|
303
|
+
references = Path(args.knowledge_base).expanduser() if args.knowledge_base else workspace.root / "knowledge"
|
|
304
|
+
semantic = None
|
|
305
|
+
if embed_model:
|
|
306
|
+
semantic = Semantic(model, embed_model, output=partial(print, flush=True),
|
|
307
|
+
cache=Semantic.cache_path(workspace, embed_model, args.index_dir) if args.remember else None)
|
|
308
|
+
print(f"Indexing {workspace.root} ...", flush=True)
|
|
309
|
+
started = time.monotonic()
|
|
310
|
+
knowledge = KnowledgeBase(references if args.knowledge_base or references.exists() else None,
|
|
311
|
+
workspace=workspace, context_budget=args.retrieval_budget, semantic=semantic,
|
|
312
|
+
cache=index_cache.path(workspace, args.index_dir) if args.remember else None)
|
|
313
|
+
reused = f", {knowledge.reused} unchanged since last time" if knowledge.reused else ""
|
|
314
|
+
print(f"Indexed {knowledge.documents} files in {time.monotonic() - started:.1f}s{reused}.", flush=True)
|
|
315
|
+
if semantic is not None:
|
|
316
|
+
# A first run embeds every passage; later runs only the changed ones. Never hold a question up for long.
|
|
317
|
+
complete = semantic.wait(SEMANTIC_WAIT, partial(print, flush=True))
|
|
318
|
+
ready, total = semantic.coverage()
|
|
319
|
+
print(f"Meaning search: on with {embed_model}, {ready} of {total} passages ready"
|
|
320
|
+
+ ("." if complete else "; the rest are prepared in the background and saved for next time."))
|
|
321
|
+
print(f"Knowledge base: {knowledge.documents_by_source['repo']} repository files, "
|
|
322
|
+
f"{knowledge.documents_by_source['user']} user references, {len(knowledge.entries)} chunks. "
|
|
323
|
+
"Add your own .md, .txt, or .rst references to " + str(references))
|
|
324
|
+
if knowledge.limited:
|
|
325
|
+
print("Index limits reached; retrieval covers only part of the available files. Use search/read for more.")
|
|
326
|
+
if knowledge.excluded_reference_roots:
|
|
327
|
+
print("Reference directory excluded by workspace rules; it was not indexed. "
|
|
328
|
+
"Use a permitted directory or an external reference library.")
|
|
329
|
+
print(f"Workspace: {workspace.root}\nRead-only: CodeHaven never changes your files.")
|
|
330
|
+
options = dict(max_steps=args.max_steps, knowledge=knowledge, retry_unverified=not args.no_retry,
|
|
331
|
+
output=partial(print, flush=True), stream=None if args.no_stream else write_stream,
|
|
332
|
+
test_options={"runner": args.test_runner, "image": args.test_image,
|
|
333
|
+
"docker_socket": args.test_docker_socket},
|
|
334
|
+
confirm_tests=lambda: input(
|
|
335
|
+
f"Run {args.test_runner} in Docker with network disabled and project read-only? [y/N] "
|
|
336
|
+
).strip().lower() == "y",
|
|
337
|
+
confirm_code=(lambda _code: input("Run this snippet in Docker with network disabled and the project "
|
|
338
|
+
"read-only? [y/N] ").strip().lower() == "y")
|
|
339
|
+
if args.allow_python else None)
|
|
340
|
+
if args.allow_edits:
|
|
341
|
+
options["editor"] = coder.Editor(
|
|
342
|
+
confirm=lambda _diff, _summary: input("Apply this change? [y/N] ").strip().lower() == "y",
|
|
343
|
+
journal=edits.journal_path(workspace), test_options=options["test_options"],
|
|
344
|
+
confirm_tests=options["confirm_tests"])
|
|
345
|
+
print("Changing code is on: each change is shown as a diff and applied only if you answer y. "
|
|
346
|
+
"Undo the last one with /undo or codehaven --undo.")
|
|
347
|
+
memory = Memory(workspace, args.memory_dir) if args.remember else None
|
|
348
|
+
if memory is not None:
|
|
349
|
+
print(f"Long-term memory: {len(memory.notes)} saved answer{'s' if len(memory.notes) != 1 else ''} for this "
|
|
350
|
+
f"workspace in {memory.folder}. Checked answers are saved there; use --no-remember to save nothing, "
|
|
351
|
+
"or --forget to delete them.")
|
|
352
|
+
if args.interactive:
|
|
353
|
+
return interactive(Session(model, workspace, memory=memory, **options), args.task)
|
|
354
|
+
if args.export:
|
|
355
|
+
session = Session(model, workspace, memory=memory, **options)
|
|
356
|
+
code = session.ask(args.task)
|
|
357
|
+
state = session.last_state
|
|
358
|
+
try:
|
|
359
|
+
written = export.write(args.export, export.markdown([(args.task, state.get("final_text") or "", state.get("issues", []))],
|
|
360
|
+
str(workspace.root), model.model))
|
|
361
|
+
print(f"Saved the answer to {written}.")
|
|
362
|
+
except FileExistsError:
|
|
363
|
+
print(f"Error: {args.export} already exists; CodeHaven does not overwrite it.", file=sys.stderr)
|
|
364
|
+
return 1
|
|
365
|
+
return code
|
|
366
|
+
return run(model, workspace, args.task, memory=memory, **options)
|
|
367
|
+
except (ValueError, OSError, EOFError) as exc:
|
|
368
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
369
|
+
return 1
|
|
370
|
+
except KeyboardInterrupt:
|
|
371
|
+
print("\nStopped.", file=sys.stderr)
|
|
372
|
+
# The usual exit code for a program stopped by Ctrl+C (128 + SIGINT's number, 2).
|
|
373
|
+
return 130
|
|
374
|
+
except Exception as exc: # Anything unexpected: a plain sentence, not a traceback.
|
|
375
|
+
errors.report(exc)
|
|
376
|
+
print(f"Error: {errors.friendly(exc)}", file=sys.stderr)
|
|
377
|
+
return 1
|
|
378
|
+
finally:
|
|
379
|
+
doctor.stop_ollama(server)
|
offline_agent/coder.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""The requests that change code, when --allow-edits is on: a fix, tests, docstrings, a rename, docs, review fixes.
|
|
2
|
+
|
|
3
|
+
Each one ends the same way: CodeHaven shows the diff, the user approves or declines it, an approved change is
|
|
4
|
+
written and recorded for undo (see edits.py). Without --allow-edits none of this runs, and CodeHaven answers a
|
|
5
|
+
change request by explaining the change, as it always has.
|
|
6
|
+
|
|
7
|
+
- A fix or other change: the model is shown the files the task names (or the definitions it names, or the files
|
|
8
|
+
retrieval ranks first) and proposes exact replacements.
|
|
9
|
+
- Fix until the tests pass: the tests run in the Docker sandbox after each approved change, and a failure is sent
|
|
10
|
+
back to the model, at most ROUNDS times.
|
|
11
|
+
- Write tests: the function the task names, and an existing test file to copy the style of, are shown; the new
|
|
12
|
+
tests go in a new file or an existing test file.
|
|
13
|
+
- Docstrings: the named file is shown, and the model adds a docstring to each function or class that has none.
|
|
14
|
+
- Rename: done by plain code, not the model: whole-word replacement in the code files that use the name.
|
|
15
|
+
- Docs: a README or architecture note written from the project tour and the libraries list.
|
|
16
|
+
- Review fixes: the file is reviewed function by function, and the model fixes what the review found.
|
|
17
|
+
"""
|
|
18
|
+
import re
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from . import edits, insights, scans
|
|
22
|
+
from .insights import CODE, is_test
|
|
23
|
+
from .review import review
|
|
24
|
+
from .tasks import named_files
|
|
25
|
+
from .test_runner import run_tests
|
|
26
|
+
|
|
27
|
+
FIX_TESTS = re.compile(r"\b(?:until|so\s+that|till)\b.*\btests?\s+pass|\bmake\s+(?:the\s+)?tests?\s+pass\b|\bfix\s+(?:the\s+)?failing\s+tests?\b", re.I)
|
|
28
|
+
TESTS = re.compile(r"\b(?:write|add|create|generate)\s+(?:(?:unit|missing|some|the)\s+)*tests?\b(?:\s+(?:for|of)\s+`?([\w.]+)`?)?", re.I)
|
|
29
|
+
DOCSTRINGS = re.compile(r"\b(?:add|write|generate)\s+(?:missing\s+)?(?:docstrings?|doc\s*comments?|comments)\b", re.I)
|
|
30
|
+
RENAME = re.compile(r"\brename\s+(?:the\s+)?(?:function\s+|method\s+|class\s+|variable\s+)?`?([A-Za-z_$][\w$]*)`?\s+(?:to|as)\s+`?([A-Za-z_$][\w$]*)`?", re.I)
|
|
31
|
+
DOCS = re.compile(r"\b(?:write|generate|create|update)\s+(?:a\s+|the\s+)?(README|readme|architecture\s+(?:notes?|docs?|overview)|"
|
|
32
|
+
r"CHANGELOG|changelog|docs?|documentation)\b", re.I)
|
|
33
|
+
FINDINGS = re.compile(r"\b(?:apply|fix)\s+(?:the\s+)?(?:review\s+)?(?:findings|problems\s+(?:the\s+)?review\s+found|review)\b", re.I)
|
|
34
|
+
CHANGE = re.compile(r"^\W*(?:please\s+|can\s+you\s+|could\s+you\s+)?(?:fix|change|update|refactor|add|remove|implement|replace|"
|
|
35
|
+
r"make|correct|patch|rewrite|handle|validate)\b", re.I)
|
|
36
|
+
ROUNDS = 3 # Changes tried by "fix until the tests pass".
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def requested(task):
|
|
40
|
+
"""The kind of change a task asks for, or None for a task that does not ask for one."""
|
|
41
|
+
for kind, pattern in (("rename", RENAME), ("fix_tests", FIX_TESTS), ("findings", FINDINGS), ("tests", TESTS),
|
|
42
|
+
("docstrings", DOCSTRINGS), ("docs", DOCS), ("change", CHANGE)):
|
|
43
|
+
if pattern.search(task):
|
|
44
|
+
return kind
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Editor:
|
|
49
|
+
"""What changing code needs: a way to ask the user, the undo journal, and the test settings."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, confirm, journal, test_options=None, confirm_tests=None):
|
|
52
|
+
"""confirm(diff, summary) returns whether to apply; confirm_tests() whether the tests may run in Docker."""
|
|
53
|
+
self.confirm, self.journal = confirm, journal
|
|
54
|
+
self.test_options, self.confirm_tests = dict(test_options or {}), confirm_tests
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def files_for(task, workspace, knowledge, files):
|
|
58
|
+
"""The files a change is about: those the task names, else those of the definitions it names, else retrieval's best."""
|
|
59
|
+
names = named_files(task, files)
|
|
60
|
+
if not names and knowledge is not None:
|
|
61
|
+
names = list(dict.fromkeys(path for _, path, _ in knowledge.named_definitions(task)))[:2]
|
|
62
|
+
if not names and knowledge is not None:
|
|
63
|
+
import json
|
|
64
|
+
rows = json.loads(knowledge.retrieve(task[:1000])).get("results", [])
|
|
65
|
+
names = list(dict.fromkeys(row["source"].removeprefix("repo/") for row in rows if row["source"].startswith("repo/")))[:2]
|
|
66
|
+
return names
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def context(workspace, names, note=""):
|
|
70
|
+
"""The files to show the model, each whole and exactly as on disk, so the text to replace can be copied."""
|
|
71
|
+
parts = []
|
|
72
|
+
for name in names:
|
|
73
|
+
try:
|
|
74
|
+
parts.append(f"File {name}:\n```\n{workspace.read(name)}\n```")
|
|
75
|
+
except (ValueError, OSError, UnicodeError):
|
|
76
|
+
continue
|
|
77
|
+
return "\n\n".join(parts) + (f"\n\n{note}" if note else "")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def offer(model, workspace, editor, task, shown, output, feedback=""):
|
|
81
|
+
"""Propose a change, show its diff, and apply it if the user agrees. Returns (applied, text for the answer)."""
|
|
82
|
+
try:
|
|
83
|
+
summary, plan = edits.propose(model, workspace, task, shown, feedback=feedback, output=output)
|
|
84
|
+
except edits.EditError as exc:
|
|
85
|
+
return False, f"No change was made: {exc}."
|
|
86
|
+
return confirm_and_apply(workspace, editor, summary, plan, output)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def confirm_and_apply(workspace, editor, summary, plan, output):
|
|
90
|
+
"""Show a plan's diff, ask, and apply it on a yes. Returns (applied, text for the answer)."""
|
|
91
|
+
patch = edits.diff(plan)
|
|
92
|
+
output(f"Proposed change: {summary}\n{patch}")
|
|
93
|
+
if not editor.confirm(patch, summary):
|
|
94
|
+
return False, f"The change was not applied: you declined it.\n\nProposed change: {summary}\n\n```diff\n{patch}```"
|
|
95
|
+
try:
|
|
96
|
+
changed = edits.apply(workspace, plan, summary, editor.journal)
|
|
97
|
+
except (edits.EditError, OSError) as exc:
|
|
98
|
+
return False, f"No change was made: {exc}."
|
|
99
|
+
return True, (f"Changed {', '.join(changed)}: {summary}\n\n```diff\n{patch}```\n\n"
|
|
100
|
+
"Undo it with /undo in a session, or codehaven --undo.")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def rename(workspace, knowledge, old, new):
|
|
104
|
+
"""A plan that renames a name, as a whole word, in every code file that uses it; raises EditError when it cannot."""
|
|
105
|
+
if not re.fullmatch(r"[A-Za-z_$][\w$]*", new) or old == new:
|
|
106
|
+
raise edits.EditError(f"{new!r} is not a new name that code can use")
|
|
107
|
+
word = re.compile(rf"(?<![\w$]){re.escape(old)}(?![\w$])")
|
|
108
|
+
if new in (getattr(knowledge, "symbols", {}) or {}):
|
|
109
|
+
raise edits.EditError(f"something named {new} is already defined, so the rename could merge two names")
|
|
110
|
+
plan = []
|
|
111
|
+
for path in workspace.files():
|
|
112
|
+
if Path(path).suffix.lower() not in CODE:
|
|
113
|
+
continue
|
|
114
|
+
try:
|
|
115
|
+
before = workspace.read(path)
|
|
116
|
+
except (ValueError, OSError, UnicodeError):
|
|
117
|
+
continue
|
|
118
|
+
after = word.sub(new, before)
|
|
119
|
+
if after != before:
|
|
120
|
+
plan.append((path, before, after))
|
|
121
|
+
if not plan:
|
|
122
|
+
raise edits.EditError(f"no code file uses the name {old}")
|
|
123
|
+
return plan
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def run(kind, model, workspace, knowledge, task, editor, output=print):
|
|
127
|
+
"""Carry out one change request. Returns {"text", "evidence", "changed"}."""
|
|
128
|
+
files = workspace.files()
|
|
129
|
+
if kind == "rename":
|
|
130
|
+
old, new = RENAME.search(task).groups()
|
|
131
|
+
try:
|
|
132
|
+
plan = rename(workspace, knowledge, old, new)
|
|
133
|
+
except edits.EditError as exc:
|
|
134
|
+
return {"text": f"Nothing was renamed: {exc}.", "evidence": [], "changed": False}
|
|
135
|
+
changed, text = confirm_and_apply(workspace, editor, f"Rename {old} to {new} in {len(plan)} file(s)", plan, output)
|
|
136
|
+
return {"text": text + ("\n\nA rename by text can miss a name built at runtime; run the tests." if changed else ""),
|
|
137
|
+
"evidence": [], "changed": changed}
|
|
138
|
+
if kind == "docs":
|
|
139
|
+
tour = insights.tour(model, workspace, knowledge, output) if knowledge is not None else {"text": ""}
|
|
140
|
+
libraries = scans.dependencies(workspace, knowledge)["text"]
|
|
141
|
+
target = "CHANGELOG.md" if "change" in task.lower() else ("docs/ARCHITECTURE.md" if "architecture" in task.lower() else "README.md")
|
|
142
|
+
names = [target] if target in files else []
|
|
143
|
+
note = (f"Write or update {target}. What CodeHaven found about the project, to write from (do not invent more):\n"
|
|
144
|
+
f"Reading order:\n{tour['text']}\n\nLibraries:\n{libraries}")
|
|
145
|
+
changed, text = offer(model, workspace, editor, task, context(workspace, names, note), output)
|
|
146
|
+
return {"text": text, "evidence": [], "changed": changed}
|
|
147
|
+
if kind == "findings":
|
|
148
|
+
names = named_files(task, files)
|
|
149
|
+
if not names:
|
|
150
|
+
return {"text": "Name the file whose review findings to fix, such as: apply the review findings in store.py.",
|
|
151
|
+
"evidence": [], "changed": False}
|
|
152
|
+
found = review(model, workspace, names[0], spans=knowledge.dependencies.spans.get(names[0]) if knowledge else None,
|
|
153
|
+
output=output)
|
|
154
|
+
if not found["problems"]:
|
|
155
|
+
return {"text": found["text"] + "\n\nThe review found nothing to fix.", "evidence": found["evidence"], "changed": False}
|
|
156
|
+
changed, text = offer(model, workspace, editor, task, context(workspace, names[:1]),
|
|
157
|
+
output, feedback="Fix these review findings, and only these:\n" + found["text"])
|
|
158
|
+
return {"text": found["text"] + "\n\n" + text, "evidence": found["evidence"], "changed": changed}
|
|
159
|
+
if kind == "tests":
|
|
160
|
+
names = files_for(task, workspace, knowledge, files)
|
|
161
|
+
examples = [name for name in files if is_test(name) and Path(name).suffix.lower() in CODE][:1]
|
|
162
|
+
note = ("Write focused tests for the code the task names. "
|
|
163
|
+
+ (f"Follow the style of {examples[0]}, shown above; add to it or create a new test file beside it."
|
|
164
|
+
if examples else "Create a new test file under tests/."))
|
|
165
|
+
changed, text = offer(model, workspace, editor, task, context(workspace, names + examples, note), output)
|
|
166
|
+
return {"text": text, "evidence": [], "changed": changed}
|
|
167
|
+
if kind == "docstrings":
|
|
168
|
+
names = files_for(task, workspace, knowledge, files)[:1]
|
|
169
|
+
note = ("Add a short docstring (or doc comment, in the language's usual form) to each function, method, and class "
|
|
170
|
+
"that has none. Do not change any code or existing docstring.")
|
|
171
|
+
changed, text = offer(model, workspace, editor, task, context(workspace, names, note), output)
|
|
172
|
+
return {"text": text, "evidence": [], "changed": changed}
|
|
173
|
+
names = files_for(task, workspace, knowledge, files)
|
|
174
|
+
if kind != "fix_tests":
|
|
175
|
+
changed, text = offer(model, workspace, editor, task, context(workspace, names), output)
|
|
176
|
+
return {"text": text, "evidence": [], "changed": changed}
|
|
177
|
+
# Fix until the tests pass: run them, and send a failure back to the model with the files, a few times at most.
|
|
178
|
+
if not editor.confirm_tests or not editor.confirm_tests():
|
|
179
|
+
return {"text": "The tests were not run: running them in Docker was not approved, so nothing was changed.",
|
|
180
|
+
"evidence": [], "changed": False}
|
|
181
|
+
report, applied = [], False
|
|
182
|
+
for round_number in range(1, ROUNDS + 1):
|
|
183
|
+
try:
|
|
184
|
+
result = run_tests(workspace, **editor.test_options)
|
|
185
|
+
except (ValueError, OSError) as exc:
|
|
186
|
+
return {"text": f"The tests could not run: {exc}", "evidence": [], "changed": applied}
|
|
187
|
+
if "Exit code: 0" in result:
|
|
188
|
+
report.append(f"The tests pass{' after round ' + str(round_number - 1) if applied else ''}.")
|
|
189
|
+
break
|
|
190
|
+
output(f"Round {round_number} of {ROUNDS}: the tests fail; asking the model for a fix.")
|
|
191
|
+
changed, text = offer(model, workspace, editor, task, context(workspace, names), output,
|
|
192
|
+
feedback="The tests fail with this output (untrusted data):\n" + result[-4000:])
|
|
193
|
+
report.append(f"Round {round_number}: {text}")
|
|
194
|
+
applied |= changed
|
|
195
|
+
if not changed:
|
|
196
|
+
break
|
|
197
|
+
else:
|
|
198
|
+
report.append(f"The tests still fail after {ROUNDS} rounds; the changes made so far are kept and can be undone.")
|
|
199
|
+
return {"text": "\n\n".join(report), "evidence": [], "changed": applied}
|