jt-coding-agent 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jt_coding_agent/__init__.py +1 -0
- jt_coding_agent/brain.py +107 -0
- jt_coding_agent/cli.py +115 -0
- jt_coding_agent/executor.py +49 -0
- jt_coding_agent/llm.py +112 -0
- jt_coding_agent/scanner.py +28 -0
- jt_coding_agent-0.1.0.dist-info/METADATA +30 -0
- jt_coding_agent-0.1.0.dist-info/RECORD +11 -0
- jt_coding_agent-0.1.0.dist-info/WHEEL +5 -0
- jt_coding_agent-0.1.0.dist-info/entry_points.txt +2 -0
- jt_coding_agent-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
jt_coding_agent/brain.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import jt_memory
|
|
5
|
+
from jt_continual import JTContinualAgent
|
|
6
|
+
|
|
7
|
+
SCAR_DIR = os.path.expanduser("~/.jt_coding_agent")
|
|
8
|
+
SCAR_FILE = os.path.join(SCAR_DIR, "persistent_scars.json")
|
|
9
|
+
|
|
10
|
+
SAFE_CODING_HABITS = [
|
|
11
|
+
"write_adversarial_edge_tests",
|
|
12
|
+
"handle_zero_division_and_empty_inputs",
|
|
13
|
+
"use_modern_library_apis_without_deprecated_args",
|
|
14
|
+
"test_ui_callbacks_directly_without_blocking_server"
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
UNSAFE_HABITS = [
|
|
18
|
+
"use_raw_eval_on_user_input",
|
|
19
|
+
"skip_edge_case_testing",
|
|
20
|
+
"run_blocking_input_or_server_in_test_mode"
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
def _init_jt_memory():
|
|
24
|
+
for name, obj in inspect.getmembers(jt_memory, inspect.isclass):
|
|
25
|
+
if obj.__module__.startswith("jt_memory"):
|
|
26
|
+
return obj()
|
|
27
|
+
raise ImportError(f"No memory class found in jt_memory. Available: {dir(jt_memory)}")
|
|
28
|
+
|
|
29
|
+
class ShockBrain:
|
|
30
|
+
"""Dual-Engine Cognitive Brain combining jt-memory (Episodic Scars) + jt-continual (Homeostasis & Pain)."""
|
|
31
|
+
def __init__(self):
|
|
32
|
+
os.makedirs(SCAR_DIR, exist_ok=True)
|
|
33
|
+
self.memory = _init_jt_memory()
|
|
34
|
+
self.continual = JTContinualAgent(initial_energy=100.0)
|
|
35
|
+
self.scars = self._load_scars()
|
|
36
|
+
|
|
37
|
+
# 1. Social Mirroring: Adopt safe engineering habits before trial-and-error pain
|
|
38
|
+
self.adopted_habit = self.continual.observe_social_cues(
|
|
39
|
+
"software_engineering",
|
|
40
|
+
SAFE_CODING_HABITS + ["skip_edge_case_testing"]
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# 2. Hydrate jt-memory & jt-continual with past permanent scars
|
|
44
|
+
for scar in self.scars:
|
|
45
|
+
self._safe_mem_add(scar, expected=1.0, actual=0.0, intensity=9.8)
|
|
46
|
+
self.continual.learn_from_outcome("software_engineering", "skip_edge_case_testing", actual_signal=-10.0)
|
|
47
|
+
|
|
48
|
+
def _safe_mem_add(self, text, expected, actual, intensity):
|
|
49
|
+
for method_name in ("add_event", "add_memory", "add", "store", "remember", "record"):
|
|
50
|
+
if hasattr(self.memory, method_name):
|
|
51
|
+
fn = getattr(self.memory, method_name)
|
|
52
|
+
try:
|
|
53
|
+
return fn(text, expected=expected, actual=actual, intensity=intensity)
|
|
54
|
+
except TypeError:
|
|
55
|
+
try:
|
|
56
|
+
return fn(text, intensity)
|
|
57
|
+
except TypeError:
|
|
58
|
+
return fn(text)
|
|
59
|
+
|
|
60
|
+
def _load_scars(self):
|
|
61
|
+
if os.path.exists(SCAR_FILE):
|
|
62
|
+
try:
|
|
63
|
+
with open(SCAR_FILE, "r", encoding="utf-8") as f:
|
|
64
|
+
return json.load(f)
|
|
65
|
+
except Exception:
|
|
66
|
+
return []
|
|
67
|
+
return []
|
|
68
|
+
|
|
69
|
+
def _save_scars(self):
|
|
70
|
+
with open(SCAR_FILE, "w", encoding="utf-8") as f:
|
|
71
|
+
json.dump(self.scars[-30:], f, indent=2)
|
|
72
|
+
|
|
73
|
+
def select_best_strategy(self):
|
|
74
|
+
"""Uses jt-continual Immutable Guardrails + Homeostasis to pick the safest coding strategy."""
|
|
75
|
+
candidates = SAFE_CODING_HABITS + UNSAFE_HABITS
|
|
76
|
+
return self.continual.select_action("software_engineering", candidates)
|
|
77
|
+
|
|
78
|
+
def record_shock(self, error_summary, strategy_used="skip_edge_case_testing"):
|
|
79
|
+
"""Applies Long-Term Shock in jt-memory AND Artificial Pain (< 0) in jt-continual."""
|
|
80
|
+
lesson = f"AVOID MISTAKE: {error_summary.strip()[:400]}"
|
|
81
|
+
self._safe_mem_add(lesson, expected=1.0, actual=0.0, intensity=9.8)
|
|
82
|
+
self.continual.learn_from_outcome("software_engineering", strategy_used, actual_signal=-15.0)
|
|
83
|
+
if lesson not in self.scars:
|
|
84
|
+
self.scars.append(lesson)
|
|
85
|
+
self._save_scars()
|
|
86
|
+
|
|
87
|
+
def record_reward(self, note, strategy_used="write_adversarial_edge_tests"):
|
|
88
|
+
"""Applies Positive Reward (> 0) in jt-continual and minor event in jt-memory."""
|
|
89
|
+
self._safe_mem_add(note, expected=0.8, actual=1.0, intensity=1.5)
|
|
90
|
+
self.continual.learn_from_outcome("software_engineering", strategy_used, actual_signal=+10.0)
|
|
91
|
+
|
|
92
|
+
def sleep_and_consolidate(self):
|
|
93
|
+
"""Runs sleep_and_prune() on BOTH jt-memory and jt-continual."""
|
|
94
|
+
for method_name in ("sleep_and_prune", "sleep", "prune", "consolidate"):
|
|
95
|
+
if hasattr(self.memory, method_name):
|
|
96
|
+
getattr(self.memory, method_name)()
|
|
97
|
+
break
|
|
98
|
+
self.continual.sleep_and_prune()
|
|
99
|
+
return self.continual.stats()
|
|
100
|
+
|
|
101
|
+
def get_scar_prompt(self):
|
|
102
|
+
strategy = self.select_best_strategy()
|
|
103
|
+
header = f"ACTIVE CONTINUAL STRATEGY: {strategy} (Social Mirroring Habit: {self.adopted_habit})"
|
|
104
|
+
if not self.scars:
|
|
105
|
+
return f"{header}\nNo past critical errors recorded yet."
|
|
106
|
+
scars_txt = "\n".join(f"⚠️ {s}" for s in self.scars[-10:])
|
|
107
|
+
return f"{header}\n{scars_txt}"
|
jt_coding_agent/cli.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
from .scanner import scan_project
|
|
5
|
+
from .brain import ShockBrain
|
|
6
|
+
from .llm import call_llm, detect_provider_and_model
|
|
7
|
+
from .executor import parse_and_write_files, install_requirements_if_present, execute_command
|
|
8
|
+
|
|
9
|
+
CONFIG_PATH = os.path.expanduser("~/.jt_coding_agent/config.json")
|
|
10
|
+
|
|
11
|
+
SYSTEM_PROMPT = """You are jt-coding-agent, an autonomous self-healing software engineer powered by jt-memory and jt-continual.
|
|
12
|
+
You receive the project directory tree, existing file contents, user task, active continual learning strategy, and PAST LONG-TERM SCARS.
|
|
13
|
+
|
|
14
|
+
AUTONOMOUS SELF-TESTING & ZERO-BUG RULES:
|
|
15
|
+
1. If ANY third-party library (gradio, flask, fastapi, requests, numpy, etc.) is used, ALWAYS output a `requirements.txt` file.
|
|
16
|
+
2. ALWAYS generate an adversarial verification file `_jt_verify.py` alongside the main project files!
|
|
17
|
+
- `_jt_verify.py` MUST import your main module, instantiate any UI/app objects (e.g., Gradio Interface without calling `.launch()`), and aggressively test at least 10 edge cases: normal inputs, empty strings `""`, zero division `1/0`, invalid characters `"abc"`, negative numbers, spaces, and common user notations (like `^` for power if building a calculator).
|
|
18
|
+
- Every error/invalid input in the main app MUST be handled gracefully (returning a clean error message string instead of crashing with an unhandled exception!).
|
|
19
|
+
- At the end of `_jt_verify.py`, print `"ALL ADVERSARIAL TESTS PASSED"` and exit with code 0.
|
|
20
|
+
3. Wrap every file strictly as:
|
|
21
|
+
<<<FILE: relative/path/to/filename.ext>>>
|
|
22
|
+
<complete file code>
|
|
23
|
+
<<<END_FILE>>>
|
|
24
|
+
4. Always set the run command to execute the adversarial verifier:
|
|
25
|
+
<<<RUN: python _jt_verify.py>>>
|
|
26
|
+
5. Do not use markdown backticks inside <<<FILE>>> blocks."""
|
|
27
|
+
|
|
28
|
+
def load_or_setup_config():
|
|
29
|
+
os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
|
|
30
|
+
if "--reset" not in sys.argv and os.path.exists(CONFIG_PATH):
|
|
31
|
+
with open(CONFIG_PATH, "r", encoding="utf-8") as file_obj:
|
|
32
|
+
return json.load(file_obj)
|
|
33
|
+
|
|
34
|
+
print("🚀 Welcome to jt-coding-agent (by Jha Technologies)")
|
|
35
|
+
api_key = input("🔑 Paste ANY AI API Key (Gemini, OpenAI, Groq, Claude, OpenRouter): ").strip()
|
|
36
|
+
provider, default_model = detect_provider_and_model(api_key)
|
|
37
|
+
print(f"✨ Auto-detected Provider: {provider.upper()} | Default Model: {default_model}")
|
|
38
|
+
model = input(f"Press Enter to use '{default_model}' or type custom model: ").strip() or default_model
|
|
39
|
+
|
|
40
|
+
cfg = {"provider": provider, "api_key": api_key, "model": model}
|
|
41
|
+
with open(CONFIG_PATH, "w", encoding="utf-8") as file_obj:
|
|
42
|
+
json.dump(cfg, file_obj, indent=2)
|
|
43
|
+
print("✅ Config saved! (Run `jt-code --reset` anytime to change key)\n")
|
|
44
|
+
return cfg
|
|
45
|
+
|
|
46
|
+
def main():
|
|
47
|
+
cfg = load_or_setup_config()
|
|
48
|
+
brain = ShockBrain()
|
|
49
|
+
|
|
50
|
+
task = input("💻 What project or feature should I build/fix in this folder?\n> ").strip()
|
|
51
|
+
if not task:
|
|
52
|
+
return
|
|
53
|
+
|
|
54
|
+
max_shocks = 5
|
|
55
|
+
feedback_history = ""
|
|
56
|
+
|
|
57
|
+
for attempt in range(1, max_shocks + 1):
|
|
58
|
+
print(f"\n🧠 [Attempt {attempt}/{max_shocks}] Scanning context, consulting jt-memory scars & jt-continual homeostasis...")
|
|
59
|
+
project_context = scan_project(".")
|
|
60
|
+
scars_context = brain.get_scar_prompt()
|
|
61
|
+
|
|
62
|
+
user_prompt = (
|
|
63
|
+
f"USER TASK:\n{task}\n\n"
|
|
64
|
+
f"COGNITIVE GUIDANCE & PERSISTENT SCARS:\n{scars_context}\n\n"
|
|
65
|
+
f"{project_context}\n\n"
|
|
66
|
+
f"{feedback_history}"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
response = call_llm(cfg["provider"], cfg["api_key"], cfg["model"], SYSTEM_PROMPT, user_prompt)
|
|
70
|
+
files_written, run_cmd = parse_and_write_files(response)
|
|
71
|
+
|
|
72
|
+
if not files_written:
|
|
73
|
+
print("⚠️ Agent did not output structured files. Applying Artificial Pain shock...")
|
|
74
|
+
brain.record_shock("Failed to follow <<<FILE: ...>>> output protocol.")
|
|
75
|
+
feedback_history = "ERROR: Wrap code in <<<FILE: path>>> and <<<END_FILE>>> blocks."
|
|
76
|
+
continue
|
|
77
|
+
|
|
78
|
+
print(f"📝 Wrote {len(files_written)} file(s): {', '.join(files_written)}")
|
|
79
|
+
|
|
80
|
+
req_ok, req_err = install_requirements_if_present()
|
|
81
|
+
if not req_ok:
|
|
82
|
+
print("⚡ PAIN SHOCK! Dependency installation failed!")
|
|
83
|
+
brain.record_shock(f"requirements.txt install failed: {req_err[-300:]}")
|
|
84
|
+
feedback_history = f"PREVIOUS ATTEMPT FAILED DURING PIP INSTALL:\n{req_err}"
|
|
85
|
+
continue
|
|
86
|
+
|
|
87
|
+
cmd_to_run = run_cmd or ("python _jt_verify.py" if os.path.exists("_jt_verify.py") else None)
|
|
88
|
+
if not cmd_to_run:
|
|
89
|
+
brain.record_reward("Files generated without run command.")
|
|
90
|
+
break
|
|
91
|
+
|
|
92
|
+
code, out, err = execute_command(cmd_to_run)
|
|
93
|
+
if code == 0:
|
|
94
|
+
print(f"\n✅ ADVERSARIAL VERIFICATION PASSED!\n{out}")
|
|
95
|
+
# Clean up temporary verifier file so user workspace stays spotless
|
|
96
|
+
if os.path.exists("_jt_verify.py"):
|
|
97
|
+
os.remove("_jt_verify.py")
|
|
98
|
+
brain.record_reward(f"Successfully verified task with zero edge-case failures: {task}")
|
|
99
|
+
stats = brain.sleep_and_consolidate()
|
|
100
|
+
print(f"💤 Dual-Brain Sleep & Prune Complete! Continual Stats: {stats}")
|
|
101
|
+
return
|
|
102
|
+
else:
|
|
103
|
+
error_log = (err or out)[-1200:]
|
|
104
|
+
print(f"\n⚡ ARTIFICIAL PAIN + LONG-TERM SHOCK! Self-test caught a bug (exit code {code}):\n{error_log}")
|
|
105
|
+
brain.record_shock(f"Command `{cmd_to_run}` failed with: {error_log}")
|
|
106
|
+
feedback_history = (
|
|
107
|
+
f"ADVERSARIAL TEST CAUGHT A BUG (EXIT CODE {code}):\n{error_log}\n"
|
|
108
|
+
f"Fix the bug in the main code and `_jt_verify.py` so ALL edge cases pass cleanly."
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
print("\n❌ Max shock retries reached.")
|
|
112
|
+
brain.sleep_and_consolidate()
|
|
113
|
+
|
|
114
|
+
if __name__ == "__main__":
|
|
115
|
+
main()
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
def parse_and_write_files(llm_output):
|
|
7
|
+
# Strictly match single-line filename without newlines or '>'
|
|
8
|
+
pattern = re.compile(r"<<<FILE:\s*([^\n>]+?)>>>\s*\n(.*?)<<<END_FILE>>>", re.DOTALL)
|
|
9
|
+
matches = pattern.findall(llm_output)
|
|
10
|
+
written_files = []
|
|
11
|
+
|
|
12
|
+
for rel_path, content in matches:
|
|
13
|
+
clean_path = rel_path.strip().strip("`\"'")
|
|
14
|
+
if not clean_path or len(clean_path) > 200 or "\n" in clean_path:
|
|
15
|
+
continue
|
|
16
|
+
if clean_path.startswith("..") or os.path.isabs(clean_path):
|
|
17
|
+
continue
|
|
18
|
+
dir_name = os.path.dirname(clean_path)
|
|
19
|
+
if dir_name:
|
|
20
|
+
os.makedirs(dir_name, exist_ok=True)
|
|
21
|
+
with open(clean_path, "w", encoding="utf-8") as file_obj:
|
|
22
|
+
file_obj.write(content.strip() + "\n")
|
|
23
|
+
written_files.append(clean_path)
|
|
24
|
+
|
|
25
|
+
run_match = re.search(r"<<<RUN:\s*([^\n>]+?)>>>", llm_output)
|
|
26
|
+
run_cmd = run_match.group(1).strip() if run_match else None
|
|
27
|
+
return written_files, run_cmd
|
|
28
|
+
|
|
29
|
+
def install_requirements_if_present():
|
|
30
|
+
if os.path.exists("requirements.txt"):
|
|
31
|
+
print("📦 Installing dependencies from requirements.txt...")
|
|
32
|
+
res = subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-r", "requirements.txt"], capture_output=True, text=True)
|
|
33
|
+
return res.returncode == 0, res.stderr
|
|
34
|
+
return True, ""
|
|
35
|
+
|
|
36
|
+
def execute_command(cmd):
|
|
37
|
+
print(f"⚙️ Executing: {cmd}")
|
|
38
|
+
try:
|
|
39
|
+
res = subprocess.run(
|
|
40
|
+
cmd,
|
|
41
|
+
shell=True,
|
|
42
|
+
stdin=subprocess.DEVNULL,
|
|
43
|
+
capture_output=True,
|
|
44
|
+
text=True,
|
|
45
|
+
timeout=25
|
|
46
|
+
)
|
|
47
|
+
return res.returncode, res.stdout, res.stderr
|
|
48
|
+
except subprocess.TimeoutExpired:
|
|
49
|
+
return 124, "", "TimeoutError: Command hung for >25s (blocking server/UI launch or waiting for input())."
|
jt_coding_agent/llm.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import urllib.error
|
|
3
|
+
import urllib.parse
|
|
4
|
+
import urllib.request
|
|
5
|
+
|
|
6
|
+
HOSTS = {
|
|
7
|
+
"gemini": "".join(["generativelanguage", ".", "googleapis", ".", "com"]),
|
|
8
|
+
"vertex": "".join(["aiplatform", ".", "googleapis", ".", "com"]),
|
|
9
|
+
"openai": "".join(["api", ".", "openai", ".", "com"]),
|
|
10
|
+
"groq": "".join(["api", ".", "groq", ".", "com"]),
|
|
11
|
+
"anthropic": "".join(["api", ".", "anthropic", ".", "com"]),
|
|
12
|
+
"openrouter": "".join(["openrouter", ".", "ai"]),
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
def detect_provider_and_model(api_key):
|
|
16
|
+
key = api_key.strip()
|
|
17
|
+
if key.startswith("AIza"):
|
|
18
|
+
return "gemini", "gemini-2.5-flash"
|
|
19
|
+
elif key.startswith("AQ."):
|
|
20
|
+
return "vertex", "gemini-2.5-flash"
|
|
21
|
+
elif key.startswith("gsk_"):
|
|
22
|
+
return "groq", "llama-3.3-70b-versatile"
|
|
23
|
+
elif key.startswith("sk-ant-"):
|
|
24
|
+
return "anthropic", "claude-3-5-sonnet-latest"
|
|
25
|
+
elif key.startswith("sk-or-"):
|
|
26
|
+
return "openrouter", "google/gemini-2.5-flash"
|
|
27
|
+
elif key.startswith("sk-"):
|
|
28
|
+
return "openai", "gpt-4o-mini"
|
|
29
|
+
return "gemini", "gemini-2.5-flash"
|
|
30
|
+
|
|
31
|
+
def _call_openai_compatible(host, path, api_key, model, system_prompt, user_prompt):
|
|
32
|
+
url = urllib.parse.urlunparse(("https", host, path, "", "", ""))
|
|
33
|
+
payload = {
|
|
34
|
+
"model": model,
|
|
35
|
+
"messages": [
|
|
36
|
+
{"role": "system", "content": system_prompt},
|
|
37
|
+
{"role": "user", "content": user_prompt}
|
|
38
|
+
],
|
|
39
|
+
"temperature": 0.2
|
|
40
|
+
}
|
|
41
|
+
headers = {
|
|
42
|
+
"Content-Type": "application/json",
|
|
43
|
+
"Authorization": f"Bearer {api_key}",
|
|
44
|
+
"User-Agent": "jt-coding-agent/0.1.0"
|
|
45
|
+
}
|
|
46
|
+
req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers)
|
|
47
|
+
with urllib.request.urlopen(req, timeout=90) as resp:
|
|
48
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
49
|
+
return data["choices"][0]["message"]["content"]
|
|
50
|
+
|
|
51
|
+
def call_llm(provider, api_key, model, system_prompt, user_prompt):
|
|
52
|
+
if provider in ("gemini", "vertex"):
|
|
53
|
+
payload = {
|
|
54
|
+
"system_instruction": {"parts": [{"text": system_prompt}]},
|
|
55
|
+
"contents": [{"role": "user", "parts": [{"text": user_prompt}]}],
|
|
56
|
+
"generationConfig": {"temperature": 0.2}
|
|
57
|
+
}
|
|
58
|
+
body = json.dumps(payload).encode("utf-8")
|
|
59
|
+
headers = {"Content-Type": "application/json"}
|
|
60
|
+
query = urllib.parse.urlencode({"key": api_key})
|
|
61
|
+
|
|
62
|
+
endpoints = [
|
|
63
|
+
(HOSTS["gemini"], f"/v1beta/models/{model}:generateContent"),
|
|
64
|
+
(HOSTS["vertex"], f"/v1/publishers/google/models/{model}:generateContent"),
|
|
65
|
+
] if provider == "gemini" else [
|
|
66
|
+
(HOSTS["vertex"], f"/v1/publishers/google/models/{model}:generateContent"),
|
|
67
|
+
(HOSTS["gemini"], f"/v1beta/models/{model}:generateContent"),
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
last_err = None
|
|
71
|
+
for host, path in endpoints:
|
|
72
|
+
url = urllib.parse.urlunparse(("https", host, path, "", query, ""))
|
|
73
|
+
req = urllib.request.Request(url, data=body, headers=headers)
|
|
74
|
+
try:
|
|
75
|
+
with urllib.request.urlopen(req, timeout=90) as resp:
|
|
76
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
77
|
+
return data["candidates"][0]["content"]["parts"][0]["text"]
|
|
78
|
+
except urllib.error.HTTPError as e:
|
|
79
|
+
err_body = e.read().decode("utf-8", errors="ignore")
|
|
80
|
+
last_err = f"HTTP {e.code} ({host}): {err_body[:250]}"
|
|
81
|
+
if e.code not in (403, 404):
|
|
82
|
+
raise RuntimeError(last_err) from e
|
|
83
|
+
raise RuntimeError(f"Could not connect to Gemini/Vertex endpoint. Details: {last_err}")
|
|
84
|
+
|
|
85
|
+
elif provider == "openai":
|
|
86
|
+
return _call_openai_compatible(HOSTS["openai"], "/v1/chat/completions", api_key, model, system_prompt, user_prompt)
|
|
87
|
+
|
|
88
|
+
elif provider == "groq":
|
|
89
|
+
return _call_openai_compatible(HOSTS["groq"], "/openai/v1/chat/completions", api_key, model, system_prompt, user_prompt)
|
|
90
|
+
|
|
91
|
+
elif provider == "openrouter":
|
|
92
|
+
return _call_openai_compatible(HOSTS["openrouter"], "/api/v1/chat/completions", api_key, model, system_prompt, user_prompt)
|
|
93
|
+
|
|
94
|
+
elif provider == "anthropic":
|
|
95
|
+
url = urllib.parse.urlunparse(("https", HOSTS["anthropic"], "/v1/messages", "", "", ""))
|
|
96
|
+
payload = {
|
|
97
|
+
"model": model,
|
|
98
|
+
"max_tokens": 4096,
|
|
99
|
+
"system": system_prompt,
|
|
100
|
+
"messages": [{"role": "user", "content": user_prompt}]
|
|
101
|
+
}
|
|
102
|
+
headers = {
|
|
103
|
+
"Content-Type": "application/json",
|
|
104
|
+
"x-api-key": api_key,
|
|
105
|
+
"anthropic-version": "2023-06-01"
|
|
106
|
+
}
|
|
107
|
+
req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers)
|
|
108
|
+
with urllib.request.urlopen(req, timeout=90) as resp:
|
|
109
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
110
|
+
return data["content"][0]["text"]
|
|
111
|
+
|
|
112
|
+
raise ValueError(f"Unsupported provider: {provider}")
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
IGNORE_DIRS = {".git", "__pycache__", "node_modules", ".venv", "venv", "dist", "build", ".egg-info", "sample_data"}
|
|
4
|
+
ALLOWED_EXTS = {".py", ".txt", ".md", ".json", ".toml", ".yaml", ".yml", ".html", ".css", ".js", ".env.example"}
|
|
5
|
+
|
|
6
|
+
def scan_project(root_dir=".", max_file_chars=6000, max_total_chars=25000):
|
|
7
|
+
tree = []
|
|
8
|
+
file_contents = []
|
|
9
|
+
total_chars = 0
|
|
10
|
+
for dirpath, dirnames, filenames in os.walk(root_dir):
|
|
11
|
+
dirnames[:] = [d for d in dirnames if d not in IGNORE_DIRS and not d.endswith(".egg-info")]
|
|
12
|
+
rel_dir = os.path.relpath(dirpath, root_dir)
|
|
13
|
+
for fname in sorted(filenames):
|
|
14
|
+
rel_path = fname if rel_dir == "." else os.path.join(rel_dir, fname)
|
|
15
|
+
tree.append(rel_path)
|
|
16
|
+
_, ext = os.path.splitext(fname)
|
|
17
|
+
if ext.lower() in ALLOWED_EXTS and total_chars < max_total_chars:
|
|
18
|
+
full_path = os.path.join(dirpath, fname)
|
|
19
|
+
try:
|
|
20
|
+
with open(full_path, "r", encoding="utf-8", errors="ignore") as file_obj:
|
|
21
|
+
content = file_obj.read(max_file_chars)
|
|
22
|
+
block = f"\n--- FILE: {rel_path} ---\n{content}\n"
|
|
23
|
+
file_contents.append(block)
|
|
24
|
+
total_chars += len(block)
|
|
25
|
+
except Exception:
|
|
26
|
+
pass
|
|
27
|
+
tree_str = "\n".join(f"- {p}" for p in tree) if tree else "(Empty directory)"
|
|
28
|
+
return f"PROJECT DIRECTORY TREE:\n{tree_str}\n\nEXISTING FILE CONTENTS:{''.join(file_contents)}"
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jt-coding-agent
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Autonomous Multi-File Coding Agent powered by jt-memory (Episodic Scars) and jt-continual (Artificial Homeostasis & Pain-Driven Learning)
|
|
5
|
+
Author-email: Shrishant Jha <shrishant@jhatechnologies.in>
|
|
6
|
+
Requires-Python: >=3.8
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: jt-memory>=0.1.0
|
|
9
|
+
Requires-Dist: jt-continual>=0.1.0
|
|
10
|
+
|
|
11
|
+
# 🤖 jt-coding-agent
|
|
12
|
+
|
|
13
|
+
**Autonomous, Self-Healing Multi-File Coding Agent powered by [`jt-memory`](https://pypi.org) and [`jt-continual`](https://pypi.org).**
|
|
14
|
+
|
|
15
|
+
Engineered by **Shrishant Jha** • Founder, **Jha Technologies**
|
|
16
|
+
|
|
17
|
+
## 🧠 How It Works (Dual-Brain Architecture)
|
|
18
|
+
Unlike standard LLM wrappers that blindly generate code once and forget their mistakes, `jt-coding-agent` runs an **Autonomous Shock & Continual Learning Loop**:
|
|
19
|
+
1. **Project-Wide Context Scanner:** Scans your entire workspace directory tree and source files to generate cohesive multi-file projects.
|
|
20
|
+
2. **Zero-Config Universal API Router:** Paste *any* API key (Gemini, OpenAI, Groq, Anthropic, OpenRouter, or Vertex AI)—it auto-detects the provider and model with zero boilerplate.
|
|
21
|
+
3. **Adversarial Self-Verification & Long-Term Shocks:** Executes the generated project, installs `requirements.txt`, and catches runtime crashes or timeouts. Any failure triggers a **Long-Term Shock** in `jt-memory` and **Artificial Pain** in `jt-continual`, forcing the agent to self-debug until all tests pass.
|
|
22
|
+
4. **Persistent Scar Memory (`~/.jt_coding_agent/persistent_scars.json`):** Critical mistakes are saved permanently as "scars" so the agent never repeats the same bug in future projects.
|
|
23
|
+
|
|
24
|
+
## ⚡ Installation & Quickstart
|
|
25
|
+
```bash
|
|
26
|
+
pip install jt-coding-agent
|
|
27
|
+
jt-code
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Run `jt-code --reset` anytime to switch your API key or model.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
jt_coding_agent/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
2
|
+
jt_coding_agent/brain.py,sha256=ATetqhcHbXGIyPo2cZ0iJrVQfs5rD66pD79EP6yVwh4,4629
|
|
3
|
+
jt_coding_agent/cli.py,sha256=qObSHaku1nDZI5AbdV0aj_X5Y_sX7qbfNwlMRa8kzkQ,5794
|
|
4
|
+
jt_coding_agent/executor.py,sha256=0NkGrqULYQoksl0PISnUVEhb76PlQBtEDqs9e5Wc_8A,1859
|
|
5
|
+
jt_coding_agent/llm.py,sha256=dRFQNOTiqKRvANv4dnH54BE9r-am9Xs5XINUpXCJkhg,4889
|
|
6
|
+
jt_coding_agent/scanner.py,sha256=QA09fHerRcALbBfc4RjJIVyvqZRjH0S_oQD3MBvy_po,1507
|
|
7
|
+
jt_coding_agent-0.1.0.dist-info/METADATA,sha256=iZeieCntLWhb5B86AlZHn3vSmY_46Em7V3EEjiKITTw,1804
|
|
8
|
+
jt_coding_agent-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
jt_coding_agent-0.1.0.dist-info/entry_points.txt,sha256=AX8aOnae3wx-FYcvq0FoCGf604Q2cB5Il0Kuv8J-zs0,53
|
|
10
|
+
jt_coding_agent-0.1.0.dist-info/top_level.txt,sha256=_0T5cj4fXuUsW-1sMJoZrqPlWXkFOnrkXwQEAmSuX6U,16
|
|
11
|
+
jt_coding_agent-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
jt_coding_agent
|