-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
2329 lines (2166 loc) · 120 KB
/
Copy pathserver.py
File metadata and controls
2329 lines (2166 loc) · 120 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 code browser and guarded source editor with Ollama-powered explanations."""
from __future__ import annotations
import argparse
import ast
from collections import deque
from concurrent.futures import ThreadPoolExecutor, as_completed
import difflib
import hashlib
import json
import logging
import mimetypes
import os
from pathlib import Path
import re
import shutil
import socket
import subprocess
import tempfile
import threading
import time
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qs, unquote, urlparse
from urllib.request import Request, urlopen
from uuid import uuid4
from metering import JsonlAuditStore, build_audit_record, calculate_credits, estimate_tokens, parse_token_count
from provider_plugins import (
PluginError,
PluginRegistry,
ProviderPluginClient,
configured_plugin_directories,
)
APP_DIR = Path(__file__).resolve().parent
STATIC_DIR = (APP_DIR / "static").resolve()
MCP_STATE_PATH = APP_DIR / ".code-browser-mcp-state.json"
LOOP_STATE_PATH = APP_DIR / ".code-browser-loop-state.json"
METERING_AUDIT_PATH = APP_DIR / ".code-browser-metering-audit.jsonl"
MAX_FILE_BYTES = 1_500_000
MAX_PDF_BYTES = 100_000_000
MAX_PDF_PAGES = 200
MAX_PDF_DISPLAY_CHARS = 300_000
MAX_ANALYSIS_CHARS = 120_000
DEEP_READING_TARGET_CHARS = 55_000
DEEP_READING_CONTEXT_CHARS = 35_000
PDF_EXTRACTION_TIMEOUT_SECONDS = 60
IGNORED_NAMES = {
".git", ".svn", ".hg", ".DS_Store", "node_modules", "__pycache__",
".venv", "venv", "dist", "build", ".next", ".cache", "coverage",
}
OLLAMA_HOSTS = [
"http://localhost:11434",
]
OLLAMA_CLOUD_HOST = "https://ollama.com"
LOCAL_CLOUD_SUFFIX = ":cloud"
PAID_CLOUD_MODELS = {"kimi-k3"}
LOOP_SOURCE_SUFFIXES = {".py"}
OLLAMA_MODEL_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$")
OLLAMA_PROBE_TTL_SECONDS = 30
POST_REQUEST_HEADER = "X-Requested-With"
POST_REQUEST_HEADER_VALUE = "CodeBrowser"
CONTENT_SECURITY_POLICY = (
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; connect-src 'self'; object-src 'none'; "
"base-uri 'none'; frame-ancestors 'none'; form-action 'self'"
)
def managed_wrapper_usage_request() -> Request | None:
base_url = os.environ.get("CODE_BROWSER_MANAGED_WRAPPER_URL", "").strip().rstrip("/")
access_token = os.environ.get("CODE_BROWSER_MANAGED_ACCESS_TOKEN", "").strip()
if not base_url or not access_token:
return None
parsed = urlparse(base_url)
local_development = parsed.hostname in {"127.0.0.1", "localhost"} and parsed.scheme == "http"
if (
(parsed.scheme != "https" and not local_development)
or not parsed.hostname
or parsed.username
or parsed.password
or parsed.query
or parsed.fragment
or parsed.path not in {"", "/"}
):
raise ValueError("CODE_BROWSER_MANAGED_WRAPPER_URL must be an HTTPS origin or a localhost development origin")
return Request(
f"{base_url}/v1/usage?limit=1",
headers={"Accept": "application/json", "Authorization": f"Bearer {access_token}"},
method="GET",
)
def fetch_managed_credit_balance() -> dict[str, object]:
request = managed_wrapper_usage_request()
if request is None:
return {"available": False, "mode": "byok"}
try:
with urlopen(request, timeout=5) as response:
raw = response.read(65_537)
if len(raw) > 65_536:
return {"available": False, "mode": "managed", "reason": "invalid_response"}
payload = json.loads(raw)
except (HTTPError, URLError, TimeoutError, OSError, json.JSONDecodeError):
return {"available": False, "mode": "managed", "reason": "unavailable"}
if not isinstance(payload, dict):
return {"available": False, "mode": "managed", "reason": "invalid_response"}
return {
"available": True,
"mode": "managed",
"plan": payload.get("plan"),
"unlimited": payload.get("unlimited") is True,
"allowancePeriod": payload.get("allowancePeriod"),
"periodAllowanceCredits": payload.get("periodAllowanceCredits"),
"periodUsedCredits": payload.get("periodUsedCredits"),
"reservedCredits": payload.get("reservedCredits"),
"remainingCredits": payload.get("remainingCredits"),
"nextGrantAt": payload.get("nextGrantAt"),
}
_ollama_probe_lock = threading.RLock()
_ollama_probe_cache: tuple[float, tuple[str, ...], str, list[dict]] | None = None
LOGGER = logging.getLogger("code_browser")
LOCAL_REPOSITORY_EXCLUDES = """# Ollama Code Browser: local-only safety exclusions
.env
.env.*
!.env.example
!.env.sample
*.pem
*.key
*.p12
*.pfx
id_rsa*
id_ed25519*
credentials*.json
secrets.*
*.db
*.db-*
*.sqlite
*.sqlite3
data/
logs/
*.log
__pycache__/
*.py[cod]
.venv/
venv/
node_modules/
dist/
build/
.DS_Store
"""
PROJECT_METADATA_NAMES = {
"readme", "readme.md", "readme.txt", "package.json", "pyproject.toml",
"cargo.toml", "go.mod", "requirements.txt", "composer.json", "pom.xml",
"build.gradle", "build.gradle.kts", "gemfile", "dockerfile",
"docker-compose.yml", "docker-compose.yaml", "wrangler.jsonc", "wrangler.toml",
}
def json_bytes(value: object) -> bytes:
return json.dumps(value, ensure_ascii=False).encode("utf-8")
def parse_byte_range(value: str, size: int) -> tuple[int, int]:
"""Parse one HTTP bytes range and return inclusive offsets."""
match = re.fullmatch(r"bytes=(\d*)-(\d*)", value.strip())
if not match or size <= 0:
raise ValueError("Invalid byte range")
raw_start, raw_end = match.groups()
if not raw_start and not raw_end:
raise ValueError("Invalid byte range")
if not raw_start:
length = int(raw_end)
if length <= 0:
raise ValueError("Invalid byte range")
return max(0, size - length), size - 1
start = int(raw_start)
end = int(raw_end) if raw_end else size - 1
if start >= size or end < start:
raise ValueError("Byte range is outside the file")
return start, min(end, size - 1)
def loop_text(language: str, japanese: str, english: str) -> str:
return english if language == "en" else japanese
def read_analysis_source(path: Path, language: str) -> bytes:
if path.stat().st_size > MAX_FILE_BYTES:
raise ValueError("Analysis target is too large" if language == "en" else "解析対象のファイルが大きすぎます")
return path.read_bytes()
class PdfExtractionError(ValueError):
"""Raised when a PDF cannot be safely converted to text."""
def file_sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _format_pdf_pages(text: str, max_chars: int) -> tuple[str, int, bool]:
pages = text.replace("\r\n", "\n").replace("\r", "\n").split("\f")
if pages and not pages[-1].strip():
pages.pop()
parts: list[str] = []
used = 0
truncated = False
for index, page in enumerate(pages, 1):
page_text = page.strip()
heading = f"[Page {index}]\n"
remaining = max_chars - used - len(heading)
if remaining <= 0:
truncated = True
break
excerpt = page_text[:remaining]
parts.append(heading + excerpt)
used += len(heading) + len(excerpt) + 2
if len(excerpt) < len(page_text):
truncated = True
break
return "\n\n".join(parts), len(parts), truncated
def extract_pdf_text(path: Path, max_chars: int = MAX_PDF_DISPLAY_CHARS) -> dict[str, object]:
"""Extract bounded PDF text with Poppler first and a pypdf fallback."""
size = path.stat().st_size
if size > MAX_PDF_BYTES:
raise PdfExtractionError(f"PDF is too large (limit: {MAX_PDF_BYTES // 1_000_000} MB)")
tool = shutil.which("pdftotext")
text = ""
total_pages: int | None = None
engine = ""
page_limited = False
if tool:
with tempfile.NamedTemporaryFile(suffix=".txt") as output:
try:
result = subprocess.run(
[tool, "-f", "1", "-l", str(MAX_PDF_PAGES), "-layout", "-enc", "UTF-8", str(path), output.name],
capture_output=True,
timeout=PDF_EXTRACTION_TIMEOUT_SECONDS,
check=False,
)
except subprocess.TimeoutExpired as exc:
raise PdfExtractionError("PDF text extraction timed out") from exc
if result.returncode != 0:
detail = result.stderr.decode("utf-8", errors="replace").strip()[:300]
raise PdfExtractionError(f"PDF text extraction failed: {detail or 'pdftotext error'}")
output.seek(0)
text = output.read(MAX_PDF_DISPLAY_CHARS * 8).decode("utf-8", errors="replace")
engine = "pdftotext"
info_tool = shutil.which("pdfinfo")
if info_tool:
try:
info = subprocess.run(
[info_tool, str(path)], capture_output=True, timeout=15, check=False,
).stdout.decode("utf-8", errors="replace")
match = re.search(r"^Pages:\s+(\d+)\s*$", info, re.MULTILINE)
if match:
total_pages = int(match.group(1))
page_limited = total_pages > MAX_PDF_PAGES
except subprocess.TimeoutExpired:
pass
else:
try:
from pypdf import PdfReader
except ImportError as exc:
raise PdfExtractionError("PDF text extraction requires Poppler pdftotext or the pypdf package") from exc
try:
reader = PdfReader(path)
total_pages = len(reader.pages)
page_limited = total_pages > MAX_PDF_PAGES
chunks = [(reader.pages[index].extract_text() or "") for index in range(min(total_pages, MAX_PDF_PAGES))]
text = "\f".join(chunks)
engine = "pypdf"
except Exception as exc:
raise PdfExtractionError(f"PDF text extraction failed: {exc}") from exc
content, extracted_pages, text_truncated = _format_pdf_pages(text, max_chars)
if not content.strip():
raise PdfExtractionError("No selectable text was found in this PDF; OCR may be required")
return {
"content": content,
"totalPages": total_pages,
"extractedPages": extracted_pages,
"truncated": page_limited or text_truncated,
"engine": engine,
}
def read_analysis_content(path: Path, language: str) -> tuple[str, dict[str, object] | None]:
if path.suffix.lower() == ".pdf":
document = extract_pdf_text(path, MAX_ANALYSIS_CHARS)
content = str(document["content"])
if document["truncated"]:
content += "\n\n[Remaining PDF pages or text omitted due to the analysis limit]"
return content, document
return read_analysis_source(path, language).decode("utf-8", errors="replace"), None
def is_probably_binary(raw: bytes) -> bool:
"""Reject binary data without relying on often-inaccurate filename MIME types."""
sample = raw[:8192]
if not sample:
return False
if b"\x00" in sample:
return True
control_bytes = sum(byte < 32 and byte not in {8, 9, 10, 12, 13} for byte in sample)
return control_bytes / len(sample) > 0.10
def atomic_write_json(path: Path, value: object, prefix: str) -> None:
temporary_name = ""
try:
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, prefix=prefix, delete=False) as temporary:
json.dump(value, temporary, ensure_ascii=False, indent=2)
temporary.flush()
os.fsync(temporary.fileno())
temporary_name = temporary.name
os.replace(temporary_name, path)
finally:
if temporary_name and os.path.exists(temporary_name):
os.unlink(temporary_name)
def resolve_static_file(relative: str, static_dir: Path = STATIC_DIR) -> Path | None:
base = static_dir.resolve()
path = (base / relative).resolve()
return path if base in path.parents and path.is_file() else None
def load_env_file(path: Path) -> None:
"""Load simple KEY=VALUE entries without adding a dotenv dependency."""
if not path.is_file():
return
try:
lines = path.read_text(encoding="utf-8").splitlines()
except OSError:
return
for raw_line in lines:
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[7:].lstrip()
if "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
if not key or not key.replace("_", "a").isalnum() or key[0].isdigit():
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
value = value[1:-1]
elif " #" in value:
value = value.split(" #", 1)[0].rstrip()
os.environ.setdefault(key, value)
load_env_file(APP_DIR / ".env")
class OutsideRootError(PermissionError):
"""Raised when a requested path escapes the active browsing root."""
class CodeBrowserServer(ThreadingHTTPServer):
daemon_threads = True
def __init__(self, address: tuple[str, int], root: Path):
super().__init__(address, RequestHandler)
self.root_lock = threading.RLock()
self.read_only_lock = threading.RLock()
self.mcp_state_lock = threading.Lock()
self._root = root.resolve()
self._read_only = True
self.plugin_registry = PluginRegistry.discover(configured_plugin_directories(APP_DIR))
self.provider_plugin_id = os.environ.get("CODE_BROWSER_PROVIDER_PLUGIN", "").strip()
if self.provider_plugin_id:
self.plugin_registry.get(self.provider_plugin_id)
self.metering_audit = JsonlAuditStore(METERING_AUDIT_PATH)
self.loop_manager = LoopManager(self)
def safe_path(self, relative: str) -> Path:
candidate, _ = self.safe_path_with_root(relative)
return candidate
def safe_path_with_root(self, relative: str) -> tuple[Path, Path]:
relative = unquote(relative).lstrip("/")
with self.root_lock:
root = self._root
candidate = (root / relative).resolve()
if candidate != root and root not in candidate.parents:
raise OutsideRootError("Paths outside the browsing root cannot be accessed")
return candidate, root
@property
def root(self) -> Path:
with self.root_lock:
return self._root
def change_root(self, root: Path) -> None:
with self.root_lock:
self._root = root.resolve()
@property
def read_only(self) -> bool:
with self.read_only_lock:
return self._read_only
@read_only.setter
def read_only(self, value: bool) -> None:
with self.read_only_lock:
self._read_only = value
class RequestHandler(BaseHTTPRequestHandler):
server: CodeBrowserServer
def log_message(self, fmt: str, *args: object) -> None:
LOGGER.info("client=%s request=%s", self.client_address[0], fmt % args)
def end_headers(self) -> None:
content_security_policy = CONTENT_SECURITY_POLICY
if getattr(self, "_allow_same_origin_frame", False):
content_security_policy = content_security_policy.replace("frame-ancestors 'none'", "frame-ancestors 'self'")
self.send_header("Content-Security-Policy", content_security_policy)
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Referrer-Policy", "no-referrer")
super().end_headers()
def send_json(self, status: int, value: object) -> None:
body = json_bytes(value)
self.send_response(status)
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)
def send_error_json(self, status: int, message: str) -> None:
self.send_json(status, {"error": message})
def do_GET(self) -> None:
parsed = urlparse(self.path)
try:
if parsed.path == "/api/config":
root = self.server.root
self.send_json(200, {
"root": str(root),
"rootName": root.name or str(root),
"parent": str(root.parent),
"maxFileBytes": MAX_FILE_BYTES,
"maxPdfBytes": MAX_PDF_BYTES,
"maxPdfPages": MAX_PDF_PAGES,
"readOnly": self.server.read_only,
"providerPlugin": self.server.provider_plugin_id or None,
"providerPlugins": self.server.plugin_registry.metadata(),
})
elif parsed.path == "/api/tree":
self.handle_tree(parse_qs(parsed.query).get("path", [""])[0])
elif parsed.path == "/api/file":
self.handle_file(parse_qs(parsed.query).get("path", [""])[0])
elif parsed.path == "/api/pdf":
self.handle_pdf(parse_qs(parsed.query).get("path", [""])[0])
elif parsed.path == "/api/models":
self.handle_models()
elif parsed.path == "/api/loop/status":
self.send_json(200, self.server.loop_manager.status())
elif parsed.path == "/api/metering/audit":
raw_limit = parse_qs(parsed.query).get("limit", ["200"])[0]
try:
limit = int(raw_limit)
except ValueError as exc:
raise ValueError("Audit limit must be an integer") from exc
self.send_json(200, self.server.metering_audit.report(limit))
elif parsed.path == "/api/account/credits":
self.send_json(200, fetch_managed_credit_balance())
elif parsed.path == "/api/resolve-reference":
query = parse_qs(parsed.query)
self.handle_resolve_reference(
query.get("reference", [""])[0],
query.get("current", [""])[0],
)
elif parsed.path.startswith("/static/"):
self.serve_static(parsed.path.removeprefix("/static/"))
elif parsed.path == "/manifest.webmanifest":
self.serve_static("manifest.webmanifest", content_type="application/manifest+json")
elif parsed.path == "/service-worker.js":
self.serve_static(
"service-worker.js",
content_type="text/javascript; charset=utf-8",
cache_control="no-cache, no-store, must-revalidate",
service_worker_allowed="/",
)
elif parsed.path == "/" or parsed.path == "/index.html":
self.serve_static("index.html")
else:
self.send_error_json(404, "Not found")
except (BrokenPipeError, ConnectionResetError) as exc:
self.log_error("client disconnected during GET %s: %s", parsed.path, exc)
except OutsideRootError as exc:
self.send_error_json(403, str(exc))
except PermissionError as exc:
self.send_error_json(403, str(exc))
except ValueError as exc:
self.send_error_json(400, str(exc))
except FileNotFoundError:
self.send_error_json(404, "File or folder not found")
except OSError as exc:
self.send_error_json(500, f"Read failed: {exc}")
def do_POST(self) -> None:
endpoint = urlparse(self.path).path
if endpoint not in {"/api/analyze", "/api/project-summary", "/api/root", "/api/file/save", "/api/git/commit", "/api/read-only", "/api/mcp-state", "/api/loop/start", "/api/loop/cancel"}:
self.send_error_json(404, "Not found")
return
if self.headers.get(POST_REQUEST_HEADER) != POST_REQUEST_HEADER_VALUE:
self.send_error_json(403, "This POST request did not originate from the Code Browser interface")
return
try:
length = int(self.headers.get("Content-Length", "0"))
max_length = 4_000_000 if endpoint == "/api/mcp-state" else 32_768 if endpoint in {"/api/root", "/api/git/commit", "/api/read-only", "/api/loop/start", "/api/loop/cancel"} else 500_000 if endpoint == "/api/project-summary" else MAX_FILE_BYTES * 2
if length <= 0 or length > max_length:
raise ValueError("Invalid request size")
payload = json.loads(self.rfile.read(length))
if endpoint == "/api/root":
self.handle_change_root(payload)
elif endpoint == "/api/read-only":
self.handle_read_only(payload)
elif endpoint == "/api/mcp-state":
self.handle_mcp_state(payload)
elif endpoint == "/api/loop/start":
self.handle_loop_start(payload)
elif endpoint == "/api/loop/cancel":
self.server.loop_manager.cancel()
self.send_json(200, self.server.loop_manager.status())
elif endpoint == "/api/file/save":
self.handle_save_file(payload)
elif endpoint == "/api/git/commit":
self.handle_git_commit(payload)
elif endpoint == "/api/project-summary":
self.handle_project_summary(payload)
else:
self.handle_analyze(payload)
except (ValueError, json.JSONDecodeError, KeyError) as exc:
self.send_error_json(400, str(exc))
except OutsideRootError as exc:
self.send_error_json(403, str(exc))
except PermissionError as exc:
self.send_error_json(403, str(exc))
except FileNotFoundError:
self.send_error_json(404, "File not found")
except (BrokenPipeError, ConnectionResetError) as exc:
self.log_error("client disconnected during POST %s: %s", endpoint, exc)
except (ConnectionError, PluginError) as exc:
self.send_json(503, {"error": "Could not connect to the model provider", "detail": str(exc)})
except OSError as exc:
self.send_error_json(500, f"Operation failed: {exc}")
def handle_change_root(self, payload: dict) -> None:
raw_path = str(payload.get("path", "")).strip()
if not raw_path:
raise ValueError("A directory is required")
new_root = Path(raw_path).expanduser()
if not new_root.is_absolute():
raise ValueError("The directory must be an absolute path")
new_root = new_root.resolve()
if not new_root.exists():
raise FileNotFoundError
if not new_root.is_dir():
raise ValueError("The selected path is not a directory")
if not os.access(new_root, os.R_OK | os.X_OK):
raise PermissionError("The selected directory is not readable")
self.server.change_root(new_root)
self.send_json(200, {
"root": str(new_root),
"rootName": new_root.name or str(new_root),
"parent": str(new_root.parent),
"maxFileBytes": MAX_FILE_BYTES,
"maxPdfBytes": MAX_PDF_BYTES,
"maxPdfPages": MAX_PDF_PAGES,
"readOnly": self.server.read_only,
})
def handle_read_only(self, payload: dict) -> None:
value = payload.get("readOnly")
if not isinstance(value, bool):
raise ValueError("readOnly must be a boolean")
self.server.read_only = value
self.send_json(200, {"readOnly": self.server.read_only})
def handle_mcp_state(self, payload: dict) -> None:
"""Persist browser-owned metadata for the read-only MCP companion."""
pinned = payload.get("pinnedProjects", [])
analyses = payload.get("analyses", [])
current = payload.get("current", {})
if not isinstance(pinned, list) or not isinstance(analyses, list) or not isinstance(current, dict):
raise ValueError("Invalid MCP synchronization data")
clean_pinned: list[str] = []
for value in pinned[:30]:
path = str(value)[:4096]
if Path(path).is_absolute() and path not in clean_pinned:
clean_pinned.append(path)
clean_analyses = []
for item in analyses[-20:]:
if not isinstance(item, dict):
continue
target = item.get("reportTarget") if isinstance(item.get("reportTarget"), dict) else {}
clean_analyses.append({
"id": str(item.get("id", ""))[:160],
"title": str(item.get("title", ""))[:500],
"mode": str(item.get("mode", ""))[:80],
"model": str(item.get("model", ""))[:200],
"host": str(item.get("host", ""))[:500],
"status": str(item.get("status", ""))[:40],
"language": str(item.get("language", ""))[:20],
"projectRoot": str(item.get("projectRoot", ""))[:4096],
"groupId": str(item.get("groupId", ""))[:160] if item.get("groupId") else None,
"tabRole": str(item.get("tabRole", "standalone"))[:40],
"target": {
"name": str(target.get("name", ""))[:500],
"path": str(target.get("path", ""))[:4096],
},
"content": str(item.get("content", ""))[:500_000],
})
state = {
"version": 1,
"updatedAt": datetime.now(timezone.utc).isoformat(),
"pinnedProjects": clean_pinned,
"current": {
"projectRoot": str(current.get("projectRoot", ""))[:4096],
"filePath": str(current.get("filePath", ""))[:4096],
"fileAbsolutePath": str(current.get("fileAbsolutePath", ""))[:4096],
"readOnly": self.server.read_only,
},
"analyses": clean_analyses,
}
with self.server.mcp_state_lock:
atomic_write_json(MCP_STATE_PATH, state, ".mcp-state.")
self.send_json(200, {"synced": True, "analyses": len(clean_analyses), "pinnedProjects": len(clean_pinned)})
def handle_loop_start(self, payload: dict) -> None:
if self.server.read_only:
self.send_error_json(423, "Disable READ ONLY before starting Loop")
return
result = self.server.loop_manager.start(payload)
self.send_json(202, result)
def handle_tree(self, relative: str) -> None:
directory, root = self.server.safe_path_with_root(relative)
if not directory.is_dir():
raise FileNotFoundError
items = []
try:
children = sorted(
directory.iterdir(),
key=lambda p: (not p.is_dir(), p.name.casefold()),
)
except PermissionError:
self.send_error_json(403, "This folder cannot be read")
return
for child in children[:1000]:
if child.name in IGNORED_NAMES or child.name.startswith(".git"):
continue
try:
resolved = child.resolve()
if resolved != root and root not in resolved.parents:
continue
is_dir = child.is_dir()
size = child.stat().st_size if child.is_file() else None
except OSError:
continue
items.append({
"name": child.name,
"path": child.relative_to(root).as_posix(),
"type": "directory" if is_dir else "file",
"size": size,
})
self.send_json(200, {"path": relative, "items": items, "truncated": len(children) > 1000})
def handle_file(self, relative: str) -> None:
path = self.server.safe_path(relative)
if not path.is_file():
raise FileNotFoundError
size = path.stat().st_size
if path.suffix.lower() == ".pdf":
document = extract_pdf_text(path)
content = str(document["content"])
self.send_json(200, {
"path": relative,
"absolutePath": str(path),
"name": path.name,
"content": content,
"size": size,
"language": "PDF text",
"lines": content.count("\n") + 1,
"fingerprint": file_sha256(path),
"git": git_file_info(path),
"editable": False,
"document": document,
})
return
if size > MAX_FILE_BYTES:
self.send_error_json(413, f"File is too large (limit: {MAX_FILE_BYTES / 1_000_000:.1f} MB)")
return
raw = path.read_bytes()
if is_probably_binary(raw):
self.send_error_json(415, "Binary files cannot be displayed")
return
try:
content = raw.decode("utf-8")
except UnicodeDecodeError:
content = raw.decode("utf-8", errors="replace")
self.send_json(200, {
"path": relative,
"absolutePath": str(path),
"name": path.name,
"content": content,
"size": size,
"language": language_for(path.suffix),
"lines": content.count("\n") + 1,
"fingerprint": hashlib.sha256(raw).hexdigest(),
"git": git_file_info(path),
"editable": True,
})
def handle_pdf(self, relative: str) -> None:
self._allow_same_origin_frame = True
path = self.server.safe_path(relative)
if not path.is_file():
raise FileNotFoundError
if path.suffix.lower() != ".pdf":
self.send_error_json(415, "Only PDF files can be opened by the PDF viewer")
return
size = path.stat().st_size
if size <= 0:
self.send_error_json(422, "PDF file is empty")
return
if size > MAX_PDF_BYTES:
self.send_error_json(413, f"PDF is too large (limit: {MAX_PDF_BYTES // 1_000_000} MB)")
return
range_header = self.headers.get("Range", "").strip()
start, end = 0, size - 1
status = 200
if range_header:
try:
start, end = parse_byte_range(range_header, size)
except ValueError:
self.send_response(416)
self.send_header("Content-Range", f"bytes */{size}")
self.send_header("Content-Length", "0")
self.send_header("Cache-Control", "no-store")
self.end_headers()
return
status = 206
length = end - start + 1
self.send_response(status)
self.send_header("Content-Type", "application/pdf")
self.send_header("Content-Length", str(length))
self.send_header("Accept-Ranges", "bytes")
self.send_header("Cache-Control", "no-store")
if status == 206:
self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
self.end_headers()
with path.open("rb") as source:
source.seek(start)
remaining = length
while remaining:
chunk = source.read(min(1024 * 1024, remaining))
if not chunk:
break
self.wfile.write(chunk)
remaining -= len(chunk)
def handle_save_file(self, payload: dict) -> None:
if self.server.read_only:
self.send_error_json(423, "Files cannot be saved while READ ONLY is enabled")
return
relative = str(payload.get("path", ""))
content = str(payload.get("content", ""))
expected = str(payload.get("fingerprint", ""))
path = self.server.safe_path(relative)
if not path.is_file():
raise FileNotFoundError
if path.suffix.lower() == ".pdf":
self.send_error_json(415, "Extracted PDF text is read-only and cannot overwrite the original PDF")
return
current = path.read_bytes()
if expected and hashlib.sha256(current).hexdigest() != expected:
self.send_error_json(409, "The file changed externally; reload it before editing")
return
encoded = content.encode("utf-8")
if len(encoded) > MAX_FILE_BYTES:
self.send_error_json(413, "The saved content exceeds the file-size limit")
return
mode = path.stat().st_mode
temporary_name = ""
try:
with tempfile.NamedTemporaryFile("wb", dir=path.parent, prefix=f".{path.name}.", delete=False) as temporary:
temporary.write(encoded)
temporary.flush()
os.fsync(temporary.fileno())
temporary_name = temporary.name
os.chmod(temporary_name, mode & 0o7777)
os.replace(temporary_name, path)
finally:
if temporary_name and os.path.exists(temporary_name):
os.unlink(temporary_name)
self.send_json(200, {
"saved": True,
"fingerprint": hashlib.sha256(encoded).hexdigest(),
"size": len(encoded),
"lines": content.count("\n") + 1,
"git": git_file_info(path),
})
def handle_git_commit(self, payload: dict) -> None:
if self.server.read_only:
self.send_error_json(423, "Git commits are disabled while READ ONLY is enabled")
return
path = self.server.safe_path(str(payload.get("path", "")))
message = str(payload.get("message", "")).strip()
if not path.is_file():
raise FileNotFoundError
if not message or len(message) > 240:
raise ValueError("Enter a commit message between 1 and 240 characters")
info = git_file_info(path)
if not info:
raise ValueError("This file is not inside a Git repository")
repository = Path(info["repoRoot"])
relative = path.relative_to(repository).as_posix()
run_git(repository, ["add", "--", relative])
result = run_git(repository, ["commit", "--only", "-m", message, "--", relative])
self.send_json(200, {"committed": True, "output": result.strip(), "git": git_file_info(path)})
def handle_resolve_reference(self, reference: str, current: str) -> None:
reference = reference.strip().strip("`'\"")
if not reference or len(reference) > 300:
raise ValueError("Invalid reference name")
result = resolve_code_reference(self.server.root, reference, current)
if not result:
self.send_error_json(404, "Reference not found")
return
self.send_json(200, result)
def probe_ollama(self) -> tuple[str, list[dict]]:
return probe_ollama_models()
def provider_plugin(self) -> ProviderPluginClient | None:
if not self.server.provider_plugin_id:
return None
return ProviderPluginClient(self.server.plugin_registry.get(self.server.provider_plugin_id))
def discover_provider_models(self) -> tuple[str, list[str]]:
plugin = self.provider_plugin()
if plugin is not None:
return f"plugin:{plugin.manifest.plugin_id}", plugin.list_models()
host, models = self.probe_ollama()
return host, allowed_model_names(host, models)
def handle_models(self) -> None:
try:
host, names = self.discover_provider_models()
except (ConnectionError, PluginError) as exc:
self.send_json(503, {"error": "Could not connect to the model provider", "detail": str(exc)})
return
preferred = choose_model(names)
self.send_json(200, {
"host": host,
"models": names,
"preferred": preferred,
"providerPlugin": self.server.provider_plugin_id or None,
})
def handle_project_summary(self, payload: dict) -> None:
model = str(payload.get("model", ""))
mode = str(payload.get("mode", "summary"))
if mode not in {"summary", "improve", "consensus"}:
mode = "summary"
language = "en" if payload.get("language") == "en" else "ja"
requested_root = Path(str(payload.get("root", self.server.root))).expanduser()
if not requested_root.is_absolute():
raise ValueError("Project root must be an absolute path" if language == "en" else "プロジェクトルートは絶対パスで指定してください")
requested_root = requested_root.resolve()
if not requested_root.is_dir() or not os.access(requested_root, os.R_OK | os.X_OK):
raise ValueError("The selected project directory is unavailable" if language == "en" else "選択したプロジェクトディレクトリを利用できません")
raw_target = str(payload.get("path", "")).strip()
candidate = Path(raw_target).expanduser()
target = candidate.resolve() if candidate.is_absolute() else (requested_root / raw_target.lstrip("/")).resolve()
if target != requested_root and requested_root not in target.parents:
raise PermissionError("The summary target is outside the selected project" if language == "en" else "構成要約の対象が選択したプロジェクトの外にあります")
if not target.is_dir():
raise ValueError("The project summary target must be a directory" if language == "en" else "構成要約の対象はディレクトリである必要があります")
if mode == "consensus":
reports = str(payload.get("reports", ""))[:120_000]
snapshot = build_project_snapshot(target, max_depth=3, max_entries=600)
if language == "en":
prompt = (
f"Project: {target.name or str(target)}\nRoot: {target}\n\n"
"Act as the lead project reviewer. Combine the model reports into one decision-oriented result. "
"Use exactly these headings:\n## Shared findings\n## Disagreements and uncertainty\n"
"## Priority order\n## Recommended implementation plan\n"
"Deduplicate equivalent suggestions, distinguish consensus from single-model claims, and do not invent findings.\n\n"
f"{snapshot}\n\n# Model reports\n{reports}"
)
system = "You are a lead software architect consolidating independent project reviews in English Markdown. Wrap file paths and symbols in backticks."
else:
prompt = (
f"プロジェクト名: {target.name or str(target)}\nルート: {target}\n\n"
"主任レビュアーとしてモデル別レポートを統合してください。必ず次の見出しを使ってください。\n"
"## 共通している指摘\n## 意見の相違・不確実性\n## 優先順位\n## 推奨実装計画\n"
"同じ提案は重複排除し、複数モデルの合意と単独モデルの主張を区別し、レポートにない問題を創作しないでください。\n\n"
f"{snapshot}\n\n# モデル別レポート\n{reports}"
)
system = "あなたは複数のプロジェクトレビューを統合する主任ソフトウェアアーキテクトです。ファイルパスとシンボル名はバッククォートで囲んでください。"
elif mode == "improve":
snapshot = build_project_improvement_snapshot(target)
if language == "en":
prompt = (
f"Project: {target.name or str(target)}\nRoot: {target}\n\n"
"Review the project as a whole and identify concrete improvements. Prioritize by impact and provide evidence, expected benefit, and practical implementation steps. "
"Cover architecture, correctness, security, performance, maintainability, testing, and developer experience only when supported by the supplied files. "
"State sampling limitations and avoid generic advice.\n\n"
f"{snapshot}"
)
system = "You are an independent senior software architect reviewing an entire project in English Markdown. Wrap file paths and symbols in backticks."
else:
prompt = (
f"プロジェクト名: {target.name or str(target)}\nルート: {target}\n\n"
"プロジェクト全体をレビューし、具体的な改善点を影響度順に示してください。各項目に根拠、期待効果、実装手順を含め、"
"提供ファイルから判断できる場合だけ、設計、正確性、セキュリティ、性能、保守性、テスト、開発体験を扱ってください。"
"抜粋による制約を明記し、一般論は避けてください。\n\n"
f"{snapshot}"
)
system = "あなたはプロジェクト全体を独立評価する上級ソフトウェアアーキテクトです。ファイルパスとシンボル名はバッククォートで囲んでください。"
elif language == "en":
snapshot = build_project_snapshot(target)
prompt = (
f"Project: {target.name or str(target)}\nRoot: {target}\n\n"
"Using only the directory structure and project metadata below, summarize the project in English.\n\n"
"Use exactly these headings:\n## Project overview\n## Technology stack\n"
"## Directory structure\n## Entry points and key files\n## Recommended reading order\n"
"## Points worth understanding\n## Relationship diagram\n"
"Under Points worth understanding, list 3 to 7 concrete concepts, control-flow decisions, state boundaries, or architectural assumptions that a reader should verify in the source. "
"Tie each point to an exact file or symbol when the supplied structure supports it, and do not invent implementation details.\n"
"Under Relationship diagram, include one fenced `relationship` block with 4 to 16 evidence-based edges in this exact format:\n"
"```relationship\nsource | source_type | short relationship | target | target_type\n```\n"
"Allowed node types are file, function, class, ui, data, external, and symbol. Prefer file structure for architecture; include exact functions and classes when supported; include UI nodes only when the supplied metadata identifies a real screen or component. "
"Use one edge per line, exact names when available, and do not use the pipe character inside a field. "
"Do not present guesses as facts. State when the structure is insufficient to determine something.\n\n"
f"{snapshot}"
)
system = "You are a software architect. Explain project structure accurately and concisely in English Markdown. Wrap file paths and symbol names in backticks."
else:
snapshot = build_project_snapshot(target)
prompt = (
f"プロジェクト名: {target.name or str(target)}\nルート: {target}\n\n"
"以下はディレクトリ構成と主要メタデータです。記載された情報だけを根拠に、"
"プロジェクト全体を日本語で要約してください。\n\n"
"必ず次の見出しを使ってください。\n## プロジェクト概要\n## 技術スタック\n"
"## ディレクトリ構成\n## 処理の入口と主要ファイル\n## 読み進める順序\n"
"## 理解しておくとよいポイント\n## 関係図\n"
"「理解しておくとよいポイント」には、読者がソースで確認すべき概念、処理分岐、状態の境界、設計上の前提を3〜7点挙げてください。"
"構成から根拠を示せる場合は正確なファイル名やシンボル名に結び付け、実装の詳細を推測で作らないでください。\n"
"関係図には、根拠のある関係を4〜16本、次の形式の`relationship`コードブロックで記述してください。\n"
"```relationship\n元ノード | 元の種類 | 短い関係 | 先ノード | 先の種類\n```\n"
"種類はfile、function、class、ui、data、external、symbolのいずれかです。アーキテクチャにはファイル構成を優先し、根拠がある場合は正確な関数・クラスを含め、UIは実在する画面やコンポーネントを構成から特定できる場合だけ含めてください。"
"1行に1関係とし、可能なら正確な名前を使い、各項目内では縦線を使わないでください。"
"不明な項目は推測で断定せず「構成からは判断できない」と記載してください。\n\n"
f"{snapshot}"
)
system = "あなたはソフトウェアアーキテクトです。プロジェクト構成を正確かつ簡潔なMarkdownで説明し、ファイルパスとシンボル名はバッククォートで囲んでください。"
self.stream_project_summary(model, [
{"role": "system", "content": system},
{"role": "user", "content": prompt},
], language, operation=f"project_{mode}")
def stream_ollama_chat(
self,
host: str,
model: str,
payload: dict,
language: str,
*,
operation: str,
) -> None:
messages = payload.get("messages", [])
prompt_text = "\n".join(