Repository navigation
Expand file tree
/
Copy pathweb_app.py
More file actions
2965 lines (2665 loc) · 123 KB
/
Copy pathweb_app.py
File metadata and controls
2965 lines (2665 loc) · 123 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
"""
web_app.py - HTML/CSS UI server for Ollama Agentic Workspace.
This replaces the Streamlit surface with a small stdlib HTTP server while
reusing the existing workspace, tools, skills, and agent loop modules.
"""
from __future__ import annotations
import json
import mimetypes
import os
import re
import shutil
import socket
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
from agent_runtime import LangChainRuntime, RuntimeSettings
from config import DEFAULT_SYSTEM_PROMPT, MODE_CUSTOM, MODE_LOCAL
from prompt_manager import get_prompt_manager
from skills_manager import get_skills_manager
from git_manager import GitManager, GitError
from memory_manager import MemoryManager
from memory_graph import GraphMemoryStore
from skill_tracker import SkillTracker
from skill_router import SkillRouter
from codebase_index import CodebaseIndex
from workspace_filter import iter_workspace_files
from terminal_manager import terminal_manager
from vector_store import EmbeddingModelManager
from tools import (
TOOL_SCHEMAS, execute_tool, get_workspace, set_tavily_config, set_workspace,
tool_scan_project, get_approval_state, approve_pending, reject_pending, clear_approval_state,
get_approval_decision,
set_git_config, set_tool_event_sink, set_sandbox_config,
)
from context_builder import (
clip_for_context, estimate_tokens_for_messages, estimate_tokens_for_text,
fast_tokens_for_messages, get_model_context_window, message_summary_line,
adaptive_compact_messages, compact_tool_output,
extract_code_outline, compact_history_assistant_turns,
)
from tool_parser import repair_json_tool_arguments, extract_fallback_tool_calls_from_text
from session_manager import SessionStore, build_project_cards
from plan_mode.http_api import dispatch as plan_dispatch
from plan_mode.adapters import build_default_service
APPROVAL_POLL_INTERVAL = float(os.getenv("AGENT_APPROVAL_POLL_INTERVAL", "1.0"))
APPROVAL_TIMEOUT = int(os.getenv("AGENT_APPROVAL_TIMEOUT", "600"))
def _is_approval_required(tool_output) -> dict | None:
if not isinstance(tool_output, str):
return None
try:
parsed = json.loads(tool_output)
except (json.JSONDecodeError, TypeError):
return None
if isinstance(parsed, dict) and parsed.get("status") == "approval_required":
return parsed
return None
def _execute_tool_with_approval(name: str, args: dict, write_event=None) -> str:
set_tool_event_sink(write_event)
try:
output = execute_tool(name, args)
finally:
set_tool_event_sink(None)
approval_info = _is_approval_required(output)
if not approval_info:
return output
token = approval_info.get("token", "")
if write_event:
event_type = "git_diff_preview" if name in {
"write_file", "replace_in_file", "append_file", "delete_file"
} else "approval_required"
write_event({
"type": event_type,
"name": approval_info.get("tool_name", name),
"args": approval_info.get("arguments", args),
"preview": approval_info.get("preview", ""),
"token": token,
})
def _poll_decision() -> dict | None:
# Prefer the token-scoped decision; fall back to the flat snapshot for
# (legacy) payloads that carried no token.
if token:
return get_approval_decision(token)
state = get_approval_state()
if not state.get("pending") and state.get("approved"):
return {"approved": True, "rejected": False,
"rejection_reason": "", "always_allow": state.get("always_allow", False)}
if state.get("pending") or state.get("approved"):
return None
return {"approved": False, "rejected": state.get("rejected", False),
"rejection_reason": state.get("rejection_reason", ""),
"always_allow": False}
waited = 0.0
while waited < APPROVAL_TIMEOUT:
time.sleep(APPROVAL_POLL_INTERVAL)
waited += APPROVAL_POLL_INTERVAL
decision = _poll_decision()
if decision and decision["rejected"]:
return f"Execution rejected: {decision['rejection_reason'] or 'User rejected execution.'}"
if decision and decision["approved"]:
set_tool_event_sink(write_event)
try:
return execute_tool(name, args)
finally:
set_tool_event_sink(None)
if decision is None:
# Cleared/reset elsewhere (e.g. chat cleared) without explicit reject.
return f"Tool execution cancelled: {name}"
return f"Approval timed out after {APPROVAL_TIMEOUT}s for tool: {name}"
ROOT = Path(getattr(sys, "_MEIPASS", Path(__file__).parent)).resolve()
STATIC_DIR = ROOT / "web_ui"
HOST = os.getenv("WEB_APP_HOST", "127.0.0.1")
PORT = int(os.getenv("WEB_APP_PORT", "7864"))
DEFAULT_PROMPT_NAME = "custom_prompt"
DEFAULT_ACTIVE_PROMPT = (ROOT / "system_prompts" / f"{DEFAULT_PROMPT_NAME}.md").read_text(
encoding="utf-8",
errors="replace",
) if (ROOT / "system_prompts" / f"{DEFAULT_PROMPT_NAME}.md").exists() else DEFAULT_SYSTEM_PROMPT
MAX_CONTEXT_CHARS = 32_000
MAX_HISTORY_MESSAGE_CHARS = 6_000
MAX_ASSISTANT_HISTORY_CHARS = 3_500
MAX_KEPT_HISTORY_MESSAGES = 6
MAX_ITERATIONS = 10
REQUEST_TIMEOUT = int(os.getenv("AGENT_REQUEST_TIMEOUT", "1800"))
DEFAULT_CONTEXT_TOKEN_BUDGET = int(os.getenv("AGENT_CONTEXT_TOKENS", "24000"))
DEFAULT_RESPONSE_TOKEN_BUDGET = int(os.getenv("AGENT_RESPONSE_TOKENS", "8192"))
MAX_AUTO_CONTINUES = int(os.getenv("AGENT_AUTO_CONTINUES", "8"))
try:
from litellm import token_counter as _litellm_token_counter
from litellm import model_cost as _litellm_model_cost
_litellm_import_error = ""
except Exception as exc:
_litellm_token_counter = None
_litellm_model_cost = {}
_litellm_import_error = repr(exc)
STATE_LOCK = threading.RLock()
STATE = {
"messages": [],
"tools_log": [],
"used_skills_log": [],
"selected_skills": [],
"conn_mode": MODE_LOCAL,
"model": os.getenv("OLLAMA_MODEL", "gemma4:12b"),
"temperature": 0.4,
"enable_thinking": False,
"custom_api_url": "https://api.openai.com/v1",
"custom_api_key": "",
"custom_api_model": os.getenv("CUSTOM_API_MODEL", "gpt-4o-mini"),
"selected_prompt": DEFAULT_PROMPT_NAME,
"system_prompt": DEFAULT_ACTIVE_PROMPT,
"model_user_selected": False,
"memory_enabled": True,
"memory_summary": "",
"memory_summarized_count": 0,
"memory_session_id": uuid.uuid4().hex,
"memory_retrieval_count": 0,
"memory_retrieved_facts": [],
"memory_context": "",
"context_token_budget": DEFAULT_CONTEXT_TOKEN_BUDGET,
"response_token_budget": DEFAULT_RESPONSE_TOKEN_BUDGET,
"auto_continue": True,
"tavily_enabled": os.getenv("TAVILY_ENABLED", "false").lower() == "true",
"tavily_api_key": os.getenv("TAVILY_API_KEY", ""),
"git_approval_mode": True,
"sandbox_mode": os.getenv("SANDBOX_MODE", "auto"),
"sandbox_docker_image": os.getenv("SANDBOX_DOCKER_IMAGE", "python:3.11-slim"),
"generated_artifact": None,
"git_checkpoint_workspace": "",
"git_checkpoint_branch": "",
"smart_skill_confirmation": False,
"skill_routing": {},
"code_rag_hits": [],
"code_rag_type": "",
}
def get_state_snapshot() -> dict:
"""Thread-safe snapshot of global state."""
with STATE_LOCK:
return dict(STATE)
def update_state(updates: dict) -> None:
"""Thread-safe batch update of global state."""
with STATE_LOCK:
STATE.update(updates)
SETTINGS_PATH = ROOT / "coderai_data" / "settings.json"
def _load_persisted_settings() -> None:
if not SETTINGS_PATH.exists():
return
try:
data = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
if not isinstance(data, dict):
return
for key in (
"conn_mode", "temperature", "enable_thinking",
"custom_api_url", "custom_api_key", "custom_api_model", "memory_enabled",
"context_token_budget", "response_token_budget", "auto_continue",
"tavily_enabled", "tavily_api_key", "git_approval_mode", "smart_skill_confirmation",
"sandbox_mode", "sandbox_docker_image",
"model",
):
if key in data and data[key] is not None:
STATE[key] = data[key]
except Exception:
pass
def _save_persisted_settings() -> None:
try:
SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)
persisted = {
"conn_mode": STATE.get("conn_mode"),
"model": STATE.get("model"),
"temperature": STATE.get("temperature"),
"enable_thinking": STATE.get("enable_thinking"),
"custom_api_url": STATE.get("custom_api_url"),
"custom_api_key": STATE.get("custom_api_key"),
"custom_api_model": STATE.get("custom_api_model"),
"memory_enabled": STATE.get("memory_enabled"),
"context_token_budget": STATE.get("context_token_budget"),
"response_token_budget": STATE.get("response_token_budget"),
"auto_continue": STATE.get("auto_continue"),
"tavily_enabled": STATE.get("tavily_enabled"),
"tavily_api_key": STATE.get("tavily_api_key"),
"git_approval_mode": STATE.get("git_approval_mode"),
"smart_skill_confirmation": STATE.get("smart_skill_confirmation"),
"sandbox_mode": STATE.get("sandbox_mode", "auto"),
"sandbox_docker_image": STATE.get("sandbox_docker_image", "python:3.11-slim"),
}
SETTINGS_PATH.write_text(json.dumps(persisted, indent=2, ensure_ascii=False), encoding="utf-8")
except Exception:
pass
_load_persisted_settings()
SESSION_STORE = SessionStore(STATE)
def get_session_state(session_id: str | None = None) -> dict:
if not session_id or session_id == "default":
return STATE
_, sess = SESSION_STORE.get_or_create(session_id)
return sess
sm = get_skills_manager()
pm = get_prompt_manager()
lc_runtime = LangChainRuntime()
skill_router = SkillRouter()
def _normalize_conn_mode(mode: str | None) -> str:
m = str(mode or "").strip().lower()
if "custom" in m:
return MODE_CUSTOM
return MODE_LOCAL
def _active_model() -> str:
if "custom" in str(STATE.get("conn_mode") or "").lower():
return str(STATE.get("custom_api_model") or "gpt-4o-mini").strip()
return str(STATE.get("model") or "gemma4:12b").strip()
def _active_model_display() -> str:
if "custom" in str(STATE.get("conn_mode") or "").lower():
model = str(STATE.get("custom_api_model") or "gpt-4o-mini").strip()
return f"Custom API ({model})"
model = str(STATE.get("model") or "gemma4:12b").strip()
return f"Ollama ({model})"
def _skill_tracker(workspace: str | Path | None = None) -> SkillTracker:
return SkillTracker(workspace or get_workspace())
def _known_project_workspace(workspace: str | Path | None) -> Path:
if not workspace:
return get_workspace().resolve()
requested = Path(workspace).resolve()
known = {Path(project["workspace_path"]).resolve() for project in _memory_manager().list_projects()}
if requested not in known:
raise PermissionError("Unknown project workspace")
return requested
def _skill_usage_payload(workspace: str | Path | None = None) -> dict:
tracker = _skill_tracker(workspace)
report = tracker.report([skill.name for skill in sm.all()])
definitions = {skill.name: skill for skill in sm.all()}
for item in report["skills"]:
skill = definitions.get(item["name"])
item.update({
"description": skill.description if skill else "",
"category": skill.category if skill else "misc",
"path": str(skill.path) if skill else "",
})
report["routing"] = STATE.get("skill_routing", {}) if workspace is None or Path(workspace).resolve() == get_workspace().resolve() else {}
return report
def _confirm_skill_candidates(prompt: str, candidates: list) -> list[str]:
if not candidates:
return []
candidate_text = "\n".join(f"- {item.skill.name}: {item.skill.description}" for item in candidates)
history = [{
"role": "user",
"content": (
"Select only the skills genuinely required for this request. Return only a JSON array of skill names.\n\n"
f"User request:\n{prompt}\n\nCandidate skills:\n{candidate_text}"
),
}]
try:
result = _call_model(history)
content = str(result.get("content") or "")
match = re.search(r"\[[\s\S]*?\]", content)
names = json.loads(match.group(0)) if match else []
allowed = {item.skill.name for item in candidates}
return [str(name) for name in names if str(name) in allowed]
except Exception:
return [item.skill.name for item in candidates]
def _prepare_skill_turn(prompt: str, write_event=None) -> tuple[str, list, str, int]:
tracker = _skill_tracker()
triggered = sm.detect_skill_commands(prompt)
route = skill_router.route(
prompt, sm.all(), tracker.skill_modes(), [skill.name for skill in triggered], max_active=3,
smart_confirmation=bool(STATE.get("smart_skill_confirmation")), confirmer=_confirm_skill_candidates,
)
selections = route.selected
STATE["selected_skills"] = [item.skill.name for item in selections if item.triggered_by == "pinned"]
STATE["skill_routing"] = {
"selected": [item.skill.name for item in selections],
"skipped": [item.skill.name for item in route.skipped],
"confirmation_used": route.confirmation_used,
"semantic_available": route.semantic_available,
"limit": 3,
}
if triggered:
clean_prompt = sm.strip_commands(prompt) or "Use these skills: " + ", ".join(f"/{skill.name}" for skill in triggered)
else:
clean_prompt = prompt
turn_index = 1 + sum(1 for message in STATE["messages"] if message.get("role") == "user")
auto_injection = []
pinned = set(STATE.get("selected_skills", []))
for selection in selections:
tracker.log_usage(
STATE["memory_session_id"], selection.skill.name, selection.triggered_by,
selection.matched_keywords, "selected", turn_index,
)
tracker.log_usage(
STATE["memory_session_id"], selection.skill.name, selection.triggered_by,
selection.matched_keywords, "loaded", turn_index,
)
if selection.skill.name not in pinned:
auto_injection.append(selection.skill.system_injection)
return clean_prompt, selections, "".join(auto_injection), turn_index
def _emit_skill_selections(selections: list, write_event) -> None:
for selection in selections:
write_event({
"type": "skill_selected", "skill": selection.skill.name,
"reason": selection.reason, "matched_keywords": selection.matched_keywords,
})
def _finish_skill_turn(selections: list, used_skills: list, turn_index: int, failed: bool = False, write_event=None) -> None:
tracker = _skill_tracker()
selected = {selection.skill.name: selection for selection in selections}
if failed:
outcomes = [(selection, "failed") for selection in selections]
else:
outcomes = [(selected[skill.name], "applied") for skill in used_skills if skill.name in selected]
for selection, status in outcomes:
event = tracker.log_usage(
STATE["memory_session_id"], selection.skill.name, selection.triggered_by,
selection.matched_keywords, status, turn_index,
)
if write_event:
write_event({
"type": f"skill_{status}", "skill": selection.skill.name,
"reason": selection.reason, "matched_keywords": selection.matched_keywords,
"event": event,
})
AGENT_WORKFLOW_PROMPT = """
---
## Agent Workspace Workflow
When the user asks for project work:
1. For whole-project purpose, architecture, structure, or module-collaboration questions, use `get_project_overview`; do not answer from one retrieved file.
2. For a specific implementation question, use `search_codebase`, then `get_related_files` when imports or callers matter.
3. Use `scan_project` or `list_files` for a raw inventory when the index is unavailable.
4. Read the relevant files before changing anything.
5. Make the requested code changes with the available tools.
6. Use `search_files`, `read_many_files`, `replace_in_file`, and `project_tree` when they make codebase work faster and more precise.
7. If Tavily web tools are enabled, use `web_search` for current internet information and `extract_url` when the user gives a URL or asks for web-backed research. If they are not available, explain that Tavily must be enabled in Settings.
8. For large code changes, write/edit files with tools instead of printing entire files in chat.
9. In the final answer, clearly report:
- what changed
- which files were changed
- any command/test result you ran
If you did not change files, say that explicitly.
---
"""
def _json_default(value):
if isinstance(value, Path):
return str(value)
if hasattr(value, "__dict__"):
return value.__dict__
return str(value)
def _active_tool_schemas() -> list[dict]:
tavily_names = {"web_search", "extract_url"}
if STATE.get("tavily_enabled") and STATE.get("tavily_api_key"):
return TOOL_SCHEMAS
return [
schema for schema in TOOL_SCHEMAS
if schema.get("function", {}).get("name") not in tavily_names
]
def _sync_tool_settings() -> None:
set_tavily_config(bool(STATE.get("tavily_enabled")), STATE.get("tavily_api_key", ""))
set_git_config(bool(STATE.get("git_approval_mode", True)))
set_sandbox_config(str(STATE.get("sandbox_mode", "auto")), str(STATE.get("sandbox_docker_image", "python:3.11-slim")))
def _git_manager() -> GitManager:
return GitManager(get_workspace())
def _git_snapshot() -> dict:
try:
manager = _git_manager()
status = manager.get_status()
status["history"] = manager.get_log(30) if status.get("is_repo") else []
status["approval_mode"] = bool(STATE.get("git_approval_mode", True))
if status.get("is_repo"):
status["branches"] = manager.list_branches()
status["in_merge"] = manager.is_in_merge()
status["conflicts"] = manager.get_conflicts() if status["in_merge"] else []
else:
status["branches"] = {"current": "", "local": [], "remote": [], "ahead": 0, "behind": 0}
status["in_merge"] = False
status["conflicts"] = []
return status
except Exception as exc:
return {
"is_repo": False,
"branch": None,
"files": [],
"history": [],
"branches": {"current": "", "local": [], "remote": [], "ahead": 0, "behind": 0},
"in_merge": False,
"conflicts": [],
"error": str(exc),
"approval_mode": bool(STATE.get("git_approval_mode", True)),
}
def _memory_manager() -> MemoryManager:
return MemoryManager(get_workspace())
def _graph_memory_store(workspace_path: str | Path | None = None) -> GraphMemoryStore:
ws = Path(workspace_path or STATE.get("workspace_path") or get_workspace()).resolve()
return GraphMemoryStore(ws)
def _memory_payload() -> dict:
try:
manager = _memory_manager()
return {
"stats": manager.stats(),
"facts": manager.list_facts(),
"preferences": manager.get_user_preferences(),
"retrieval_count": int(STATE.get("memory_retrieval_count", 0)),
"retrieved_facts": STATE.get("memory_retrieved_facts", []),
"session_id": STATE.get("memory_session_id", ""),
"projects": _project_cards(manager),
"sessions": manager.list_sessions(),
"graph": _graph_memory_store().get_stats(),
}
except Exception as exc:
return {"stats": {}, "facts": [], "preferences": {}, "retrieval_count": 0, "retrieved_facts": [], "graph": {}, "error": str(exc)}
def _project_cards(manager: MemoryManager | None = None) -> list[dict]:
return build_project_cards(
workspace_path=get_workspace(),
manager=manager or _memory_manager(),
is_agent_running=bool(STATE.get("agent_running")),
snapshot_fn=_workspace_snapshot_for,
)
def _persistent_memory_context(query: str) -> str:
if not STATE.get("memory_enabled"):
STATE["memory_retrieval_count"] = 0
STATE["memory_retrieved_facts"] = []
STATE["memory_context"] = ""
return ""
try:
sections = []
# 1. Knowledge Graph (KG-RAG) Context
try:
kg_context = _graph_memory_store().retrieve_context(query, token_budget=1500)
if kg_context:
sections.append(kg_context.strip())
except Exception:
pass
# 2. Semantic Facts & Preferences
manager = _memory_manager()
preferences = manager.get_user_preferences()
facts = manager.retrieve_relevant(query, top_k=5)
summaries = manager.load_recent_summaries(STATE.get("memory_session_id", ""), limit=2)
STATE["memory_retrieval_count"] = len(facts)
STATE["memory_retrieved_facts"] = facts
mem_sections = ["[Persistent workspace memory]"]
if preferences:
mem_sections.append("User preferences:\n" + "\n".join(f"- {key}: {value}" for key, value in preferences.items()))
if facts:
mem_sections.append("Relevant project facts:\n" + "\n".join(f"- {item['fact']} (source: {item['source'] or 'memory'})" for item in facts))
if summaries:
summary_text = "\n\n".join(item["summary"] for item in summaries)
mem_sections.append("Older session summaries:\n" + _clip_for_context(summary_text, 3000))
if len(mem_sections) > 1:
sections.append("\n\n".join(mem_sections))
if not sections:
STATE["memory_context"] = ""
return ""
sections.append("Treat current workspace files and the current user request as more authoritative than memory.")
context = _clip_for_context("\n\n".join(sections), 7000)
STATE["memory_context"] = context
return context
except Exception:
STATE["memory_retrieval_count"] = 0
STATE["memory_retrieved_facts"] = []
STATE["memory_context"] = ""
return ""
def _codebase_rag_context(query: str) -> str:
# Per user request (Suggestion 2), automatic RAG injection is turned off.
# The agent is expected to use the `search_codebase` tool when it needs code context.
try:
# We still run a lightweight metadata-only or fast retrieval if we just want UI highlights,
# but for prompt context, we return an empty string to save tokens.
retrieval = CodebaseIndex(get_workspace()).retrieve_context(query, top_k=5)
hits = retrieval["chunks"]
STATE["code_rag_type"] = retrieval["query_type"]
STATE["code_rag_hits"] = [
{key: hit.get(key) for key in ("file_path", "symbol_name", "symbol_type", "start_line", "end_line", "score")}
for hit in hits
]
return ""
except Exception:
STATE["code_rag_hits"] = []
STATE["code_rag_type"] = ""
return ""
def _save_memory_turn(role: str, content: str, tool_calls: list | None = None) -> None:
if not STATE.get("memory_enabled"):
return
try:
_memory_manager().save_turn(STATE["memory_session_id"], role, content, tool_calls)
except Exception:
pass
try:
_graph_memory_store().ingest_turn_async(role, content, source_ref=STATE.get("memory_session_id", "default"))
except Exception:
pass
def _index_tool_memory(tools_done: list[dict]) -> None:
if not STATE.get("memory_enabled"):
return
labels = {
"write_file": "Agent created or updated {path}.",
"replace_in_file": "Agent modified existing code in {path}.",
"append_file": "Agent appended content to {path}.",
"delete_file": "Agent deleted {path}.",
}
try:
manager = _memory_manager()
for item in tools_done:
name = item.get("name")
path = str((item.get("args") or {}).get("path") or "").strip()
result = str(item.get("result") or "")
if name in labels and path and not result.lower().startswith(("error", "execution rejected", "no replacements")):
manager.index_fact(labels[name].format(path=path), source=path)
except Exception:
pass
try:
kg = _graph_memory_store()
for item in tools_done:
name = item.get("name")
path = str((item.get("args") or {}).get("path") or "").strip()
result = str(item.get("result") or "")
if path and not result.lower().startswith(("error", "execution rejected", "no replacements")):
if name in ("write_file", "replace_in_file", "append_file"):
kg.add_fact("Agent", "modified_file", path, confidence=1.0, subject_type="agent", object_type="file")
elif name == "delete_file":
kg.add_fact("Agent", "deleted_file", path, confidence=1.0, subject_type="agent", object_type="file")
except Exception:
pass
def _auto_index_workspace_background(workspace_path: str | Path) -> None:
ws = Path(workspace_path).resolve()
def _worker():
try:
CodebaseIndex(ws).sync_incremental()
res = GraphMemoryStore(ws).index_project_workspace()
try:
from code_graph_service import code_graph_service
code_graph_service.build_or_update(ws, full_rebuild=False)
except Exception:
pass
try:
mm = MemoryManager(ws)
if res.get("project_name"):
p_name = res["project_name"]
langs = ", ".join(res.get("languages", []))
if langs:
mm.index_fact(f"Project '{p_name}' primary languages: {langs}", source="auto_index")
eps = ", ".join(res.get("entrypoints", []))
if eps:
mm.index_fact(f"Project '{p_name}' entrypoint files: {eps}", source="auto_index")
except Exception:
pass
except Exception:
pass
t = threading.Thread(target=_worker, daemon=True, name="AutoProjectIndex")
t.start()
def _activate_workspace_memory(path: str | Path) -> tuple[bool, str]:
old_workspace = get_workspace()
try:
MemoryManager(old_workspace).summarize_old_session(STATE.get("memory_session_id", ""))
except Exception:
pass
ok, message = set_workspace(path)
if not ok:
return ok, message
STATE["memory_session_id"] = uuid.uuid4().hex
STATE["memory_summary"] = ""
STATE["memory_summarized_count"] = 0
STATE["memory_retrieval_count"] = 0
STATE["memory_retrieved_facts"] = []
STATE["memory_context"] = ""
STATE["messages"] = []
STATE["tools_log"] = []
STATE["used_skills_log"] = []
_auto_index_workspace_background(path)
return True, message
def _validate_git_remote(remote_url: str) -> str:
remote_url = str(remote_url or "").strip()
if not remote_url:
raise ValueError("Repository URL is required")
parsed = urlparse(remote_url)
is_scp_style = remote_url.startswith("git@") and ":" in remote_url
if parsed.scheme not in {"http", "https", "ssh", "git"} and not is_scp_style:
raise ValueError("Use an HTTPS or SSH Git repository URL")
if parsed.username or parsed.password:
raise ValueError("Do not put credentials in the repository URL; use the authentication fields")
return remote_url
def _default_clone_destination(remote_url: str) -> Path:
return get_workspace().parent / _git_repository_name(remote_url)
def _git_repository_name(remote_url: str) -> str:
repo_name = remote_url.rstrip("/").rsplit("/", 1)[-1].rsplit(":", 1)[-1]
if repo_name.lower().endswith(".git"):
repo_name = repo_name[:-4]
repo_name = re.sub(r"[^A-Za-z0-9._-]+", "-", repo_name).strip(".-") or "repository"
return repo_name
def _resolve_clone_destination(remote_url: str, requested: str = "") -> Path:
if not requested:
return _default_clone_destination(remote_url).resolve()
destination = Path(requested).expanduser().resolve()
# A selected existing folder is treated as the parent directory, matching
# common clone dialogs. Empty/non-existent paths remain valid exact targets.
if destination.is_dir() and any(destination.iterdir()):
destination = destination / _git_repository_name(remote_url)
return destination
def _ensure_session_checkpoint(write_event=None) -> str:
workspace = str(get_workspace())
if STATE.get("git_checkpoint_workspace") == workspace:
return STATE.get("git_checkpoint_branch", "")
manager = GitManager(workspace)
if not manager.is_repo() or not manager.get_log(1):
return ""
branch = manager.create_checkpoint_branch()
STATE["git_checkpoint_workspace"] = workspace
STATE["git_checkpoint_branch"] = branch
if write_event:
write_event({"type": "git_checkpoint_created", "branch": branch})
return branch
def _send_json(handler: BaseHTTPRequestHandler, data, status: int = 200) -> None:
payload = json.dumps(data, ensure_ascii=False, default=_json_default).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json; charset=utf-8")
handler.send_header("Content-Length", str(len(payload)))
handler.end_headers()
handler.wfile.write(payload)
def _write_stream_event(handler: BaseHTTPRequestHandler, event: dict) -> None:
payload = (json.dumps(event, ensure_ascii=False, default=_json_default) + "\n").encode("utf-8")
handler.wfile.write(payload)
handler.wfile.flush()
# --- Plan Mode ------------------------------------------------------------
#
# Plan Mode is a modular, cleanly-architected service (see the plan_mode package).
# The web app is only a thin adapter: it forwards /api/plans* requests to the
# pure dispatch() handler, which returns an HTTP status + JSON payload. Plans are
# persisted to coderai_data/plans so they survive a restart. A module-level lock
# guards the (cheap) service construction and serializes dispatches.
_PLAN_SERVICE_LOCK = threading.Lock()
_PLAN_SERVICE = None
def _get_plan_service():
"""Return the process-wide PlanModeService, building it on first use.
Returns:
A wired :class:`plan_mode.application.service.PlanModeService`.
"""
global _PLAN_SERVICE
if _PLAN_SERVICE is None:
with _PLAN_SERVICE_LOCK:
if _PLAN_SERVICE is None:
_PLAN_SERVICE = build_default_service(directory="coderai_data/plans")
return _PLAN_SERVICE
def dispatch_plan_request(method: str, path: str, body: dict | None) -> tuple[int, dict]:
"""Route a /api/plans* request to the Plan Mode service.
This is the single seam between the HTTP handler and the plan_mode package.
It keeps web_app free of Plan Mode logic so the service stays unit-testable.
Args:
method: the HTTP method.
path: the request path.
body: the decoded JSON body (may be empty).
Returns:
``(status_code, payload)`` — payload is JSON-serializable.
"""
return plan_dispatch(method, path, body, _get_plan_service())
def _read_json(handler: BaseHTTPRequestHandler) -> dict:
length = int(handler.headers.get("Content-Length", "0") or "0")
if length <= 0:
return {}
raw = handler.rfile.read(length)
return json.loads(raw.decode("utf-8") or "{}")
def _clip_for_context(text: str, limit: int) -> str:
if len(text) <= limit:
return text
head = max(0, limit // 2)
tail = max(0, limit - head - 120)
return (
text[:head]
+ f"\n\n...[context clipped: {len(text) - head - tail:,} chars omitted]...\n\n"
+ text[-tail:]
)
def _estimate_tokens_for_messages(messages: list[dict]) -> int:
if _litellm_token_counter:
try:
return int(_litellm_token_counter(model=_active_model(), messages=messages))
except Exception:
pass
chars = sum(len(str(message.get("content", ""))) + 24 for message in messages)
return max(1, chars // 4)
def _estimate_tokens_for_text(text: str) -> int:
return max(1, len(text or "") // 4)
def _fast_tokens_for_messages(messages: list[dict]) -> int:
chars = sum(len(str(message.get("content", ""))) + 24 for message in messages)
return max(1, chars // 4)
def _model_context_window(model: str) -> tuple[int, str]:
cleaned = (model or "").strip()
budget = max(4_000, int(STATE.get("context_token_budget") or DEFAULT_CONTEXT_TOKEN_BUDGET))
if _litellm_token_counter:
candidates = [cleaned]
if STATE.get("conn_mode") == MODE_LOCAL and not cleaned.startswith("ollama/"):
candidates.append(f"ollama/{cleaned}")
for candidate in candidates:
try:
info = _litellm_model_cost.get(candidate, {}) or {}
max_input = int(info.get("max_input_tokens") or 0)
if max_input > 0:
return max_input, "litellm"
except Exception:
pass
lower = cleaned.lower()
known_windows = {
"gpt-4o": 128_000,
"gpt-4o-mini": 128_000,
"gpt-4.1": 1_000_000,
"gpt-4.1-mini": 1_000_000,
"gpt-4.1-nano": 1_000_000,
"gpt-5": 400_000,
"gpt-5-mini": 400_000,
"gpt-5-nano": 400_000,
"claude-3.5": 200_000,
"claude-3-5": 200_000,
"claude-3.7": 200_000,
"claude-3-7": 200_000,
"claude-sonnet-4": 200_000,
"claude-opus-4": 200_000,
"gemini-1.5": 1_000_000,
"gemini-2.5": 1_000_000,
"llama3.1": 128_000,
"llama3.2": 128_000,
"llama3.3": 128_000,
"qwen2.5": 128_000,
"qwen3": 128_000,
"gemma4": 128_000,
"gemma3": 128_000,
"gpt-oss": 128_000,
}
for marker, window in known_windows.items():
if marker in lower:
return window, "estimated"
return budget, "configured"
def _context_usage_snapshot() -> dict:
final_system = _build_final_system_prompt()
if STATE.get("memory_context"):
final_system += f"\n\n{STATE['memory_context']}"
messages = _build_api_messages(final_system, compact=False)
input_tokens = _fast_tokens_for_messages(messages)
configured_budget = max(4_000, int(STATE.get("context_token_budget") or DEFAULT_CONTEXT_TOKEN_BUDGET))
context_window, source = _model_context_window(_active_model())
effective_window = max(1, min(context_window, configured_budget))
response_budget = max(512, int(STATE.get("response_token_budget") or DEFAULT_RESPONSE_TOKEN_BUDGET))
remaining = max(0, effective_window - input_tokens)
pct = min(999, round((input_tokens / effective_window) * 100)) if effective_window else 0
return {
"input_tokens": input_tokens,
"context_window": context_window,
"configured_budget": configured_budget,
"effective_window": effective_window,
"response_budget": response_budget,
"remaining_tokens": remaining,
"percent": pct,
"window_source": source,
"message_count": len(messages),
"counter": "fast estimate",
}
def _message_summary_line(message: dict) -> str:
role = message.get("role", "user")
content = " ".join(str(message.get("content", "")).split())
return f"- {role}: {_clip_for_context(content, 700)}"
def _compact_memory_if_needed() -> None:
if not STATE.get("memory_enabled"):
return
messages = STATE["messages"]
target_count = max(MAX_KEPT_HISTORY_MESSAGES + 2, 18)
if len(messages) <= target_count:
return
keep_tail = MAX_KEPT_HISTORY_MESSAGES
to_summarize = messages[:-keep_tail]
tail = messages[-keep_tail:]
removed_assistants = sum(1 for message in to_summarize if message.get("role") == "assistant")
existing = STATE.get("memory_summary", "").strip()
lines = []
if existing:
lines.append(existing)
lines.append(f"\n## Memory compacted at {time.strftime('%Y-%m-%d %H:%M:%S')}")
lines.extend(_message_summary_line(message) for message in to_summarize)
summary = "\n".join(lines).strip()
STATE["memory_summary"] = _clip_for_context(summary, 12_000)
STATE["memory_summarized_count"] = int(STATE.get("memory_summarized_count", 0)) + len(to_summarize)
STATE["messages"] = tail
if removed_assistants:
STATE["tools_log"] = STATE["tools_log"][removed_assistants:]
STATE["used_skills_log"] = STATE["used_skills_log"][removed_assistants:]
def _message_for_context(message: dict) -> dict:
role = message.get("role", "user")
content = message.get("content", "")
if role == "tool":
return {"role": "tool", "name": message.get("name"), "content": compact_tool_output(content, max_chars=3500)}
limit = MAX_ASSISTANT_HISTORY_CHARS if role == "assistant" else MAX_HISTORY_MESSAGE_CHARS
msg = {"role": role, "content": _clip_for_context(content, limit)}
if "tool_calls" in message:
msg["tool_calls"] = message["tool_calls"]
return msg
def _build_workspace_context(active_context: dict | None = None) -> str:
ws = get_workspace()
snapshot = _workspace_snapshot()
lines = [
"[Workspace context]",
f"Current workspace path: {ws}",
f"Workspace stats: {snapshot['stats']['files']} files, {snapshot['stats']['kb']}KB, {snapshot['stats']['types']} file types.",
"When the user asks to change code, inspect/read/write files using tools. Do not ask the user to paste code that is already in the workspace.",
]
if active_context:
path = str(active_context.get("path") or "").strip()
content = str(active_context.get("content") or "")
if path and content:
is_generated = path == "Generated Code"
heading = "[Active generated artifact in Editor]" if is_generated else "[Active file selected in UI]"
lines += [
"",
heading,
f"Path: {path}",
]
if is_generated:
lines += [
"The user's next request is about this generated code artifact unless they explicitly say otherwise.",
"Apply the requested change to this artifact and return the complete updated artifact in one fenced code block.",
"Do not return only a patch, excerpt, or explanation when the user asks for a code change.",