codetheory 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.
- codetheory-0.1.0.dist-info/METADATA +58 -0
- codetheory-0.1.0.dist-info/RECORD +15 -0
- codetheory-0.1.0.dist-info/WHEEL +5 -0
- codetheory-0.1.0.dist-info/entry_points.txt +2 -0
- codetheory-0.1.0.dist-info/licenses/LICENSE +21 -0
- codetheory-0.1.0.dist-info/top_level.txt +1 -0
- local_agent/__init__.py +4 -0
- local_agent/cli.py +698 -0
- local_agent/config.py +263 -0
- local_agent/loop.py +460 -0
- local_agent/orchestrator.py +221 -0
- local_agent/providers.py +593 -0
- local_agent/sessions.py +85 -0
- local_agent/tools.py +820 -0
- local_agent/ui.py +448 -0
local_agent/config.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""Configuration, provider registry, settings, themes, and secret redaction."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import socket
|
|
7
|
+
import struct
|
|
8
|
+
import sys
|
|
9
|
+
import tempfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
# ── Limits & Defaults ─────────────────────────────────────────────────────────
|
|
14
|
+
|
|
15
|
+
MAX_READ_BYTES = 12_000
|
|
16
|
+
MAX_EDIT_BYTES = 5_000_000
|
|
17
|
+
MAX_CMD_OUTPUT = 8_000
|
|
18
|
+
MAX_TOOL_MSG = 3_000
|
|
19
|
+
MAX_LIST_ENTRIES = 100
|
|
20
|
+
MAX_FETCH_BYTES = 1_000_000
|
|
21
|
+
DEFAULT_CMD_TIMEOUT = 60
|
|
22
|
+
INSTALL_TIMEOUT = 900
|
|
23
|
+
HTTP_TIMEOUT = 180
|
|
24
|
+
MAX_RETRIES = 4
|
|
25
|
+
TRASH_DIR = Path.home() / ".agent_trash"
|
|
26
|
+
|
|
27
|
+
SETTINGS_DEFAULTS: dict[str, Any] = {
|
|
28
|
+
"num_ctx": int(os.getenv("OLLAMA_NUM_CTX", "16384")),
|
|
29
|
+
"max_output_tokens": 4096,
|
|
30
|
+
"temperature": 0.2,
|
|
31
|
+
"max_turns": 15,
|
|
32
|
+
"num_gpu": int(os.getenv("OLLAMA_NUM_GPU", "33")),
|
|
33
|
+
"theme": "cyan",
|
|
34
|
+
"shell": "auto",
|
|
35
|
+
"auto_approve": os.getenv("AGENT_AUTO", "1") != "0",
|
|
36
|
+
"think_mode": False,
|
|
37
|
+
"alt_screen": True,
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ── ANSI Themes ───────────────────────────────────────────────────────────────
|
|
42
|
+
|
|
43
|
+
THEMES: dict[str, dict[str, str]] = {
|
|
44
|
+
"cyan": {"primary": "\033[36m", "accent": "\033[32m", "warn": "\033[33m", "sub": "\033[35m", "prompt": "\033[34m"},
|
|
45
|
+
"emerald": {"primary": "\033[32m", "accent": "\033[36m", "warn": "\033[33m", "sub": "\033[34m", "prompt": "\033[32m"},
|
|
46
|
+
"amber": {"primary": "\033[33m", "accent": "\033[32m", "warn": "\033[35m", "sub": "\033[36m", "prompt": "\033[33m"},
|
|
47
|
+
"rose": {"primary": "\033[35m", "accent": "\033[36m", "warn": "\033[33m", "sub": "\033[31m", "prompt": "\033[35m"},
|
|
48
|
+
"plain": {"primary": "", "accent": "", "warn": "", "sub": "", "prompt": ""},
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class C:
|
|
53
|
+
RESET = "\033[0m"
|
|
54
|
+
BOLD = "\033[1m"
|
|
55
|
+
DIM = "\033[2m"
|
|
56
|
+
ITALIC = "\033[3m"
|
|
57
|
+
CYAN = "\033[36m"
|
|
58
|
+
GREEN = "\033[32m"
|
|
59
|
+
YELLOW = "\033[33m"
|
|
60
|
+
RED = "\033[31m"
|
|
61
|
+
MAGENTA = "\033[35m"
|
|
62
|
+
BLUE = "\033[34m"
|
|
63
|
+
GRAY = "\033[90m"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def apply_theme(name: str) -> None:
|
|
67
|
+
t = THEMES.get(name, THEMES["cyan"])
|
|
68
|
+
if name == "plain" or not sys.stdout.isatty():
|
|
69
|
+
for attr in ("RESET", "BOLD", "DIM", "ITALIC", "CYAN", "GREEN", "YELLOW", "RED", "MAGENTA", "BLUE", "GRAY"):
|
|
70
|
+
setattr(C, attr, "" if name == "plain" else getattr(C, attr))
|
|
71
|
+
if name != "plain":
|
|
72
|
+
C.CYAN, C.GREEN, C.YELLOW = t["primary"], t["accent"], t["warn"]
|
|
73
|
+
C.MAGENTA, C.BLUE = t["sub"], t["prompt"]
|
|
74
|
+
return
|
|
75
|
+
C.RESET = "\033[0m"
|
|
76
|
+
C.BOLD = "\033[1m"
|
|
77
|
+
C.DIM = "\033[2m"
|
|
78
|
+
C.ITALIC = "\033[3m"
|
|
79
|
+
C.RED = "\033[31m"
|
|
80
|
+
C.GRAY = "\033[90m"
|
|
81
|
+
C.CYAN = t["primary"]
|
|
82
|
+
C.GREEN = t["accent"]
|
|
83
|
+
C.YELLOW = t["warn"]
|
|
84
|
+
C.MAGENTA = t["sub"]
|
|
85
|
+
C.BLUE = t["prompt"]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# ── Provider & Search Registries ──────────────────────────────────────────────
|
|
89
|
+
|
|
90
|
+
def _p(label: str, kind: str, base: str, env: list[str], key_url: str, model: str = "",
|
|
91
|
+
needs_key: bool = True) -> dict[str, Any]:
|
|
92
|
+
return {"label": label, "kind": kind, "base_url": base, "env": env,
|
|
93
|
+
"key_url": key_url, "model": model, "needs_key": needs_key}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
PROVIDERS: dict[str, dict[str, Any]] = {
|
|
97
|
+
"ollama": _p("Ollama (local)", "ollama", "", [], "https://ollama.com/download", needs_key=False),
|
|
98
|
+
"lmstudio": _p("LM Studio (local)", "openai", "http://127.0.0.1:1234/v1", [], "https://lmstudio.ai", needs_key=False),
|
|
99
|
+
"openai": _p("OpenAI", "openai", "https://api.openai.com/v1", ["OPENAI_API_KEY"],
|
|
100
|
+
"https://platform.openai.com/api-keys"),
|
|
101
|
+
"anthropic": _p("Anthropic (Claude)", "anthropic", "https://api.anthropic.com/v1", ["ANTHROPIC_API_KEY"],
|
|
102
|
+
"https://console.anthropic.com/settings/keys", "claude-sonnet-4-20250514"),
|
|
103
|
+
"gemini": _p("Google Gemini", "openai", "https://generativelanguage.googleapis.com/v1beta/openai",
|
|
104
|
+
["GEMINI_API_KEY", "GOOGLE_API_KEY"], "https://aistudio.google.com/apikey"),
|
|
105
|
+
"groq": _p("Groq", "openai", "https://api.groq.com/openai/v1", ["GROQ_API_KEY"],
|
|
106
|
+
"https://console.groq.com/keys", "openai/gpt-oss-120b"),
|
|
107
|
+
"openrouter": _p("OpenRouter", "openai", "https://openrouter.ai/api/v1", ["OPENROUTER_API_KEY"],
|
|
108
|
+
"https://openrouter.ai/keys", "openrouter/free"),
|
|
109
|
+
"mistral": _p("Mistral", "openai", "https://api.mistral.ai/v1", ["MISTRAL_API_KEY"],
|
|
110
|
+
"https://console.mistral.ai/api-keys"),
|
|
111
|
+
"deepseek": _p("DeepSeek", "openai", "https://api.deepseek.com/v1", ["DEEPSEEK_API_KEY"],
|
|
112
|
+
"https://platform.deepseek.com/api_keys"),
|
|
113
|
+
"xai": _p("xAI (Grok)", "openai", "https://api.x.ai/v1", ["XAI_API_KEY"], "https://console.x.ai"),
|
|
114
|
+
"together": _p("Together AI", "openai", "https://api.together.xyz/v1", ["TOGETHER_API_KEY"],
|
|
115
|
+
"https://api.together.ai/settings/api-keys"),
|
|
116
|
+
"fireworks": _p("Fireworks AI", "openai", "https://api.fireworks.ai/inference/v1", ["FIREWORKS_API_KEY"],
|
|
117
|
+
"https://fireworks.ai/account/api-keys"),
|
|
118
|
+
"cerebras": _p("Cerebras", "openai", "https://api.cerebras.ai/v1", ["CEREBRAS_API_KEY"],
|
|
119
|
+
"https://cloud.cerebras.ai"),
|
|
120
|
+
"nvidia": _p("NVIDIA NIM", "openai", "https://integrate.api.nvidia.com/v1", ["NVIDIA_API_KEY"],
|
|
121
|
+
"https://build.nvidia.com"),
|
|
122
|
+
"custom": _p("Custom (OpenAI-compatible URL)", "openai", "", ["CUSTOM_API_KEY"],
|
|
123
|
+
"your provider's dashboard", needs_key=False),
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
SEARCH_BACKENDS: dict[str, dict[str, Any]] = {
|
|
127
|
+
"duckduckgo": {"label": "DuckDuckGo (no key, best effort)", "env": None, "key_url": ""},
|
|
128
|
+
"brave": {"label": "Brave Search API", "env": "BRAVE_API_KEY", "key_url": "https://brave.com/search/api/"},
|
|
129
|
+
"tavily": {"label": "Tavily", "env": "TAVILY_API_KEY", "key_url": "https://app.tavily.com"},
|
|
130
|
+
"searxng": {"label": "SearXNG (your own instance URL)", "env": "SEARXNG_URL", "key_url": ""},
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ── Persistent Config & Secrets ───────────────────────────────────────────────
|
|
135
|
+
|
|
136
|
+
CONFIG_DIR = Path(os.getenv("AGENT_CONFIG_DIR") or (Path.home() / ".config" / "local_agent"))
|
|
137
|
+
CONFIG_PATH = CONFIG_DIR / "config.json"
|
|
138
|
+
SESSIONS_DIR = CONFIG_DIR / "sessions"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def atomic_json_write(path: Path, data: Any) -> None:
|
|
142
|
+
"""Write JSON atomically with owner-only permissions (0o600)."""
|
|
143
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
144
|
+
try:
|
|
145
|
+
os.chmod(path.parent, 0o700)
|
|
146
|
+
except OSError:
|
|
147
|
+
pass # nosec B110: chmod may be unsupported on Windows mounts
|
|
148
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
|
|
149
|
+
try:
|
|
150
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
151
|
+
json.dump(data, f, indent=2, ensure_ascii=False)
|
|
152
|
+
os.replace(tmp, path)
|
|
153
|
+
except BaseException:
|
|
154
|
+
try:
|
|
155
|
+
os.unlink(tmp)
|
|
156
|
+
except OSError:
|
|
157
|
+
pass # nosec B110: cleanup best-effort
|
|
158
|
+
raise
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def load_config() -> dict[str, Any]:
|
|
162
|
+
try:
|
|
163
|
+
data = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
|
|
164
|
+
return data if isinstance(data, dict) else {}
|
|
165
|
+
except (OSError, ValueError):
|
|
166
|
+
return {}
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
CFG: dict[str, Any] = load_config()
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def save_config() -> None:
|
|
173
|
+
atomic_json_write(CONFIG_PATH, CFG)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def pcfg(name: str) -> dict[str, Any]:
|
|
177
|
+
return CFG.setdefault("providers", {}).setdefault(name, {})
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def scfg() -> dict[str, Any]:
|
|
181
|
+
return CFG.setdefault("search", {})
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def setting(key: str) -> Any:
|
|
185
|
+
return CFG.get("settings", {}).get(key, SETTINGS_DEFAULTS[key])
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def set_setting(key: str, val: Any) -> None:
|
|
189
|
+
CFG.setdefault("settings", {})[key] = val
|
|
190
|
+
save_config()
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def get_key(provider: str) -> tuple[str, str]:
|
|
194
|
+
saved = pcfg(provider).get("api_key", "")
|
|
195
|
+
if saved:
|
|
196
|
+
return saved, "config"
|
|
197
|
+
for var in PROVIDERS[provider]["env"]:
|
|
198
|
+
if os.getenv(var):
|
|
199
|
+
return os.environ[var], f"env {var}"
|
|
200
|
+
return "", ""
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def mask(key: str) -> str:
|
|
204
|
+
return "…" + key[-4:] if len(key) > 8 else "set"
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def all_configured_secrets() -> list[str]:
|
|
208
|
+
secrets: set[str] = set()
|
|
209
|
+
for name, meta in PROVIDERS.items():
|
|
210
|
+
saved = pcfg(name).get("api_key", "")
|
|
211
|
+
if len(saved) >= 8:
|
|
212
|
+
secrets.add(saved)
|
|
213
|
+
for var in meta["env"]:
|
|
214
|
+
val = os.getenv(var, "")
|
|
215
|
+
if len(val) >= 8:
|
|
216
|
+
secrets.add(val)
|
|
217
|
+
for b, bmeta in SEARCH_BACKENDS.items():
|
|
218
|
+
saved = scfg().get("keys", {}).get(b, "")
|
|
219
|
+
if len(saved) >= 8 and b != "searxng":
|
|
220
|
+
secrets.add(saved)
|
|
221
|
+
if bmeta["env"] and b != "searxng":
|
|
222
|
+
val = os.getenv(bmeta["env"], "")
|
|
223
|
+
if len(val) >= 8:
|
|
224
|
+
secrets.add(val)
|
|
225
|
+
return sorted(secrets, key=len, reverse=True)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def redact_secrets(text: str, extra_secret: str = "") -> str:
|
|
229
|
+
if not text:
|
|
230
|
+
return text
|
|
231
|
+
out = text.replace(extra_secret, "***REDACTED***") if extra_secret else text
|
|
232
|
+
for sec in all_configured_secrets():
|
|
233
|
+
if sec in out:
|
|
234
|
+
out = out.replace(sec, "***REDACTED***")
|
|
235
|
+
return out
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def get_windows_ollama_url() -> str:
|
|
239
|
+
env_url = os.getenv("OLLAMA_URL")
|
|
240
|
+
if env_url:
|
|
241
|
+
return env_url.rstrip("/")
|
|
242
|
+
try:
|
|
243
|
+
with open("/proc/net/route") as f:
|
|
244
|
+
for line in f:
|
|
245
|
+
fields = line.split()
|
|
246
|
+
if len(fields) >= 3 and fields[1] == "00000000":
|
|
247
|
+
host_ip = socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
|
|
248
|
+
return f"http://{host_ip}:11434"
|
|
249
|
+
except OSError:
|
|
250
|
+
pass # nosec B110: non-Linux OS has no /proc/net/route
|
|
251
|
+
return "http://127.0.0.1:11434"
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
OLLAMA_URL = get_windows_ollama_url()
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def base_url(provider: str) -> str:
|
|
258
|
+
if provider == "ollama":
|
|
259
|
+
return (pcfg("ollama").get("base_url") or OLLAMA_URL).rstrip("/")
|
|
260
|
+
return (pcfg(provider).get("base_url") or PROVIDERS[provider]["base_url"]).rstrip("/")
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
apply_theme(str(setting("theme")))
|