frontierharness 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.
@@ -0,0 +1,4 @@
1
+ """Backward compatibility alias for frontierharness."""
2
+
3
+ from frontierharness import *
4
+ from frontierharness import __version__, __author__, __license__
@@ -0,0 +1,83 @@
1
+ """
2
+ frontierharness: The high-speed, zero-dependency core tool execution & safety engine for frontier AI agents.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from .engine import ToolEngine
8
+ from .filesystem import SafeFilesystem
9
+ from .process import SubprocessManager, DockerSandbox
10
+ from .session import SessionManager, SessionEvent, TokenBudget
11
+ from .verifier import VerificationGate, VerificationReport
12
+ from .checkpoint import Checkpoint, CheckpointManager
13
+ from .orchestrator import AdaptiveOrchestrator, SubagentRole, PlanStep, ROLES
14
+ from .interactive import DiffViewer, PlanRenderer, ApprovalGate
15
+ from .types import (
16
+ ToolCall,
17
+ ToolResult,
18
+ FileSpan,
19
+ TaskHandle,
20
+ ExecutionMetrics,
21
+ )
22
+ from .context import (
23
+ strip_ansi,
24
+ truncate_lines,
25
+ truncate_bytes,
26
+ format_observation,
27
+ )
28
+ from .exceptions import (
29
+ HarnessError,
30
+ PathTraversalError,
31
+ FileOperationError,
32
+ TargetNotFoundError,
33
+ AmbiguousTargetError,
34
+ CommandExecutionError,
35
+ CommandTimeoutError,
36
+ )
37
+
38
+ __version__ = "0.1.0"
39
+ __author__ = "AgentHarness Core Team"
40
+ __license__ = "MIT"
41
+
42
+ __all__ = [
43
+ # Core Engine
44
+ "ToolEngine",
45
+ "SafeFilesystem",
46
+ "SubprocessManager",
47
+ "DockerSandbox",
48
+ # Frontier Cognitive & Orchestration
49
+ "AdaptiveOrchestrator",
50
+ "SubagentRole",
51
+ "PlanStep",
52
+ "ROLES",
53
+ "SessionManager",
54
+ "SessionEvent",
55
+ "TokenBudget",
56
+ "Checkpoint",
57
+ "CheckpointManager",
58
+ "VerificationGate",
59
+ "VerificationReport",
60
+ # Interactive UI & Diff Gates
61
+ "DiffViewer",
62
+ "PlanRenderer",
63
+ "ApprovalGate",
64
+ # Types & Telemetry
65
+ "ToolCall",
66
+ "ToolResult",
67
+ "FileSpan",
68
+ "TaskHandle",
69
+ "ExecutionMetrics",
70
+ # Context Protection
71
+ "strip_ansi",
72
+ "truncate_lines",
73
+ "truncate_bytes",
74
+ "format_observation",
75
+ # Exceptions
76
+ "HarnessError",
77
+ "PathTraversalError",
78
+ "FileOperationError",
79
+ "TargetNotFoundError",
80
+ "AmbiguousTargetError",
81
+ "CommandExecutionError",
82
+ "CommandTimeoutError",
83
+ ]
@@ -0,0 +1,4 @@
1
+ from agentharness.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,169 @@
1
+ """Time-travel checkpointing, workspace state snapshotting, and rewind engine."""
2
+
3
+ from __future__ import annotations
4
+ import os
5
+ import shutil
6
+ import time
7
+ import uuid
8
+ import json
9
+ from pathlib import Path
10
+ from dataclasses import dataclass, field, asdict
11
+ from typing import Dict, List, Optional, Any, Union
12
+
13
+ from .exceptions import HarnessError
14
+
15
+
16
+ @dataclass
17
+ class Checkpoint:
18
+ """Snapshot representing a discrete workspace and session state."""
19
+ checkpoint_id: str
20
+ label: str
21
+ timestamp: float = field(default_factory=time.time)
22
+ file_snapshots: Dict[str, str] = field(default_factory=dict) # path -> original content
23
+ created_files: List[str] = field(default_factory=list) # files created after checkpoint
24
+ session_event_index: int = 0 # index in SessionManager
25
+
26
+ def to_dict(self) -> Dict[str, Any]:
27
+ return {
28
+ "checkpoint_id": self.checkpoint_id,
29
+ "label": self.label,
30
+ "timestamp": self.timestamp,
31
+ "file_count": len(self.file_snapshots),
32
+ "created_count": len(self.created_files),
33
+ "session_event_index": self.session_event_index,
34
+ }
35
+
36
+
37
+ class CheckpointManager:
38
+ """
39
+ Manages pre-mutation file snapshots, state rollbacks, and session memory rewinding.
40
+
41
+ Enables instant undo of failed or unwanted edits, resetting files to their exact
42
+ pre-mutation states and cleaning up newly created files.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ storage_dir: Optional[Union[str, Path]] = None,
48
+ session_id: Optional[str] = None,
49
+ ):
50
+ self.session_id = session_id or f"sess_{uuid.uuid4().hex[:8]}"
51
+ base = Path(storage_dir) if storage_dir else Path.cwd() / ".harness" / "checkpoints"
52
+ self.storage_dir = base / self.session_id
53
+ self._checkpoints: List[Checkpoint] = []
54
+ self._active_checkpoint: Optional[Checkpoint] = None
55
+ self._ensure_storage()
56
+
57
+ def _ensure_storage(self) -> None:
58
+ self.storage_dir.mkdir(parents=True, exist_ok=True)
59
+
60
+ def create_checkpoint(self, label: str, session_event_index: int = 0) -> Checkpoint:
61
+ """Create a new state checkpoint before executing an agent step."""
62
+ cid = f"cp_{len(self._checkpoints) + 1:03d}_{uuid.uuid4().hex[:6]}"
63
+ cp = Checkpoint(
64
+ checkpoint_id=cid,
65
+ label=label,
66
+ timestamp=time.time(),
67
+ session_event_index=session_event_index,
68
+ )
69
+ self._checkpoints.append(cp)
70
+ self._active_checkpoint = cp
71
+ return cp
72
+
73
+ def record_pre_mutation(self, file_path: Union[str, Path]) -> None:
74
+ """
75
+ Record the state of a file immediately before it is modified or created.
76
+ If the file exists, saves its current content. If not, marks it as newly created.
77
+ """
78
+ if not self._active_checkpoint:
79
+ self.create_checkpoint("auto_pre_mutation")
80
+
81
+ target = Path(file_path).resolve()
82
+ target_str = str(target)
83
+
84
+ # If already tracked in current checkpoint, keep the original pre-step version
85
+ if target_str in self._active_checkpoint.file_snapshots or target_str in self._active_checkpoint.created_files:
86
+ return
87
+
88
+ if target.exists() and target.is_file():
89
+ try:
90
+ with open(target, "r", encoding="utf-8", errors="replace") as f:
91
+ content = f.read()
92
+ self._active_checkpoint.file_snapshots[target_str] = content
93
+ except OSError as e:
94
+ raise HarnessError(f"Failed to snapshot '{target}' for checkpoint: {e}") from e
95
+ else:
96
+ # File does not exist yet; will be created by this mutation
97
+ self._active_checkpoint.created_files.append(target_str)
98
+
99
+ def revert(self, checkpoint_id: Optional[str] = None) -> Dict[str, Any]:
100
+ """
101
+ Rewind files and created files to the specified checkpoint (or latest if None).
102
+
103
+ Restores modified files to their original byte contents and deletes newly created files.
104
+ """
105
+ if not self._checkpoints:
106
+ return {
107
+ "success": False,
108
+ "error": "No checkpoints available to revert.",
109
+ "reverted_files": [],
110
+ "deleted_files": [],
111
+ }
112
+
113
+ target_cp: Optional[Checkpoint] = None
114
+ target_idx: int = -1
115
+
116
+ if checkpoint_id:
117
+ for idx, cp in enumerate(self._checkpoints):
118
+ if cp.checkpoint_id == checkpoint_id or cp.label == checkpoint_id:
119
+ target_cp = cp
120
+ target_idx = idx
121
+ break
122
+ if not target_cp:
123
+ return {
124
+ "success": False,
125
+ "error": f"Checkpoint '{checkpoint_id}' not found.",
126
+ "reverted_files": [],
127
+ "deleted_files": [],
128
+ }
129
+ else:
130
+ target_cp = self._checkpoints[-1]
131
+ target_idx = len(self._checkpoints) - 1
132
+
133
+ reverted_files: List[str] = []
134
+ deleted_files: List[str] = []
135
+
136
+ # 1. Restore modified files
137
+ for path_str, original_content in target_cp.file_snapshots.items():
138
+ p = Path(path_str)
139
+ p.parent.mkdir(parents=True, exist_ok=True)
140
+ with open(p, "w", encoding="utf-8") as f:
141
+ f.write(original_content)
142
+ reverted_files.append(path_str)
143
+
144
+ # 2. Delete newly created files
145
+ for created_path in target_cp.created_files:
146
+ p = Path(created_path)
147
+ if p.exists() and p.is_file():
148
+ try:
149
+ p.unlink()
150
+ deleted_files.append(created_path)
151
+ except OSError:
152
+ pass
153
+
154
+ # Pop reverted checkpoints
155
+ self._checkpoints = self._checkpoints[:target_idx]
156
+ self._active_checkpoint = self._checkpoints[-1] if self._checkpoints else None
157
+
158
+ return {
159
+ "success": True,
160
+ "checkpoint_id": target_cp.checkpoint_id,
161
+ "label": target_cp.label,
162
+ "reverted_files": reverted_files,
163
+ "deleted_files": deleted_files,
164
+ "session_event_index": target_cp.session_event_index,
165
+ }
166
+
167
+ def list_checkpoints(self) -> List[Dict[str, Any]]:
168
+ """Return list of all registered checkpoints."""
169
+ return [cp.to_dict() for cp in self._checkpoints]
frontierharness/cli.py ADDED
@@ -0,0 +1,138 @@
1
+ """CLI entry point for agentharness."""
2
+
3
+ from __future__ import annotations
4
+ import sys
5
+ import json
6
+ import argparse
7
+ import time
8
+ from pathlib import Path
9
+
10
+ from .engine import ToolEngine
11
+ from .verifier import VerificationGate
12
+ from .session import SessionManager
13
+ from .checkpoint import CheckpointManager
14
+ from .interactive import ApprovalGate, DiffViewer, PlanRenderer
15
+ from . import __version__
16
+
17
+
18
+ def benchmark_suite(iterations: int = 500) -> None:
19
+ """Run an empirical latency benchmark on core filesystem and execution paths."""
20
+ print(f"=== Running frontierharness Empirical Latency Benchmark ({iterations} iterations) ===")
21
+ import tempfile
22
+ with tempfile.TemporaryDirectory() as tmpdir:
23
+ engine = ToolEngine(workspace_roots=[tmpdir])
24
+ test_file = Path(tmpdir) / "benchmark_sample.txt"
25
+
26
+ # Test 1: Write file
27
+ t0 = time.perf_counter()
28
+ for i in range(iterations):
29
+ engine.execute("write_file", {"path": str(test_file), "content": f"hello world {i}", "overwrite": True})
30
+ write_p50 = ((time.perf_counter() - t0) / iterations) * 1000.0
31
+
32
+ # Test 2: Edit file (surgical replacement)
33
+ t0 = time.perf_counter()
34
+ for i in range(iterations):
35
+ engine.execute("edit_file", {"path": str(test_file), "target": f"hello world {i}", "replacement": f"hello world {i+1}"})
36
+ edit_p50 = ((time.perf_counter() - t0) / iterations) * 1000.0
37
+
38
+ # Test 3: Read file slice
39
+ t0 = time.perf_counter()
40
+ for _ in range(iterations):
41
+ engine.execute("read_file", {"path": str(test_file), "start_line": 1, "end_line": 1})
42
+ read_p50 = ((time.perf_counter() - t0) / iterations) * 1000.0
43
+
44
+ print(f"[OK] read_file P50 latency: {read_p50:.3f} ms")
45
+ print(f"[OK] write_file P50 latency: {write_p50:.3f} ms")
46
+ print(f"[OK] edit_file P50 latency: {edit_p50:.3f} ms")
47
+ print("=== Benchmark Finished Successfully ===")
48
+
49
+
50
+ def main() -> None:
51
+ parser = argparse.ArgumentParser(
52
+ prog="frontierharness",
53
+ description="Core Tool Execution & Safety Engine for Frontier AI Agents",
54
+ )
55
+ parser.add_argument("--version", action="version", version=f"frontierharness {__version__}")
56
+ subparsers = parser.add_subparsers(dest="subcommand", help="Subcommand to execute")
57
+
58
+ # Benchmark command
59
+ bench_parser = subparsers.add_parser("benchmark", help="Run harness latency benchmark")
60
+ bench_parser.add_argument("--iterations", "-n", type=int, default=500, help="Number of benchmark iterations")
61
+
62
+ # Run tool command
63
+ run_parser = subparsers.add_parser("run", help="Execute a single tool call directly")
64
+ run_parser.add_argument("tool", type=str, help="Tool name to execute")
65
+ run_parser.add_argument("args", type=str, nargs="?", default="{}", help="JSON dictionary of tool arguments")
66
+ run_parser.add_argument("--workspace", "-w", type=str, default=".", help="Workspace root directory")
67
+ run_parser.add_argument("--interactive", "-i", action="store_true", help="Enable interactive diff viewer and approval gates")
68
+
69
+ # Verify command
70
+ verify_parser = subparsers.add_parser("verify", help="Run verification check on a file")
71
+ verify_parser.add_argument("path", type=str, help="File path to verify")
72
+
73
+ # Undo command
74
+ undo_parser = subparsers.add_parser("undo", help="Revert workspace to previous checkpoint")
75
+ undo_parser.add_argument("--workspace", "-w", type=str, default=".", help="Workspace root directory")
76
+
77
+ # Rewind command
78
+ rewind_parser = subparsers.add_parser("rewind", help="Rewind workspace to specific checkpoint")
79
+ rewind_parser.add_argument("checkpoint_id", type=str, help="Checkpoint ID to rewind to")
80
+ rewind_parser.add_argument("--workspace", "-w", type=str, default=".", help="Workspace root directory")
81
+
82
+ args = parser.parse_args()
83
+
84
+ if args.subcommand == "benchmark":
85
+ benchmark_suite(iterations=args.iterations)
86
+ elif args.subcommand == "verify":
87
+ gate = VerificationGate()
88
+ ok, err = gate.check_syntax(args.path)
89
+ if ok:
90
+ print(f"[PASS] Syntax verification passed for '{args.path}'")
91
+ sys.exit(0)
92
+ else:
93
+ print(f"[FAIL] {err}", file=sys.stderr)
94
+ sys.exit(1)
95
+ elif args.subcommand == "run":
96
+ gate = ApprovalGate(interactive=True) if args.interactive else None
97
+ engine = ToolEngine(workspace_roots=[args.workspace], approval_gate=gate)
98
+ try:
99
+ parsed_args = json.loads(args.args)
100
+ except json.JSONDecodeError as e:
101
+ print(f"Error parsing JSON arguments: {e}", file=sys.stderr)
102
+ sys.exit(1)
103
+
104
+ result = engine.execute(args.tool, parsed_args)
105
+ print(json.dumps(result.to_dict(), indent=2))
106
+ sys.exit(0 if result.success else 1)
107
+ elif args.subcommand == "undo":
108
+ mgr = CheckpointManager(storage_dir=Path(args.workspace) / ".harness" / "checkpoints")
109
+ report = mgr.revert()
110
+ if report.get("success"):
111
+ print(f"[OK] Successfully reverted to checkpoint '{report.get('checkpoint_id')}' ({report.get('label')})")
112
+ for rf in report.get("reverted_files", []):
113
+ print(f" Restored: {rf}")
114
+ for df in report.get("deleted_files", []):
115
+ print(f" Deleted: {df}")
116
+ sys.exit(0)
117
+ else:
118
+ print(f"[FAIL] {report.get('error')}", file=sys.stderr)
119
+ sys.exit(1)
120
+ elif args.subcommand == "rewind":
121
+ mgr = CheckpointManager(storage_dir=Path(args.workspace) / ".harness" / "checkpoints")
122
+ report = mgr.revert(checkpoint_id=args.checkpoint_id)
123
+ if report.get("success"):
124
+ print(f"[OK] Successfully rewound to '{report.get('checkpoint_id')}' ({report.get('label')})")
125
+ for rf in report.get("reverted_files", []):
126
+ print(f" Restored: {rf}")
127
+ for df in report.get("deleted_files", []):
128
+ print(f" Deleted: {df}")
129
+ sys.exit(0)
130
+ else:
131
+ print(f"[FAIL] {report.get('error')}", file=sys.stderr)
132
+ sys.exit(1)
133
+ else:
134
+ parser.print_help()
135
+
136
+
137
+ if __name__ == "__main__":
138
+ main()
@@ -0,0 +1,81 @@
1
+ """Context protection, observation formatting, and ANSI stripping for LLM safety."""
2
+
3
+ from __future__ import annotations
4
+ import re
5
+ from typing import Tuple
6
+
7
+ # Standard regex for ANSI escape sequences
8
+ _ANSI_ESCAPE_PATTERN = re.compile(
9
+ r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])"
10
+ )
11
+
12
+
13
+ def strip_ansi(text: str) -> str:
14
+ """Remove ANSI color codes and terminal control sequences from text."""
15
+ if not text:
16
+ return ""
17
+ return _ANSI_ESCAPE_PATTERN.sub("", text)
18
+
19
+
20
+ def truncate_lines(
21
+ text: str,
22
+ max_lines: int = 400,
23
+ head_lines: int = 100,
24
+ tail_lines: int = 100,
25
+ ) -> Tuple[str, bool]:
26
+ """
27
+ Truncate text preserving the top head_lines and bottom tail_lines.
28
+
29
+ Returns:
30
+ (truncated_text, was_truncated)
31
+ """
32
+ if not text:
33
+ return "", False
34
+
35
+ lines = text.splitlines(keepends=True)
36
+ total_lines = len(lines)
37
+
38
+ if total_lines <= max_lines:
39
+ return text, False
40
+
41
+ head = lines[:head_lines]
42
+ tail = lines[-tail_lines:] if tail_lines > 0 else []
43
+ truncated_count = total_lines - (head_lines + tail_lines)
44
+
45
+ marker = f"\n[... truncated {truncated_count} lines to protect agent context ...]\n"
46
+ result = "".join(head) + marker + "".join(tail)
47
+ return result, True
48
+
49
+
50
+ def truncate_bytes(text: str, max_bytes: int = 65536) -> Tuple[str, bool]:
51
+ """
52
+ Truncate text at max_bytes without splitting multi-byte UTF-8 sequences.
53
+
54
+ Returns:
55
+ (truncated_text, was_truncated)
56
+ """
57
+ if not text:
58
+ return "", False
59
+
60
+ encoded = text.encode("utf-8", errors="replace")
61
+ if len(encoded) <= max_bytes:
62
+ return text, False
63
+
64
+ sliced = encoded[:max_bytes]
65
+ decoded = sliced.decode("utf-8", errors="ignore")
66
+ marker = f"\n[... truncated output exceeding {max_bytes} bytes ...]"
67
+ return decoded + marker, True
68
+
69
+
70
+ def format_observation(
71
+ content: str,
72
+ max_lines: int = 400,
73
+ head_lines: int = 100,
74
+ tail_lines: int = 100,
75
+ max_bytes: int = 65536,
76
+ ) -> str:
77
+ """Sanitize and boundedly truncate tool execution output for LLM consumption."""
78
+ cleaned = strip_ansi(content)
79
+ line_truncated, _ = truncate_lines(cleaned, max_lines=max_lines, head_lines=head_lines, tail_lines=tail_lines)
80
+ byte_truncated, _ = truncate_bytes(line_truncated, max_bytes=max_bytes)
81
+ return byte_truncated