-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1425 lines (1292 loc) · 59.1 KB
/
Copy pathserver.py
File metadata and controls
1425 lines (1292 loc) · 59.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Local server for Codebase Graph: static files + sandboxed file/notes/chats/LLM API.
Usage:
python generate.py --root /path/to/repo
python server.py # http://127.0.0.1:8765
python server.py --port 8765
Serves:
GET/PUT /api/file?path=rel/path
GET /api/media?path=rel/path # binary images for Overview preview
GET /api/project-icon # favicon/logo if present under repo root
GET/PUT /api/notes
GET /api/notes/history?key=&limit=
POST /api/notes/restore # { id: revisionId }
POST /api/notes/history/delete # { id: revisionId }
POST /api/notes/document # bulk LLM document files → path notes
GET /api/notes/document/status
GET/PUT /api/chats # GET ?cursorLimit=&cursorOffset= (top-K Cursor hot set)
GET /api/chats/cursor?q=&limit=&offset= # search / paginate Cursor imports
GET /api/chats/thread?path=&thread= # fetch one thread into working set
GET /api/chats/history?path=&thread=&limit=
POST /api/chats/restore # { id: revisionId }
POST /api/chats/import # cursor | langsmith → threads + trace
POST /api/langsmith/validate # check api key + project
POST /api/llm/chat # optional LangSmith wrap when backends.langsmith.tracing
GET /api/workspaces # current + known scanned repos
POST /api/workspaces/open # { root, regenerate? }
GET /api/meta
GET /api/crg/status
POST /api/crg/build
POST /api/crg/update
GET /api/crg/impact?path=
GET /api/crg/query?pattern=&symbol=
GET /api/crg/relations?path=
GET /api/crg/context?path=
GET /api/crg/symbols?path= # Overview function/class blocks
GET /api/crg/search?q=&kind=&limit= # Symbol FTS / semantic (Phase 2)
GET /api/crg/trace?symbol= # Callers/callees (Phase 3)
POST /api/crg/embed # Vector embeddings for semantic search
GET /api/github/status
POST /api/github/sync
GET /api/github/branches
GET /api/github/diff?ref=&base=
GET /api/git/status
POST /api/git/switch # { branch, stashIfDirty?, refreshGraph? }
POST /api/git/stash # confirm-gated from UI
POST /api/git/fetch
POST /api/git/rebase # { onto? } default @{upstream}
GET /api/git/file-log?path=&limit=
GET /api/git/file-show?path=&commit=
GET /api/git/activity?path=&days=&buckets= # Overview commit bars / 30d stats
GET /api/graphs/caches
POST /api/graphs/cache # save current branch graph
POST /api/graphs/restore # load cache or regenerate for HEAD
GET/POST /api/snapshots
GET /api/snapshots/compare?a=&b=
POST /api/snapshots/delete
GET/PUT /api/backends # claude-context + Serena + CodeGraph + document/github/langsmith
GET /api/claude-context/status
POST /api/claude-context/index
GET /api/serena/status
POST /api/serena/refine
GET /api/semantic/search?q=&backend=&limit= # routes CRG vs claude-context (+ optional Serena refine)
GET /data.json # active workspace graph
Static: ./dist if present, else project root (and Vite proxies /api in dev)
"""
from __future__ import annotations
import argparse
import json
import mimetypes
import os
import subprocess
import sys
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
import backends_config
import chat_import
import claude_context_bridge
import crg_bridge
import document_notes
import github_notes
import git_ops
import branch_cache
import llm_chat
import langsmith_bridge
import notes_store
import serena_bridge
import snapshots_store
import workspace as workspace_mod
TOOL_DIR = Path(__file__).resolve().parent
MAX_FILE_BYTES = 2_000_000
MAX_MEDIA_BYTES = 25_000_000
# Cursor imports make chats.json large; allow big JSON API bodies (chats PUT).
MAX_JSON_BODY_BYTES = 64_000_000
IMAGE_EXTS = {
".png",
".jpg",
".jpeg",
".gif",
".webp",
".bmp",
".ico",
".svg",
".avif",
}
PROJECT_ICON_CANDIDATES = (
"favicon.ico",
"favicon.png",
"favicon.svg",
"apple-touch-icon.png",
"logo.svg",
"logo.png",
"icon.png",
"icon.svg",
"assets/favicon.ico",
"assets/logo.svg",
"assets/logo.png",
"docs/favicon.ico",
"public/favicon.ico",
)
LLM_TIMEOUT_SEC = 300
def stamp_git_metadata(obj: dict, *, repo: Path | None = None) -> dict:
"""Attach git.branch/commit to a note or thread if missing."""
if not isinstance(obj, dict):
return obj
existing = obj.get("git")
if isinstance(existing, dict) and (existing.get("branch") or existing.get("commit")):
return obj
try:
ref = git_ops.git_ref(repo or root())
except Exception: # noqa: BLE001
return obj
if not ref.get("commit") and not ref.get("branch"):
return obj
return {**obj, "git": {"branch": ref.get("branch") or "", "commit": ref.get("commit") or ""}}
def stamp_notes_document(notes: dict) -> dict:
if not isinstance(notes, dict):
return notes
out = {}
for key, note in notes.items():
if isinstance(note, dict):
out[key] = stamp_git_metadata(note)
else:
out[key] = note
return out
def stamp_chats_document(chats: dict) -> dict:
if not isinstance(chats, dict):
return chats
by_path = chats.get("byPath")
if not isinstance(by_path, dict):
return chats
next_by = {}
for path, threads in by_path.items():
if not isinstance(threads, list):
next_by[path] = threads
continue
next_by[path] = [
stamp_git_metadata(t) if isinstance(t, dict) else t for t in threads
]
return {**chats, "byPath": next_by}
def send_image_bytes(handler: BaseHTTPRequestHandler, path: Path) -> bool:
"""Write an image file response. Returns False if too large."""
raw = path.read_bytes()
if len(raw) > MAX_MEDIA_BYTES:
return False
ctype = mimetypes.guess_type(str(path))[0] or "application/octet-stream"
if path.suffix.lower() == ".svg":
ctype = "image/svg+xml"
handler.send_response(200)
handler.send_header("Content-Type", ctype)
handler.send_header("Content-Length", str(len(raw)))
handler.send_header("Cache-Control", "private, max-age=60")
handler.end_headers()
handler.wfile.write(raw)
return True
def root() -> Path:
return workspace_mod.get().root
def notes_path() -> Path:
return workspace_mod.get().notes_path
def notes_db_path() -> Path:
return workspace_mod.get().notes_db_path
def chats_path() -> Path:
return workspace_mod.get().chats_path
def data_path() -> Path:
return workspace_mod.get().data_path
def cursor_project_slug() -> str:
"""Cursor ~/.cursor/projects/<slug> for the scanned repo."""
return notes_store.cursor_slug_from_path(root())
def safe_resolve(rel: str) -> Path | None:
rel = (rel or "").replace("\\", "/").lstrip("/")
base = root()
if rel in ("", "."):
return base
if ".." in rel.split("/"):
return None
candidate = (base / rel).resolve()
try:
candidate.relative_to(base)
except ValueError:
return None
return candidate
def send_workspace_json(handler: BaseHTTPRequestHandler, path: Path, *, missing: str) -> None:
if not path.is_file():
json_response(handler, 404, {"error": missing})
return
raw = path.read_bytes()
handler.send_response(200)
handler.send_header("Content-Type", "application/json; charset=utf-8")
handler.send_header("Content-Length", str(len(raw)))
handler.send_header("Cache-Control", "no-store")
handler.end_headers()
handler.wfile.write(raw)
def _job_blocks_switch() -> str | None:
crg = crg_bridge.job_snapshot()
if crg.get("running"):
return f"CRG job running ({crg.get('op') or 'job'}) — wait or cancel before switching repos"
doc = document_notes.job_snapshot()
if doc.get("running"):
return "document job running — wait before switching repos"
return None
def json_response(handler: BaseHTTPRequestHandler, status: int, payload: dict) -> None:
body = json.dumps(payload).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json; charset=utf-8")
handler.send_header("Content-Length", str(len(body)))
handler.send_header("Cache-Control", "no-store")
handler.end_headers()
handler.wfile.write(body)
def read_body(handler: BaseHTTPRequestHandler, *, max_bytes: int | None = None) -> bytes:
length = int(handler.headers.get("Content-Length") or 0)
if length <= 0:
return b""
limit = MAX_JSON_BODY_BYTES if max_bytes is None else max_bytes
if length > limit:
# Drain so the client still receives a clean HTTP error instead of a reset.
remaining = length
while remaining > 0:
chunk = handler.rfile.read(min(65_536, remaining))
if not chunk:
break
remaining -= len(chunk)
raise ValueError(f"body too large ({length} bytes; limit {limit})")
return handler.rfile.read(length)
def _format_llm_http_error(
code: int, detail: str, *, provider: str, model: str, url: str
) -> str:
msg = detail
try:
parsed = json.loads(detail)
err = parsed.get("error")
if isinstance(err, dict):
msg = err.get("message") or msg
elif isinstance(err, str):
msg = err
except (json.JSONDecodeError, TypeError):
pass
text = str(msg or detail or "").strip()
lower = text.lower()
if code == 404:
# llama.cpp returns {"message":"File Not Found","type":"not_found_error"} for bad paths.
if "file not found" in lower or "not_found_error" in lower:
return (
f"LLM endpoint not found (HTTP 404) at {url}. "
"For llama.cpp use Chat provider Local with base URL http://127.0.0.1:8080/v1. "
"Ollama uses provider Ollama and http://127.0.0.1:11434."
)
if provider == "ollama":
pull_name = model.split(":")[0] if model else "your-model"
return (
f"Ollama model not found: {model or '(none)'}. "
f"Pull it with: ollama pull {pull_name}"
)
return (
f"LLM endpoint not found (HTTP 404). "
f"Check Settings → AI base URL. Tried: {url}"
)
if code == 401:
return "LLM authentication failed (HTTP 401). Check your API key in Settings → AI."
return f"LLM HTTP {code}: {text or detail}"
def proxy_llm_chat(payload: dict) -> dict:
provider = (payload.get("provider") or "openai").strip().lower()
base = (payload.get("baseUrl") or "").rstrip("/")
model = payload.get("model") or ""
messages = payload.get("messages")
if not isinstance(messages, list) or not messages:
raise ValueError("messages required")
if not model:
raise ValueError("model required")
if not base:
raise ValueError("baseUrl required")
def _call() -> dict:
built = llm_chat.build_chat_request(payload)
url = built["url"]
headers = built["headers"]
body = json.dumps(built["body"]).encode("utf-8")
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
try:
with urllib.request.urlopen(req, timeout=LLM_TIMEOUT_SEC) as resp:
raw = resp.read().decode("utf-8")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")[:800]
raise RuntimeError(
_format_llm_http_error(
exc.code,
detail or exc.reason,
provider=provider,
model=model,
url=url,
)
) from exc
except urllib.error.URLError as exc:
raise RuntimeError(f"LLM unreachable: {exc.reason}") from exc
data = json.loads(raw)
if provider == "ollama":
msg = data.get("message") or {}
content, reasoning = llm_chat.split_reasoning_from_message(msg, msg.get("content") or "")
out = {"content": content, "raw": data}
if reasoning:
out["reasoning"] = reasoning
return out
choices = data.get("choices") or []
if not choices:
raise RuntimeError("LLM returned no choices")
message = choices[0].get("message") or {}
content, reasoning = llm_chat.split_reasoning_from_message(message, message.get("content") or "")
out = {"content": content, "raw": data}
if reasoning:
out["reasoning"] = reasoning
return out
ls_cfg = backends_config.load_backends().get("langsmith") or {}
return langsmith_bridge.wrap_llm_call(
cfg=ls_cfg if isinstance(ls_cfg, dict) else {},
model=model,
messages=messages,
call=_call,
)
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt: str, *args) -> None:
sys.stderr.write("%s - %s\n" % (self.address_string(), fmt % args))
def do_OPTIONS(self) -> None:
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
def do_GET(self) -> None:
parsed = urlparse(self.path)
if parsed.path == "/api/meta":
data = {}
dp = data_path()
if dp.is_file():
try:
data = json.loads(dp.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
pass
return json_response(
self,
200,
{
"root_path": str(root()),
"root_name": data.get("root_name") or root().name,
"stats": data.get("stats"),
"generated_at": data.get("generated_at"),
"git": git_ops.status(root()),
"workspace": workspace_mod.summary(),
},
)
if parsed.path == "/api/workspaces":
return json_response(
self,
200,
{
"ok": True,
"current": workspace_mod.summary(),
"workspaces": workspace_mod.list_known(),
},
)
if parsed.path == "/api/notes":
if notes_path().is_file():
try:
notes = json.loads(notes_path().read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
return json_response(self, 500, {"error": str(exc)})
else:
notes = {}
return json_response(self, 200, {"notes": notes})
if parsed.path == "/api/notes/history":
qs = parse_qs(parsed.query)
key = unquote((qs.get("key") or [""])[0])
try:
limit = int((qs.get("limit") or ["50"])[0])
except ValueError:
limit = 50
try:
history = notes_store.list_history(key, limit=limit, db_path=notes_db_path())
except OSError as exc:
return json_response(self, 500, {"error": str(exc)})
return json_response(self, 200, {"key": key, "history": history})
if parsed.path == "/api/notes/document/status":
return json_response(self, 200, {"job": document_notes.job_snapshot()})
if parsed.path == "/api/github/status":
return json_response(self, 200, github_notes.status(root()))
if parsed.path == "/api/github/branches":
return json_response(self, 200, github_notes.list_branches(root()))
if parsed.path == "/api/git/status":
return json_response(self, 200, github_notes.git_status(root()))
if parsed.path == "/api/git/file-log":
qs = parse_qs(parsed.query)
rel = unquote((qs.get("path") or [""])[0])
try:
limit = int((qs.get("limit") or ["20"])[0])
except ValueError:
limit = 20
return json_response(self, 200, git_ops.file_log(root(), rel, limit=limit))
if parsed.path == "/api/git/activity":
qs = parse_qs(parsed.query)
rel = unquote((qs.get("path") or [""])[0])
try:
days = int((qs.get("days") or ["30"])[0])
except ValueError:
days = 30
try:
buckets = int((qs.get("buckets") or ["12"])[0])
except ValueError:
buckets = 12
result = git_ops.activity(root(), rel, days=days, buckets=buckets)
return json_response(self, 200 if result.get("ok") else 400, result)
if parsed.path == "/api/git/file-show":
qs = parse_qs(parsed.query)
rel = unquote((qs.get("path") or [""])[0])
commit = unquote((qs.get("commit") or [""])[0])
result = git_ops.file_show(root(), rel, commit)
return json_response(self, 200 if result.get("ok") else 404, result)
if parsed.path == "/api/graphs/caches":
return json_response(self, 200, branch_cache.list_caches())
if parsed.path == "/api/github/diff":
qs = parse_qs(parsed.query)
ref = unquote((qs.get("ref") or [""])[0])
base = unquote((qs.get("base") or ["HEAD"])[0]) or "HEAD"
if not ref:
return json_response(self, 400, {"error": "ref required"})
return json_response(self, 200, github_notes.diff_branch(root(), ref, base=base))
if parsed.path == "/api/snapshots":
return json_response(self, 200, snapshots_store.list_snapshots())
if parsed.path == "/api/snapshots/compare":
qs = parse_qs(parsed.query)
a = unquote((qs.get("a") or [""])[0])
b = unquote((qs.get("b") or [""])[0])
if not a or not b:
return json_response(self, 400, {"error": "a and b snapshot ids required"})
return json_response(self, 200, snapshots_store.compare(a, b))
if parsed.path == "/api/chats":
qs = parse_qs(parsed.query)
cursor_limit = notes_store.CURSOR_HOT_LIMIT
cursor_offset = 0
raw_limit = (qs.get("cursorLimit") or qs.get("cursor_limit") or [None])[0]
raw_offset = (qs.get("cursorOffset") or qs.get("cursor_offset") or ["0"])[0]
if raw_limit is not None and str(raw_limit).strip().lower() in ("all", "none", "-1"):
cursor_limit = None
elif raw_limit is not None:
try:
cursor_limit = max(0, int(raw_limit))
except ValueError:
cursor_limit = notes_store.CURSOR_HOT_LIMIT
try:
cursor_offset = max(0, int(raw_offset))
except ValueError:
cursor_offset = 0
try:
chats = notes_store.ensure_chats_db(
chats_path(),
db_path=notes_db_path(),
cursor_limit=cursor_limit,
cursor_offset=cursor_offset,
cursor_project=cursor_project_slug(),
)
except OSError as exc:
return json_response(self, 500, {"error": str(exc)})
return json_response(self, 200, {"chats": chats})
if parsed.path == "/api/chats/cursor":
qs = parse_qs(parsed.query)
q = unquote((qs.get("q") or qs.get("query") or [""])[0])
try:
limit = int((qs.get("limit") or ["20"])[0])
except ValueError:
limit = 20
try:
offset = int((qs.get("offset") or ["0"])[0])
except ValueError:
offset = 0
try:
notes_store.ensure_chats_db(chats_path(), db_path=notes_db_path())
result = notes_store.search_cursor_threads(
query=q,
limit=limit,
offset=offset,
db_path=notes_db_path(),
cursor_project=cursor_project_slug(),
)
except OSError as exc:
return json_response(self, 500, {"error": str(exc)})
return json_response(self, 200, result)
if parsed.path == "/api/chats/thread":
qs = parse_qs(parsed.query)
path_key = unquote((qs.get("path") or [""])[0])
thread_id = unquote((qs.get("thread") or [""])[0])
if not thread_id:
return json_response(self, 400, {"error": "thread required"})
try:
notes_store.ensure_chats_db(chats_path(), db_path=notes_db_path())
found = notes_store.get_chat_thread(
path_key, thread_id, db_path=notes_db_path()
)
except OSError as exc:
return json_response(self, 500, {"error": str(exc)})
if not found:
return json_response(self, 404, {"error": "thread not found"})
return json_response(self, 200, found)
if parsed.path == "/api/chats/history":
qs = parse_qs(parsed.query)
path_key = unquote((qs.get("path") or [""])[0])
thread_id = unquote((qs.get("thread") or [""])[0]) or None
try:
limit = int((qs.get("limit") or ["50"])[0])
except ValueError:
limit = 50
try:
history = notes_store.list_chat_history(
path_key,
thread_id=thread_id,
limit=limit,
db_path=notes_db_path(),
)
except OSError as exc:
return json_response(self, 500, {"error": str(exc)})
return json_response(
self,
200,
{"path": path_key, "thread": thread_id, "history": history},
)
if parsed.path == "/api/file":
qs = parse_qs(parsed.query)
rel = unquote((qs.get("path") or [""])[0])
path = safe_resolve(rel)
if path is None:
return json_response(self, 400, {"error": "invalid path"})
if not path.is_file():
return json_response(self, 404, {"error": "not a file"})
try:
raw = path.read_bytes()
except OSError as exc:
return json_response(self, 500, {"error": str(exc)})
if len(raw) > MAX_FILE_BYTES:
return json_response(self, 413, {"error": "file too large to edit in panel"})
try:
text = raw.decode("utf-8")
except UnicodeDecodeError:
return json_response(self, 415, {"error": "binary or non-UTF-8 file"})
return json_response(self, 200, {"path": rel, "content": text})
if parsed.path == "/api/media":
qs = parse_qs(parsed.query)
rel = unquote((qs.get("path") or [""])[0])
path = safe_resolve(rel)
if path is None:
return json_response(self, 400, {"error": "invalid path"})
if not path.is_file():
return json_response(self, 404, {"error": "not a file"})
if path.suffix.lower() not in IMAGE_EXTS:
return json_response(self, 415, {"error": "not a supported image type"})
try:
if not send_image_bytes(self, path):
return json_response(self, 413, {"error": "image too large to preview"})
except OSError as exc:
return json_response(self, 500, {"error": str(exc)})
return
if parsed.path == "/api/project-icon":
for rel in PROJECT_ICON_CANDIDATES:
path = safe_resolve(rel)
if path is None or not path.is_file():
continue
if path.suffix.lower() not in IMAGE_EXTS:
continue
try:
if send_image_bytes(self, path):
return
except OSError:
continue
return json_response(self, 404, {"error": "no project icon"})
if parsed.path == "/api/crg/status":
try:
payload = crg_bridge.status(root())
# Ensure job is always present for Settings polling
if "job" not in payload:
payload["job"] = crg_bridge.job_snapshot()
payload["bridge"] = "async-job-v1"
return json_response(self, 200, payload)
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ready": False, "error": str(exc)})
if parsed.path == "/api/crg/impact":
qs = parse_qs(parsed.query)
rel = unquote((qs.get("path") or [""])[0])
try:
depth = int((qs.get("depth") or ["2"])[0])
except ValueError:
depth = 2
try:
return json_response(self, 200, crg_bridge.impact(root(), rel, depth=depth))
except FileNotFoundError as exc:
return json_response(self, 503, {"ok": False, "error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
if parsed.path == "/api/crg/query":
qs = parse_qs(parsed.query)
pattern = unquote((qs.get("pattern") or [""])[0])
symbol = unquote((qs.get("symbol") or qs.get("target") or [""])[0])
try:
return json_response(self, 200, crg_bridge.query(root(), pattern, symbol))
except FileNotFoundError as exc:
return json_response(self, 503, {"ok": False, "error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
if parsed.path == "/api/crg/relations":
qs = parse_qs(parsed.query)
rel = unquote((qs.get("path") or [""])[0])
try:
return json_response(self, 200, crg_bridge.one_hop_file_edges(root(), rel))
except FileNotFoundError as exc:
return json_response(self, 503, {"ok": False, "error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
if parsed.path == "/api/crg/context":
qs = parse_qs(parsed.query)
rel = unquote((qs.get("path") or [""])[0])
try:
text = crg_bridge.compact_context_for_ai(root(), rel)
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
return json_response(self, 200, {"ok": True, "path": rel, "context": text})
if parsed.path == "/api/crg/symbols":
qs = parse_qs(parsed.query)
rel = unquote((qs.get("path") or [""])[0])
with_body = (qs.get("body") or ["1"])[0] not in ("0", "false", "no")
try:
if with_body:
payload = crg_bridge.blocks_for_file(root(), rel)
else:
payload = crg_bridge.symbols_for_file(root(), rel)
return json_response(self, 200, payload)
except FileNotFoundError as exc:
return json_response(self, 503, {"ok": False, "error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
if parsed.path == "/api/crg/search":
qs = parse_qs(parsed.query)
q = unquote((qs.get("q") or qs.get("query") or [""])[0])
kind = unquote((qs.get("kind") or [""])[0]) or None
try:
limit = int((qs.get("limit") or ["30"])[0])
except ValueError:
limit = 30
try:
return json_response(
self, 200, crg_bridge.search_symbols(root(), q, kind=kind, limit=limit)
)
except FileNotFoundError as exc:
return json_response(self, 503, {"ok": False, "error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
if parsed.path == "/api/crg/trace":
qs = parse_qs(parsed.query)
symbol = unquote((qs.get("symbol") or qs.get("target") or [""])[0])
try:
return json_response(self, 200, crg_bridge.trace_symbol(root(), symbol))
except FileNotFoundError as exc:
return json_response(self, 503, {"ok": False, "error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
if parsed.path == "/api/backends":
return json_response(self, 200, {"backends": backends_config.public_backends()})
if parsed.path == "/api/claude-context/status":
try:
return json_response(self, 200, claude_context_bridge.status(root()))
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
if parsed.path == "/api/serena/status":
try:
return json_response(self, 200, serena_bridge.status(root()))
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
if parsed.path == "/api/semantic/search":
qs = parse_qs(parsed.query)
q = unquote((qs.get("q") or qs.get("query") or [""])[0])
backend = unquote((qs.get("backend") or ["crg"])[0]).strip().lower() or "crg"
refine = (qs.get("refine") or ["0"])[0] not in ("0", "false", "no")
try:
limit = int((qs.get("limit") or ["24"])[0])
except ValueError:
limit = 24
try:
if backend in ("claude-context", "claude_context", "cc"):
payload = claude_context_bridge.search(root(), q, limit=limit)
else:
payload = crg_bridge.search_symbols(root(), q, limit=limit)
results = payload.get("results") if isinstance(payload, dict) else []
if refine and isinstance(results, list) and results:
refined = serena_bridge.refine_hits(root(), results)
payload = {
**(payload if isinstance(payload, dict) else {}),
"results": refined.get("results") or results,
"serena": {
"refined": bool(refined.get("refined")),
"reason": refined.get("reason"),
},
}
return json_response(self, 200, payload)
except FileNotFoundError as exc:
return json_response(self, 503, {"ok": False, "error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
if parsed.path == "/data.json":
return send_workspace_json(self, data_path(), missing="data.json missing — generate.py --root or Settings → Open")
if parsed.path == "/notes.json":
np = notes_path()
if not np.is_file():
body = b"{}\n"
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
return
return send_workspace_json(self, np, missing="notes.json missing")
return self.serve_static(parsed.path)
def do_POST(self) -> None:
parsed = urlparse(self.path)
try:
raw = read_body(self)
payload = json.loads(raw.decode("utf-8") or "{}")
except (ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc:
return json_response(self, 400, {"error": f"bad json: {exc}"})
if parsed.path == "/api/workspaces/open":
blocked = _job_blocks_switch()
if blocked:
return json_response(self, 409, {"ok": False, "error": blocked})
raw_root = payload.get("root") or payload.get("path")
if not isinstance(raw_root, str) or not raw_root.strip():
return json_response(self, 400, {"ok": False, "error": "root required"})
regenerate = bool(payload.get("regenerate"))
result = workspace_mod.open_root(raw_root.strip(), regenerate=regenerate)
return json_response(self, 200 if result.get("ok") else 400, result)
if parsed.path == "/api/llm/chat":
try:
result = proxy_llm_chat(payload)
except ValueError as exc:
return json_response(self, 400, {"error": str(exc)})
except RuntimeError as exc:
return json_response(self, 502, {"error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"error": str(exc)})
return json_response(self, 200, result)
if parsed.path == "/api/crg/build":
skip_flows = payload.get("skipFlows", True)
try:
result = crg_bridge.start_job(root(), "build", skip_flows=bool(skip_flows))
except FileNotFoundError as exc:
return json_response(self, 503, {"ok": False, "error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
return json_response(self, 200, result)
if parsed.path == "/api/crg/update":
skip_flows = payload.get("skipFlows", True)
try:
result = crg_bridge.start_job(root(), "update", skip_flows=bool(skip_flows))
except FileNotFoundError as exc:
return json_response(self, 503, {"ok": False, "error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
return json_response(self, 200, result)
if parsed.path == "/api/crg/embed":
provider = str(payload.get("provider") or "local")
model = payload.get("model")
try:
result = crg_bridge.start_job(
root(),
"embed",
provider=provider,
model=str(model) if model else None,
)
except FileNotFoundError as exc:
return json_response(self, 503, {"ok": False, "error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
return json_response(self, 200, result)
if parsed.path == "/api/claude-context/index":
force = bool(payload.get("force"))
try:
return json_response(self, 200, claude_context_bridge.index(root(), force=force))
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
if parsed.path == "/api/serena/refine":
hits = payload.get("hits")
if not isinstance(hits, list):
return json_response(self, 400, {"error": "hits must be an array"})
try:
return json_response(self, 200, serena_bridge.refine_hits(root(), hits))
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
if parsed.path == "/api/notes/document":
mode = str(payload.get("mode") or "missing")
paths = payload.get("paths")
if paths is not None and not isinstance(paths, list):
return json_response(self, 400, {"error": "paths must be an array"})
directory = payload.get("directory")
if directory is not None and not isinstance(directory, str):
return json_response(self, 400, {"error": "directory must be a string"})
llm = payload.get("llm") if isinstance(payload.get("llm"), dict) else {}
# Prefer client LLM settings; fill model from backends.document if empty.
# Document reasoning is its own backends field — never inherit chat effort.
doc_cfg = backends_config.load_backends().get("document") or {}
llm = {k: v for k, v in llm.items() if k not in ("reasoningEffort", "reasoning_effort")}
if doc_cfg.get("generator_model") and not llm.get("model"):
llm = {**llm, "model": doc_cfg["generator_model"]}
doc_effort = str(doc_cfg.get("reasoning_effort") or "").strip().lower()
if doc_effort in ("low", "medium", "high"):
llm = {**llm, "reasoningEffort": doc_effort}
try:
result = document_notes.start_document_job(
root(),
mode=mode,
paths=[str(p) for p in paths] if paths else None,
directory=directory.strip() if isinstance(directory, str) and directory.strip() else None,
llm_settings=llm,
llm_chat=proxy_llm_chat,
)
except ValueError as exc:
return json_response(self, 400, {"ok": False, "error": str(exc)})
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
status = 200 if result.get("ok") else 409
return json_response(self, status, result)
if parsed.path == "/api/github/sync":
types = payload.get("types")
if types is not None and not isinstance(types, list):
return json_response(self, 400, {"error": "types must be an array"})
state = str(payload.get("state") or "all")
try:
limit = int(payload.get("limit") or 30)
except (TypeError, ValueError):
limit = 30
try:
result = github_notes.sync(
root(),
types=[str(t) for t in types] if types else None,
state=state,
limit=limit,
)
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
return json_response(self, 200 if result.get("ok") else 502, result)
if parsed.path == "/api/git/switch":
branch = str(payload.get("branch") or "").strip()
if not branch:
return json_response(self, 400, {"error": "branch required"})
stash_if_dirty = bool(payload.get("stashIfDirty") or payload.get("stash_if_dirty"))
refresh_graph = payload.get("refreshGraph")
if refresh_graph is None:
refresh_graph = True
try:
# Cache outgoing HEAD graph before leaving the branch.
cached_before = None
try:
cached_before = branch_cache.save_current(root=root())
except Exception: # noqa: BLE001
cached_before = None
result = github_notes.git_switch(root(), branch, stash_if_dirty=stash_if_dirty)
if result.get("ok") and refresh_graph:
graph = branch_cache.after_switch(root=root(), prefer_cache=True)
result = {**result, "graph": graph, "cachedBefore": cached_before}
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
return json_response(self, 200 if result.get("ok") else 409, result)
if parsed.path == "/api/git/stash":
message = payload.get("message") if isinstance(payload.get("message"), str) else None
include_untracked = payload.get("includeUntracked")
if include_untracked is None:
include_untracked = True
try:
result = git_ops.stash(
root(),
message=message,
include_untracked=bool(include_untracked),
)
except Exception as exc: # noqa: BLE001
return json_response(self, 500, {"ok": False, "error": str(exc)})
return json_response(self, 200 if result.get("ok") else 409, result)
if parsed.path == "/api/git/fetch":
prune = payload.get("prune")