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/providers.py
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
"""Provider transport: SSRF-safe HTTP, model discovery, and streaming for Ollama/Anthropic/OpenAI."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import ipaddress
|
|
5
|
+
import json
|
|
6
|
+
import socket
|
|
7
|
+
import time
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.parse
|
|
10
|
+
import urllib.request
|
|
11
|
+
import uuid
|
|
12
|
+
from typing import Any, Callable
|
|
13
|
+
|
|
14
|
+
from .config import (
|
|
15
|
+
HTTP_TIMEOUT,
|
|
16
|
+
MAX_RETRIES,
|
|
17
|
+
PROVIDERS,
|
|
18
|
+
C,
|
|
19
|
+
base_url,
|
|
20
|
+
get_key,
|
|
21
|
+
redact_secrets,
|
|
22
|
+
setting,
|
|
23
|
+
)
|
|
24
|
+
from .ui import countdown
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def is_local_url(url: str) -> bool:
|
|
28
|
+
host = urllib.parse.urlparse(url).hostname or ""
|
|
29
|
+
if host in ("localhost", "::1") or host.endswith(".local"):
|
|
30
|
+
return True
|
|
31
|
+
try:
|
|
32
|
+
ip = ipaddress.ip_address(host)
|
|
33
|
+
return ip.is_loopback or ip.is_private
|
|
34
|
+
except ValueError:
|
|
35
|
+
return False
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def ask_bool(prompt: str) -> bool:
|
|
39
|
+
try:
|
|
40
|
+
return input(prompt).strip().lower() == "y"
|
|
41
|
+
except (EOFError, KeyboardInterrupt):
|
|
42
|
+
print()
|
|
43
|
+
return False
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def validate_fetch_url(url: str) -> None:
|
|
47
|
+
"""Block SSRF against cloud metadata / link-local / unspecified IPs; gate private LAN/loopback."""
|
|
48
|
+
parsed = urllib.parse.urlparse(url)
|
|
49
|
+
host = parsed.hostname
|
|
50
|
+
if not host:
|
|
51
|
+
raise RuntimeError("Invalid URL hostname.")
|
|
52
|
+
if host.lower() in ("metadata.google.internal", "metadata", "169.254.169.254"):
|
|
53
|
+
raise RuntimeError("Blocked: access to cloud metadata endpoints is forbidden.")
|
|
54
|
+
try:
|
|
55
|
+
infos = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80),
|
|
56
|
+
type=socket.SOCK_STREAM)
|
|
57
|
+
except socket.gaierror as e:
|
|
58
|
+
raise RuntimeError(f"DNS resolution failed for {host}: {e}") from None
|
|
59
|
+
|
|
60
|
+
private_ips: list[str] = []
|
|
61
|
+
for info in infos:
|
|
62
|
+
ip_str = info[4][0].split("%")[0]
|
|
63
|
+
try:
|
|
64
|
+
ip = ipaddress.ip_address(ip_str)
|
|
65
|
+
except ValueError:
|
|
66
|
+
continue
|
|
67
|
+
if ip.is_link_local or ip.is_unspecified or ip.is_multicast:
|
|
68
|
+
raise RuntimeError(f"Blocked SSRF target IP ({ip_str}) for host {host}.")
|
|
69
|
+
if ip.is_loopback or ip.is_private or ip.is_reserved:
|
|
70
|
+
private_ips.append(ip_str)
|
|
71
|
+
if private_ips and not ask_bool(
|
|
72
|
+
f" {C.YELLOW}⚠ URL resolves to local/private IP {private_ips[0]}. Allow fetch? [y/N]:{C.RESET} "
|
|
73
|
+
):
|
|
74
|
+
raise RuntimeError(f"Denied fetch to private/loopback address ({private_ips[0]}).")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class _SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
78
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
79
|
+
parsed = urllib.parse.urlparse(newurl)
|
|
80
|
+
if parsed.scheme not in ("http", "https"):
|
|
81
|
+
raise RuntimeError(f"Blocked unsafe redirect scheme: {parsed.scheme}")
|
|
82
|
+
validate_fetch_url(newurl)
|
|
83
|
+
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def retry_after_seconds(err: urllib.error.HTTPError) -> float | None:
|
|
87
|
+
try:
|
|
88
|
+
return max(1.0, float(err.headers.get("Retry-After", "")))
|
|
89
|
+
except (TypeError, ValueError):
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def http_open(url: str, *, payload: Any = None, data: bytes | None = None, headers: dict[str, str] | None = None,
|
|
94
|
+
method: str | None = None, timeout: float = HTTP_TIMEOUT, secret: str = "",
|
|
95
|
+
ssrf_check: bool = False):
|
|
96
|
+
parsed = urllib.parse.urlparse(url)
|
|
97
|
+
if parsed.scheme not in ("http", "https"):
|
|
98
|
+
raise RuntimeError(f"Unsupported URL scheme: {parsed.scheme}")
|
|
99
|
+
host = parsed.netloc
|
|
100
|
+
if secret and url.startswith("http://") and not is_local_url(url):
|
|
101
|
+
raise RuntimeError(f"Refusing to send an API key over plain http to {host}. Use https.")
|
|
102
|
+
if ssrf_check:
|
|
103
|
+
validate_fetch_url(url)
|
|
104
|
+
opener = urllib.request.build_opener(_SafeRedirectHandler()) if ssrf_check else urllib.request.build_opener()
|
|
105
|
+
body = json.dumps(payload).encode("utf-8") if payload is not None else data
|
|
106
|
+
hdrs = dict(headers or {})
|
|
107
|
+
if payload is not None:
|
|
108
|
+
hdrs.setdefault("Content-Type", "application/json")
|
|
109
|
+
delay = 5.0
|
|
110
|
+
for attempt in range(MAX_RETRIES):
|
|
111
|
+
req = urllib.request.Request(url, data=body, headers=hdrs, method=method or ("POST" if body else "GET"))
|
|
112
|
+
try:
|
|
113
|
+
return opener.open(req, timeout=timeout) # nosec B310: scheme validated above
|
|
114
|
+
except urllib.error.HTTPError as e:
|
|
115
|
+
if e.code == 429 and attempt < MAX_RETRIES - 1:
|
|
116
|
+
countdown(retry_after_seconds(e) or delay, f"{host} rate limited (retry {attempt + 1}/{MAX_RETRIES - 1})")
|
|
117
|
+
delay *= 2
|
|
118
|
+
continue
|
|
119
|
+
text = redact_secrets(e.read().decode("utf-8", errors="replace")[:300], secret)
|
|
120
|
+
raise RuntimeError(f"HTTP {e.code} from {host}: {text}") from None
|
|
121
|
+
except urllib.error.URLError as e:
|
|
122
|
+
raise RuntimeError(f"Cannot reach {host}: {redact_secrets(str(e.reason), secret)}") from None
|
|
123
|
+
except (TimeoutError, socket.timeout):
|
|
124
|
+
raise RuntimeError(f"Timed out talking to {host}") from None
|
|
125
|
+
raise RuntimeError(f"Rate limit from {host} persisted after {MAX_RETRIES} attempts.")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def provider_headers(provider: str) -> dict[str, str]:
|
|
129
|
+
h = {"Accept": "application/json"}
|
|
130
|
+
key, _ = get_key(provider)
|
|
131
|
+
if not key:
|
|
132
|
+
return h
|
|
133
|
+
if provider == "anthropic":
|
|
134
|
+
h["x-api-key"] = key
|
|
135
|
+
h["anthropic-version"] = "2023-06-01"
|
|
136
|
+
else:
|
|
137
|
+
h["Authorization"] = f"Bearer {key}"
|
|
138
|
+
return h
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def resolve_provider_arg(token: str) -> str | None:
|
|
142
|
+
tok = token.strip().lower()
|
|
143
|
+
if tok in PROVIDERS:
|
|
144
|
+
return tok
|
|
145
|
+
if tok.isdigit():
|
|
146
|
+
idx = int(tok)
|
|
147
|
+
keys = list(PROVIDERS)
|
|
148
|
+
if 1 <= idx <= len(keys):
|
|
149
|
+
return keys[idx - 1]
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
_FREE_TIER_PROVIDERS = {"groq", "gemini", "cerebras", "nvidia"}
|
|
154
|
+
_LOCAL_PROVIDERS = {"ollama", "lmstudio"}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _classify_model(provider: str, item: Any) -> dict[str, str]:
|
|
158
|
+
"""Classify a model entry into tier ('free', 'local', or 'paid') and extract cost/ctx metadata."""
|
|
159
|
+
if isinstance(item, dict):
|
|
160
|
+
mid = str(item.get("id") or item.get("name") or "").removeprefix("models/")
|
|
161
|
+
pricing = item.get("pricing") or {}
|
|
162
|
+
ctx = item.get("context_length")
|
|
163
|
+
else:
|
|
164
|
+
mid = str(item).removeprefix("models/")
|
|
165
|
+
pricing = {}
|
|
166
|
+
ctx = None
|
|
167
|
+
|
|
168
|
+
ctx_s = f" • ctx {ctx}" if ctx else ""
|
|
169
|
+
if provider in _LOCAL_PROVIDERS:
|
|
170
|
+
return {"name": mid, "tier": "free" if mid.endswith(":cloud") else "local", "meta": f"free{ctx_s}"}
|
|
171
|
+
|
|
172
|
+
if pricing:
|
|
173
|
+
try:
|
|
174
|
+
pin = float(pricing.get("prompt", 0) or 0)
|
|
175
|
+
pout = float(pricing.get("completion", 0) or 0)
|
|
176
|
+
if pin == 0 and pout == 0:
|
|
177
|
+
return {"name": mid, "tier": "free", "meta": f"free{ctx_s}"}
|
|
178
|
+
return {"name": mid, "tier": "paid", "meta": f"${pin * 1e6:.2f}/M in, ${pout * 1e6:.2f}/M out{ctx_s}"}
|
|
179
|
+
except (TypeError, ValueError):
|
|
180
|
+
pass
|
|
181
|
+
|
|
182
|
+
if ":free" in mid.lower() or mid.endswith(":cloud"):
|
|
183
|
+
return {"name": mid, "tier": "free", "meta": f"free{ctx_s}"}
|
|
184
|
+
if provider in _FREE_TIER_PROVIDERS:
|
|
185
|
+
return {"name": mid, "tier": "free", "meta": f"free tier / rate-limited{ctx_s}"}
|
|
186
|
+
return {"name": mid, "tier": "paid", "meta": f"paid / billing{ctx_s}"}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def list_models(provider: str) -> list[dict[str, str]]:
|
|
190
|
+
key, _ = get_key(provider)
|
|
191
|
+
url = base_url(provider)
|
|
192
|
+
if not url:
|
|
193
|
+
raise RuntimeError("no base URL configured (use /setup custom)")
|
|
194
|
+
if provider == "ollama":
|
|
195
|
+
with http_open(f"{url}/api/tags", timeout=8, headers=provider_headers(provider), secret=key) as resp:
|
|
196
|
+
models = json.loads(resp.read().decode("utf-8")).get("models", [])
|
|
197
|
+
out = []
|
|
198
|
+
for m in models:
|
|
199
|
+
name = m.get("name", "unknown")
|
|
200
|
+
size = m.get("size", 0)
|
|
201
|
+
size_s = "cloud (free tier)" if size < 1024 * 1024 else f"{size / (1024 ** 3):.1f} GB • local free"
|
|
202
|
+
param = m.get("details", {}).get("parameter_size", "")
|
|
203
|
+
tier = "free" if size < 1024 * 1024 else "local"
|
|
204
|
+
out.append({"name": name, "tier": tier, "meta": size_s + (f" • {param}" if param else "")})
|
|
205
|
+
return out
|
|
206
|
+
with http_open(f"{url}/models", timeout=15, headers=provider_headers(provider), secret=key) as resp:
|
|
207
|
+
payload = json.loads(resp.read().decode("utf-8"))
|
|
208
|
+
items = payload.get("data", payload.get("models", [])) if isinstance(payload, dict) else payload
|
|
209
|
+
seen: dict[str, dict[str, str]] = {}
|
|
210
|
+
for it in items or []:
|
|
211
|
+
entry = _classify_model(provider, it)
|
|
212
|
+
if entry["name"] and entry["name"] not in seen:
|
|
213
|
+
seen[entry["name"]] = entry
|
|
214
|
+
# Sort free/local first, then paid, alphabetically within each tier
|
|
215
|
+
tier_order = {"local": 0, "free": 1, "paid": 2}
|
|
216
|
+
return sorted(seen.values(), key=lambda m: (tier_order.get(m["tier"], 9), m["name"].lower()))
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def select_model_interactive(provider: str, current: str) -> str:
|
|
220
|
+
try:
|
|
221
|
+
models = list_models(provider)
|
|
222
|
+
except (RuntimeError, ValueError) as e:
|
|
223
|
+
print(f"{C.YELLOW}Could not list models for {provider}: {e}{C.RESET}")
|
|
224
|
+
models = []
|
|
225
|
+
names = {m["name"] for m in models}
|
|
226
|
+
view = models
|
|
227
|
+
label = PROVIDERS[provider]["label"]
|
|
228
|
+
while True:
|
|
229
|
+
shown = view[:40]
|
|
230
|
+
if shown:
|
|
231
|
+
free_items = [(i, m) for i, m in enumerate(shown, 1) if m.get("tier") in ("free", "local")]
|
|
232
|
+
paid_items = [(i, m) for i, m in enumerate(shown, 1) if m.get("tier") == "paid"]
|
|
233
|
+
print(f"\n{C.CYAN}{C.BOLD}Models for {label}{C.RESET} {C.DIM}({len(models)} total){C.RESET}")
|
|
234
|
+
if free_items:
|
|
235
|
+
print(f" {C.GREEN}{C.BOLD}── FREE / LOCAL ({len(free_items)}) ──{C.RESET}")
|
|
236
|
+
for idx, m in free_items:
|
|
237
|
+
active = f" {C.GREEN}*(active){C.RESET}" if m["name"] == current else ""
|
|
238
|
+
meta = f" {C.DIM}({m['meta']}){C.RESET}" if m.get("meta") else ""
|
|
239
|
+
print(f" {C.BOLD}{idx:>2}.{C.RESET} {C.GREEN}{m['name']}{C.RESET}{meta}{active}")
|
|
240
|
+
if paid_items:
|
|
241
|
+
print(f" {C.YELLOW}{C.BOLD}── PAID / BILLING ({len(paid_items)}) ──{C.RESET}")
|
|
242
|
+
for idx, m in paid_items:
|
|
243
|
+
active = f" {C.GREEN}*(active){C.RESET}" if m["name"] == current else ""
|
|
244
|
+
meta = f" {C.DIM}({m['meta']}){C.RESET}" if m.get("meta") else ""
|
|
245
|
+
print(f" {C.BOLD}{idx:>2}.{C.RESET} {C.YELLOW}{m['name']}{C.RESET}{meta}{active}")
|
|
246
|
+
if len(view) > 40:
|
|
247
|
+
print(f" {C.GRAY}... {len(view) - 40} more: type 'free', 'paid', or text to filter{C.RESET}")
|
|
248
|
+
hint = "number, exact name, or 'free'/'paid'/text to filter" if models else "type a model name"
|
|
249
|
+
try:
|
|
250
|
+
choice = input(f"\n{C.BLUE}Select model ({hint}; Enter keeps '{current or 'none'}'):{C.RESET} ").strip()
|
|
251
|
+
except (EOFError, KeyboardInterrupt):
|
|
252
|
+
print()
|
|
253
|
+
return current
|
|
254
|
+
if not choice:
|
|
255
|
+
return current
|
|
256
|
+
if choice.isdigit() and 1 <= int(choice) <= len(shown):
|
|
257
|
+
selected = shown[int(choice) - 1]["name"]
|
|
258
|
+
elif choice in names or not models:
|
|
259
|
+
selected = choice
|
|
260
|
+
elif choice.lower() in ("free", "local", "paid"):
|
|
261
|
+
t_q = choice.lower()
|
|
262
|
+
matches = [m for m in models if m.get("tier") == t_q or (t_q == "free" and m.get("tier") == "local")]
|
|
263
|
+
if matches:
|
|
264
|
+
view = matches
|
|
265
|
+
continue
|
|
266
|
+
print(f"{C.YELLOW}No {t_q} models in this provider list.{C.RESET}")
|
|
267
|
+
continue
|
|
268
|
+
else:
|
|
269
|
+
matches = [m for m in models if choice.lower() in m["name"].lower()]
|
|
270
|
+
if matches:
|
|
271
|
+
view = matches
|
|
272
|
+
continue
|
|
273
|
+
selected = choice
|
|
274
|
+
print(f"{C.YELLOW}'{choice}' is not in the list; using it as a custom model name.{C.RESET}")
|
|
275
|
+
print(f"Selected model: {C.GREEN}{selected}{C.RESET}")
|
|
276
|
+
return selected
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
# ── Message Converters & Streaming ────────────────────────────────────────────
|
|
280
|
+
|
|
281
|
+
def parse_args(raw: Any) -> dict[str, Any]:
|
|
282
|
+
if isinstance(raw, dict):
|
|
283
|
+
return raw
|
|
284
|
+
if isinstance(raw, str):
|
|
285
|
+
try:
|
|
286
|
+
parsed = json.loads(raw or "{}")
|
|
287
|
+
return parsed if isinstance(parsed, dict) else {}
|
|
288
|
+
except ValueError:
|
|
289
|
+
return {}
|
|
290
|
+
return {}
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def to_openai_messages(messages: list[dict]) -> list[dict]:
|
|
294
|
+
out: list[dict] = []
|
|
295
|
+
for m in messages:
|
|
296
|
+
role = m.get("role")
|
|
297
|
+
if role == "assistant" and m.get("tool_calls"):
|
|
298
|
+
out.append({
|
|
299
|
+
"role": "assistant",
|
|
300
|
+
"content": m.get("content") or None,
|
|
301
|
+
"tool_calls": [{
|
|
302
|
+
"id": tc.get("id") or f"call_{uuid.uuid4().hex[:8]}",
|
|
303
|
+
"type": "function",
|
|
304
|
+
"function": {
|
|
305
|
+
"name": tc["function"]["name"],
|
|
306
|
+
"arguments": json.dumps(tc["function"].get("arguments") or {}, ensure_ascii=False),
|
|
307
|
+
},
|
|
308
|
+
} for tc in m["tool_calls"]],
|
|
309
|
+
})
|
|
310
|
+
elif role == "tool":
|
|
311
|
+
out.append({"role": "tool", "tool_call_id": m.get("tool_call_id", ""), "content": m.get("content", "")})
|
|
312
|
+
else:
|
|
313
|
+
out.append({"role": role, "content": m.get("content", "")})
|
|
314
|
+
return out
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def to_ollama_messages(messages: list[dict]) -> list[dict]:
|
|
318
|
+
out: list[dict] = []
|
|
319
|
+
for m in messages:
|
|
320
|
+
role = m.get("role")
|
|
321
|
+
if role == "assistant" and m.get("tool_calls"):
|
|
322
|
+
out.append({
|
|
323
|
+
"role": "assistant",
|
|
324
|
+
"content": m.get("content", ""),
|
|
325
|
+
"tool_calls": [{"function": {"name": tc["function"]["name"],
|
|
326
|
+
"arguments": tc["function"].get("arguments") or {}}}
|
|
327
|
+
for tc in m["tool_calls"]],
|
|
328
|
+
})
|
|
329
|
+
elif role == "tool":
|
|
330
|
+
out.append({"role": "tool", "tool_name": m.get("tool_name", ""), "content": m.get("content", "")})
|
|
331
|
+
else:
|
|
332
|
+
out.append({"role": role, "content": m.get("content", "")})
|
|
333
|
+
return out
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def to_anthropic_payload(messages: list[dict], tools: list[dict]) -> tuple[str, list[dict], list[dict]]:
|
|
337
|
+
system_parts: list[str] = []
|
|
338
|
+
out: list[dict] = []
|
|
339
|
+
for m in messages:
|
|
340
|
+
role = m.get("role")
|
|
341
|
+
if role == "system":
|
|
342
|
+
if m.get("content"):
|
|
343
|
+
system_parts.append(str(m["content"]))
|
|
344
|
+
elif role == "assistant":
|
|
345
|
+
blocks: list[dict[str, Any]] = []
|
|
346
|
+
if m.get("content"):
|
|
347
|
+
blocks.append({"type": "text", "text": str(m["content"])})
|
|
348
|
+
for tc in m.get("tool_calls") or []:
|
|
349
|
+
blocks.append({
|
|
350
|
+
"type": "tool_use",
|
|
351
|
+
"id": tc.get("id") or f"toolu_{uuid.uuid4().hex[:12]}",
|
|
352
|
+
"name": tc["function"]["name"],
|
|
353
|
+
"input": tc["function"].get("arguments") or {},
|
|
354
|
+
})
|
|
355
|
+
if blocks:
|
|
356
|
+
out.append({"role": "assistant", "content": blocks})
|
|
357
|
+
elif role == "tool":
|
|
358
|
+
result_block = {
|
|
359
|
+
"type": "tool_result",
|
|
360
|
+
"tool_use_id": m.get("tool_call_id", ""),
|
|
361
|
+
"content": str(m.get("content", "")),
|
|
362
|
+
}
|
|
363
|
+
if out and out[-1]["role"] == "user" and isinstance(out[-1]["content"], list):
|
|
364
|
+
out[-1]["content"].append(result_block)
|
|
365
|
+
else:
|
|
366
|
+
out.append({"role": "user", "content": [result_block]})
|
|
367
|
+
else:
|
|
368
|
+
text_block = {"type": "text", "text": str(m.get("content", ""))}
|
|
369
|
+
if out and out[-1]["role"] == "user" and isinstance(out[-1]["content"], list):
|
|
370
|
+
out[-1]["content"].append(text_block)
|
|
371
|
+
else:
|
|
372
|
+
out.append({"role": "user", "content": [text_block]})
|
|
373
|
+
|
|
374
|
+
anth_tools = [{
|
|
375
|
+
"name": t["function"]["name"],
|
|
376
|
+
"description": t["function"].get("description", ""),
|
|
377
|
+
"input_schema": t["function"].get("parameters", {"type": "object", "properties": {}}),
|
|
378
|
+
} for t in tools]
|
|
379
|
+
return "\n\n".join(system_parts), out, anth_tools
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def build_ollama_options(model: str) -> dict[str, Any]:
|
|
383
|
+
ctx = int(setting("num_ctx"))
|
|
384
|
+
ngpu = int(setting("num_gpu"))
|
|
385
|
+
temp = float(setting("temperature"))
|
|
386
|
+
opts: dict[str, Any] = {"num_ctx": ctx, "num_batch": 1024, "temperature": temp}
|
|
387
|
+
if model.startswith(("qwen3.5", "qwen35")):
|
|
388
|
+
opts["num_gpu"] = ngpu
|
|
389
|
+
elif model.startswith(("qwen2.5", "qwen25")):
|
|
390
|
+
opts["num_gpu"] = 99
|
|
391
|
+
return opts
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _stream_ollama(url: str, model: str, messages: list[dict], tools: list[dict], think: bool,
|
|
395
|
+
headers: dict[str, str], key: str,
|
|
396
|
+
on_think: Callable[[str], None] | None,
|
|
397
|
+
on_token: Callable[[str], None] | None) -> tuple[str, list[dict], dict[str, Any]]:
|
|
398
|
+
content = ""
|
|
399
|
+
tool_calls: list[dict] = []
|
|
400
|
+
stats: dict[str, Any] = {}
|
|
401
|
+
opts = build_ollama_options(model)
|
|
402
|
+
payload = {"model": model, "messages": to_ollama_messages(messages), "tools": tools,
|
|
403
|
+
"stream": True, "think": think, "keep_alive": "15m", "options": opts}
|
|
404
|
+
with http_open(f"{url}/api/chat", payload=payload, headers=headers, secret=key) as resp:
|
|
405
|
+
for raw in resp:
|
|
406
|
+
line = raw.decode("utf-8", errors="replace").strip()
|
|
407
|
+
if not line:
|
|
408
|
+
continue
|
|
409
|
+
try:
|
|
410
|
+
chunk = json.loads(line)
|
|
411
|
+
except ValueError:
|
|
412
|
+
continue
|
|
413
|
+
msg = chunk.get("message", {})
|
|
414
|
+
if msg.get("thinking") and on_think:
|
|
415
|
+
on_think(msg["thinking"])
|
|
416
|
+
if msg.get("content"):
|
|
417
|
+
content += msg["content"]
|
|
418
|
+
if on_token:
|
|
419
|
+
on_token(msg["content"])
|
|
420
|
+
for tc in msg.get("tool_calls") or []:
|
|
421
|
+
tool_calls.append({"id": f"call_{uuid.uuid4().hex[:8]}",
|
|
422
|
+
"function": {"name": tc["function"]["name"],
|
|
423
|
+
"arguments": parse_args(tc["function"].get("arguments"))}})
|
|
424
|
+
if chunk.get("done"):
|
|
425
|
+
stats = {"eval_count": chunk.get("eval_count", 0),
|
|
426
|
+
"secs": chunk.get("eval_duration", 0) / 1e9,
|
|
427
|
+
"prompt_tokens": chunk.get("prompt_eval_count", 0),
|
|
428
|
+
"done_reason": chunk.get("done_reason", ""),
|
|
429
|
+
"ctx": opts["num_ctx"]}
|
|
430
|
+
return content, tool_calls, stats
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _stream_anthropic(url: str, model: str, messages: list[dict], tools: list[dict], think: bool,
|
|
434
|
+
headers: dict[str, str], key: str,
|
|
435
|
+
on_think: Callable[[str], None] | None,
|
|
436
|
+
on_token: Callable[[str], None] | None) -> tuple[str, list[dict], dict[str, Any]]:
|
|
437
|
+
system_txt, anth_msgs, anth_tools = to_anthropic_payload(messages, tools)
|
|
438
|
+
max_out = max(256, int(setting("max_output_tokens")))
|
|
439
|
+
payload: dict[str, Any] = {"model": model, "messages": anth_msgs, "max_tokens": max_out, "stream": True}
|
|
440
|
+
if system_txt:
|
|
441
|
+
payload["system"] = system_txt
|
|
442
|
+
if anth_tools:
|
|
443
|
+
payload["tools"] = anth_tools
|
|
444
|
+
if think:
|
|
445
|
+
budget = min(2048, max(1024, max_out // 2))
|
|
446
|
+
payload["thinking"] = {"type": "enabled", "budget_tokens": budget}
|
|
447
|
+
if max_out <= budget:
|
|
448
|
+
payload["max_tokens"] = budget + 1024
|
|
449
|
+
else:
|
|
450
|
+
payload["temperature"] = float(setting("temperature"))
|
|
451
|
+
|
|
452
|
+
content = ""
|
|
453
|
+
blocks: dict[int, dict[str, Any]] = {}
|
|
454
|
+
stop_reason = ""
|
|
455
|
+
usage: dict[str, int] = {}
|
|
456
|
+
t0 = time.perf_counter()
|
|
457
|
+
|
|
458
|
+
with http_open(f"{url}/messages", payload=payload, headers=headers, secret=key) as resp:
|
|
459
|
+
for raw in resp:
|
|
460
|
+
line = raw.decode("utf-8", errors="replace").strip()
|
|
461
|
+
if not line.startswith("data:"):
|
|
462
|
+
continue
|
|
463
|
+
data = line[5:].strip()
|
|
464
|
+
if not data or data == "[DONE]":
|
|
465
|
+
continue
|
|
466
|
+
try:
|
|
467
|
+
ev = json.loads(data)
|
|
468
|
+
except ValueError:
|
|
469
|
+
continue
|
|
470
|
+
etype = ev.get("type")
|
|
471
|
+
if etype == "message_start":
|
|
472
|
+
u = (ev.get("message") or {}).get("usage") or {}
|
|
473
|
+
usage["input"] = u.get("input_tokens", 0)
|
|
474
|
+
elif etype == "content_block_start":
|
|
475
|
+
idx = ev.get("index", 0)
|
|
476
|
+
cb = ev.get("content_block") or {}
|
|
477
|
+
blocks[idx] = {"type": cb.get("type", ""), "id": cb.get("id", ""),
|
|
478
|
+
"name": cb.get("name", ""), "args": ""}
|
|
479
|
+
elif etype == "content_block_delta":
|
|
480
|
+
idx = ev.get("index", 0)
|
|
481
|
+
delta = ev.get("delta") or {}
|
|
482
|
+
dtype = delta.get("type")
|
|
483
|
+
if dtype == "text_delta" and delta.get("text"):
|
|
484
|
+
content += delta["text"]
|
|
485
|
+
if on_token:
|
|
486
|
+
on_token(delta["text"])
|
|
487
|
+
elif dtype == "thinking_delta" and delta.get("thinking"):
|
|
488
|
+
if on_think:
|
|
489
|
+
on_think(delta["thinking"])
|
|
490
|
+
elif dtype == "input_json_delta" and idx in blocks:
|
|
491
|
+
blocks[idx]["args"] += delta.get("partial_json", "")
|
|
492
|
+
elif etype == "message_delta":
|
|
493
|
+
d = ev.get("delta") or {}
|
|
494
|
+
if d.get("stop_reason"):
|
|
495
|
+
stop_reason = d["stop_reason"]
|
|
496
|
+
u = ev.get("usage") or {}
|
|
497
|
+
if u.get("output_tokens"):
|
|
498
|
+
usage["output"] = u["output_tokens"]
|
|
499
|
+
|
|
500
|
+
tool_calls = []
|
|
501
|
+
for idx in sorted(blocks):
|
|
502
|
+
b = blocks[idx]
|
|
503
|
+
if b["type"] == "tool_use" and b["name"]:
|
|
504
|
+
tool_calls.append({"id": b["id"] or f"toolu_{uuid.uuid4().hex[:12]}",
|
|
505
|
+
"function": {"name": b["name"], "arguments": parse_args(b["args"])}})
|
|
506
|
+
norm_reason = "length" if stop_reason == "max_tokens" else stop_reason
|
|
507
|
+
stats = {"eval_count": usage.get("output", 0), "secs": time.perf_counter() - t0,
|
|
508
|
+
"prompt_tokens": usage.get("input", 0), "done_reason": norm_reason}
|
|
509
|
+
return content, tool_calls, stats
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _stream_openai(url: str, model: str, messages: list[dict], tools: list[dict],
|
|
513
|
+
headers: dict[str, str], key: str,
|
|
514
|
+
on_think: Callable[[str], None] | None,
|
|
515
|
+
on_token: Callable[[str], None] | None) -> tuple[str, list[dict], dict[str, Any]]:
|
|
516
|
+
payload: dict[str, Any] = {
|
|
517
|
+
"model": model, "messages": to_openai_messages(messages), "stream": True,
|
|
518
|
+
"max_tokens": int(setting("max_output_tokens")), "temperature": float(setting("temperature")),
|
|
519
|
+
}
|
|
520
|
+
if tools:
|
|
521
|
+
payload["tools"] = tools
|
|
522
|
+
content = ""
|
|
523
|
+
acc: dict[int, dict[str, str]] = {}
|
|
524
|
+
finish = ""
|
|
525
|
+
usage: dict[str, Any] = {}
|
|
526
|
+
t0 = time.perf_counter()
|
|
527
|
+
|
|
528
|
+
with http_open(f"{url}/chat/completions", payload=payload, headers=headers, secret=key) as resp:
|
|
529
|
+
for raw in resp:
|
|
530
|
+
line = raw.decode("utf-8", errors="replace").strip()
|
|
531
|
+
if not line.startswith("data:"):
|
|
532
|
+
continue
|
|
533
|
+
data = line[5:].strip()
|
|
534
|
+
if data == "[DONE]":
|
|
535
|
+
break
|
|
536
|
+
try:
|
|
537
|
+
chunk = json.loads(data)
|
|
538
|
+
except ValueError:
|
|
539
|
+
continue
|
|
540
|
+
if chunk.get("usage"):
|
|
541
|
+
usage = chunk["usage"]
|
|
542
|
+
for ch in chunk.get("choices") or []:
|
|
543
|
+
delta = ch.get("delta") or {}
|
|
544
|
+
reasoning = delta.get("reasoning_content") or delta.get("reasoning")
|
|
545
|
+
if reasoning and on_think:
|
|
546
|
+
on_think(reasoning)
|
|
547
|
+
if delta.get("content"):
|
|
548
|
+
content += delta["content"]
|
|
549
|
+
if on_token:
|
|
550
|
+
on_token(delta["content"])
|
|
551
|
+
for tcd in delta.get("tool_calls") or []:
|
|
552
|
+
fn = tcd.get("function") or {}
|
|
553
|
+
idx = tcd.get("index")
|
|
554
|
+
if idx is None:
|
|
555
|
+
idx = len(acc) if (fn.get("name") or not acc) else max(acc)
|
|
556
|
+
slot = acc.setdefault(idx, {"id": "", "name": "", "args": ""})
|
|
557
|
+
if tcd.get("id"):
|
|
558
|
+
slot["id"] = tcd["id"]
|
|
559
|
+
if fn.get("name") and not slot["name"]:
|
|
560
|
+
slot["name"] = fn["name"]
|
|
561
|
+
if fn.get("arguments"):
|
|
562
|
+
slot["args"] += fn["arguments"]
|
|
563
|
+
if ch.get("finish_reason"):
|
|
564
|
+
finish = ch["finish_reason"]
|
|
565
|
+
|
|
566
|
+
tool_calls = [{"id": slot["id"] or f"call_{uuid.uuid4().hex[:8]}",
|
|
567
|
+
"function": {"name": slot["name"], "arguments": parse_args(slot["args"])}}
|
|
568
|
+
for idx in sorted(acc) if (slot := acc[idx])["name"]]
|
|
569
|
+
stats = {"eval_count": usage.get("completion_tokens", 0), "secs": time.perf_counter() - t0,
|
|
570
|
+
"prompt_tokens": usage.get("prompt_tokens", 0),
|
|
571
|
+
"done_reason": "length" if finish == "length" else finish}
|
|
572
|
+
return content, tool_calls, stats
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def chat_stream(provider: str, model: str, messages: list[dict], tools: list[dict], think: bool,
|
|
576
|
+
on_think: Callable[[str], None] | None = None,
|
|
577
|
+
on_token: Callable[[str], None] | None = None) -> tuple[str, list[dict], dict[str, Any]]:
|
|
578
|
+
key, _ = get_key(provider)
|
|
579
|
+
url = base_url(provider)
|
|
580
|
+
if not url:
|
|
581
|
+
raise RuntimeError(f"{provider} has no base URL. Run /setup {provider}.")
|
|
582
|
+
if PROVIDERS[provider]["needs_key"] and not key:
|
|
583
|
+
envs = ", ".join(PROVIDERS[provider]["env"])
|
|
584
|
+
raise RuntimeError(f"No API key for {provider}. Run /key {provider} or export {envs}.")
|
|
585
|
+
if not model:
|
|
586
|
+
raise RuntimeError(f"No model selected for {provider}. Run /models.")
|
|
587
|
+
hdrs = provider_headers(provider)
|
|
588
|
+
kind = PROVIDERS[provider]["kind"]
|
|
589
|
+
if kind == "ollama":
|
|
590
|
+
return _stream_ollama(url, model, messages, tools, think, hdrs, key, on_think, on_token)
|
|
591
|
+
if kind == "anthropic":
|
|
592
|
+
return _stream_anthropic(url, model, messages, tools, think, hdrs, key, on_think, on_token)
|
|
593
|
+
return _stream_openai(url, model, messages, tools, hdrs, key, on_think, on_token)
|
local_agent/sessions.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Per-session persistent chat history storage and transcript rendering."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
import uuid
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .config import C, SESSIONS_DIR, atomic_json_write, redact_secrets
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def new_session_id() -> str:
|
|
15
|
+
return f"{datetime.now():%Y%m%d_%H%M%S}_{uuid.uuid4().hex[:6]}"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def safe_session_path(session_id: str) -> Path:
|
|
19
|
+
clean = re.sub(r"[^A-Za-z0-9_.-]", "_", session_id).strip("._") or new_session_id()
|
|
20
|
+
return SESSIONS_DIR / f"{clean}.json"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _scrub_messages(messages: list[dict]) -> list[dict]:
|
|
24
|
+
scrubbed: list[dict] = []
|
|
25
|
+
for m in messages:
|
|
26
|
+
copy_m = dict(m)
|
|
27
|
+
if isinstance(copy_m.get("content"), str):
|
|
28
|
+
copy_m["content"] = redact_secrets(copy_m["content"])
|
|
29
|
+
scrubbed.append(copy_m)
|
|
30
|
+
return scrubbed
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def save_session(session_id: str, provider: str, model: str, messages: list[dict]) -> None:
|
|
34
|
+
user_msgs = [m for m in messages if m.get("role") == "user" and m.get("content")]
|
|
35
|
+
if not user_msgs:
|
|
36
|
+
return
|
|
37
|
+
title = str(user_msgs[0]["content"]).splitlines()[0][:80]
|
|
38
|
+
data = {
|
|
39
|
+
"session_id": session_id,
|
|
40
|
+
"title": redact_secrets(title),
|
|
41
|
+
"provider": provider,
|
|
42
|
+
"model": model,
|
|
43
|
+
"updated_at": datetime.now().isoformat(timespec="seconds"),
|
|
44
|
+
"messages": _scrub_messages(messages),
|
|
45
|
+
}
|
|
46
|
+
atomic_json_write(safe_session_path(session_id), data)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def list_sessions() -> list[dict[str, Any]]:
|
|
50
|
+
if not SESSIONS_DIR.is_dir():
|
|
51
|
+
return []
|
|
52
|
+
out: list[dict[str, Any]] = []
|
|
53
|
+
for f in SESSIONS_DIR.glob("*.json"):
|
|
54
|
+
try:
|
|
55
|
+
d = json.loads(f.read_text(encoding="utf-8"))
|
|
56
|
+
if isinstance(d, dict) and d.get("session_id"):
|
|
57
|
+
out.append(d)
|
|
58
|
+
except (OSError, ValueError):
|
|
59
|
+
continue
|
|
60
|
+
out.sort(key=lambda x: x.get("updated_at", ""), reverse=True)
|
|
61
|
+
return out
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def print_session_transcript(messages: list[dict], session_id: str) -> None:
|
|
65
|
+
print(f"\n{C.CYAN}{C.BOLD}Session History [{session_id}]{C.RESET}")
|
|
66
|
+
has_turns = False
|
|
67
|
+
for m in messages:
|
|
68
|
+
role = m.get("role")
|
|
69
|
+
if role == "system":
|
|
70
|
+
continue
|
|
71
|
+
has_turns = True
|
|
72
|
+
if role == "user":
|
|
73
|
+
print(f" {C.BLUE}{C.BOLD}You:{C.RESET} {m.get('content', '')}")
|
|
74
|
+
elif role == "assistant":
|
|
75
|
+
txt = (m.get("content") or "").strip()
|
|
76
|
+
tcalls = [tc["function"]["name"] for tc in (m.get("tool_calls") or []) if "function" in tc]
|
|
77
|
+
tc_s = f" {C.YELLOW}[tools: {', '.join(tcalls)}]{C.RESET}" if tcalls else ""
|
|
78
|
+
preview = txt[:280] + ("..." if len(txt) > 280 else "")
|
|
79
|
+
print(f" {C.GREEN}{C.BOLD}Agent:{C.RESET}{tc_s} {preview}")
|
|
80
|
+
elif role == "tool":
|
|
81
|
+
tname = m.get("tool_name", "tool")
|
|
82
|
+
first = str(m.get("content", "")).splitlines()[0][:90] if m.get("content") else ""
|
|
83
|
+
print(f" {C.DIM}↳ {tname}: {first}{C.RESET}")
|
|
84
|
+
if not has_turns:
|
|
85
|
+
print(f" {C.DIM}(no messages yet in this session){C.RESET}")
|