tokensafe 4.6.4 → 4.7.1
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.
- package/.codex-plugin/plugin.json +2 -2
- package/LICENSE +202 -21
- package/README.md +30 -4
- package/hooks/claude_code_hook.py +17 -15
- package/hooks/kimi_hook.py +14 -12
- package/hooks/pre_invocation.py +7 -12
- package/hooks/session_start.py +8 -2
- package/kimi.plugin.json +2 -2
- package/package.json +2 -2
- package/plugin.json +2 -1
- package/rules/AGENTS.md +1 -1
- package/server.json +3 -3
- package/src/acp/__init__.py +15 -0
- package/src/acp/server.py +328 -0
- package/src/adapter_core.py +2 -1
- package/src/agent/__init__.py +11 -0
- package/src/agent/context.py +99 -0
- package/src/agent/loop.py +385 -0
- package/src/agent/pricing.py +77 -0
- package/src/agent/providers.py +486 -0
- package/src/agent/tools.py +98 -0
- package/src/agent_firewall.py +16 -1
- package/src/auto_inject.py +93 -7
- package/src/batch_editor.py +106 -15
- package/src/bench/__init__.py +1 -0
- package/src/bench/driver.py +234 -0
- package/src/bench/go_target.py +646 -0
- package/src/bench/mechanics.py +214 -0
- package/src/bench/react_target.py +541 -0
- package/src/bench/runner.py +331 -0
- package/src/bench/tokensafe_mcp.py +144 -0
- package/src/cli.py +156 -0
- package/src/history_compactor.py +200 -2
- package/src/installer.py +3 -3
- package/src/mcp_server.py +510 -237
- package/src/paths.py +41 -2
- package/src/retrofit.py +27 -5
- package/src/scaffold.py +8 -6
- package/src/scoped_search.py +67 -5
- package/src/session_brief.py +180 -15
- package/src/session_context.py +124 -0
- package/src/skeletonizer.py +9 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/src/auto_inject.py
CHANGED
|
@@ -291,6 +291,75 @@ def _go_tidy(workspace: str) -> Tuple[bool, str]:
|
|
|
291
291
|
return proc.returncode == 0, (proc.stderr or proc.stdout or "").strip()
|
|
292
292
|
|
|
293
293
|
|
|
294
|
+
_GO_SERVE_PATTERNS = {
|
|
295
|
+
# `r.Run(":8080")` — gin
|
|
296
|
+
"gin": re.compile(r'(?m)^(?P<indent>[ \t]*)(?P<router>[A-Za-z_]\w*)\.Run\((?P<addr>[^()\n]*)\)[ \t]*$'),
|
|
297
|
+
# `http.ListenAndServe(":8080", r)` — chi
|
|
298
|
+
"chi": re.compile(
|
|
299
|
+
r'(?m)^(?P<indent>[ \t]*)http\.ListenAndServe\((?P<addr>[^,()\n]+),\s*(?P<router>[A-Za-z_]\w*)\)[ \t]*$'
|
|
300
|
+
),
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _go_router_var(source: str, framework: str) -> Optional[str]:
|
|
305
|
+
_, _, anchor_a, anchor_b, _ = _GO_ADAPTERS[framework]
|
|
306
|
+
for anchor in (anchor_a, anchor_b):
|
|
307
|
+
if not anchor:
|
|
308
|
+
continue
|
|
309
|
+
idx = source.find(anchor)
|
|
310
|
+
if idx == -1:
|
|
311
|
+
continue
|
|
312
|
+
line_start = source.rfind("\n", 0, idx) + 1
|
|
313
|
+
line_end = source.find("\n", idx)
|
|
314
|
+
line = source[line_start : line_end if line_end != -1 else len(source)]
|
|
315
|
+
match = re.search(r"([A-Za-z_]\w*)\s*:?=\s*" + re.escape(anchor), line)
|
|
316
|
+
if match:
|
|
317
|
+
return match.group(1)
|
|
318
|
+
return None
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _wrap_go_serve(source: str, framework: str) -> Optional[Tuple[str, str]]:
|
|
322
|
+
"""Rewrites a simple serve call to the discovery-announcing wrapper.
|
|
323
|
+
|
|
324
|
+
`r.Run(":8080")` → `oumvgin.AutoMountAndServe(r, ":8080")`, so the §9.2
|
|
325
|
+
descriptor carries the port the kernel actually assigned. Only a one-line call
|
|
326
|
+
with no nested parentheses is rewritten; anything else falls back to a bare
|
|
327
|
+
AutoMount (the user can swap the serve call manually).
|
|
328
|
+
"""
|
|
329
|
+
pattern = _GO_SERVE_PATTERNS.get(framework)
|
|
330
|
+
if pattern is None:
|
|
331
|
+
return None
|
|
332
|
+
router_var = _go_router_var(source, framework)
|
|
333
|
+
for match in pattern.finditer(source):
|
|
334
|
+
if router_var and match.group("router") != router_var:
|
|
335
|
+
continue
|
|
336
|
+
alias = _GO_ADAPTERS[framework][0]
|
|
337
|
+
router = match.group("router")
|
|
338
|
+
addr = match.group("addr").strip()
|
|
339
|
+
indent = match.group("indent")
|
|
340
|
+
block = (
|
|
341
|
+
f"{indent}{_MARK_BEGIN}\n"
|
|
342
|
+
f"{indent}if err := {alias}.AutoMountAndServe({router}, {addr}); err != nil {{\n"
|
|
343
|
+
f"{indent}\tlog.Fatal(err)\n"
|
|
344
|
+
f"{indent}}}\n"
|
|
345
|
+
f"{indent}{_MARK_END}\n"
|
|
346
|
+
)
|
|
347
|
+
return source[: match.start()] + block + source[match.end() :], block.strip()
|
|
348
|
+
return None
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _ensure_std_import(source: str, package: str) -> str:
|
|
352
|
+
if re.search(r'^\s*(?:\w+\s+)?"%s"\s*$' % re.escape(package), source, re.M):
|
|
353
|
+
return source
|
|
354
|
+
idx = source.find("import (")
|
|
355
|
+
if idx == -1:
|
|
356
|
+
return source
|
|
357
|
+
line_end = source.find("\n", idx)
|
|
358
|
+
if line_end == -1:
|
|
359
|
+
return source
|
|
360
|
+
return source[: line_end + 1] + f'\t"{package}"\n' + source[line_end + 1 :]
|
|
361
|
+
|
|
362
|
+
|
|
294
363
|
def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
295
364
|
"""Ensures the module dependency, inserts the AutoMount call, validates with `go build`.
|
|
296
365
|
|
|
@@ -312,15 +381,21 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
312
381
|
return {"status": "already-patched", "entrypoint": path, "framework": framework}
|
|
313
382
|
|
|
314
383
|
anchor = _go_anchor(original, framework)
|
|
315
|
-
|
|
384
|
+
alias, import_path, _, _, call = _GO_ADAPTERS[framework]
|
|
385
|
+
wrapped = _wrap_go_serve(original, framework)
|
|
386
|
+
if wrapped is None and anchor is None:
|
|
316
387
|
return {
|
|
317
388
|
"status": "skipped",
|
|
318
389
|
"reason": f"could not find router construction ({framework}) in {os.path.relpath(path, workspace)}",
|
|
319
390
|
}
|
|
320
391
|
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
392
|
+
if wrapped is not None:
|
|
393
|
+
patched, preview = wrapped
|
|
394
|
+
patched = _ensure_std_import(patched, "log")
|
|
395
|
+
else:
|
|
396
|
+
insert = f"\t{_MARK_BEGIN}\n{call}\t{_MARK_END}\n"
|
|
397
|
+
patched = original[:anchor] + insert + original[anchor:]
|
|
398
|
+
preview = insert.strip()
|
|
324
399
|
|
|
325
400
|
import_line = f'\t{alias} "{import_path}"\n'
|
|
326
401
|
if import_path not in patched:
|
|
@@ -335,7 +410,8 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
335
410
|
"status": "would-patch",
|
|
336
411
|
"entrypoint": os.path.relpath(path, workspace),
|
|
337
412
|
"framework": framework,
|
|
338
|
-
"
|
|
413
|
+
"mode": "serve" if wrapped is not None else "mount",
|
|
414
|
+
"preview": preview,
|
|
339
415
|
}
|
|
340
416
|
|
|
341
417
|
backup_dir = _inject_dir(workspace)
|
|
@@ -369,14 +445,24 @@ def apply_go_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
|
369
445
|
}
|
|
370
446
|
|
|
371
447
|
with open(os.path.join(backup_dir, "manifest.json"), "w", encoding="utf-8") as f:
|
|
372
|
-
json.dump(
|
|
448
|
+
json.dump(
|
|
449
|
+
{
|
|
450
|
+
"entrypoint": path,
|
|
451
|
+
"backup": backup_path,
|
|
452
|
+
"framework": framework,
|
|
453
|
+
"mode": "serve" if wrapped is not None else "mount",
|
|
454
|
+
},
|
|
455
|
+
f,
|
|
456
|
+
indent=2,
|
|
457
|
+
)
|
|
373
458
|
|
|
374
459
|
return {
|
|
375
460
|
"status": "patched",
|
|
376
461
|
"entrypoint": os.path.relpath(path, workspace),
|
|
377
462
|
"framework": framework,
|
|
463
|
+
"mode": "serve" if wrapped is not None else "mount",
|
|
378
464
|
"backup": backup_path,
|
|
379
|
-
"line": call.strip(),
|
|
465
|
+
"line": (preview.splitlines()[1].strip() if wrapped is not None else call.strip()),
|
|
380
466
|
}
|
|
381
467
|
|
|
382
468
|
|
package/src/batch_editor.py
CHANGED
|
@@ -23,6 +23,7 @@ Key capabilities:
|
|
|
23
23
|
import os
|
|
24
24
|
import re
|
|
25
25
|
import stat
|
|
26
|
+
import sys
|
|
26
27
|
import difflib
|
|
27
28
|
import shlex
|
|
28
29
|
import subprocess
|
|
@@ -309,7 +310,17 @@ def _apply_hunk_to_text(
|
|
|
309
310
|
return None, f"Target not found in lines {s_idx+1}..{e_idx}: {hint}"
|
|
310
311
|
count = sub_text.count(match_target)
|
|
311
312
|
if count > 1 and not replace_all:
|
|
312
|
-
|
|
313
|
+
# Report where: the caller just narrowed to a window and needs the exact
|
|
314
|
+
# sub-range (or a longer unique snippet) to finish the edit in one retry.
|
|
315
|
+
occ, scan = [], 0
|
|
316
|
+
while len(occ) < 5:
|
|
317
|
+
pos = sub_text.find(match_target, scan)
|
|
318
|
+
if pos < 0:
|
|
319
|
+
break
|
|
320
|
+
occ.append(str(s_idx + sub_text.count("\n", 0, pos) + 1))
|
|
321
|
+
scan = pos + 1
|
|
322
|
+
locs = f" (near lines {', '.join(occ)})" if occ else ""
|
|
323
|
+
return None, f"Target occurs {count} times within lines {s_idx+1}..{e_idx}{locs}. Specify replace_all=True or narrow the range."
|
|
313
324
|
prepared_replacement = _normalize_eol(replacement, nl)
|
|
314
325
|
new_sub = sub_text.replace(match_target, prepared_replacement) if replace_all else sub_text.replace(match_target, prepared_replacement, 1)
|
|
315
326
|
new_lines = lines[:s_idx] + [new_sub] + lines[e_idx:]
|
|
@@ -335,6 +346,60 @@ def _apply_hunk_to_text(
|
|
|
335
346
|
return new_content, None
|
|
336
347
|
|
|
337
348
|
|
|
349
|
+
def detect_verify_command(base_dir: str, files: Optional[List[str]] = None) -> Optional[List[str]]:
|
|
350
|
+
"""The project's own test command, for `apply_edits(verify="auto")`.
|
|
351
|
+
|
|
352
|
+
Only commands the project already declares are used — never a guess about which
|
|
353
|
+
files are tests — and only runner/flag shapes that `validate_verify_command`
|
|
354
|
+
accepts, so a resolved command can never come back blocked. Returning None is a normal
|
|
355
|
+
outcome: the caller then says "applied unverified" instead of inventing a verdict.
|
|
356
|
+
|
|
357
|
+
`files` (the paths being edited) narrows the run to the edited packages: an
|
|
358
|
+
unscoped `go test ./...` in a real module outlives the MCP tool timeout and can be
|
|
359
|
+
red on unrelated pre-existing failures, which would roll back a good edit.
|
|
360
|
+
"""
|
|
361
|
+
def has(name: str) -> bool:
|
|
362
|
+
return os.path.exists(os.path.join(base_dir, name))
|
|
363
|
+
|
|
364
|
+
if has("go.mod"):
|
|
365
|
+
pkgs: List[str] = []
|
|
366
|
+
for f in files or []:
|
|
367
|
+
abs_f = os.path.abspath(os.path.join(base_dir, f))
|
|
368
|
+
rel = os.path.relpath(abs_f, base_dir).replace("\\", "/")
|
|
369
|
+
if rel.startswith(".."):
|
|
370
|
+
continue
|
|
371
|
+
pkg = os.path.dirname(rel) or "."
|
|
372
|
+
pkg = "." if pkg == "." else "./" + pkg
|
|
373
|
+
if pkg not in pkgs:
|
|
374
|
+
pkgs.append(pkg)
|
|
375
|
+
return ["go", "test"] + (pkgs or ["./..."])
|
|
376
|
+
if has("Cargo.toml"):
|
|
377
|
+
return ["cargo", "test", "--quiet"]
|
|
378
|
+
pkg = os.path.join(base_dir, "package.json")
|
|
379
|
+
if os.path.exists(pkg):
|
|
380
|
+
try:
|
|
381
|
+
import json as _json
|
|
382
|
+
with open(pkg, "r", encoding="utf-8") as f:
|
|
383
|
+
scripts = (_json.load(f) or {}).get("scripts") or {}
|
|
384
|
+
if isinstance(scripts, dict) and scripts.get("test"):
|
|
385
|
+
return ["npm", "test", "--silent"]
|
|
386
|
+
except (OSError, ValueError):
|
|
387
|
+
pass
|
|
388
|
+
py_files = []
|
|
389
|
+
for f in files or []:
|
|
390
|
+
if not str(f).endswith(".py"):
|
|
391
|
+
continue
|
|
392
|
+
rel = os.path.relpath(os.path.abspath(os.path.join(base_dir, f)), base_dir).replace("\\", "/")
|
|
393
|
+
if not rel.startswith(".."):
|
|
394
|
+
py_files.append(rel)
|
|
395
|
+
for marker in ("pytest.ini", "tox.ini", "pyproject.toml", "setup.cfg", "conftest.py"):
|
|
396
|
+
if has(marker):
|
|
397
|
+
return ["python3", "-m", "pytest", "-q"] + py_files
|
|
398
|
+
if os.path.isdir(os.path.join(base_dir, "tests")):
|
|
399
|
+
return ["python3", "-m", "pytest", "-q"] + py_files
|
|
400
|
+
return None
|
|
401
|
+
|
|
402
|
+
|
|
338
403
|
def execute_batch_edits(
|
|
339
404
|
edits: List[Dict[str, Any]],
|
|
340
405
|
best_effort: bool = False,
|
|
@@ -374,20 +439,36 @@ def execute_batch_edits(
|
|
|
374
439
|
}
|
|
375
440
|
|
|
376
441
|
verified_argv: Optional[List[str]] = None
|
|
442
|
+
auto_verify_note = ""
|
|
377
443
|
if verify:
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
"
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
444
|
+
# verify="auto" -> run the project's own declared test command. This is the
|
|
445
|
+
# tool's strongest convergence lever (edit + verdict in one call) and it was
|
|
446
|
+
# never used because agents had to type the command from the task text.
|
|
447
|
+
if str(verify).strip().lower() == "auto":
|
|
448
|
+
requested = [str(e.get("path") or "") for e in edits if isinstance(e, dict) and e.get("path")]
|
|
449
|
+
verified_argv = detect_verify_command(real_base, files=requested)
|
|
450
|
+
if verified_argv:
|
|
451
|
+
verify = " ".join(verified_argv)
|
|
452
|
+
else:
|
|
453
|
+
auto_verify_note = (
|
|
454
|
+
"no declared test command found (go.mod / package.json scripts.test / "
|
|
455
|
+
"pytest config / a tests/ directory)"
|
|
456
|
+
)
|
|
457
|
+
verify = ""
|
|
458
|
+
if verify:
|
|
459
|
+
verified_argv, verify_err, verify_check = validate_verify_command(str(verify), base_dir=real_base)
|
|
460
|
+
if verify_err or not verified_argv:
|
|
461
|
+
return {
|
|
462
|
+
"success": False,
|
|
463
|
+
"blocked": True,
|
|
464
|
+
"check_name": verify_check or "VERIFY_COMMAND_BLOCKED",
|
|
465
|
+
"error": verify_err or "Verification command blocked.",
|
|
466
|
+
"applied_count": 0,
|
|
467
|
+
"applied_files": [],
|
|
468
|
+
"failed_count": 0,
|
|
469
|
+
"failed_files": [],
|
|
470
|
+
"dry_run": dry_run,
|
|
471
|
+
}
|
|
391
472
|
|
|
392
473
|
# Pre-validation & secret check
|
|
393
474
|
prepared_files: Dict[str, Dict[str, Any]] = {}
|
|
@@ -404,7 +485,13 @@ def execute_batch_edits(
|
|
|
404
485
|
continue
|
|
405
486
|
|
|
406
487
|
if os.path.isabs(rel_path):
|
|
407
|
-
failed_files.append({
|
|
488
|
+
failed_files.append({
|
|
489
|
+
"path": rel_path,
|
|
490
|
+
"error": (
|
|
491
|
+
"Absolute paths are disallowed: edit paths are resolved inside one working directory. "
|
|
492
|
+
"Pass 'cwd' (the repo root, absolute) with repo-relative 'path' values instead."
|
|
493
|
+
),
|
|
494
|
+
})
|
|
408
495
|
continue
|
|
409
496
|
|
|
410
497
|
abs_path = os.path.normpath(os.path.join(base_dir, rel_path))
|
|
@@ -747,6 +834,10 @@ def execute_batch_edits(
|
|
|
747
834
|
result["success"] = False
|
|
748
835
|
_rollback_after_verify_failure()
|
|
749
836
|
|
|
837
|
+
if auto_verify_note and applied_files_info and not dry_run:
|
|
838
|
+
# Asked to verify, could not: say so plainly instead of reporting success as a pass.
|
|
839
|
+
result["verify"] = {"command": "auto", "passed": None, "note": auto_verify_note}
|
|
840
|
+
|
|
750
841
|
if best_effort and applied_files_info:
|
|
751
842
|
result.setdefault("edits_kept", True)
|
|
752
843
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Measured OUMV benchmarks (driver + targets + report)."""
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Minimal, measured agent loop for OUMV benchmarks.
|
|
2
|
+
|
|
3
|
+
Deliberately small: one OpenAI-compatible endpoint (DeepSeek by default), explicit
|
|
4
|
+
tool schemas, a hard step cap and a hard USD budget. Every token number comes from
|
|
5
|
+
the provider's own `usage` payload — nothing is estimated from bytes, and no
|
|
6
|
+
fixture traces are involved.
|
|
7
|
+
|
|
8
|
+
Prices are a pinned snapshot; the report prints them so a reader can recompute the
|
|
9
|
+
cost. Update the table when the provider changes prices (and bump `PRICE_SNAPSHOT`).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.request
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
20
|
+
|
|
21
|
+
PRICE_SNAPSHOT = "2026-11-26"
|
|
22
|
+
# USD per 1M tokens: cache-miss input, cache-hit input, output.
|
|
23
|
+
PRICES: Dict[str, Dict[str, float]] = {
|
|
24
|
+
"deepseek-chat": {"input_miss": 0.27, "input_hit": 0.07, "output": 1.10},
|
|
25
|
+
"deepseek-flash": {"input_miss": 0.27, "input_hit": 0.07, "output": 1.10},
|
|
26
|
+
}
|
|
27
|
+
DEFAULT_BASE_URL = "https://api.deepseek.com"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resolve_api_key() -> str:
|
|
31
|
+
key = os.environ.get("DEEPSEEK_API_KEY", "").strip()
|
|
32
|
+
if key:
|
|
33
|
+
return key
|
|
34
|
+
path = os.path.expanduser("~/.tokensafe/data/config.json")
|
|
35
|
+
try:
|
|
36
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
37
|
+
return str(json.load(f).get("deepseek_api_key") or "").strip()
|
|
38
|
+
except Exception:
|
|
39
|
+
return ""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Usage:
|
|
44
|
+
input_tokens: int = 0
|
|
45
|
+
cache_hit_tokens: int = 0
|
|
46
|
+
output_tokens: int = 0
|
|
47
|
+
calls: int = 0
|
|
48
|
+
|
|
49
|
+
def add(self, payload: Dict[str, Any]) -> None:
|
|
50
|
+
self.calls += 1
|
|
51
|
+
self.input_tokens += int(payload.get("prompt_tokens") or 0)
|
|
52
|
+
self.cache_hit_tokens += int(payload.get("prompt_cache_hit_tokens") or 0)
|
|
53
|
+
self.output_tokens += int(payload.get("completion_tokens") or 0)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def cache_miss_tokens(self) -> int:
|
|
57
|
+
return max(self.input_tokens - self.cache_hit_tokens, 0)
|
|
58
|
+
|
|
59
|
+
def usd(self, model: str) -> float:
|
|
60
|
+
price = PRICES.get(model, PRICES["deepseek-chat"])
|
|
61
|
+
return round(
|
|
62
|
+
(self.cache_miss_tokens / 1_000_000) * price["input_miss"]
|
|
63
|
+
+ (self.cache_hit_tokens / 1_000_000) * price["input_hit"]
|
|
64
|
+
+ (self.output_tokens / 1_000_000) * price["output"],
|
|
65
|
+
6,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
def as_dict(self, model: str) -> Dict[str, Any]:
|
|
69
|
+
return {
|
|
70
|
+
"calls": self.calls,
|
|
71
|
+
"input_tokens": self.input_tokens,
|
|
72
|
+
"cache_hit_tokens": self.cache_hit_tokens,
|
|
73
|
+
"cache_miss_tokens": self.cache_miss_tokens,
|
|
74
|
+
"output_tokens": self.output_tokens,
|
|
75
|
+
"usd": self.usd(model),
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class BudgetExceeded(RuntimeError):
|
|
80
|
+
def __init__(self, message: str, usage: Optional[Dict[str, Any]] = None):
|
|
81
|
+
super().__init__(message)
|
|
82
|
+
self.usage = usage or {}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class DeepSeekClient:
|
|
86
|
+
def __init__(
|
|
87
|
+
self,
|
|
88
|
+
model: str = "deepseek-chat",
|
|
89
|
+
temperature: float = 0.0,
|
|
90
|
+
base_url: Optional[str] = None,
|
|
91
|
+
timeout: float = 120.0,
|
|
92
|
+
):
|
|
93
|
+
self.model = model
|
|
94
|
+
self.temperature = temperature
|
|
95
|
+
self.base_url = (base_url or os.environ.get("DEEPSEEK_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
96
|
+
self.timeout = timeout
|
|
97
|
+
self.api_key = resolve_api_key()
|
|
98
|
+
if not self.api_key:
|
|
99
|
+
raise RuntimeError(
|
|
100
|
+
"no DeepSeek API key: set DEEPSEEK_API_KEY or write deepseek_api_key "
|
|
101
|
+
"into ~/.tokensafe/data/config.json"
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
def chat(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
|
105
|
+
body: Dict[str, Any] = {
|
|
106
|
+
"model": self.model,
|
|
107
|
+
"messages": messages,
|
|
108
|
+
"temperature": self.temperature,
|
|
109
|
+
}
|
|
110
|
+
if tools:
|
|
111
|
+
body["tools"] = tools
|
|
112
|
+
body["tool_choice"] = "auto"
|
|
113
|
+
req = urllib.request.Request(
|
|
114
|
+
f"{self.base_url}/chat/completions",
|
|
115
|
+
data=json.dumps(body).encode(),
|
|
116
|
+
headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}"},
|
|
117
|
+
method="POST",
|
|
118
|
+
)
|
|
119
|
+
try:
|
|
120
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
121
|
+
payload = json.loads(resp.read().decode())
|
|
122
|
+
except urllib.error.HTTPError as exc:
|
|
123
|
+
raise RuntimeError(f"provider HTTP {exc.code}: {exc.read().decode()[:300]}") from exc
|
|
124
|
+
return payload["choices"][0]["message"], payload.get("usage") or {}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
ToolFn = Callable[..., Any]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass
|
|
131
|
+
class StepRecord:
|
|
132
|
+
index: int
|
|
133
|
+
tool_calls: List[str] = field(default_factory=list)
|
|
134
|
+
result_chars: List[int] = field(default_factory=list)
|
|
135
|
+
duration_ms: float = 0.0
|
|
136
|
+
oracle_passed: Optional[int] = None
|
|
137
|
+
oracle_failed: List[str] = field(default_factory=list)
|
|
138
|
+
note: str = ""
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def run_agent(
|
|
142
|
+
client: DeepSeekClient,
|
|
143
|
+
system_prompt: str,
|
|
144
|
+
task_prompt: str,
|
|
145
|
+
tools: List[Dict[str, Any]],
|
|
146
|
+
registry: Dict[str, ToolFn],
|
|
147
|
+
max_steps: int = 14,
|
|
148
|
+
budget_usd: float = 1.0,
|
|
149
|
+
after_step: Optional[Callable[[int], Tuple[Optional[int], List[str], str]]] = None,
|
|
150
|
+
stop_when_solved: bool = True,
|
|
151
|
+
) -> Dict[str, Any]:
|
|
152
|
+
"""Runs one tool loop. Returns messages-independent accounting + step log."""
|
|
153
|
+
usage = Usage()
|
|
154
|
+
steps: List[StepRecord] = []
|
|
155
|
+
tool_counts: Dict[str, int] = {}
|
|
156
|
+
tool_chars: Dict[str, int] = {}
|
|
157
|
+
messages: List[Dict[str, Any]] = [
|
|
158
|
+
{"role": "system", "content": system_prompt},
|
|
159
|
+
{"role": "user", "content": task_prompt},
|
|
160
|
+
]
|
|
161
|
+
stop_reason = "step_limit"
|
|
162
|
+
|
|
163
|
+
for index in range(1, max_steps + 1):
|
|
164
|
+
message, raw_usage = client.chat(messages, tools)
|
|
165
|
+
usage.add(raw_usage)
|
|
166
|
+
|
|
167
|
+
calls = message.get("tool_calls") or []
|
|
168
|
+
messages.append(message)
|
|
169
|
+
|
|
170
|
+
record = StepRecord(index=index, tool_calls=[c["function"]["name"] for c in calls])
|
|
171
|
+
if not calls:
|
|
172
|
+
stop_reason = "agent_finished"
|
|
173
|
+
steps.append(record)
|
|
174
|
+
break
|
|
175
|
+
|
|
176
|
+
for call in calls:
|
|
177
|
+
name = call["function"]["name"]
|
|
178
|
+
try:
|
|
179
|
+
args = json.loads(call["function"].get("arguments") or "{}")
|
|
180
|
+
except json.JSONDecodeError:
|
|
181
|
+
args = {}
|
|
182
|
+
fn = registry.get(name)
|
|
183
|
+
try:
|
|
184
|
+
result = fn(**args) if fn else {"error": f"unknown tool {name}"}
|
|
185
|
+
except Exception as exc: # tool errors are observations, not crashes
|
|
186
|
+
result = {"error": f"{type(exc).__name__}: {exc}"}
|
|
187
|
+
content = json.dumps(result, ensure_ascii=False)[:6000]
|
|
188
|
+
tool_counts[name] = tool_counts.get(name, 0) + 1
|
|
189
|
+
tool_chars[name] = tool_chars.get(name, 0) + len(content)
|
|
190
|
+
record.result_chars.append(len(content))
|
|
191
|
+
messages.append({
|
|
192
|
+
"role": "tool",
|
|
193
|
+
"tool_call_id": call.get("id", ""),
|
|
194
|
+
"content": content,
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
if after_step:
|
|
198
|
+
passed, failed, note = after_step(index)
|
|
199
|
+
record.oracle_passed, record.oracle_failed, record.note = passed, failed, note
|
|
200
|
+
steps.append(record)
|
|
201
|
+
|
|
202
|
+
if stop_when_solved and record.oracle_passed == 12:
|
|
203
|
+
stop_reason = "solved"
|
|
204
|
+
break
|
|
205
|
+
|
|
206
|
+
if usage.usd(client.model) > budget_usd:
|
|
207
|
+
raise BudgetExceeded(
|
|
208
|
+
f"budget ${budget_usd} exceeded at step {index} (${usage.usd(client.model)})",
|
|
209
|
+
usage.as_dict(client.model),
|
|
210
|
+
)
|
|
211
|
+
else:
|
|
212
|
+
stop_reason = "max_steps"
|
|
213
|
+
|
|
214
|
+
return {
|
|
215
|
+
"model": client.model,
|
|
216
|
+
"temperature": client.temperature,
|
|
217
|
+
"price_snapshot": PRICE_SNAPSHOT,
|
|
218
|
+
"prices_usd_per_mtok": PRICES.get(client.model),
|
|
219
|
+
"stop_reason": stop_reason,
|
|
220
|
+
"usage": usage.as_dict(client.model),
|
|
221
|
+
"tool_calls": tool_counts,
|
|
222
|
+
"tool_result_chars": tool_chars,
|
|
223
|
+
"steps": [
|
|
224
|
+
{
|
|
225
|
+
"index": s.index,
|
|
226
|
+
"tools": s.tool_calls,
|
|
227
|
+
"result_chars": s.result_chars,
|
|
228
|
+
"oracle_passed": s.oracle_passed,
|
|
229
|
+
"oracle_failed": s.oracle_failed,
|
|
230
|
+
"note": s.note,
|
|
231
|
+
}
|
|
232
|
+
for s in steps
|
|
233
|
+
],
|
|
234
|
+
}
|