tokensafe 4.15.0 → 4.16.0
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 +1 -1
- package/bin/tokensafe-acp.js +38 -0
- package/hooks/claude_code_hook.py +26 -0
- package/hooks/post_tool_use.py +10 -0
- package/hooks/pre_invocation.py +44 -11
- package/hooks/pre_tool_use.py +22 -1
- package/kimi.plugin.json +1 -1
- package/package.json +3 -2
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +157 -3
- package/src/angular_cli.py +181 -0
- package/src/auto_inject.py +36 -2
- package/src/backend_release.py +1 -1
- package/src/batch_editor.py +119 -2
- package/src/bench/driver.py +54 -6
- package/src/bench/runner.py +58 -8
- package/src/build_parsers.py +35 -2
- package/src/burn_monitor.py +69 -1
- package/src/cache_normalizer.py +1 -1
- package/src/cli.py +109 -4
- package/src/command_sanitizer.py +21 -5
- package/src/dashboard.py +26 -0
- package/src/delegation.py +253 -0
- package/src/format_parsers/game_assets.py +259 -0
- package/src/fts_index.py +1 -1
- package/src/governor.py +54 -8
- package/src/installer.py +1 -1
- package/src/license_manager.py +128 -1
- package/src/mcp_server.py +318 -39
- package/src/metrics.py +313 -29
- package/src/savings.py +9 -4
- package/src/skeletonizer.py +51 -0
- package/src/telemetry_sync.py +1 -1
- package/src/usage_ledger.py +333 -0
- package/src/version_checker.py +1 -1
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Angular CLI injection: point a workspace's `serve` target at the TokenSafe builder.
|
|
2
|
+
|
|
3
|
+
`ng serve` is the only way into an Angular app that is not on Vite, and it has no
|
|
4
|
+
third-party plugin slot. What it does have is a configurable builder per project:
|
|
5
|
+
`projects.<name>.architect.serve.builder`. This module rewrites that value to
|
|
6
|
+
`@tokensafe-ui/angular-builder:dev-server` and records the previous value so
|
|
7
|
+
`tokensafe inject --revert` restores byte-for-byte what was there.
|
|
8
|
+
|
|
9
|
+
Refusals are deliberate:
|
|
10
|
+
- no `angular.json` / no `architect.serve` → nothing to point at;
|
|
11
|
+
- the builder package is not installed in the workspace → `ng serve` would fail
|
|
12
|
+
while `tokensafe` claimed the app was wired, so the inject reports the install
|
|
13
|
+
command instead of writing a builder it cannot resolve.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
from typing import Any, Dict, Optional
|
|
19
|
+
|
|
20
|
+
BUILDER_ID = "@tokensafe-ui/angular-builder:dev-server"
|
|
21
|
+
INSTALL_COMMAND = "npm install --save-dev @tokensafe-ui/angular-builder"
|
|
22
|
+
STATE_REL_PATH = os.path.join(".tokensafe", "angular-cli.json")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _angular_json(app_root: str) -> str:
|
|
26
|
+
return os.path.join(app_root, "angular.json")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _state_path(workspace: str) -> str:
|
|
30
|
+
return os.path.join(workspace, STATE_REL_PATH)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _load_state(workspace: str) -> Dict[str, Any]:
|
|
34
|
+
try:
|
|
35
|
+
with open(_state_path(workspace), "r", encoding="utf-8") as handle:
|
|
36
|
+
data = json.load(handle)
|
|
37
|
+
return data if isinstance(data, dict) else {}
|
|
38
|
+
except Exception:
|
|
39
|
+
return {}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _save_state(workspace: str, state: Dict[str, Any]) -> None:
|
|
43
|
+
from src.atomic_io import write_text_atomic
|
|
44
|
+
|
|
45
|
+
path = _state_path(workspace)
|
|
46
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
47
|
+
write_text_atomic(path, json.dumps(state, indent=2, ensure_ascii=False))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _read_angular_json(app_root: str) -> Optional[Dict[str, Any]]:
|
|
51
|
+
try:
|
|
52
|
+
with open(_angular_json(app_root), "r", encoding="utf-8") as handle:
|
|
53
|
+
data = json.load(handle)
|
|
54
|
+
return data if isinstance(data, dict) else None
|
|
55
|
+
except Exception:
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _ensure_tokensafe_gitignored(app_root: str) -> None:
|
|
60
|
+
try:
|
|
61
|
+
from src.paths import ensure_tokensafe_gitignore
|
|
62
|
+
|
|
63
|
+
ensure_tokensafe_gitignore(app_root)
|
|
64
|
+
except Exception:
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def package_installed(app_root: str) -> bool:
|
|
69
|
+
"""The builder must be resolvable from the workspace or `ng serve` cannot load it."""
|
|
70
|
+
marker = os.path.join(app_root, "node_modules", "@tokensafe-ui", "angular-builder", "package.json")
|
|
71
|
+
return os.path.isfile(marker)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def serve_targets(data: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
|
|
75
|
+
"""Project name → its `architect.serve` block (Angular keeps it under `architect`)."""
|
|
76
|
+
out: Dict[str, Dict[str, Any]] = {}
|
|
77
|
+
for name, project in (data.get("projects") or {}).items():
|
|
78
|
+
if not isinstance(project, dict):
|
|
79
|
+
continue
|
|
80
|
+
architect = project.get("architect") if isinstance(project.get("architect"), dict) else {}
|
|
81
|
+
serve = architect.get("serve") if isinstance(architect.get("serve"), dict) else {}
|
|
82
|
+
if serve:
|
|
83
|
+
out[name] = serve
|
|
84
|
+
return out
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def patch_state(app_root: str) -> Dict[str, Any]:
|
|
88
|
+
"""What `apply` would find: is there a target, is it already patched, is the package installed."""
|
|
89
|
+
data = _read_angular_json(app_root)
|
|
90
|
+
if data is None:
|
|
91
|
+
return {"patched": False, "projects": [], "reason": f"no readable angular.json in {app_root}"}
|
|
92
|
+
targets = serve_targets(data)
|
|
93
|
+
if not targets:
|
|
94
|
+
return {"patched": False, "projects": [], "reason": "angular.json has no architect.serve target"}
|
|
95
|
+
already = [name for name, serve in targets.items() if str(serve.get("builder") or "") == BUILDER_ID]
|
|
96
|
+
return {
|
|
97
|
+
"patched": len(already) == len(targets),
|
|
98
|
+
"projects": sorted(targets),
|
|
99
|
+
"patched_projects": sorted(already),
|
|
100
|
+
"installed": package_installed(app_root),
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def apply(workspace: str, app_root: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
105
|
+
"""Rewrites `architect.serve.builder` for every project in the app."""
|
|
106
|
+
state = patch_state(app_root)
|
|
107
|
+
if state.get("reason"):
|
|
108
|
+
return {"status": "skipped", "kind": "angular_cli_builder", "reason": state["reason"]}
|
|
109
|
+
if not state.get("installed"):
|
|
110
|
+
return {
|
|
111
|
+
"status": "skipped",
|
|
112
|
+
"kind": "angular_cli_builder",
|
|
113
|
+
"reason": "the TokenSafe Angular builder is not installed in this workspace, so ng serve could not load it",
|
|
114
|
+
"install": INSTALL_COMMAND,
|
|
115
|
+
}
|
|
116
|
+
data = _read_angular_json(app_root) or {}
|
|
117
|
+
targets = serve_targets(data)
|
|
118
|
+
previous: Dict[str, str] = {}
|
|
119
|
+
for name, serve in targets.items():
|
|
120
|
+
previous[name] = str(serve.get("builder") or "")
|
|
121
|
+
serve["builder"] = BUILDER_ID
|
|
122
|
+
|
|
123
|
+
if not dry_run:
|
|
124
|
+
from src.atomic_io import write_text_atomic
|
|
125
|
+
|
|
126
|
+
write_text_atomic(_angular_json(app_root), json.dumps(data, indent=2, ensure_ascii=False) + "\n")
|
|
127
|
+
recorded = _load_state(workspace)
|
|
128
|
+
apps = recorded.get("apps") if isinstance(recorded.get("apps"), dict) else {}
|
|
129
|
+
apps[os.path.abspath(app_root)] = previous
|
|
130
|
+
recorded["apps"] = apps
|
|
131
|
+
_save_state(workspace, recorded)
|
|
132
|
+
_ensure_tokensafe_gitignored(app_root)
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
"status": "ready",
|
|
136
|
+
"kind": "angular_cli_builder",
|
|
137
|
+
"builder": BUILDER_ID,
|
|
138
|
+
"projects": sorted(previous),
|
|
139
|
+
"previous": previous,
|
|
140
|
+
"dry_run": dry_run,
|
|
141
|
+
"run": "ng serve",
|
|
142
|
+
"note": "the bridge is served by the builder; no source file is touched",
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def revert_all(workspace: str) -> Dict[str, Any]:
|
|
147
|
+
"""Restores every recorded builder value and removes the state file."""
|
|
148
|
+
recorded = _load_state(workspace)
|
|
149
|
+
apps = recorded.get("apps") if isinstance(recorded.get("apps"), dict) else {}
|
|
150
|
+
restored: Dict[str, Any] = {}
|
|
151
|
+
for app_root, previous in apps.items():
|
|
152
|
+
if not isinstance(previous, dict):
|
|
153
|
+
continue
|
|
154
|
+
data = _read_angular_json(app_root)
|
|
155
|
+
if data is None:
|
|
156
|
+
restored[app_root] = {"status": "skipped", "reason": "angular.json is missing"}
|
|
157
|
+
continue
|
|
158
|
+
targets = serve_targets(data)
|
|
159
|
+
changed = []
|
|
160
|
+
for name, builder in previous.items():
|
|
161
|
+
serve = targets.get(name)
|
|
162
|
+
if not serve:
|
|
163
|
+
continue
|
|
164
|
+
if str(serve.get("builder") or "") != BUILDER_ID:
|
|
165
|
+
# Someone changed it after the inject: leave their value alone.
|
|
166
|
+
continue
|
|
167
|
+
serve["builder"] = builder
|
|
168
|
+
changed.append(name)
|
|
169
|
+
if changed:
|
|
170
|
+
from src.atomic_io import write_text_atomic
|
|
171
|
+
|
|
172
|
+
write_text_atomic(_angular_json(app_root), json.dumps(data, indent=2, ensure_ascii=False) + "\n")
|
|
173
|
+
restored[app_root] = {"status": "reverted", "projects": changed}
|
|
174
|
+
try:
|
|
175
|
+
if os.path.isfile(_state_path(workspace)):
|
|
176
|
+
os.unlink(_state_path(workspace))
|
|
177
|
+
except OSError:
|
|
178
|
+
pass
|
|
179
|
+
if not restored:
|
|
180
|
+
return {"status": "nothing-to-revert"}
|
|
181
|
+
return {"status": "reverted", "apps": restored}
|
package/src/auto_inject.py
CHANGED
|
@@ -28,6 +28,8 @@ import glob
|
|
|
28
28
|
import hashlib
|
|
29
29
|
import json
|
|
30
30
|
import os
|
|
31
|
+
|
|
32
|
+
from src import angular_cli
|
|
31
33
|
import re
|
|
32
34
|
import shutil
|
|
33
35
|
import subprocess
|
|
@@ -1937,12 +1939,12 @@ _SIDECARS = {
|
|
|
1937
1939
|
"spring": (
|
|
1938
1940
|
"java/src/dev/tokensafe/oumv/OumvSpring.java",
|
|
1939
1941
|
"OumvSpring.java",
|
|
1940
|
-
"
|
|
1942
|
+
"6d99e1165b62a8053dcb3ae08bebeb5f6dd7d092e9b39eb98deaf596afd3c4e7",
|
|
1941
1943
|
),
|
|
1942
1944
|
"php": (
|
|
1943
1945
|
"php/bin/oumv-php",
|
|
1944
1946
|
"oumv-php",
|
|
1945
|
-
"
|
|
1947
|
+
"a075372d575c394d42134b5af62f0f228c271a1ce95984bf4dae9811808945fd",
|
|
1946
1948
|
),
|
|
1947
1949
|
}
|
|
1948
1950
|
|
|
@@ -2191,6 +2193,27 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
2191
2193
|
}
|
|
2192
2194
|
actions.append(action)
|
|
2193
2195
|
continue
|
|
2196
|
+
if framework in ("angular", "angular-cli"):
|
|
2197
|
+
app_root = _app_root(workspace, root)
|
|
2198
|
+
angular_state = angular_cli.patch_state(app_root)
|
|
2199
|
+
if angular_state.get("projects"):
|
|
2200
|
+
actions.append({
|
|
2201
|
+
"kind": "angular_cli_builder",
|
|
2202
|
+
"profile": "frontend",
|
|
2203
|
+
"app": root,
|
|
2204
|
+
"framework": "angular",
|
|
2205
|
+
"writes_repo": True,
|
|
2206
|
+
"already_patched": angular_state["patched"],
|
|
2207
|
+
"projects": angular_state["projects"],
|
|
2208
|
+
"installed": angular_state.get("installed"),
|
|
2209
|
+
"install": angular_cli.INSTALL_COMMAND,
|
|
2210
|
+
"run": "ng serve",
|
|
2211
|
+
"description": (
|
|
2212
|
+
"points projects.*.architect.serve.builder at "
|
|
2213
|
+
f"{angular_cli.BUILDER_ID}; no source file is touched and --revert restores the previous builder"
|
|
2214
|
+
),
|
|
2215
|
+
})
|
|
2216
|
+
continue
|
|
2194
2217
|
if not app["supported"]:
|
|
2195
2218
|
reason = app["reason"] or f"no OUMV adapter for {framework} yet"
|
|
2196
2219
|
actions.append({
|
|
@@ -2388,6 +2411,16 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
|
|
|
2388
2411
|
"app": root,
|
|
2389
2412
|
**apply_next_patch(workspace, dry_run=dry_run, root=root),
|
|
2390
2413
|
})
|
|
2414
|
+
elif framework in ("angular", "angular-cli"):
|
|
2415
|
+
app_root = _app_root(workspace, root)
|
|
2416
|
+
if angular_cli.patch_state(app_root).get("projects"):
|
|
2417
|
+
results["actions"].append({
|
|
2418
|
+
"kind": "angular_cli_builder",
|
|
2419
|
+
"profile": "frontend",
|
|
2420
|
+
"app": root,
|
|
2421
|
+
**angular_cli.apply(workspace, app_root, dry_run=dry_run),
|
|
2422
|
+
})
|
|
2423
|
+
continue
|
|
2391
2424
|
elif not app["supported"]:
|
|
2392
2425
|
results["actions"].append({
|
|
2393
2426
|
"kind": "frontend_unsupported",
|
|
@@ -2555,4 +2588,5 @@ def revert(workspace: str) -> Dict[str, Any]:
|
|
|
2555
2588
|
results[kind] = _revert_manifest(workspace, kind, manifest)
|
|
2556
2589
|
|
|
2557
2590
|
results["config"] = revert_config(workspace)
|
|
2591
|
+
results["angular_cli_builder"] = angular_cli.revert_all(workspace)
|
|
2558
2592
|
return results
|
package/src/backend_release.py
CHANGED
|
@@ -10,7 +10,7 @@ from __future__ import annotations
|
|
|
10
10
|
|
|
11
11
|
# Backend tag (`vX.Y.Z`); the Go module resolves against the matching `go/vX.Y.Z`,
|
|
12
12
|
# which the backend release workflow creates alongside it.
|
|
13
|
-
BACKEND_RELEASE_TAG = "v0.
|
|
13
|
+
BACKEND_RELEASE_TAG = "v0.22.1"
|
|
14
14
|
|
|
15
15
|
# Wire version that tag speaks. Printed in briefs so an agent never mixes a
|
|
16
16
|
# backend release with an older protocol line.
|
package/src/batch_editor.py
CHANGED
|
@@ -38,6 +38,10 @@ from src.format_parsers.ansi import strip_ansi
|
|
|
38
38
|
|
|
39
39
|
MAX_BATCH_FILES = 50
|
|
40
40
|
MAX_VERIFY_OUTPUT_CHARS = 4000
|
|
41
|
+
# Payload caps: a single call that re-emits libraries is a rewrite in disguise.
|
|
42
|
+
MAX_REPLACEMENT_CHARS = int(os.environ.get("TOKENSAFE_MAX_REPLACEMENT_CHARS", "200000") or 200000)
|
|
43
|
+
MAX_HUNKS_PER_FILE = int(os.environ.get("TOKENSAFE_MAX_HUNKS_PER_FILE", "200") or 200)
|
|
44
|
+
MAX_BATCH_CHARS = int(os.environ.get("TOKENSAFE_MAX_BATCH_CHARS", "600000") or 600000)
|
|
41
45
|
|
|
42
46
|
_VERIFY_SIMPLE_RUNNERS = frozenset({
|
|
43
47
|
"pytest", "py.test", "ruff", "mypy", "pyright", "flake8", "tox", "nox",
|
|
@@ -482,17 +486,52 @@ def detect_verify_command(base_dir: str, files: Optional[List[str]] = None) -> O
|
|
|
482
486
|
return None
|
|
483
487
|
|
|
484
488
|
|
|
489
|
+
def _normalize_hunk_text(value: Any) -> Any:
|
|
490
|
+
"""Accepts a string or an array of lines for a hunk field.
|
|
491
|
+
|
|
492
|
+
Models break JSON mostly by putting raw newlines inside a string: 16
|
|
493
|
+
apply_edits calls in sess_ba3e8135 died as SyntaxError before the request
|
|
494
|
+
ever reached this server. An array of lines removes newline escaping from
|
|
495
|
+
the payload; everything downstream keeps seeing one string.
|
|
496
|
+
"""
|
|
497
|
+
if isinstance(value, list):
|
|
498
|
+
return "\n".join(str(part) for part in value)
|
|
499
|
+
return value
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _normalize_hunks(edits: List[Any]) -> None:
|
|
503
|
+
"""In-place: joins array-form target/replacement into strings."""
|
|
504
|
+
for edit in edits:
|
|
505
|
+
if not isinstance(edit, dict):
|
|
506
|
+
continue
|
|
507
|
+
hunks = edit.get("hunks")
|
|
508
|
+
if not isinstance(hunks, list):
|
|
509
|
+
continue
|
|
510
|
+
for hunk in hunks:
|
|
511
|
+
if not isinstance(hunk, dict):
|
|
512
|
+
continue
|
|
513
|
+
for key in ("target", "replacement"):
|
|
514
|
+
if isinstance(hunk.get(key), list):
|
|
515
|
+
hunk[key] = _normalize_hunk_text(hunk[key])
|
|
516
|
+
|
|
517
|
+
|
|
485
518
|
def execute_batch_edits(
|
|
486
519
|
edits: List[Dict[str, Any]],
|
|
487
520
|
best_effort: bool = False,
|
|
488
521
|
dry_run: bool = False,
|
|
489
522
|
verify: Optional[str] = None,
|
|
490
|
-
verify_timeout_sec: int =
|
|
523
|
+
verify_timeout_sec: int = 120,
|
|
524
|
+
strict_verify: bool = False,
|
|
491
525
|
cwd: Optional[str] = None
|
|
492
526
|
) -> Dict[str, Any]:
|
|
493
527
|
"""
|
|
494
528
|
Applies multi-file, multi-hunk edits in memory, writes atomically or best-effort,
|
|
495
529
|
and optionally executes an inline verify command.
|
|
530
|
+
|
|
531
|
+
`strict_verify` only decides what a failed verify does to the tree: with it, the
|
|
532
|
+
edit is rolled back (the old atomic contract); without it, the edits stay and the
|
|
533
|
+
verdict is reported, because a red suite is information rather than an instruction
|
|
534
|
+
to discard the caller's work.
|
|
496
535
|
"""
|
|
497
536
|
if not isinstance(edits, list) or not edits:
|
|
498
537
|
return {
|
|
@@ -502,6 +541,9 @@ def execute_batch_edits(
|
|
|
502
541
|
"failed_files": []
|
|
503
542
|
}
|
|
504
543
|
|
|
544
|
+
# Array-form hunk text is the JSON-safe envelope, not a second edit language.
|
|
545
|
+
_normalize_hunks(edits)
|
|
546
|
+
|
|
505
547
|
if len(edits) > MAX_BATCH_FILES:
|
|
506
548
|
return {
|
|
507
549
|
"success": False,
|
|
@@ -555,6 +597,8 @@ def execute_batch_edits(
|
|
|
555
597
|
# Pre-validation & secret check
|
|
556
598
|
prepared_files: Dict[str, Dict[str, Any]] = {}
|
|
557
599
|
failed_files: List[Dict[str, Any]] = []
|
|
600
|
+
warnings: List[Dict[str, str]] = []
|
|
601
|
+
total_payload_chars = 0
|
|
558
602
|
|
|
559
603
|
for item in edits:
|
|
560
604
|
if not isinstance(item, dict):
|
|
@@ -603,6 +647,24 @@ def execute_batch_edits(
|
|
|
603
647
|
create_content = item.get("create")
|
|
604
648
|
overwrite = bool(item.get("overwrite"))
|
|
605
649
|
hunks = item.get("hunks") or []
|
|
650
|
+
item_path = str(item.get("path") or "?")
|
|
651
|
+
|
|
652
|
+
if isinstance(create_content, str) and len(create_content) > MAX_REPLACEMENT_CHARS:
|
|
653
|
+
failed_files.append({
|
|
654
|
+
"path": item_path,
|
|
655
|
+
"error": f"'create' content is {len(create_content):,} chars (cap {MAX_REPLACEMENT_CHARS:,}). Send hunks or split the file.",
|
|
656
|
+
})
|
|
657
|
+
continue
|
|
658
|
+
if isinstance(hunks, list) and len(hunks) > MAX_HUNKS_PER_FILE:
|
|
659
|
+
failed_files.append({
|
|
660
|
+
"path": item_path,
|
|
661
|
+
"error": f"{len(hunks)} hunks in one file (cap {MAX_HUNKS_PER_FILE}). Split into smaller calls.",
|
|
662
|
+
})
|
|
663
|
+
continue
|
|
664
|
+
total_payload_chars += (
|
|
665
|
+
len(create_content) if isinstance(create_content, str)
|
|
666
|
+
else sum(len(str(h.get("target") or "")) + len(str(h.get("replacement") or "")) for h in hunks if isinstance(h, dict))
|
|
667
|
+
)
|
|
606
668
|
|
|
607
669
|
if create_content is not None:
|
|
608
670
|
# Creation mode
|
|
@@ -624,6 +686,25 @@ def execute_batch_edits(
|
|
|
624
686
|
failed_files.append({"path": rel_path, "error": f"File '{rel_path}' already exists. Set 'overwrite: true' to overwrite."})
|
|
625
687
|
continue
|
|
626
688
|
|
|
689
|
+
if os.path.exists(abs_path) and overwrite and os.environ.get("TOKENSAFE_CREATE_OVERWRITE_GUARD", "1").strip().lower() not in ("0", "false", "no"):
|
|
690
|
+
try:
|
|
691
|
+
with open(abs_path, "rb") as bf:
|
|
692
|
+
existing_text = bf.read().decode("utf-8")
|
|
693
|
+
existing_lines = existing_text.splitlines()
|
|
694
|
+
if len(existing_lines) >= 40:
|
|
695
|
+
ratio = difflib.SequenceMatcher(None, existing_text, create_content).quick_ratio()
|
|
696
|
+
if ratio >= 0.6:
|
|
697
|
+
failed_files.append({
|
|
698
|
+
"path": rel_path,
|
|
699
|
+
"error": (
|
|
700
|
+
f"TokenSafe Output Guard: 'create'+overwrite re-emits ~{ratio:.0%} of "
|
|
701
|
+
f"'{rel_path}' ({len(existing_lines)} lines). Send hunks instead of the whole file."
|
|
702
|
+
),
|
|
703
|
+
})
|
|
704
|
+
continue
|
|
705
|
+
except (OSError, UnicodeDecodeError):
|
|
706
|
+
pass
|
|
707
|
+
|
|
627
708
|
prepared_files[abs_path] = {
|
|
628
709
|
"rel_path": rel_path,
|
|
629
710
|
"new_content": create_content,
|
|
@@ -647,6 +728,8 @@ def execute_batch_edits(
|
|
|
647
728
|
prev_noop_count = prior_prepared.get("noop_hunks", 0)
|
|
648
729
|
prev_clamped_count = prior_prepared.get("clamped_hunks", 0)
|
|
649
730
|
is_create = prior_prepared["is_create"]
|
|
731
|
+
original_chars = prior_prepared.get("original_chars", len(current_text))
|
|
732
|
+
original_lines = prior_prepared.get("original_lines", len(current_text.splitlines()))
|
|
650
733
|
else:
|
|
651
734
|
if not os.path.exists(abs_path):
|
|
652
735
|
failed_files.append({"path": rel_path, "error": f"File '{rel_path}' does not exist on disk."})
|
|
@@ -669,6 +752,8 @@ def execute_batch_edits(
|
|
|
669
752
|
prev_noop_count = 0
|
|
670
753
|
prev_clamped_count = 0
|
|
671
754
|
is_create = False
|
|
755
|
+
original_chars = len(current_text)
|
|
756
|
+
original_lines = len(current_text.splitlines())
|
|
672
757
|
|
|
673
758
|
file_failed = False
|
|
674
759
|
applied_hunk_count = 0
|
|
@@ -742,6 +827,15 @@ def execute_batch_edits(
|
|
|
742
827
|
hunk_clamped = False
|
|
743
828
|
|
|
744
829
|
if not file_failed:
|
|
830
|
+
replacement_chars = sum(len(str(h.get("replacement") or "")) for h in hunks if isinstance(h, dict))
|
|
831
|
+
if original_lines >= 40 and replacement_chars and replacement_chars / max(1, original_chars) >= 0.6:
|
|
832
|
+
warnings.append({
|
|
833
|
+
"path": rel_path,
|
|
834
|
+
"message": (
|
|
835
|
+
f"replacement re-emits ~{replacement_chars / original_chars:.0%} of a "
|
|
836
|
+
f"{original_lines}-line file; hunks this wide cost like a rewrite."
|
|
837
|
+
),
|
|
838
|
+
})
|
|
745
839
|
prepared_files[abs_path] = {
|
|
746
840
|
"rel_path": rel_path,
|
|
747
841
|
"new_content": current_text,
|
|
@@ -749,8 +843,21 @@ def execute_batch_edits(
|
|
|
749
843
|
"hunk_count": prev_hunk_count + applied_hunk_count,
|
|
750
844
|
"noop_hunks": noop_hunk_count,
|
|
751
845
|
"clamped_hunks": prev_clamped_count + clamped_hunk_count,
|
|
846
|
+
"original_chars": original_chars,
|
|
847
|
+
"original_lines": original_lines,
|
|
752
848
|
}
|
|
753
849
|
|
|
850
|
+
if total_payload_chars > MAX_BATCH_CHARS:
|
|
851
|
+
return {
|
|
852
|
+
"success": False,
|
|
853
|
+
"error": f"Batch payload is {total_payload_chars:,} chars (cap {MAX_BATCH_CHARS:,}); split into smaller calls.",
|
|
854
|
+
"applied_count": 0,
|
|
855
|
+
"applied_files": [],
|
|
856
|
+
"failed_count": len(failed_files),
|
|
857
|
+
"failed_files": failed_files,
|
|
858
|
+
"warnings": warnings,
|
|
859
|
+
}
|
|
860
|
+
|
|
754
861
|
# Atomic enforcement: if any file failed and not best_effort, reject all
|
|
755
862
|
if failed_files and not best_effort:
|
|
756
863
|
return {
|
|
@@ -850,15 +957,25 @@ def execute_batch_edits(
|
|
|
850
957
|
"changed_hunks": total_changed_hunks,
|
|
851
958
|
"failed_count": len(failed_files),
|
|
852
959
|
"failed_files": failed_files,
|
|
960
|
+
"warnings": warnings,
|
|
853
961
|
"dry_run": dry_run,
|
|
854
962
|
"rolled_back": rolled_back,
|
|
855
963
|
}
|
|
856
964
|
|
|
857
965
|
def _rollback_after_verify_failure() -> None:
|
|
858
|
-
"""
|
|
966
|
+
"""Report a failed verdict; only `strict_verify` restores the tree."""
|
|
859
967
|
nonlocal rolled_back
|
|
860
968
|
if best_effort:
|
|
861
969
|
return
|
|
970
|
+
if not strict_verify:
|
|
971
|
+
result["edits_kept"] = True
|
|
972
|
+
if isinstance(result.get("verify"), dict):
|
|
973
|
+
result["verify"]["rolled_back"] = False
|
|
974
|
+
result["verify"]["hint"] = (
|
|
975
|
+
"Edits kept: a failed verify is a verdict, not a rollback. "
|
|
976
|
+
"Pass strict_verify=true to restore the files on failure."
|
|
977
|
+
)
|
|
978
|
+
return
|
|
862
979
|
_restore_backups()
|
|
863
980
|
rolled_back = True
|
|
864
981
|
result["rolled_back"] = True
|
package/src/bench/driver.py
CHANGED
|
@@ -40,18 +40,35 @@ def resolve_api_key() -> str:
|
|
|
40
40
|
return ""
|
|
41
41
|
|
|
42
42
|
|
|
43
|
+
def _usage_snapshot(payload: Optional[Dict[str, Any]]) -> Dict[str, int]:
|
|
44
|
+
"""Normalizes one provider `usage` payload (reasoning tokens included
|
|
45
|
+
when the provider reports them under completion_tokens_details)."""
|
|
46
|
+
payload = payload or {}
|
|
47
|
+
details = payload.get("completion_tokens_details")
|
|
48
|
+
reasoning = int(details.get("reasoning_tokens") or 0) if isinstance(details, dict) else 0
|
|
49
|
+
return {
|
|
50
|
+
"input_tokens": int(payload.get("prompt_tokens") or 0),
|
|
51
|
+
"cache_hit_tokens": int(payload.get("prompt_cache_hit_tokens") or 0),
|
|
52
|
+
"output_tokens": int(payload.get("completion_tokens") or 0),
|
|
53
|
+
"reasoning_tokens": reasoning,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
43
57
|
@dataclass
|
|
44
58
|
class Usage:
|
|
45
59
|
input_tokens: int = 0
|
|
46
60
|
cache_hit_tokens: int = 0
|
|
47
61
|
output_tokens: int = 0
|
|
62
|
+
reasoning_tokens: int = 0
|
|
48
63
|
calls: int = 0
|
|
49
64
|
|
|
50
65
|
def add(self, payload: Dict[str, Any]) -> None:
|
|
66
|
+
snap = _usage_snapshot(payload)
|
|
51
67
|
self.calls += 1
|
|
52
|
-
self.input_tokens +=
|
|
53
|
-
self.cache_hit_tokens +=
|
|
54
|
-
self.output_tokens +=
|
|
68
|
+
self.input_tokens += snap["input_tokens"]
|
|
69
|
+
self.cache_hit_tokens += snap["cache_hit_tokens"]
|
|
70
|
+
self.output_tokens += snap["output_tokens"]
|
|
71
|
+
self.reasoning_tokens += snap["reasoning_tokens"]
|
|
55
72
|
|
|
56
73
|
@property
|
|
57
74
|
def cache_miss_tokens(self) -> int:
|
|
@@ -73,6 +90,7 @@ class Usage:
|
|
|
73
90
|
"cache_hit_tokens": self.cache_hit_tokens,
|
|
74
91
|
"cache_miss_tokens": self.cache_miss_tokens,
|
|
75
92
|
"output_tokens": self.output_tokens,
|
|
93
|
+
"reasoning_tokens": self.reasoning_tokens,
|
|
76
94
|
"usd": self.usd(model),
|
|
77
95
|
}
|
|
78
96
|
|
|
@@ -99,6 +117,10 @@ class DeepSeekClient:
|
|
|
99
117
|
self.base_url = (base_url or os.environ.get("DEEPSEEK_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
100
118
|
self.timeout = timeout
|
|
101
119
|
self.retries = max(1, int(retries))
|
|
120
|
+
# A/B knob: hold the reasoning budget constant across arms. Providers
|
|
121
|
+
# that do not understand reasoning_effort ignore it; the artifact records
|
|
122
|
+
# which value was requested so a run is never ambiguous.
|
|
123
|
+
self.reasoning_effort = (os.environ.get("TOKENSAFE_BENCH_REASONING_EFFORT") or "").strip()
|
|
102
124
|
self.api_key = resolve_api_key()
|
|
103
125
|
if not self.api_key:
|
|
104
126
|
raise RuntimeError(
|
|
@@ -111,16 +133,31 @@ class DeepSeekClient:
|
|
|
111
133
|
# 5s, 15s, 30s: a paid matrix must survive a flaky read, not restart.
|
|
112
134
|
return min(30.0, 5.0 * (3 ** (attempt - 1)))
|
|
113
135
|
|
|
114
|
-
def
|
|
136
|
+
def build_body(
|
|
137
|
+
self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None
|
|
138
|
+
) -> Dict[str, Any]:
|
|
139
|
+
"""Request body shared by chat() and tests, so effort/max_tokens knobs
|
|
140
|
+
are verifiable without a network call."""
|
|
115
141
|
body: Dict[str, Any] = {
|
|
116
142
|
"model": self.model,
|
|
117
143
|
"messages": messages,
|
|
118
144
|
"temperature": self.temperature,
|
|
119
145
|
}
|
|
146
|
+
if self.reasoning_effort:
|
|
147
|
+
body["reasoning_effort"] = self.reasoning_effort
|
|
148
|
+
max_tokens = os.environ.get("TOKENSAFE_BENCH_MAX_TOKENS", "").strip()
|
|
149
|
+
if max_tokens:
|
|
150
|
+
try:
|
|
151
|
+
body["max_tokens"] = int(max_tokens)
|
|
152
|
+
except ValueError:
|
|
153
|
+
pass
|
|
120
154
|
if tools:
|
|
121
155
|
body["tools"] = tools
|
|
122
156
|
body["tool_choice"] = "auto"
|
|
123
|
-
|
|
157
|
+
return body
|
|
158
|
+
|
|
159
|
+
def chat(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
|
160
|
+
data = json.dumps(self.build_body(messages, tools)).encode()
|
|
124
161
|
last_error = ""
|
|
125
162
|
for attempt in range(1, self.retries + 1):
|
|
126
163
|
req = urllib.request.Request(
|
|
@@ -192,6 +229,7 @@ class StepRecord:
|
|
|
192
229
|
tool_args: List[str] = field(default_factory=list)
|
|
193
230
|
error_codes: List[Optional[str]] = field(default_factory=list)
|
|
194
231
|
duration_ms: float = 0.0
|
|
232
|
+
usage: Dict[str, int] = field(default_factory=dict)
|
|
195
233
|
oracle_passed: Optional[int] = None
|
|
196
234
|
oracle_failed: List[str] = field(default_factory=list)
|
|
197
235
|
note: str = ""
|
|
@@ -220,13 +258,20 @@ def run_agent(
|
|
|
220
258
|
stop_reason = "step_limit"
|
|
221
259
|
|
|
222
260
|
for index in range(1, max_steps + 1):
|
|
261
|
+
started = time.perf_counter()
|
|
223
262
|
message, raw_usage = client.chat(messages, tools)
|
|
263
|
+
elapsed_ms = (time.perf_counter() - started) * 1000.0
|
|
224
264
|
usage.add(raw_usage)
|
|
225
265
|
|
|
226
266
|
calls = message.get("tool_calls") or []
|
|
227
267
|
messages.append(message)
|
|
228
268
|
|
|
229
|
-
record = StepRecord(
|
|
269
|
+
record = StepRecord(
|
|
270
|
+
index=index,
|
|
271
|
+
tool_calls=[c["function"]["name"] for c in calls],
|
|
272
|
+
duration_ms=round(elapsed_ms, 1),
|
|
273
|
+
usage=_usage_snapshot(raw_usage),
|
|
274
|
+
)
|
|
230
275
|
if not calls:
|
|
231
276
|
stop_reason = "agent_finished"
|
|
232
277
|
steps.append(record)
|
|
@@ -277,6 +322,7 @@ def run_agent(
|
|
|
277
322
|
return {
|
|
278
323
|
"model": client.model,
|
|
279
324
|
"temperature": client.temperature,
|
|
325
|
+
"reasoning_effort": getattr(client, "reasoning_effort", ""),
|
|
280
326
|
"price_snapshot": PRICE_SNAPSHOT,
|
|
281
327
|
"prices_usd_per_mtok": PRICES.get(client.model),
|
|
282
328
|
"stop_reason": stop_reason,
|
|
@@ -290,6 +336,8 @@ def run_agent(
|
|
|
290
336
|
"result_chars": s.result_chars,
|
|
291
337
|
"tool_args": s.tool_args,
|
|
292
338
|
"error_codes": s.error_codes,
|
|
339
|
+
"duration_ms": s.duration_ms,
|
|
340
|
+
"usage": s.usage,
|
|
293
341
|
"oracle_passed": s.oracle_passed,
|
|
294
342
|
"oracle_failed": s.oracle_failed,
|
|
295
343
|
"note": s.note,
|