tokensafe 4.4.9 → 4.5.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/hooks/session_start.py +20 -9
- package/kimi.plugin.json +1 -1
- package/mcp_config.json +18 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +5 -2
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +10 -0
- package/src/batch_editor.py +352 -0
- package/src/batch_search.py +408 -0
- package/src/cli.py +51 -0
- package/src/graph_engine.py +202 -44
- package/src/mcp_proxy.py +13 -7
- package/src/mcp_server.py +301 -8
- package/src/oumv_gateway.py +81 -7
- package/src/snapshot.py +249 -0
- package/src/syntax_guard.py +84 -0
- package/src/telemetry_sync.py +1 -1
- package/src/transcript_analyzer.py +281 -0
- package/src/version_checker.py +1 -1
package/hooks/session_start.py
CHANGED
|
@@ -116,8 +116,27 @@ def main():
|
|
|
116
116
|
except Exception:
|
|
117
117
|
pass
|
|
118
118
|
|
|
119
|
+
system_sections = [directives]
|
|
120
|
+
|
|
121
|
+
try:
|
|
122
|
+
from src.mistakes import MistakesLedger
|
|
123
|
+
mistake_guard = MistakesLedger.get_guard_prompt(project_root=workspace_root)
|
|
124
|
+
if mistake_guard:
|
|
125
|
+
system_sections.append(mistake_guard)
|
|
126
|
+
except Exception:
|
|
127
|
+
pass
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
if workspace_paths:
|
|
131
|
+
from src.snapshot import build_workspace_snapshot
|
|
132
|
+
snapshot = build_workspace_snapshot(workspace_root, max_bytes=1400)
|
|
133
|
+
if snapshot:
|
|
134
|
+
system_sections.append(snapshot)
|
|
135
|
+
except Exception:
|
|
136
|
+
pass
|
|
137
|
+
|
|
119
138
|
inject_steps = [
|
|
120
|
-
{"systemMessage": {"systemMessage":
|
|
139
|
+
{"systemMessage": {"systemMessage": "\n\n".join(system_sections), "metadata": {}}}
|
|
121
140
|
]
|
|
122
141
|
|
|
123
142
|
try:
|
|
@@ -150,14 +169,6 @@ def main():
|
|
|
150
169
|
except Exception:
|
|
151
170
|
pass
|
|
152
171
|
|
|
153
|
-
try:
|
|
154
|
-
from src.mistakes import MistakesLedger
|
|
155
|
-
mistake_guard = MistakesLedger.get_guard_prompt(project_root=workspace_root)
|
|
156
|
-
if mistake_guard:
|
|
157
|
-
inject_steps.append({"systemMessage": {"systemMessage": mistake_guard, "metadata": {}}})
|
|
158
|
-
except Exception:
|
|
159
|
-
pass
|
|
160
|
-
|
|
161
172
|
print(json.dumps({"injectSteps": inject_steps}))
|
|
162
173
|
|
|
163
174
|
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.5.0",
|
|
4
4
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
5
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "MIT",
|
package/mcp_config.json
CHANGED
|
@@ -5,7 +5,24 @@
|
|
|
5
5
|
"args": [
|
|
6
6
|
"-c",
|
|
7
7
|
"exec \"${TOKENSAFE_PYTHON:-python3}\" \"$PLUGIN_ROOT/src/mcp_server.py\""
|
|
8
|
-
]
|
|
8
|
+
],
|
|
9
|
+
"tools": {
|
|
10
|
+
"apply_edits": {
|
|
11
|
+
"eager": true
|
|
12
|
+
},
|
|
13
|
+
"batch_search": {
|
|
14
|
+
"eager": true
|
|
15
|
+
},
|
|
16
|
+
"scoped_search": {
|
|
17
|
+
"eager": true
|
|
18
|
+
},
|
|
19
|
+
"smart_read_file": {
|
|
20
|
+
"eager": true
|
|
21
|
+
},
|
|
22
|
+
"get_architecture_graph": {
|
|
23
|
+
"eager": true
|
|
24
|
+
}
|
|
25
|
+
}
|
|
9
26
|
}
|
|
10
27
|
}
|
|
11
28
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.5.0",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.5.0",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"logo": "assets/logo.png",
|
|
7
7
|
"developerName": "TokenSafe",
|
package/rules/AGENTS.md
CHANGED
|
@@ -21,14 +21,17 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
21
21
|
|
|
22
22
|
### 2. Zero-Fluff Output Directives (Egress Optimization)
|
|
23
23
|
1. **No Conversational Filler**: Never include courtesy greetings or sign-offs (e.g., "Certainly!", "Sure, I can help", "Let me know if you need anything else").
|
|
24
|
-
2. **Surgical Code Edits & Zero In-Place Stream Editing**: Prefer `
|
|
24
|
+
2. **Surgical Code Edits, Batching & Zero In-Place Stream Editing**: Prefer `apply_edits` for >=2 hunks/files or edit + verify loops (`tokensafe:apply_edits(edits=[...], verify="npm test")`) to replace serial edit turns. For single surgical tweaks, prefer `edit_file` with concise `Target` and `Replacement`. NEVER run terminal stream editors (`sed -i`, `perl -i`, `awk -i`) to edit or delete source code — blind numeric ranges cause line-drift and silent code loss (hard-blocked by TokenSafe Guard). NEVER suppress errors (`2>/dev/null`) on file modifications.
|
|
25
25
|
3. **Diff-Centric Responses**: Never reprint entire unmodified files or long boilerplate blocks. Reference file lines instead (e.g., `wallet.ts#L42-L50`).
|
|
26
26
|
4. **Dense Formatting**: Use compact bullet points and direct technical prose.
|
|
27
27
|
5. **Repeat Read Deduplication**: Never re-read unchanged files or symbols in the same session. Reuse the skeleton or pointer reference (`// [TokenSafe: Pointer Hit ...]`) returned earlier; only pass `force_full=true` if your context was compacted or you are a fresh subagent.
|
|
28
28
|
6. **Compact Test Output Execution**: Run unit tests with concise flags or via `tokensafe tests [cmd]` so passing test runs return a 1-line summary (`PASS: ...`) rather than flooding `Messages` history with hundreds of verbose log lines. Full output is preserved only on failure.
|
|
29
|
+
7. **Multimodal Image Isolation (Prompt Cache Protection)**: Loading `.png`/`.jpg`/`.webp` images or screenshots into a long (>150k-token) coding conversation triggers KV-cache invalidation and a 3-7x TTFT cliff (40-97s/turn). ALWAYS delegate visual inspection of any screenshot or image to a subagent that returns a concise text-only list of findings (selectors, coordinates, values, error text); NEVER load raw images into the main coding session.
|
|
30
|
+
8. **Startup Snapshot Utilization**: On turn 1 of any session, check the injected `[TokenSafe Workspace Snapshot]` (git branch, modified tree, last 3 commits, 2-level layout, detected scripts) before running exploratory `ls`, `git status`, or reading project scripts.
|
|
31
|
+
9. **Zero-Spill 8.8 KB Cap & Reversible Stash**: All TokenSafe MCP outputs are hard-capped at <= 8.8 KB (UTF-8) with `[TokenSafe folded: #hash ...]` anchors to prevent Antigravity `output.txt` disk spills. Call `tokensafe:expand_ref(hash)` if full raw content is needed.
|
|
29
32
|
|
|
30
33
|
### 3. Architecture & Code Navigation Directives (Graph-Guided)
|
|
31
|
-
1. **Zero Raw Terminal Grep/Find (Blocked & Replaced by `scoped_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard. To search for text, symbols, or functions across unknown files,
|
|
34
|
+
1. **Zero Raw Terminal Grep/Find (Blocked & Replaced by `scoped_search` / `batch_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard. To search for text, symbols, or functions across unknown files, call `tokensafe:scoped_search(query, path=".", scope="code")`. When running >=2 queries (or combining code search with git checks), ALWAYS call `tokensafe:batch_search(queries=[...])` to execute up to 20 queries concurrently in 1 call (<70ms local) without paying per-command remote safety check overhead.
|
|
32
35
|
2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` (relative e.g. `"src/service.ts"` or absolute) and `symbol`. By default (`dep_mode="signature"`), it preserves the full executable target and compact 1-line 1-hop dependency signatures while folding inert code (-95%+ tokens). Pass `dep_mode="full"` only when dependency bodies are needed, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview). Lockfiles (`package-lock.json`, `Cargo.lock`) and tabular data (`.csv`, `.tsv`, `.sql`, `.har`) auto-reduce to compact schemas with reversible hash anchors.
|
|
33
36
|
3. **Reversible Hash Stashing (`expand_ref`)**: Whenever TokenSafe folds a long command output, test log, file, or MCP payload, it tags it with an 8-character hash `[TokenSafe folded: #a1b2c3d4 ...]`. If full raw content is ever needed, ALWAYS call `tokensafe:expand_ref(hash="a1b2c3d4")` or run `tokensafe expand-ref a1b2c3d4` to retrieve the exact original bytes without re-running.
|
|
34
37
|
4. **Web & Documentation Reading (`read_web_page`)**: To read web pages, documentation, or API references, ALWAYS call `tokensafe:read_web_page(url)` or run `tokensafe web <url>` instead of raw HTML fetches — it strips scripts, styles, navbars, and cookie banners (-80-95% tokens).
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.
|
|
6
|
+
"version": "4.5.0",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"registryType": "npm",
|
|
24
24
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
25
25
|
"identifier": "tokensafe",
|
|
26
|
-
"version": "4.
|
|
26
|
+
"version": "4.5.0",
|
|
27
27
|
"runtimeHint": "npx",
|
|
28
28
|
"transport": {
|
|
29
29
|
"type": "stdio"
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"registryType": "pypi",
|
|
40
40
|
"registryBaseUrl": "https://pypi.org",
|
|
41
41
|
"identifier": "tokensafe",
|
|
42
|
-
"version": "4.
|
|
42
|
+
"version": "4.5.0",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
|
@@ -66,6 +66,14 @@ folds multi-turn conversation history, guards against secret leaks, and standard
|
|
|
66
66
|
- Run unit tests with concise flags or via `tokensafe wrap '<cmd>'` or `tokensafe tests [cmd]`. Native support for `bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`, `cargo test`, and `go test` collapses passing test suites into a single-line summary (`✓ PASS: ...`) rather than flooding `Messages` history with hundreds of verbose log lines. Full traceback is strictly preserved on failure.
|
|
67
67
|
- Commands like `git push` automatically strip interactive object-counting progress spam (`--no-progress`), and `git commit` is wrapped when pre-commit/husky hooks exist.
|
|
68
68
|
|
|
69
|
+
12. **MULTIMODAL ISOLATION (PROMPT CACHE PROTECTION)**:
|
|
70
|
+
- Loading screenshots or images into a long (>150k-token) coding conversation triggers full KV-cache invalidation and a 3-7x TTFT cliff (40-97s/turn).
|
|
71
|
+
- ALWAYS delegate visual inspection of screenshots/mockups to a subagent that returns a concise text-only summary of findings (selectors, coordinates, values, errors); NEVER load raw images into the main coding session.
|
|
72
|
+
|
|
73
|
+
13. **BATCH EDITS & SEARCH ACCELERATION (`apply_edits` & `batch_search`)**:
|
|
74
|
+
- When editing >=2 hunks/files or running an edit + verify loop, call `tokensafe:apply_edits(edits=[...], verify="npm test")` to consolidate operations into 1 turn instead of serial turns.
|
|
75
|
+
- When running >=2 searches or combining code search with git inspection, call `tokensafe:batch_search(queries=[...])` for concurrent execution in <70ms.
|
|
76
|
+
|
|
69
77
|
---
|
|
70
78
|
|
|
71
79
|
## Core MCP Tools (`tokensafe`)
|
|
@@ -78,6 +86,8 @@ The full tool table with efficiency impact, JSON workflow examples, the Guard ch
|
|
|
78
86
|
|
|
79
87
|
Quick pointers:
|
|
80
88
|
|
|
89
|
+
- Batch Edits + Verify: `tokensafe:apply_edits(edits=[...], best_effort=true, verify="npm test")` — atomic/best-effort multi-file edits + inline test/typecheck in 1 turn.
|
|
90
|
+
- Batch Search: `tokensafe:batch_search(queries=[{pattern, type}])` — up to 20 concurrent text, regex, glob, fuzzy, or read-only git queries in 1 call.
|
|
81
91
|
- Search: `tokensafe:scoped_search(query, path=".", scope="code")` — safe keyword & symbol search, never raw grep.
|
|
82
92
|
- Inspect: `tokensafe:smart_read_file(path, symbol)` — definition + 1-hop deps. Auto-slices lockfiles, CSV/TSV, SQL dumps.
|
|
83
93
|
- External Types: `tokensafe:slice_external_type(package_name, type_name)` — extracts 3rd-party TypeScript definitions from `node_modules` without file crawling (-95% tokens, L1/L2/L3 synced).
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Batch Editor Engine (v3.5.0).
|
|
3
|
+
|
|
4
|
+
Consolidates multi-hunk and multi-file code modifications into a single
|
|
5
|
+
atomic or best-effort operation with an optional inline verification command.
|
|
6
|
+
|
|
7
|
+
Key capabilities:
|
|
8
|
+
- In-memory pre-validation across up to 50 files before touching disk (0 files modified on error).
|
|
9
|
+
- best_effort mode: commits valid files atomically while returning closest-line / drift hints for retries.
|
|
10
|
+
- Secret leak prevention: detects credentials and private key fallbacks before writing.
|
|
11
|
+
- Preservation of CRLF vs LF line endings, UTF-8 encodings, and file permissions.
|
|
12
|
+
- Inline verify command execution (e.g. `npm test`, `pytest`, `cargo test`) with ANSI stripping
|
|
13
|
+
and Head-Tail output folding, cutting unnecessary LLM round-trip turns.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import difflib
|
|
19
|
+
import subprocess
|
|
20
|
+
import time
|
|
21
|
+
from typing import Dict, Any, List, Optional, Tuple
|
|
22
|
+
|
|
23
|
+
from src.secret_redactor import SecretRedactor
|
|
24
|
+
from src.format_parsers.ansi import strip_ansi
|
|
25
|
+
|
|
26
|
+
MAX_BATCH_FILES = 50
|
|
27
|
+
MAX_VERIFY_OUTPUT_CHARS = 4000
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _find_closest_line_hint(target: str, content: str, max_lines_preview: int = 5) -> str:
|
|
31
|
+
"""Finds closest matching snippet in content to provide actionable line-drift retry guidance."""
|
|
32
|
+
target_first = target.splitlines()[0].strip() if target.splitlines() else target.strip()
|
|
33
|
+
if not target_first:
|
|
34
|
+
return "Target string is empty."
|
|
35
|
+
|
|
36
|
+
lines = content.splitlines()
|
|
37
|
+
best_ratio = 0.0
|
|
38
|
+
best_idx = -1
|
|
39
|
+
for idx, line in enumerate(lines):
|
|
40
|
+
ratio = difflib.SequenceMatcher(None, target_first, line.strip()).ratio()
|
|
41
|
+
if ratio > best_ratio:
|
|
42
|
+
best_ratio = ratio
|
|
43
|
+
best_idx = idx
|
|
44
|
+
|
|
45
|
+
if best_idx >= 0 and best_ratio > 0.4:
|
|
46
|
+
start = max(0, best_idx - 2)
|
|
47
|
+
end = min(len(lines), best_idx + 3)
|
|
48
|
+
preview = []
|
|
49
|
+
for i in range(start, end):
|
|
50
|
+
marker = ">> " if i == best_idx else " "
|
|
51
|
+
preview.append(f"{marker}L{i+1}: {lines[i]}")
|
|
52
|
+
return f"Target not matched. Closest match at line {best_idx+1} (similarity {best_ratio:.0%}):\n" + "\n".join(preview)
|
|
53
|
+
return "Target string not found anywhere in file."
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _apply_hunk_to_text(
|
|
57
|
+
content: str,
|
|
58
|
+
target: str,
|
|
59
|
+
replacement: str,
|
|
60
|
+
start_line: Optional[int] = None,
|
|
61
|
+
end_line: Optional[int] = None,
|
|
62
|
+
replace_all: bool = False
|
|
63
|
+
) -> Tuple[Optional[str], Optional[str]]:
|
|
64
|
+
"""Applies a single hunk to text in-memory. Returns (new_text, error_message)."""
|
|
65
|
+
if not target:
|
|
66
|
+
return None, "Target string cannot be empty."
|
|
67
|
+
|
|
68
|
+
lines = content.splitlines(keepends=True)
|
|
69
|
+
newline = "\r\n" if "\r\n" in content else "\n"
|
|
70
|
+
|
|
71
|
+
# Line-bounded search if start_line or end_line is specified
|
|
72
|
+
if start_line is not None or end_line is not None:
|
|
73
|
+
s_idx = max(0, (start_line - 1)) if start_line is not None else 0
|
|
74
|
+
e_idx = min(len(lines), end_line) if end_line is not None else len(lines)
|
|
75
|
+
if s_idx >= len(lines) or s_idx >= e_idx:
|
|
76
|
+
return None, f"Specified line range [{start_line}, {end_line}] is outside file length ({len(lines)} lines)."
|
|
77
|
+
sub_text = "".join(lines[s_idx:e_idx])
|
|
78
|
+
if target not in sub_text:
|
|
79
|
+
hint = _find_closest_line_hint(target, sub_text)
|
|
80
|
+
return None, f"Target not found in lines {s_idx+1}..{e_idx}: {hint}"
|
|
81
|
+
count = sub_text.count(target)
|
|
82
|
+
if count > 1 and not replace_all:
|
|
83
|
+
return None, f"Target occurs {count} times within lines {s_idx+1}..{e_idx}. Specify replace_all=True or narrow the range."
|
|
84
|
+
new_sub = sub_text.replace(target, replacement) if replace_all else sub_text.replace(target, replacement, 1)
|
|
85
|
+
new_lines = lines[:s_idx] + [new_sub] + lines[e_idx:]
|
|
86
|
+
return "".join(new_lines), None
|
|
87
|
+
|
|
88
|
+
if target not in content:
|
|
89
|
+
hint = _find_closest_line_hint(target, content)
|
|
90
|
+
return None, f"Target not found: {hint}"
|
|
91
|
+
|
|
92
|
+
count = content.count(target)
|
|
93
|
+
if count > 1 and not replace_all:
|
|
94
|
+
# Find line numbers of occurrences
|
|
95
|
+
occ_lines = []
|
|
96
|
+
for i, l in enumerate(lines):
|
|
97
|
+
if target in l:
|
|
98
|
+
occ_lines.append(str(i + 1))
|
|
99
|
+
locs = f"lines {', '.join(occ_lines[:5])}" if occ_lines else "multiple locations"
|
|
100
|
+
return None, f"Target occurs {count} times (near {locs}). Specify replace_all=True or pass start_line/end_line."
|
|
101
|
+
|
|
102
|
+
new_content = content.replace(target, replacement) if replace_all else content.replace(target, replacement, 1)
|
|
103
|
+
return new_content, None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def execute_batch_edits(
|
|
107
|
+
edits: List[Dict[str, Any]],
|
|
108
|
+
best_effort: bool = False,
|
|
109
|
+
dry_run: bool = False,
|
|
110
|
+
verify: Optional[str] = None,
|
|
111
|
+
verify_timeout_sec: int = 30,
|
|
112
|
+
cwd: Optional[str] = None
|
|
113
|
+
) -> Dict[str, Any]:
|
|
114
|
+
"""
|
|
115
|
+
Applies multi-file, multi-hunk edits in memory, writes atomically or best-effort,
|
|
116
|
+
and optionally executes an inline verify command.
|
|
117
|
+
"""
|
|
118
|
+
if not isinstance(edits, list) or not edits:
|
|
119
|
+
return {
|
|
120
|
+
"success": False,
|
|
121
|
+
"error": "Edits list must be a non-empty array of file edit objects.",
|
|
122
|
+
"applied_files": [],
|
|
123
|
+
"failed_files": []
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if len(edits) > MAX_BATCH_FILES:
|
|
127
|
+
return {
|
|
128
|
+
"success": False,
|
|
129
|
+
"error": f"Batch edits exceeds maximum of {MAX_BATCH_FILES} files per call (got {len(edits)}).",
|
|
130
|
+
"applied_files": [],
|
|
131
|
+
"failed_files": []
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
base_dir = os.path.abspath(cwd or os.getcwd())
|
|
135
|
+
|
|
136
|
+
# Pre-validation & secret check
|
|
137
|
+
prepared_files: Dict[str, Dict[str, Any]] = {}
|
|
138
|
+
failed_files: List[Dict[str, Any]] = []
|
|
139
|
+
|
|
140
|
+
for item in edits:
|
|
141
|
+
if not isinstance(item, dict):
|
|
142
|
+
failed_files.append({"path": "unknown", "error": f"Invalid edit entry: expected object, got {type(item).__name__}"})
|
|
143
|
+
continue
|
|
144
|
+
|
|
145
|
+
rel_path = str(item.get("path") or "").strip()
|
|
146
|
+
if not rel_path:
|
|
147
|
+
failed_files.append({"path": "", "error": "Missing 'path' parameter in edit entry."})
|
|
148
|
+
continue
|
|
149
|
+
|
|
150
|
+
abs_path = os.path.normpath(os.path.join(base_dir, rel_path))
|
|
151
|
+
|
|
152
|
+
# Check for directory traversal escapes
|
|
153
|
+
if not abs_path.startswith(base_dir) and not os.path.isabs(rel_path):
|
|
154
|
+
failed_files.append({"path": rel_path, "error": "Path traversal outside workspace root is disallowed."})
|
|
155
|
+
continue
|
|
156
|
+
|
|
157
|
+
# File creation vs hunk modification
|
|
158
|
+
create_content = item.get("create")
|
|
159
|
+
overwrite = bool(item.get("overwrite"))
|
|
160
|
+
hunks = item.get("hunks") or []
|
|
161
|
+
|
|
162
|
+
if create_content is not None:
|
|
163
|
+
# Creation mode
|
|
164
|
+
if not isinstance(create_content, str):
|
|
165
|
+
failed_files.append({"path": rel_path, "error": "'create' content must be a string."})
|
|
166
|
+
continue
|
|
167
|
+
|
|
168
|
+
# Secret check on new content
|
|
169
|
+
is_leak, leak_reason = SecretRedactor.check_secret_fallback(create_content, file_path=rel_path)
|
|
170
|
+
if is_leak:
|
|
171
|
+
failed_files.append({"path": rel_path, "error": f"TokenSafe Security Guard blocked edit: {leak_reason}"})
|
|
172
|
+
continue
|
|
173
|
+
|
|
174
|
+
if os.path.exists(abs_path) and not overwrite:
|
|
175
|
+
failed_files.append({"path": rel_path, "error": f"File '{rel_path}' already exists. Set 'overwrite: true' to overwrite."})
|
|
176
|
+
continue
|
|
177
|
+
|
|
178
|
+
prepared_files[abs_path] = {
|
|
179
|
+
"rel_path": rel_path,
|
|
180
|
+
"new_content": create_content,
|
|
181
|
+
"is_create": not os.path.exists(abs_path),
|
|
182
|
+
"hunk_count": 0,
|
|
183
|
+
}
|
|
184
|
+
continue
|
|
185
|
+
|
|
186
|
+
# Hunk edit mode
|
|
187
|
+
if not isinstance(hunks, list) or not hunks:
|
|
188
|
+
failed_files.append({"path": rel_path, "error": "Must specify either 'create' string or non-empty 'hunks' array."})
|
|
189
|
+
continue
|
|
190
|
+
|
|
191
|
+
if not os.path.exists(abs_path):
|
|
192
|
+
failed_files.append({"path": rel_path, "error": f"File '{rel_path}' does not exist on disk."})
|
|
193
|
+
continue
|
|
194
|
+
|
|
195
|
+
try:
|
|
196
|
+
with open(abs_path, "r", encoding="utf-8", errors="replace") as f:
|
|
197
|
+
content = f.read()
|
|
198
|
+
except Exception as e:
|
|
199
|
+
failed_files.append({"path": rel_path, "error": f"Failed to read file: {e}"})
|
|
200
|
+
continue
|
|
201
|
+
|
|
202
|
+
current_text = content
|
|
203
|
+
file_failed = False
|
|
204
|
+
applied_hunk_count = 0
|
|
205
|
+
|
|
206
|
+
for hunk_idx, hunk in enumerate(hunks):
|
|
207
|
+
if not isinstance(hunk, dict):
|
|
208
|
+
failed_files.append({"path": rel_path, "error": f"Hunk #{hunk_idx+1} is not a valid dictionary."})
|
|
209
|
+
file_failed = True
|
|
210
|
+
break
|
|
211
|
+
|
|
212
|
+
target = hunk.get("target")
|
|
213
|
+
replacement = hunk.get("replacement")
|
|
214
|
+
start_line = hunk.get("start_line")
|
|
215
|
+
end_line = hunk.get("end_line")
|
|
216
|
+
replace_all = bool(hunk.get("replace_all"))
|
|
217
|
+
|
|
218
|
+
if target is None or replacement is None:
|
|
219
|
+
failed_files.append({"path": rel_path, "error": f"Hunk #{hunk_idx+1} missing 'target' or 'replacement'."})
|
|
220
|
+
file_failed = True
|
|
221
|
+
break
|
|
222
|
+
|
|
223
|
+
# Secret check on replacement
|
|
224
|
+
is_leak, leak_reason = SecretRedactor.check_secret_fallback(replacement, file_path=rel_path)
|
|
225
|
+
if is_leak:
|
|
226
|
+
failed_files.append({"path": rel_path, "error": f"TokenSafe Security Guard: {leak_reason}"})
|
|
227
|
+
file_failed = True
|
|
228
|
+
break
|
|
229
|
+
|
|
230
|
+
new_text, err = _apply_hunk_to_text(
|
|
231
|
+
current_text,
|
|
232
|
+
target=str(target),
|
|
233
|
+
replacement=str(replacement),
|
|
234
|
+
start_line=int(start_line) if start_line is not None else None,
|
|
235
|
+
end_line=int(end_line) if end_line is not None else None,
|
|
236
|
+
replace_all=replace_all
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
if err is not None:
|
|
240
|
+
failed_files.append({"path": rel_path, "error": f"Hunk #{hunk_idx+1} failed: {err}"})
|
|
241
|
+
file_failed = True
|
|
242
|
+
break
|
|
243
|
+
|
|
244
|
+
current_text = new_text
|
|
245
|
+
applied_hunk_count += 1
|
|
246
|
+
|
|
247
|
+
if not file_failed:
|
|
248
|
+
prepared_files[abs_path] = {
|
|
249
|
+
"rel_path": rel_path,
|
|
250
|
+
"new_content": current_text,
|
|
251
|
+
"is_create": False,
|
|
252
|
+
"hunk_count": applied_hunk_count,
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
# Atomic enforcement: if any file failed and not best_effort, reject all
|
|
256
|
+
if failed_files and not best_effort:
|
|
257
|
+
return {
|
|
258
|
+
"success": False,
|
|
259
|
+
"error": f"Batch edit validation failed on {len(failed_files)} file(s). 0 files modified.",
|
|
260
|
+
"applied_count": 0,
|
|
261
|
+
"applied_files": [],
|
|
262
|
+
"failed_count": len(failed_files),
|
|
263
|
+
"failed_files": failed_files,
|
|
264
|
+
"dry_run": dry_run
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
applied_files_info: List[Dict[str, Any]] = []
|
|
268
|
+
|
|
269
|
+
# Write files to disk if not dry_run
|
|
270
|
+
if not dry_run:
|
|
271
|
+
for abs_p, p_info in prepared_files.items():
|
|
272
|
+
try:
|
|
273
|
+
os.makedirs(os.path.dirname(abs_p), exist_ok=True)
|
|
274
|
+
with open(abs_p, "w", encoding="utf-8", newline="") as f:
|
|
275
|
+
f.write(p_info["new_content"])
|
|
276
|
+
applied_files_info.append({
|
|
277
|
+
"path": p_info["rel_path"],
|
|
278
|
+
"hunks": p_info["hunk_count"],
|
|
279
|
+
"is_create": p_info["is_create"]
|
|
280
|
+
})
|
|
281
|
+
except Exception as e:
|
|
282
|
+
failed_files.append({"path": p_info["rel_path"], "error": f"Disk write failed: {e}"})
|
|
283
|
+
else:
|
|
284
|
+
for abs_p, p_info in prepared_files.items():
|
|
285
|
+
applied_files_info.append({
|
|
286
|
+
"path": p_info["rel_path"],
|
|
287
|
+
"hunks": p_info["hunk_count"],
|
|
288
|
+
"is_create": p_info["is_create"],
|
|
289
|
+
"dry_run": True
|
|
290
|
+
})
|
|
291
|
+
|
|
292
|
+
result: Dict[str, Any] = {
|
|
293
|
+
"success": len(applied_files_info) > 0 and len(failed_files) == 0,
|
|
294
|
+
"applied_count": len(applied_files_info),
|
|
295
|
+
"applied_files": applied_files_info,
|
|
296
|
+
"failed_count": len(failed_files),
|
|
297
|
+
"failed_files": failed_files,
|
|
298
|
+
"dry_run": dry_run
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
# Execute inline verify command if requested and files were modified
|
|
302
|
+
if verify and applied_files_info and not dry_run:
|
|
303
|
+
cmd_str = str(verify).strip()
|
|
304
|
+
t0 = time.time()
|
|
305
|
+
try:
|
|
306
|
+
proc = subprocess.run(
|
|
307
|
+
cmd_str,
|
|
308
|
+
shell=True,
|
|
309
|
+
cwd=base_dir,
|
|
310
|
+
stdout=subprocess.PIPE,
|
|
311
|
+
stderr=subprocess.STDOUT,
|
|
312
|
+
text=True,
|
|
313
|
+
timeout=max(1, min(verify_timeout_sec, 120))
|
|
314
|
+
)
|
|
315
|
+
elapsed = time.time() - t0
|
|
316
|
+
raw_out = strip_ansi(proc.stdout or "")
|
|
317
|
+
if len(raw_out) > MAX_VERIFY_OUTPUT_CHARS:
|
|
318
|
+
lines = raw_out.splitlines()
|
|
319
|
+
head = lines[:20]
|
|
320
|
+
tail = lines[-15:]
|
|
321
|
+
folded_lines = head + [f"... [{len(lines) - 35} lines folded] ..."] + tail
|
|
322
|
+
compact_out = "\n".join(folded_lines)
|
|
323
|
+
else:
|
|
324
|
+
compact_out = raw_out
|
|
325
|
+
|
|
326
|
+
result["verify"] = {
|
|
327
|
+
"command": cmd_str,
|
|
328
|
+
"passed": proc.returncode == 0,
|
|
329
|
+
"exit_code": proc.returncode,
|
|
330
|
+
"duration_seconds": round(elapsed, 2),
|
|
331
|
+
"output": compact_out.strip() or "(no output)"
|
|
332
|
+
}
|
|
333
|
+
if proc.returncode != 0:
|
|
334
|
+
result["success"] = False
|
|
335
|
+
except subprocess.TimeoutExpired:
|
|
336
|
+
result["verify"] = {
|
|
337
|
+
"command": cmd_str,
|
|
338
|
+
"passed": False,
|
|
339
|
+
"exit_code": -1,
|
|
340
|
+
"error": f"Verification command timed out after {verify_timeout_sec}s"
|
|
341
|
+
}
|
|
342
|
+
result["success"] = False
|
|
343
|
+
except Exception as e:
|
|
344
|
+
result["verify"] = {
|
|
345
|
+
"command": cmd_str,
|
|
346
|
+
"passed": False,
|
|
347
|
+
"exit_code": -1,
|
|
348
|
+
"error": f"Failed to execute verify command: {e}"
|
|
349
|
+
}
|
|
350
|
+
result["success"] = False
|
|
351
|
+
|
|
352
|
+
return result
|