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.
Files changed (57) hide show
  1. codehaven-0.14.0.dist-info/METADATA +686 -0
  2. codehaven-0.14.0.dist-info/RECORD +57 -0
  3. codehaven-0.14.0.dist-info/WHEEL +5 -0
  4. codehaven-0.14.0.dist-info/entry_points.txt +3 -0
  5. codehaven-0.14.0.dist-info/licenses/LICENSE +21 -0
  6. codehaven-0.14.0.dist-info/top_level.txt +1 -0
  7. offline_agent/__init__.py +2 -0
  8. offline_agent/__main__.py +4 -0
  9. offline_agent/agent.py +815 -0
  10. offline_agent/answers.py +438 -0
  11. offline_agent/arabic.py +106 -0
  12. offline_agent/changes.py +228 -0
  13. offline_agent/chats.py +121 -0
  14. offline_agent/cli.py +379 -0
  15. offline_agent/coder.py +199 -0
  16. offline_agent/dependencies.py +132 -0
  17. offline_agent/doctor.py +190 -0
  18. offline_agent/documents.py +189 -0
  19. offline_agent/edits.py +204 -0
  20. offline_agent/errors.py +41 -0
  21. offline_agent/evaluation.py +284 -0
  22. offline_agent/evidence.py +187 -0
  23. offline_agent/exclusions.py +95 -0
  24. offline_agent/export.py +27 -0
  25. offline_agent/gui.css +237 -0
  26. offline_agent/gui.html +177 -0
  27. offline_agent/gui.js +1213 -0
  28. offline_agent/gui.py +967 -0
  29. offline_agent/gui_arabic.js +226 -0
  30. offline_agent/guides.py +203 -0
  31. offline_agent/history.py +126 -0
  32. offline_agent/index_cache.py +78 -0
  33. offline_agent/insights.py +333 -0
  34. offline_agent/javascript.py +200 -0
  35. offline_agent/knowledge.py +569 -0
  36. offline_agent/languages.py +396 -0
  37. offline_agent/memory.py +192 -0
  38. offline_agent/messages.py +51 -0
  39. offline_agent/model.py +498 -0
  40. offline_agent/more_languages.py +253 -0
  41. offline_agent/ocr.py +204 -0
  42. offline_agent/prompts.py +130 -0
  43. offline_agent/references/langgraph-approvals.md +38 -0
  44. offline_agent/references/langgraph-checkpoints.md +37 -0
  45. offline_agent/references/langgraph-graphs.md +42 -0
  46. offline_agent/references/langgraph.md +49 -0
  47. offline_agent/review.py +205 -0
  48. offline_agent/scans.py +325 -0
  49. offline_agent/semantic.py +264 -0
  50. offline_agent/slash.py +53 -0
  51. offline_agent/study.py +210 -0
  52. offline_agent/symbols.py +201 -0
  53. offline_agent/tasks.py +164 -0
  54. offline_agent/test_runner.py +264 -0
  55. offline_agent/trace.py +239 -0
  56. offline_agent/tracebacks.py +98 -0
  57. offline_agent/workspace.py +419 -0
offline_agent/gui.py ADDED
@@ -0,0 +1,967 @@
1
+ """CodeHaven in the browser: pick a repository, index it, and chat about its code.
2
+
3
+ The server listens on 127.0.0.1 only and serves one self-contained page: no scripts, styles, or fonts come
4
+ from the internet, and the page's Content-Security-Policy forbids loading any. Every request must carry the
5
+ secret token from the link the server prints, and a Host header naming this machine, so other websites open
6
+ in the same browser cannot use the server to read files. Like the rest of CodeHaven, it never changes files.
7
+
8
+ A single file can be uploaded instead of choosing a folder. The page sends it to this server only; a copy is
9
+ kept in a private temporary folder, which is the workspace for that chat, and deleted when another repository
10
+ or file is opened or the server stops. The original file is never touched.
11
+
12
+ The uploaded file can also be a picture of code, such as a screenshot. Tesseract, a program installed on this
13
+ computer, reads it into a text file in that same temporary folder, which the page offers to save. See ocr.py.
14
+
15
+ Besides chat, the page offers two study aids for one file or a group of files: a structure map, drawn from
16
+ static analysis without the model, and flashcards, written by the local model with looked-up line citations.
17
+
18
+ Unless started with --no-remember, checked answers about a repository are saved on this computer and recalled
19
+ in later sessions while the files they cite are unchanged. Uploaded files are never remembered.
20
+
21
+ With --allow-clone, and only then, a GitHub repository can be downloaded once by its address. This is the one
22
+ use of the network: git, run by this server, downloads the latest snapshot into the clone folder, and from then
23
+ on the copy opens offline like any other folder. Nothing is uploaded. CodeHaven never asks for, sees, or stores
24
+ a GitHub password or token: private repositories work only through the sign-in git already has on this machine.
25
+ """
26
+ import contextlib
27
+ import json
28
+ import os
29
+ import queue
30
+ import re
31
+ import secrets
32
+ import shutil
33
+ import signal
34
+ import subprocess
35
+ import tempfile
36
+ import threading
37
+ import time
38
+ import webbrowser
39
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
40
+ from pathlib import Path
41
+ from urllib.parse import parse_qs, urlsplit
42
+
43
+ from . import coder, documents, edits, errors, index_cache, ocr, slash, study
44
+ from .agent import Session
45
+ from .chats import Chats, new_id
46
+ from .knowledge import KnowledgeBase
47
+ from .memory import Memory
48
+ from .model import MODEL, Stopped
49
+ from .semantic import Semantic
50
+ from .workspace import MAX_BYTES, MAX_FILES, Workspace, combined
51
+
52
+ PAGE = Path(__file__).with_name("gui.html")
53
+ # The page is kept as four files and served as one: each mark in the markup or the script is replaced by a file.
54
+ # The order matters: the script holds the mark for the Arabic sentences.
55
+ PAGE_PARTS = (("/*__STYLE__*/", "gui.css"), ("/*__SCRIPT__*/", "gui.js"), ("/*__ARABIC__*/", "gui_arabic.js"))
56
+ FILE_CONTEXT, FILE_LINES = 6, 400 # Lines shown around a citation, and the most one request returns.
57
+ # Limits: folders listed by the folder browser, bytes in a JSON request, characters kept of an uploaded file's name.
58
+ DIRECTORY_ENTRIES = 400
59
+ REQUEST_BYTES = 64_000
60
+ UPLOAD_NAME_CHARACTERS = 120
61
+ CLONE_FOLDER = Path.home() / "CodeHaven" / "repos"
62
+ CLONE_SECONDS, CLONE_BYTES = 180, 500_000_000 # A download is stopped after 3 minutes or 500 MB on disk.
63
+ # The characters accepted in a GitHub owner name and repository name; anything else is refused before git runs.
64
+ OWNER = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})")
65
+ REPOSITORY = re.compile(r"[A-Za-z0-9._-]{1,100}")
66
+ SEMANTIC_WAIT = 15 # Seconds indexing waits for meaning search; the rest is prepared in the background.
67
+ CLONE_OFF = "Cloning from GitHub is off, so CodeHaven stays offline. Restart it with --allow-clone to turn it on."
68
+
69
+
70
+ def page_text():
71
+ """The whole page as one self-contained document: markup, styles, script, and Arabic sentences."""
72
+ text = PAGE.read_text(encoding="utf-8")
73
+ for mark, name in PAGE_PARTS:
74
+ text = text.replace(mark, PAGE.with_name(name).read_text(encoding="utf-8"))
75
+ return text
76
+
77
+
78
+ class Busy(Exception):
79
+ """Another indexing run or question is still in progress."""
80
+
81
+
82
+ class App:
83
+ """One repository and one conversation at a time, shared by the request threads."""
84
+
85
+ def __init__(self, model, *, max_steps=12, retrieval_budget=4000, excludes=(), allow_clone=False, clone_folder=None,
86
+ remember=False, memory_folder=None, embed_model=None, index_folder=None, chats_folder=None,
87
+ retry_unverified=False, allow_edits=False):
88
+ """Keep the settings. Nothing is indexed until open(), clone(), or open_file() is called.
89
+
90
+ retry_unverified asks the model once to correct an answer that fails its checks (serve() turns it on)."""
91
+ self.retry_unverified = bool(retry_unverified)
92
+ # Changing code (--allow-edits): a proposed change waits here for the user's Apply or Decline on the page.
93
+ self.allow_edits, self.decision = bool(allow_edits), None
94
+ self.chats_folder, self.chats, self.chat_id = chats_folder, None, new_id()
95
+ self.embed_model, self.index_folder, self.semantic = embed_model, index_folder, None
96
+ self.remember, self.memory_folder, self.memory = bool(remember), memory_folder, None
97
+ self.model, self.max_steps, self.retrieval_budget = model, max_steps, retrieval_budget
98
+ self.excludes = tuple(excludes)
99
+ self.allow_clone = bool(allow_clone)
100
+ self.clone_folder = Path(clone_folder).expanduser() if clone_folder else CLONE_FOLDER
101
+ # One request at a time uses the model: busy is the flag, and the lock only guards reading and setting it.
102
+ self.lock = threading.Lock()
103
+ self.busy = False
104
+ self.stoppable = False # True while an answer or flashcards run, which are what stop() can end.
105
+ # While a repository is indexed or downloaded, stop() sets this event; indexing and the download check it.
106
+ self.cancel = threading.Event()
107
+ self.cancellable = False
108
+ self.workspace = self.knowledge = self.session = None
109
+ self.upload = self.upload_folder = None # The uploaded file's name and its private temporary folder.
110
+ self.picture = None # When the upload was a picture: how reading it went, for the page to show.
111
+ self.document = None # When the upload was a notebook or a PDF: what was read from it.
112
+ # While an answer runs, the queue its log lines and streamed text are put on; see ask() and emit().
113
+ self.sink = None
114
+
115
+ def claim(self):
116
+ """Mark the app busy, or raise Busy if another request is still running. Always paired with release()."""
117
+ with self.lock:
118
+ if self.busy:
119
+ raise Busy("CodeHaven is still working on the previous request.")
120
+ self.busy = True
121
+
122
+ def release(self):
123
+ """Let the next request in."""
124
+ with self.lock:
125
+ self.busy = self.stoppable = self.cancellable = False
126
+
127
+ def claim_model(self):
128
+ """claim() for work the Stop button can end: an answer or flashcards. A stop meant for earlier work is cleared."""
129
+ with self.lock:
130
+ if self.busy:
131
+ raise Busy("CodeHaven is still working on the previous request.")
132
+ self.busy = self.stoppable = True
133
+ if hasattr(self.model, "allow"):
134
+ self.model.allow()
135
+
136
+ def claim_index(self):
137
+ """claim() for indexing or a download, which the Stop button can end. A stop meant for earlier work is cleared."""
138
+ with self.lock:
139
+ if self.busy:
140
+ raise Busy("CodeHaven is still working on the previous request.")
141
+ self.busy = self.cancellable = True
142
+ self.cancel.clear()
143
+
144
+ def stop(self):
145
+ """Stop the answer, flashcards, index, or download in progress. Returns whether there was anything to stop.
146
+
147
+ The lock makes this and the claims take turns, so a late stop can never end the next request.
148
+ """
149
+ if self.decision is not None: # A change waiting for an answer is declined.
150
+ self.decision["event"].set()
151
+ with self.lock:
152
+ stopped = self.stoppable and hasattr(self.model, "stop")
153
+ if stopped:
154
+ self.model.stop()
155
+ elif self.cancellable:
156
+ self.cancel.set()
157
+ stopped = True
158
+ return {"stopped": bool(stopped)}
159
+
160
+ def confirm(self, diff, summary):
161
+ """Show a proposed change's diff on the page and wait for Apply or Decline. Stop, or 15 minutes, declines it."""
162
+ decision = self.decision = {"event": threading.Event(), "apply": False}
163
+ self.emit({"type": "diff", "diff": diff, "summary": summary})
164
+ decision["event"].wait(900)
165
+ self.decision = None
166
+ return decision["apply"]
167
+
168
+ def decide(self, apply):
169
+ """The user's answer to the change shown on the page."""
170
+ decision = self.decision
171
+ if decision is None:
172
+ raise ValueError("There is no change waiting for an answer.")
173
+ decision["apply"] = bool(apply) is True
174
+ decision["event"].set()
175
+ return {"ok": True}
176
+
177
+ def undo(self):
178
+ """Undo the last change CodeHaven made in the open repository."""
179
+ if not self.allow_edits or self.workspace is None:
180
+ raise ValueError("Changing code is off. Start CodeHaven with --allow-edits to turn it on.")
181
+ self.claim()
182
+ try:
183
+ return {"undone": edits.undo(self.workspace, edits.journal_path(self.workspace))}
184
+ finally:
185
+ self.release()
186
+
187
+ def stopped_summary(self):
188
+ """What the page shows after a stopped index or download: whatever was open before, unchanged."""
189
+ return {**self.summary(), "stopped": True}
190
+
191
+ def emit(self, event):
192
+ """Pass a log line or a piece of streamed text to the answer being sent, if one is running."""
193
+ if self.sink is not None:
194
+ self.sink.put(event)
195
+
196
+ def open(self, path, excludes=()):
197
+ """Index a repository and start a fresh conversation about it. Stop ends it and keeps what was open."""
198
+ self.claim_index()
199
+ try:
200
+ return self.index(path, excludes)
201
+ except Stopped:
202
+ return self.stopped_summary()
203
+ finally:
204
+ self.release()
205
+
206
+ def index(self, path, excludes=()):
207
+ """Index the folder at path and return the page's summary. The caller already holds the busy claim."""
208
+ # Several repositories can be opened together, their full paths separated by ";" or new lines.
209
+ roots = [Path(part.strip()).expanduser() for part in re.split(r"[;\n]", path) if part.strip()] or [Path(path)]
210
+ if not all(root.is_absolute() for root in roots):
211
+ raise ValueError("Use the full path of the repository folder, such as /Users/you/dev/project.")
212
+ workspace = (combined(roots, excludes=self.excludes + tuple(excludes)) if len(roots) > 1
213
+ else Workspace(roots[0], excludes=self.excludes + tuple(excludes)))
214
+ # A knowledge folder inside the repository holds the user's own reference notes; it is indexed when present.
215
+ references = workspace.root / "knowledge"
216
+ self.load(workspace, references if references.exists() else None)
217
+ return self.summary()
218
+
219
+ def clone(self, address):
220
+ """Download a GitHub repository once (only with --allow-clone), then index the local copy.
221
+
222
+ A repository cloned earlier is opened from disk without touching the network.
223
+ """
224
+ if not self.allow_clone:
225
+ raise ValueError(CLONE_OFF)
226
+ owner, name, ssh = github_repository(address)
227
+ target = self.clone_folder / owner / name
228
+ self.claim_index()
229
+ try:
230
+ if target.exists():
231
+ if origin_repository(target) != (owner.lower(), name.lower()):
232
+ raise ValueError(f"{target} already exists and is not a copy of github.com/{owner}/{name}.")
233
+ summary = self.index(str(target))
234
+ return {**summary, "cloned": False, "source": f"github.com/{owner}/{name}"}
235
+ download(owner, name, ssh, target, cancel=self.cancel)
236
+ summary = self.index(str(target))
237
+ return {**summary, "cloned": True, "source": f"github.com/{owner}/{name}"}
238
+ except Stopped:
239
+ return self.stopped_summary() # A stopped download leaves nothing behind; see download().
240
+ finally:
241
+ self.release()
242
+
243
+ def open_file(self, name, data):
244
+ """Chat about one uploaded file: a copy in a private temporary folder becomes the workspace.
245
+
246
+ A picture of code is first read into text by Tesseract on this computer; the chat is about that text.
247
+ """
248
+ if ocr.image_suffix(data):
249
+ return self.open_picture(upload_name(name), data)
250
+ if documents.kind(name, data):
251
+ return self.open_document(upload_name(name), data)
252
+ if len(data) > MAX_BYTES:
253
+ raise ValueError(f"Only UTF-8 text files up to {MAX_BYTES // 1000} KB can be uploaded.")
254
+ if b"\0" in data:
255
+ raise ValueError("Only text files and PNG or JPEG pictures of code can be uploaded; this file looks binary.")
256
+ try:
257
+ data.decode("utf-8")
258
+ except UnicodeDecodeError as exc:
259
+ raise ValueError("Only UTF-8 text files can be uploaded.") from exc
260
+ name = upload_name(name)
261
+ self.claim()
262
+ try:
263
+ return self.open_copy(name, data)
264
+ finally:
265
+ self.release()
266
+
267
+ def open_picture(self, name, data):
268
+ """Read a picture of code into text with Tesseract, and open that text as the uploaded file."""
269
+ self.claim() # Before reading, so two pictures are never read at once.
270
+ try:
271
+ found = ocr.read_code(name, data)
272
+ summary = self.open_copy(found["name"], found["text"].encode("utf-8"))
273
+ self.picture = {key: found[key] for key in ("image", "lines", "check", "syntax")}
274
+ return {**summary, "picture": self.picture} # The summary was made before the picture's notes were kept.
275
+ finally:
276
+ self.release()
277
+
278
+ def open_document(self, name, data):
279
+ """Chat about a notebook or a PDF: its cells or pages are read into one text file on this computer."""
280
+ self.claim()
281
+ try:
282
+ found = documents.read_document(name, data)
283
+ summary = self.open_copy(upload_name(found["name"]), found["text"].encode("utf-8"))
284
+ self.document = {key: found[key] for key in ("source", "kind", "note")}
285
+ return {**summary, "document": self.document}
286
+ finally:
287
+ self.release()
288
+
289
+ def open_copy(self, name, data):
290
+ """Write the uploaded bytes into a new private temporary folder and make that folder the workspace."""
291
+ folder = Path(tempfile.mkdtemp(prefix="codehaven-upload-")) # Readable by this user only.
292
+ try:
293
+ (folder / name).write_bytes(data)
294
+ workspace = Workspace(folder, excludes=self.excludes)
295
+ workspace.read(name) # Refuses names the workspace rules hide, such as --exclude patterns.
296
+ # A file attached in the middle of a chat continues it, so "explain the picture I just sent" works.
297
+ self.load(workspace, None, upload=name, upload_folder=folder, keep_chat=True)
298
+ return self.summary()
299
+ except BaseException:
300
+ shutil.rmtree(folder, ignore_errors=True)
301
+ raise
302
+
303
+ def load(self, workspace, references, *, upload=None, upload_folder=None, keep_chat=False):
304
+ """Replace what is open: build the search index, memory, and saved chats for workspace, and a new Session."""
305
+ turns = self.session.turns if keep_chat and self.session is not None else []
306
+ semantic = None
307
+ if self.embed_model:
308
+ # An uploaded file lives in a temporary folder, so its vectors are kept in memory only.
309
+ keep = self.remember and upload is None
310
+ semantic = Semantic(self.model, self.embed_model, output=lambda line: self.emit({"type": "log", "text": str(line)}),
311
+ cache=Semantic.cache_path(workspace, self.embed_model, self.index_folder) if keep else None)
312
+ # The keyword index of a repository is kept so it reopens quickly; an uploaded file's is not.
313
+ cache = index_cache.path(workspace, self.index_folder) if self.remember and upload is None else None
314
+ knowledge = KnowledgeBase(references, workspace=workspace, context_budget=self.retrieval_budget, semantic=semantic,
315
+ cancel=self.cancel if self.cancellable else None, cache=cache)
316
+ if semantic is not None:
317
+ semantic.wait(SEMANTIC_WAIT)
318
+ self.semantic = semantic
319
+ # Only now, once the new index was built without an error, is the previous upload's temporary folder deleted.
320
+ self.discard_upload()
321
+ self.workspace, self.knowledge = workspace, knowledge
322
+ self.upload, self.upload_folder = upload, upload_folder
323
+ # An uploaded file lives in a temporary folder that is deleted, so there is nothing lasting to remember.
324
+ self.memory = Memory(workspace, self.memory_folder) if self.remember and upload is None else None
325
+ self.chats = Chats(workspace, self.chats_folder) if self.remember and upload is None else None
326
+ if not turns:
327
+ self.chat_id = new_id() # A newly opened repository starts a new chat; an attached file continues one.
328
+ self.session = Session(self.model, workspace, knowledge=knowledge, max_steps=self.max_steps, focus_file=upload,
329
+ memory=self.memory, retry_unverified=self.retry_unverified,
330
+ editor=coder.Editor(confirm=self.confirm, journal=edits.journal_path(workspace))
331
+ if self.allow_edits and upload is None else None,
332
+ output=lambda line: self.emit({"type": "log", "text": str(line)}),
333
+ stream=lambda text: self.emit({"type": "text", "text": text}))
334
+ # Earlier questions and answers carry over; evidence does not, because it quotes files no longer open.
335
+ self.session.turns = list(turns)
336
+
337
+ def discard_upload(self):
338
+ """Delete the temporary copy of an uploaded file, if one is open."""
339
+ if self.upload_folder is not None:
340
+ shutil.rmtree(self.upload_folder, ignore_errors=True)
341
+ self.upload = self.upload_folder = self.picture = self.document = None
342
+
343
+ def close(self):
344
+ """Clean up when the server stops: delete the uploaded file's temporary copy."""
345
+ self.discard_upload()
346
+
347
+ def model_name(self):
348
+ """The name of the chat model in use, or the default name when the model object does not give one."""
349
+ return getattr(self.model, "model", MODEL)
350
+
351
+ def models(self):
352
+ """Installed local chat models for the picker, and which one is in use."""
353
+ try:
354
+ found = self.model.local_models() if hasattr(self.model, "local_models") else []
355
+ except ValueError:
356
+ found = []
357
+ return {"models": found, "current": self.model_name(), "default": MODEL}
358
+
359
+ def use_model(self, name):
360
+ """Switch to another installed chat model and return the refreshed list for the picker."""
361
+ if not hasattr(self.model, "use"):
362
+ raise ValueError("This model cannot be changed.")
363
+ self.claim()
364
+ try:
365
+ self.model.use(name)
366
+ return self.models()
367
+ finally:
368
+ self.release()
369
+
370
+ def summary(self):
371
+ """What the page needs to show the current state: model, settings, saved chats, and what is open."""
372
+ meaning = None
373
+ if self.semantic is not None:
374
+ ready, total = self.semantic.coverage()
375
+ meaning = {"model": self.embed_model, "ready": ready, "total": total, "failed": bool(self.semantic.failed)}
376
+ base = {"model": self.model_name(), "clone": self.allow_clone, "remember": self.remember, "meaning": meaning,
377
+ "edits": self.allow_edits,
378
+ "chats": self.chats.listing() if self.chats is not None else [],
379
+ "saved": len(self.memory.notes) if self.memory is not None else 0}
380
+ workspace, knowledge = self.workspace, self.knowledge
381
+ if workspace is None or knowledge is None:
382
+ return {**base, "repository": None, "upload": None, "picture": None, "document": None}
383
+ counts = knowledge.documents_by_source
384
+ if self.upload is not None:
385
+ # The temporary folder means nothing to the user; the file is readable even if its type is not indexed.
386
+ return {**base, "repository": None, "upload": self.upload, "picture": self.picture,
387
+ "document": self.document, "files": 1,
388
+ "references": 0, "chunks": len(knowledge.entries), "limited": False}
389
+ return {**base, "repository": str(workspace.root), "upload": None, "picture": None, "document": None,
390
+ "files": counts["repo"],
391
+ "git": (workspace.root / ".git").exists(),
392
+ "references": counts["user"], "chunks": len(knowledge.entries), "limited": knowledge.limited}
393
+
394
+ def forget(self):
395
+ """Delete the answers saved for the open repository."""
396
+ self.claim()
397
+ try:
398
+ if self.memory is not None:
399
+ self.memory.forget()
400
+ if self.chats is not None:
401
+ self.chats.forget()
402
+ if self.semantic is not None:
403
+ self.semantic.forget() # The saved vectors go too; they are rebuilt when the repository is indexed again.
404
+ if self.knowledge is not None:
405
+ self.knowledge.forget()
406
+ return self.summary()
407
+ finally:
408
+ self.release()
409
+
410
+ def reset(self):
411
+ """Start a new chat: the session forgets earlier questions, and later ones are saved under a new id."""
412
+ if self.session is not None:
413
+ self.claim()
414
+ try:
415
+ self.session.reset()
416
+ self.chat_id = new_id()
417
+ finally:
418
+ self.release()
419
+
420
+ def open_chat(self, chat_id):
421
+ """Reopen a saved chat: the page shows it again, and follow-ups remember it as they did when it was live."""
422
+ if self.chats is None or self.session is None:
423
+ raise ValueError("Saved chats are off, or no repository is open.")
424
+ self.claim()
425
+ try:
426
+ chat = self.chats.get(str(chat_id))
427
+ self.session.reset()
428
+ self.session.turns = [(turn["question"], turn["answer"]) for turn in chat["turns"]][-self.session.TURNS:]
429
+ self.chat_id = chat["id"]
430
+ return {"id": chat["id"], "title": chat["title"], "updated": chat["updated"], "turns": chat["turns"],
431
+ "remembered": len(self.session.turns), "memory": self.session.TURNS}
432
+ finally:
433
+ self.release()
434
+
435
+ def delete_chat(self, chat_id):
436
+ """Delete one saved chat and return the chats that remain."""
437
+ if self.chats is None:
438
+ raise ValueError("Saved chats are off, or no repository is open.")
439
+ self.claim()
440
+ try:
441
+ self.chats.delete(str(chat_id))
442
+ if self.chat_id == chat_id:
443
+ self.chat_id = new_id() # Further questions in the open chat start a new saved one.
444
+ return {"chats": self.chats.listing()}
445
+ finally:
446
+ self.release()
447
+
448
+ def ask(self, question):
449
+ """Yield the events of one answer: log lines, streamed text, and a final done or error event."""
450
+ session, chats, chat_id = self.session, self.chats, self.chat_id
451
+ if session is None:
452
+ raise ValueError("Choose a repository or upload a file first.")
453
+ if not isinstance(question, str) or not question.strip():
454
+ raise ValueError("Type a question first.")
455
+ expanded = slash.expand(question) # /trace name and the like; raises ValueError for an unknown command.
456
+ if expanded is None:
457
+ yield {"type": "done", "exit_code": 0, "steps": 0, "answer": slash.help_text(
458
+ ["/undo: undo the last change (with --allow-edits)", "/export: save this chat as Markdown"]),
459
+ "complete": True, "issues": [], "remembered": len(session.turns), "memory": session.TURNS,
460
+ "kept": False, "saved": len(session.memory.notes) if session.memory else 0,
461
+ "chats": chats.listing() if chats is not None else []}
462
+ return
463
+ question = expanded
464
+ self.claim_model()
465
+ # The answer runs on a worker thread; its events reach this request thread, which writes them out, through a queue.
466
+ events = queue.Queue()
467
+ self.sink = events
468
+
469
+ def work():
470
+ """Answer the question, save the chat, and queue the final done or error event."""
471
+ try:
472
+ code = session.ask(question.strip())
473
+ state = session.last_state
474
+ answer = state.get("final_text")
475
+ if chats is not None and answer:
476
+ with contextlib.suppress(OSError): # A chat that cannot be saved must not cost the answer.
477
+ chats.record(chat_id, question, answer, state.get("issues", []))
478
+ events.put({"type": "done", "exit_code": code, "steps": state.get("steps", 0),
479
+ "answer": answer if answer is not None else "",
480
+ "complete": answer is not None, "issues": state.get("issues", []),
481
+ "remembered": len(session.turns), "memory": session.TURNS,
482
+ "kept": session.saved, "saved": len(session.memory.notes) if session.memory else 0,
483
+ "chats": chats.listing() if chats is not None else []})
484
+ except Stopped:
485
+ # Nothing was recorded: a stopped question is not remembered by follow-ups, saved, or kept in a chat.
486
+ events.put({"type": "stopped", "remembered": len(session.turns), "memory": session.TURNS})
487
+ except Exception as exc: # Reported to the page in plain words; the server keeps running.
488
+ if not isinstance(exc, (ValueError, OSError, UnicodeError)):
489
+ errors.report(exc, always=True)
490
+ events.put({"type": "error", "message": errors.friendly(exc)})
491
+ finally:
492
+ # Always sent, even after an error: None tells the loop below that the answer is over.
493
+ events.put(None)
494
+
495
+ threading.Thread(target=work, daemon=True).start()
496
+ try:
497
+ while (event := events.get()) is not None:
498
+ yield event
499
+ finally:
500
+ # Also reached when the page goes away and the generator is closed early, so the app never stays busy.
501
+ self.sink = None
502
+ self.release()
503
+
504
+ def file(self, path, start=1, end=None):
505
+ """Lines of a repository file around a cited range, through the same rules as the agent's reads."""
506
+ if self.workspace is None:
507
+ raise ValueError("Choose a repository or upload a file first.")
508
+ lines = self.workspace.read(path.removeprefix("repo/")).splitlines()
509
+ start = max(1, int(start))
510
+ end = max(start, int(end or start))
511
+ first = max(1, start - FILE_CONTEXT)
512
+ last = min(len(lines), end + FILE_CONTEXT, first + FILE_LINES - 1)
513
+ return {"path": path.removeprefix("repo/"), "start": start, "end": end, "total": len(lines),
514
+ "first": first, "lines": lines[first - 1:last]}
515
+
516
+ def text(self):
517
+ """The whole uploaded file, so the page can save the text read from a picture."""
518
+ if self.workspace is None or self.upload is None:
519
+ raise ValueError("Upload a file first.")
520
+ return {"name": self.upload, "text": self.workspace.read(self.upload)}
521
+
522
+ def opened(self):
523
+ """The open workspace, or ValueError when nothing is open yet."""
524
+ if self.workspace is None:
525
+ raise ValueError("Choose a repository or upload a file first.")
526
+ return self.workspace
527
+
528
+ def selection(self, paths):
529
+ """The files a study aid is about: the chosen ones, or the uploaded file when one is open."""
530
+ return [self.upload] if self.upload is not None and not paths else paths
531
+
532
+ def files(self):
533
+ """Files that can be chosen for a map or flashcards: the same listing the agent sees."""
534
+ names = self.opened().files()
535
+ return {"files": names, "limited": len(names) >= MAX_FILES,
536
+ "limits": {"map": study.MAP_FILES, "flashcards": study.CARD_FILES, "cards": study.CARDS,
537
+ "default_cards": study.DEFAULT_CARDS}}
538
+
539
+ def structure(self, paths):
540
+ """The structure map of the chosen files. Static analysis only, so it needs no model and no waiting turn."""
541
+ workspace, knowledge = self.opened(), self.knowledge
542
+ return study.structure(workspace, knowledge, self.selection(paths))
543
+
544
+ def flashcards(self, paths, count=study.DEFAULT_CARDS, in_arabic=False):
545
+ """Yield the events of making flashcards for the chosen files; the model is busy until they end.
546
+
547
+ in_arabic is set by the Arabic page, so its cards are written in Arabic."""
548
+ workspace = self.opened()
549
+ self.claim_model()
550
+ try:
551
+ yield from study.flashcards(self.model, workspace, self.selection(paths), count, in_arabic=in_arabic)
552
+ except Stopped:
553
+ yield {"type": "stopped"} # The cards already sent stay on the page.
554
+ finally:
555
+ self.release()
556
+
557
+
558
+ def upload_name(name):
559
+ """A safe file name for an uploaded copy, keeping the original name where it can.
560
+
561
+ Only the last part of the name is kept, and characters other than English and Arabic letters, digits, dot,
562
+ dash, and underscore become underscores, so citations such as notes_v2.py:12 stay clickable.
563
+ """
564
+ name = re.split(r"[\\/]", str(name or ""))[-1].strip()
565
+ name = re.sub(r"[^A-Za-z0-9_.\-\u0621-\u064A]", "_", name)[-UPLOAD_NAME_CHARACTERS:]
566
+ if not name.strip("._"):
567
+ raise ValueError("The uploaded file needs a name.")
568
+ if name.startswith("."):
569
+ raise ValueError("Hidden files such as .env cannot be uploaded.")
570
+ return name
571
+
572
+
573
+ def github_repository(address):
574
+ """(owner, name, ssh) for a GitHub repository address, or ValueError.
575
+
576
+ Accepts https://github.com/owner/name (with or without https://, .git, or a trailing /tree/... part) and
577
+ git@github.com:owner/name.git. Addresses carrying a user name, password, or token are refused, so no secret
578
+ can reach the clone's settings or the page's list of recent repositories.
579
+ """
580
+ text = str(address or "").strip()
581
+ ssh = re.fullmatch(r"(?:ssh://)?git@github\.com[:/]([^/\s]+)/([^/\s]+?)/?", text, flags=re.IGNORECASE)
582
+ if ssh:
583
+ owner, name = ssh.groups()
584
+ else:
585
+ url = urlsplit(text if "://" in text else "https://" + text)
586
+ if url.scheme.lower() not in ("https", "http") or "@" in url.netloc:
587
+ raise ValueError("Use a GitHub address such as https://github.com/owner/repository, without a password "
588
+ "or token. Private repositories use the sign-in git already has on this computer.")
589
+ if url.netloc.lower() not in ("github.com", "www.github.com"):
590
+ raise ValueError("Only github.com addresses can be cloned, such as https://github.com/owner/repository.")
591
+ parts = [part for part in url.path.split("/") if part]
592
+ if len(parts) < 2:
593
+ raise ValueError("Include the owner and the repository, such as https://github.com/owner/repository.")
594
+ owner, name = parts[0], parts[1]
595
+ name = name[:-4] if name.lower().endswith(".git") else name
596
+ if not OWNER.fullmatch(owner) or not REPOSITORY.fullmatch(name) or name.strip(".") == "":
597
+ raise ValueError("That does not look like a GitHub repository address.")
598
+ return owner, name, bool(ssh)
599
+
600
+
601
+ def origin_repository(folder):
602
+ """(owner, name) in lower case of the GitHub repository a local clone came from, read from disk only."""
603
+ git = shutil.which("git")
604
+ if git is None or not (folder / ".git").exists():
605
+ return None
606
+ try:
607
+ found = subprocess.run([git, "-C", str(folder), "config", "--get", "remote.origin.url"], capture_output=True,
608
+ text=True, timeout=10, stdin=subprocess.DEVNULL)
609
+ owner, name, _ = github_repository(found.stdout.strip())
610
+ except (OSError, subprocess.SubprocessError, ValueError):
611
+ return None
612
+ return owner.lower(), name.lower()
613
+
614
+
615
+ def folder_bytes(folder):
616
+ """Bytes on disk under folder, counting links as themselves; used to stop a download that grows too large."""
617
+ total = 0
618
+ for root, _dirs, names in os.walk(folder):
619
+ for name in names:
620
+ with contextlib.suppress(OSError):
621
+ total += os.lstat(os.path.join(root, name)).st_size
622
+ return total
623
+
624
+
625
+ def download(owner, name, ssh, target, cancel=None):
626
+ """Clone the latest snapshot of one GitHub repository into target: the only network use in CodeHaven.
627
+
628
+ git gets no password from CodeHaven and may not prompt for one, so only public repositories and the sign-in
629
+ git already has (a credential helper or an SSH key) work. Submodules, Git LFS files, tags, history, hooks,
630
+ and symlinks are left out, and the download stops after CLONE_SECONDS or CLONE_BYTES, or with Stopped once
631
+ cancel, an optional threading.Event, is set. A stopped or failed download leaves nothing behind.
632
+ """
633
+ git = shutil.which("git")
634
+ if git is None:
635
+ raise ValueError("Cloning needs git, which is not installed on this computer.")
636
+ url = f"git@github.com:{owner}/{name}.git" if ssh else f"https://github.com/{owner}/{name}.git"
637
+ target.parent.mkdir(parents=True, exist_ok=True)
638
+ partial = Path(tempfile.mkdtemp(prefix=f".{name}-", dir=target.parent)) # Hidden until the clone is complete.
639
+ env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "GIT_LFS_SKIP_SMUDGE": "1"}
640
+ env.setdefault("GIT_SSH_COMMAND", "ssh -o BatchMode=yes") # Never wait for a passphrase nobody can type.
641
+ # Only the https and ssh transports are allowed, and the clone can run no hooks, LFS filters, or template files.
642
+ command = [git, "-c", "protocol.allow=never", "-c", "protocol.https.allow=always", "-c", "protocol.ssh.allow=always",
643
+ "-c", f"core.hooksPath={os.devnull}", "-c", "core.symlinks=false", "-c", "filter.lfs.required=false",
644
+ "-c", "filter.lfs.smudge=", "-c", "filter.lfs.process=",
645
+ "clone", "--depth", "1", "--single-branch", "--no-tags", "--template=", "--quiet", "--", url, str(partial)]
646
+ try:
647
+ # git's messages go to a temporary file, not a pipe, because nothing reads them while the loop below polls.
648
+ with tempfile.TemporaryFile() as errors:
649
+ process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=errors,
650
+ env=env)
651
+ deadline, stopped = time.monotonic() + CLONE_SECONDS, None
652
+ # Polled rather than waited for, so that both the time limit and the size limit can stop the download.
653
+ while process.poll() is None:
654
+ if cancel is not None and cancel.is_set():
655
+ process.kill()
656
+ process.wait()
657
+ raise Stopped()
658
+ if time.monotonic() > deadline:
659
+ stopped = f"The download took longer than {CLONE_SECONDS // 60} minutes and was stopped."
660
+ elif folder_bytes(partial) > CLONE_BYTES:
661
+ stopped = f"The repository is larger than {CLONE_BYTES // 1_000_000} MB and was not downloaded."
662
+ if stopped:
663
+ process.kill()
664
+ process.wait()
665
+ raise ValueError(stopped)
666
+ time.sleep(0.5)
667
+ errors.seek(0)
668
+ message = errors.read().decode("utf-8", "replace")
669
+ if process.returncode != 0:
670
+ raise ValueError(clone_error(message, owner, name))
671
+ # The finished clone appears under its real name in one step; a failed one never does.
672
+ partial.rename(target)
673
+ except BaseException:
674
+ shutil.rmtree(partial, ignore_errors=True)
675
+ raise
676
+
677
+
678
+ def clone_error(message, owner, name):
679
+ """Turn git's error output into a plain-English message for the page."""
680
+ lowered = message.lower()
681
+ if "could not resolve host" in lowered or "could not resolve hostname" in lowered:
682
+ return "GitHub could not be reached. Check the internet connection, or open a copy already on this computer."
683
+ if any(text in lowered for text in ("repository not found", "authentication failed", "could not read username",
684
+ "permission denied", "terminal prompts disabled")):
685
+ return (f"GitHub did not share github.com/{owner}/{name}: it does not exist, or it is private and git on "
686
+ "this computer is not signed in to an account that can read it. CodeHaven never asks for your "
687
+ "GitHub password. Sign git in (for example with `gh auth login`), or clone it yourself and index "
688
+ "the folder.")
689
+ last = [line.strip() for line in message.splitlines() if line.strip()]
690
+ return "git could not clone the repository" + (f": {last[-1]}" if last else ".")
691
+
692
+
693
+ def directories(path=""):
694
+ """Folders inside path, for choosing a repository. Hidden folders are left out."""
695
+ folder = Path(path).expanduser() if path else Path.home()
696
+ if not folder.is_absolute() or not folder.is_dir():
697
+ raise ValueError("That folder does not exist.")
698
+ folder = folder.resolve()
699
+ entries = []
700
+ try:
701
+ names = sorted(os.scandir(folder), key=lambda entry: entry.name.lower())
702
+ except PermissionError as exc:
703
+ raise ValueError("This folder cannot be opened.") from exc
704
+ for entry in names:
705
+ if entry.name.startswith(".") or not entry.is_dir(follow_symlinks=False):
706
+ continue
707
+ entries.append({"name": entry.name, "path": str(Path(entry.path)),
708
+ "repository": Path(entry.path, ".git").exists()})
709
+ if len(entries) >= DIRECTORY_ENTRIES:
710
+ break
711
+ return {"path": str(folder), "parent": str(folder.parent) if folder.parent != folder else None,
712
+ "repository": (folder / ".git").exists(), "entries": entries}
713
+
714
+
715
+ def make_handler(app, token, port_holder):
716
+ """The request handler class for one app and token. port_holder is filled in once the server knows its port."""
717
+ nonce_holder = {}
718
+
719
+ class Handler(BaseHTTPRequestHandler):
720
+ """Serves the page and its JSON API. Every request must pass authorized() before anything else happens."""
721
+
722
+ server_version = "CodeHaven"
723
+ sys_version = ""
724
+ replying = False # A streamed reply has begun, so a later problem cannot be sent as its own response.
725
+
726
+ def log_message(self, *_args):
727
+ """Log nothing."""
728
+ pass # Requests carry file paths and questions; keep them out of the terminal.
729
+
730
+ def allowed_host(self):
731
+ """Whether the Host header names this server on this machine.
732
+
733
+ A website whose own name is made to resolve to 127.0.0.1 (DNS rebinding) still sends its own name here,
734
+ so it is refused even though the request reaches this server.
735
+ """
736
+ port = port_holder["port"]
737
+ return self.headers.get("Host", "") in (f"127.0.0.1:{port}", f"localhost:{port}")
738
+
739
+ def send(self, status, body, content_type="application/json"):
740
+ """Send a complete response: bytes as they are (the page), anything else as JSON."""
741
+ data = body if isinstance(body, bytes) else json.dumps(body).encode()
742
+ self.send_response(status)
743
+ self.send_header("Content-Type", content_type + "; charset=utf-8")
744
+ self.send_header("Content-Length", str(len(data)))
745
+ self.security_headers()
746
+ self.end_headers()
747
+ self.wfile.write(data)
748
+
749
+ def security_headers(self):
750
+ """Headers on every response: no caching, sniffing, or framing, and only the script with this page's nonce runs."""
751
+ nonce = nonce_holder.get("nonce", "")
752
+ self.send_header("Cache-Control", "no-store")
753
+ self.send_header("X-Content-Type-Options", "nosniff")
754
+ self.send_header("Referrer-Policy", "no-referrer")
755
+ self.send_header("X-Frame-Options", "DENY")
756
+ # Nothing may load from anywhere but this server: the page stays offline even if a link sneaks in.
757
+ self.send_header("Content-Security-Policy",
758
+ f"default-src 'none'; script-src 'nonce-{nonce}'; style-src 'unsafe-inline'; "
759
+ "connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'")
760
+
761
+ def refuse(self, status, message):
762
+ """Send an error as JSON, which the page shows to the user."""
763
+ self.send(status, {"error": message})
764
+
765
+ def authorized(self, query):
766
+ """Check the Host header, then the secret token. Sends a 403 and returns False if either is wrong."""
767
+ if not self.allowed_host():
768
+ self.refuse(403, "Unknown host.")
769
+ return False
770
+ # The page sends the token in a header; only the first page load carries it in the link's query string.
771
+ sent = self.headers.get("X-CodeHaven-Token") or query.get("token", [""])[0]
772
+ # compare_digest takes the same time wherever the first difference is, so timing reveals nothing about the token.
773
+ if not secrets.compare_digest(sent, token):
774
+ self.refuse(403, "Open the link CodeHaven printed in the terminal.")
775
+ return False
776
+ return True
777
+
778
+ def body(self):
779
+ """The request's JSON object. Bodies over REQUEST_BYTES are refused without being read."""
780
+ length = int(self.headers.get("Content-Length") or 0)
781
+ if not 0 <= length <= REQUEST_BYTES: # A negative length would make the read wait for the connection to close.
782
+ self.close_connection = True # The body is not read, so the connection cannot be reused.
783
+ raise ValueError("Request too large.")
784
+ data = json.loads(self.rfile.read(length) or b"{}")
785
+ if not isinstance(data, dict):
786
+ raise ValueError("Request must be a JSON object.")
787
+ return data
788
+
789
+ def do_GET(self):
790
+ """Serve the page itself and the routes that only read."""
791
+ url = urlsplit(self.path)
792
+ query = parse_qs(url.query)
793
+ self.replying = False
794
+ if not self.authorized(query):
795
+ return
796
+ try:
797
+ if url.path == "/":
798
+ # A new nonce for every page load: it goes into the page's script tag and into the policy header.
799
+ nonce_holder["nonce"] = secrets.token_urlsafe(16)
800
+ page = page_text().replace("__NONCE__", nonce_holder["nonce"])
801
+ self.send(200, page.encode(), "text/html")
802
+ elif url.path == "/api/status":
803
+ self.send(200, app.summary())
804
+ elif url.path == "/api/models":
805
+ self.send(200, app.models())
806
+ elif url.path == "/api/files":
807
+ self.send(200, app.files())
808
+ elif url.path == "/api/text":
809
+ self.send(200, app.text())
810
+ elif url.path == "/api/dirs":
811
+ self.send(200, directories(query.get("path", [""])[0]))
812
+ elif url.path == "/api/file":
813
+ self.send(200, app.file(query.get("path", [""])[0], query.get("start", ["1"])[0],
814
+ query.get("end", [""])[0] or None))
815
+ else:
816
+ self.refuse(404, "Not found.")
817
+ except (ValueError, OSError, UnicodeError) as exc:
818
+ self.refuse(400, str(exc))
819
+ except Exception as exc: # Shown on the page in plain words; the traceback goes to this terminal.
820
+ self.unexpected(exc)
821
+
822
+ def unexpected(self, exc):
823
+ """Answer an unexpected problem with a plain message, unless a reply is already under way."""
824
+ errors.report(exc, always=True)
825
+ if not self.replying:
826
+ self.refuse(500, errors.friendly(exc))
827
+
828
+ def upload(self):
829
+ """The raw bytes of an uploaded file. Bodies over the picture limit are refused without being read."""
830
+ length = int(self.headers.get("Content-Length") or 0)
831
+ if not 0 <= length <= ocr.IMAGE_BYTES: # Text files have a smaller limit, checked once the bytes are seen.
832
+ self.close_connection = True # The body is not read, so the connection cannot be reused.
833
+ raise ValueError(f"Only text files up to {MAX_BYTES // 1000} KB, and pictures, notebooks, and PDFs up "
834
+ f"to {ocr.IMAGE_BYTES // 1_000_000} MB, can be uploaded.")
835
+ return self.rfile.read(length)
836
+
837
+ def do_POST(self):
838
+ """Handle an upload, and the JSON routes that open something, change state, or start an answer."""
839
+ url = urlsplit(self.path)
840
+ query = parse_qs(url.query)
841
+ self.replying = False
842
+ # The empty query means a POST must carry the token in its header; one in the address is not accepted.
843
+ if not self.authorized({}):
844
+ return
845
+ try:
846
+ if url.path == "/api/upload":
847
+ self.send(200, app.open_file(query.get("name", [""])[0], self.upload()))
848
+ return
849
+ data = self.body()
850
+ if url.path == "/api/open":
851
+ self.send(200, app.open(str(data.get("path", "")), data.get("excludes") or ()))
852
+ elif url.path == "/api/clone":
853
+ self.send(200, app.clone(str(data.get("address", ""))))
854
+ elif url.path == "/api/model":
855
+ self.send(200, app.use_model(str(data.get("name", ""))))
856
+ elif url.path == "/api/forget":
857
+ self.send(200, app.forget())
858
+ elif url.path == "/api/chat":
859
+ self.send(200, app.open_chat(data.get("id", "")))
860
+ elif url.path == "/api/chat/delete":
861
+ self.send(200, app.delete_chat(data.get("id", "")))
862
+ elif url.path == "/api/reset":
863
+ app.reset()
864
+ self.send(200, {"ok": True})
865
+ elif url.path == "/api/decide":
866
+ self.send(200, app.decide(data.get("apply") is True))
867
+ elif url.path == "/api/undo":
868
+ self.send(200, app.undo())
869
+ elif url.path == "/api/stop":
870
+ self.send(200, app.stop())
871
+ elif url.path == "/api/ask":
872
+ self.stream(app.ask(data.get("question", "")))
873
+ elif url.path == "/api/map":
874
+ self.send(200, app.structure(data.get("paths") or []))
875
+ elif url.path == "/api/flashcards":
876
+ self.stream(app.flashcards(data.get("paths") or [], data.get("count", study.DEFAULT_CARDS),
877
+ in_arabic=data.get("language") == "ar"), drain=False)
878
+ else:
879
+ self.refuse(404, "Not found.")
880
+ except Busy as exc:
881
+ self.refuse(409, str(exc))
882
+ except (ValueError, OSError, UnicodeError) as exc:
883
+ self.refuse(400, str(exc))
884
+ except Exception as exc:
885
+ self.unexpected(exc)
886
+
887
+ def stream(self, events, drain=True):
888
+ """Send events as lines of JSON. If the page goes away, an answer is drained so its worker thread
889
+ can finish; work done by the generator itself, such as flashcards, is stopped instead."""
890
+ first = next(events) # Raises Busy or ValueError before any response is sent.
891
+ self.replying = True # From here on, a problem is reported as an event, not as a second response.
892
+ self.send_response(200)
893
+ self.send_header("Content-Type", "application/x-ndjson; charset=utf-8")
894
+ self.security_headers()
895
+ self.end_headers()
896
+ try:
897
+ self.wfile.write(json.dumps(first).encode() + b"\n")
898
+ self.wfile.flush()
899
+ for event in events:
900
+ self.wfile.write(json.dumps(event).encode() + b"\n")
901
+ self.wfile.flush()
902
+ except (BrokenPipeError, ConnectionResetError):
903
+ if drain:
904
+ for _ in events: # The page closed; let the answer finish so the next question can start.
905
+ pass
906
+ except Exception as exc: # Work such as flashcards failed part way: the page gets a plain error event.
907
+ if not isinstance(exc, (ValueError, OSError, UnicodeError)):
908
+ errors.report(exc, always=True)
909
+ with contextlib.suppress(OSError):
910
+ self.wfile.write(json.dumps({"type": "error", "fatal": True, "message": errors.friendly(exc)}).encode()
911
+ + b"\n")
912
+ self.wfile.flush()
913
+ finally:
914
+ events.close() # Releases the model if the generator was left unfinished.
915
+
916
+ return Handler
917
+
918
+
919
+ def make_server(app, port=0):
920
+ """A server bound to 127.0.0.1, its secret token, and its URL. port=0 picks a free port."""
921
+ token = secrets.token_urlsafe(24)
922
+ port_holder = {}
923
+ server = ThreadingHTTPServer(("127.0.0.1", port), make_handler(app, token, port_holder))
924
+ # Request threads must not keep the program alive once the server is stopped.
925
+ server.daemon_threads = True
926
+ # With port=0 the port is known only now; the handler reads it for its Host check.
927
+ port_holder["port"] = server.server_address[1]
928
+ return server, token, f"http://127.0.0.1:{port_holder['port']}/?token={token}"
929
+
930
+
931
+ def serve(model, *, port=0, open_browser=True, repository=None, max_steps=12, retrieval_budget=4000, excludes=(),
932
+ allow_clone=False, clone_folder=None, remember=False, memory_folder=None, embed_model=None, index_folder=None,
933
+ chats_folder=None, allow_edits=False):
934
+ """Run the GUI until Ctrl+C. Returns an exit code like the CLI's."""
935
+ app = App(model, max_steps=max_steps, retrieval_budget=retrieval_budget, excludes=excludes,
936
+ allow_clone=allow_clone, clone_folder=clone_folder, remember=remember, memory_folder=memory_folder,
937
+ embed_model=embed_model, index_folder=index_folder, chats_folder=chats_folder, retry_unverified=True,
938
+ allow_edits=allow_edits)
939
+ if repository:
940
+ summary = app.open(str(Path(repository).expanduser().resolve()))
941
+ print(f"Indexed {summary['files']} files from {summary['repository']}.")
942
+ server, _, url = make_server(app, port)
943
+ print(f"CodeHaven is running at:\n {url}\nOnly this machine can reach it. Press Ctrl+C to stop.", flush=True)
944
+ if allow_clone:
945
+ print(f"Cloning from GitHub is on: git may download repositories you ask for into {app.clone_folder}. "
946
+ "Nothing is uploaded. Restart without --allow-clone to stay fully offline.", flush=True)
947
+ if remember:
948
+ print("Long-term memory is on: checked answers and your chats are saved on this computer, so answers can be "
949
+ "recalled and chats reopened in later sessions. Restart with --no-remember to save nothing.", flush=True)
950
+ print(f"Meaning search is on, using the local embedding model {embed_model}." if embed_model else
951
+ "Meaning search is off: answers use key-word search. To turn it on, install a local embedding model once "
952
+ "while online (ollama pull nomic-embed-text).", flush=True)
953
+ if open_browser:
954
+ webbrowser.open(url)
955
+
956
+ def stop(_signum, _frame):
957
+ """Treat a kill signal like Ctrl+C, so the cleanup below still runs."""
958
+ raise KeyboardInterrupt # A plain kill also deletes the uploaded file's temporary copy.
959
+ signal.signal(signal.SIGTERM, stop)
960
+ try:
961
+ server.serve_forever()
962
+ except KeyboardInterrupt:
963
+ print("\nStopped.")
964
+ finally:
965
+ server.server_close()
966
+ app.close()
967
+ return 0