loopcircuit 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,43 @@
1
+ """
2
+ loopcircuit: Enterprise-grade autonomous agent circuit breaker and loop governor.
3
+ """
4
+
5
+ from loopcircuit.circuit import CircuitBreaker
6
+ from loopcircuit.detector import canonical_action_hash, normalize_error_signature
7
+ from loopcircuit.exceptions import (
8
+ BudgetExceededError,
9
+ CircuitTrippedError,
10
+ ErrorVortexError,
11
+ LoopCircuitError,
12
+ MaxStepsExceededError,
13
+ ThrashDetectedError,
14
+ )
15
+ from loopcircuit.governor import governed
16
+ from loopcircuit.types import (
17
+ ActionRecord,
18
+ CircuitMetrics,
19
+ CircuitState,
20
+ Intervention,
21
+ ThrashType,
22
+ )
23
+
24
+ __version__ = "0.1.0"
25
+ __author__ = "Vikas Patel"
26
+
27
+ __all__ = [
28
+ "CircuitBreaker",
29
+ "governed",
30
+ "CircuitState",
31
+ "ThrashType",
32
+ "ActionRecord",
33
+ "Intervention",
34
+ "CircuitMetrics",
35
+ "LoopCircuitError",
36
+ "CircuitTrippedError",
37
+ "ThrashDetectedError",
38
+ "BudgetExceededError",
39
+ "MaxStepsExceededError",
40
+ "ErrorVortexError",
41
+ "canonical_action_hash",
42
+ "normalize_error_signature",
43
+ ]
loopcircuit/circuit.py ADDED
@@ -0,0 +1,270 @@
1
+ """Enterprise CircuitBreaker engine for autonomous agent loop governance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any, Dict, List, Optional, Tuple
7
+
8
+ from loopcircuit.detector import ThrashDetector, canonical_action_hash
9
+ from loopcircuit.exceptions import (
10
+ BudgetExceededError,
11
+ CircuitTrippedError,
12
+ ErrorVortexError,
13
+ MaxStepsExceededError,
14
+ ThrashDetectedError,
15
+ )
16
+ from loopcircuit.intervention import generate_recovery_prompt
17
+ from loopcircuit.types import (
18
+ ActionRecord,
19
+ CircuitMetrics,
20
+ CircuitState,
21
+ Intervention,
22
+ ThrashType,
23
+ )
24
+
25
+
26
+ class CircuitBreaker:
27
+ """
28
+ Enterprise-grade, zero-dependency circuit breaker and reliability governor for AI agent loops.
29
+ Protects against infinite loops, oscillating state traps, error cascades, and budget blowouts.
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ max_steps: int = 30,
35
+ max_cost_usd: float = 5.00,
36
+ max_tokens: int = 200_000,
37
+ repetition_threshold: int = 3,
38
+ oscillation_threshold: int = 2,
39
+ max_consecutive_errors: int = 3,
40
+ on_trip: str = "raise", # "raise", "intervene", "warn", "silent"
41
+ window_size: int = 15,
42
+ ) -> None:
43
+ """
44
+ Args:
45
+ max_steps: Maximum allowable agent iterations before tripping (default: 30).
46
+ max_cost_usd: Hard financial spend ceiling in USD (default: $5.00).
47
+ max_tokens: Cumulative token consumption threshold (default: 200,000).
48
+ repetition_threshold: Number of identical consecutive tool calls to trip (default: 3).
49
+ oscillation_threshold: Number of repeated 2-4 step cycles to trip (default: 2).
50
+ max_consecutive_errors: Consecutive identical error signatures to trip (default: 3).
51
+ on_trip: Action policy when breaker trips ("raise", "intervene", "warn", "silent").
52
+ window_size: History depth for cyclic detection.
53
+ """
54
+ self.max_steps = max_steps
55
+ self.max_cost_usd = max_cost_usd
56
+ self.max_tokens = max_tokens
57
+ self.on_trip = on_trip
58
+
59
+ self.detector = ThrashDetector(
60
+ repetition_threshold=repetition_threshold,
61
+ oscillation_threshold=oscillation_threshold,
62
+ max_consecutive_errors=max_consecutive_errors,
63
+ window_size=window_size,
64
+ )
65
+
66
+ self._state = CircuitState.CLOSED
67
+ self._step_counter = 0
68
+ self._total_cost_usd = 0.0
69
+ self._total_tokens = 0
70
+ self._thrash_events_count = 0
71
+ self._interventions_count = 0
72
+ self._last_intervention: Optional[Intervention] = None
73
+ self._history: List[ActionRecord] = []
74
+ self._violations: List[Dict[str, Any]] = []
75
+
76
+ @property
77
+ def state(self) -> CircuitState:
78
+ return self._state
79
+
80
+ @property
81
+ def is_healthy(self) -> bool:
82
+ return self._state in (CircuitState.CLOSED, CircuitState.HALF_OPEN)
83
+
84
+ @property
85
+ def is_tripped(self) -> bool:
86
+ return self._state == CircuitState.OPEN
87
+
88
+ def record(
89
+ self,
90
+ tool_name: str,
91
+ arguments: Optional[Dict[str, Any]] = None,
92
+ result: Any = None,
93
+ error: Optional[str] = None,
94
+ cost_usd: float = 0.0,
95
+ tokens_used: int = 0,
96
+ ) -> Intervention:
97
+ """
98
+ Records an agent action step, updates financial and step telemetry, and evaluates
99
+ cycle and loop health. Returns an Intervention indicating whether the agent should halt
100
+ or receive a corrective prompt.
101
+
102
+ Args:
103
+ tool_name: Name of the invoked tool or action.
104
+ arguments: Tool parameters dictionary.
105
+ result: Return value or observation from the action.
106
+ error: Error message string if the action threw an exception.
107
+ cost_usd: Financial cost incurred by this step (e.g. LLM API cost).
108
+ tokens_used: Tokens consumed by this step.
109
+
110
+ Returns:
111
+ Intervention decision with status, thrash type, and recovery prompt.
112
+ """
113
+ self._step_counter += 1
114
+ self._total_cost_usd += max(0.0, cost_usd)
115
+ self._total_tokens += max(0, tokens_used)
116
+ now = time.time()
117
+
118
+ args = arguments or {}
119
+ a_hash = canonical_action_hash(tool_name, args)
120
+
121
+ record = ActionRecord(
122
+ step_index=self._step_counter,
123
+ tool_name=tool_name,
124
+ arguments=args,
125
+ result=result,
126
+ error=error,
127
+ cost_usd=cost_usd,
128
+ tokens_used=tokens_used,
129
+ timestamp=now,
130
+ action_hash=a_hash,
131
+ )
132
+
133
+ self._history.append(record)
134
+ self.detector.record_action(record)
135
+
136
+ # 1. Budget Checks
137
+ if self._total_cost_usd > self.max_cost_usd:
138
+ return self._handle_trip(
139
+ ThrashType.BUDGET_EXCEEDED,
140
+ f"Financial budget exceeded: ${self._total_cost_usd:.4f} > ${self.max_cost_usd:.4f}",
141
+ {"cost_usd": self._total_cost_usd, "max_cost_usd": self.max_cost_usd},
142
+ BudgetExceededError,
143
+ )
144
+
145
+ if self._total_tokens > self.max_tokens:
146
+ return self._handle_trip(
147
+ ThrashType.BUDGET_EXCEEDED,
148
+ f"Token budget exceeded: {self._total_tokens} > {self.max_tokens} tokens",
149
+ {"tokens": self._total_tokens, "max_tokens": self.max_tokens},
150
+ BudgetExceededError,
151
+ )
152
+
153
+ # 2. Step Limit Check
154
+ if self._step_counter > self.max_steps:
155
+ return self._handle_trip(
156
+ ThrashType.STEP_LIMIT_EXCEEDED,
157
+ f"Execution step limit exceeded: {self._step_counter} > {self.max_steps} steps",
158
+ {"steps": self._step_counter, "max_steps": self.max_steps},
159
+ MaxStepsExceededError,
160
+ )
161
+
162
+ # 3. Thrash & Loop Checks
163
+ has_thrashed, thrash_type, reason, details = self.detector.detect_thrash()
164
+ if has_thrashed and thrash_type:
165
+ exc_class = ErrorVortexError if thrash_type == ThrashType.ERROR_VORTEX else ThrashDetectedError
166
+ return self._handle_trip(thrash_type, reason, details, exc_class)
167
+
168
+ # Healthy continuation
169
+ self._state = CircuitState.CLOSED
170
+ return Intervention(should_trip=False, is_warning=False)
171
+
172
+ def _handle_trip(
173
+ self,
174
+ thrash_type: ThrashType,
175
+ reason: str,
176
+ details: Dict[str, Any],
177
+ exc_class: type[CircuitTrippedError],
178
+ ) -> Intervention:
179
+ self._thrash_events_count += 1
180
+ prompt = generate_recovery_prompt(thrash_type, details)
181
+
182
+ violation = {
183
+ "step": self._step_counter,
184
+ "thrash_type": thrash_type.value,
185
+ "reason": reason,
186
+ "details": details,
187
+ }
188
+ self._violations.append(violation)
189
+
190
+ if self.on_trip == "raise":
191
+ self._state = CircuitState.OPEN
192
+ intervention = Intervention(
193
+ should_trip=True,
194
+ thrash_type=thrash_type,
195
+ reason=reason,
196
+ recovery_prompt=prompt,
197
+ details=details,
198
+ )
199
+ self._last_intervention = intervention
200
+ raise exc_class(
201
+ message=reason,
202
+ reason=thrash_type.value,
203
+ metrics=self.metrics.to_dict(),
204
+ recovery_prompt=prompt,
205
+ )
206
+
207
+ elif self.on_trip == "intervene":
208
+ self._state = CircuitState.RECOVERING
209
+ self._interventions_count += 1
210
+ intervention = Intervention(
211
+ should_trip=False,
212
+ is_warning=True,
213
+ thrash_type=thrash_type,
214
+ reason=reason,
215
+ recovery_prompt=prompt,
216
+ details=details,
217
+ )
218
+ self._last_intervention = intervention
219
+ return intervention
220
+
221
+ elif self.on_trip == "warn":
222
+ self._state = CircuitState.HALF_OPEN
223
+ intervention = Intervention(
224
+ should_trip=False,
225
+ is_warning=True,
226
+ thrash_type=thrash_type,
227
+ reason=reason,
228
+ recovery_prompt=prompt,
229
+ details=details,
230
+ )
231
+ self._last_intervention = intervention
232
+ return intervention
233
+
234
+ else: # silent
235
+ self._state = CircuitState.HALF_OPEN
236
+ return Intervention(should_trip=False)
237
+
238
+ @property
239
+ def metrics(self) -> CircuitMetrics:
240
+ """Returns comprehensive telemetry for the current breaker session."""
241
+ return CircuitMetrics(
242
+ total_steps=self._step_counter,
243
+ total_cost_usd=self._total_cost_usd,
244
+ total_tokens=self._total_tokens,
245
+ thrash_events_count=self._thrash_events_count,
246
+ interventions_count=self._interventions_count,
247
+ state=self._state,
248
+ history_length=len(self._history),
249
+ violations=list(self._violations),
250
+ )
251
+
252
+ def reset(self) -> None:
253
+ """Resets breaker state, history, and counters to fresh initialized state."""
254
+ self._state = CircuitState.CLOSED
255
+ self._step_counter = 0
256
+ self._total_cost_usd = 0.0
257
+ self._total_tokens = 0
258
+ self._thrash_events_count = 0
259
+ self._interventions_count = 0
260
+ self._last_intervention = None
261
+ self._history.clear()
262
+ self._violations.clear()
263
+ self.detector.history.clear()
264
+
265
+ def __enter__(self) -> CircuitBreaker:
266
+ return self
267
+
268
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
269
+ # Pass through exceptions naturally
270
+ return False
loopcircuit/cli.py ADDED
@@ -0,0 +1,127 @@
1
+ """Command-line interface (CLI) and trace auditor for loopcircuit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import List, Optional
10
+
11
+ from loopcircuit.circuit import CircuitBreaker
12
+
13
+
14
+ def audit_trace_file(
15
+ file_path: str,
16
+ max_steps: int = 30,
17
+ max_cost: float = 5.0,
18
+ repetition_thresh: int = 3,
19
+ output_json: bool = False
20
+ ) -> int:
21
+ """Replays an agent execution log (JSONL) through CircuitBreaker to identify thrash events."""
22
+ path = Path(file_path)
23
+ if not path.is_file():
24
+ print(f"Error: Trace file not found: {file_path}", file=sys.stderr)
25
+ return 1
26
+
27
+ breaker = CircuitBreaker(
28
+ max_steps=max_steps,
29
+ max_cost_usd=max_cost,
30
+ repetition_threshold=repetition_thresh,
31
+ on_trip="intervene",
32
+ )
33
+
34
+ events: List[dict] = []
35
+ line_num = 0
36
+
37
+ with path.open(encoding="utf-8") as f:
38
+ for line in f:
39
+ line = line.strip()
40
+ if not line:
41
+ continue
42
+ line_num += 1
43
+ try:
44
+ item = json.loads(line)
45
+ except json.JSONDecodeError:
46
+ continue
47
+
48
+ tool = item.get("tool") or item.get("tool_name") or item.get("action") or "unknown"
49
+ args = item.get("args") or item.get("arguments") or {}
50
+ result = item.get("result") or item.get("observation")
51
+ error = item.get("error")
52
+ cost = float(item.get("cost") or item.get("cost_usd") or 0.0)
53
+ tokens = int(item.get("tokens") or item.get("tokens_used") or 0)
54
+
55
+ intervention = breaker.record(
56
+ tool_name=tool,
57
+ arguments=args,
58
+ result=result,
59
+ error=error,
60
+ cost_usd=cost,
61
+ tokens_used=tokens,
62
+ )
63
+
64
+ if intervention.thrash_type:
65
+ events.append({
66
+ "line": line_num,
67
+ "step": breaker.metrics.total_steps,
68
+ "type": intervention.thrash_type.value,
69
+ "reason": intervention.reason,
70
+ })
71
+
72
+ metrics = breaker.metrics.to_dict()
73
+
74
+ if output_json:
75
+ print(json.dumps({"metrics": metrics, "thrash_events": events}, indent=2))
76
+ else:
77
+ print("=" * 65)
78
+ print("loopcircuit Trace Audit Summary")
79
+ print("=" * 65)
80
+ print(f"Total Steps Replayed: {metrics['total_steps']}")
81
+ print(f"Total Cost Incurred: ${metrics['total_cost_usd']:.4f}")
82
+ print(f"Tokens Consumed: {metrics['total_tokens']}")
83
+ print(f"Thrash Events Caught: {len(events)}")
84
+ print(f"Final Circuit State: {metrics['state'].upper()}")
85
+
86
+ if events:
87
+ print("\n[!] DETECTED FAILURE PATTERNS:")
88
+ for ev in events:
89
+ print(f" - Step {ev['step']} (line {ev['line']}): [{ev['type'].upper()}] {ev['reason']}")
90
+ else:
91
+ print("\n✅ Trace is clean: No repetitive loops, oscillations, or vortex traps found.")
92
+ print("=" * 65)
93
+
94
+ return 0 if not events else 1
95
+
96
+
97
+ def main(argv: Optional[List[str]] = None) -> int:
98
+ parser = argparse.ArgumentParser(
99
+ prog="loopcircuit",
100
+ description="Autonomous agent loop governor, circuit-breaker, and trace auditor."
101
+ )
102
+ subparsers = parser.add_subparsers(dest="command", required=True)
103
+
104
+ # Subcommand: audit
105
+ audit_cmd = subparsers.add_parser("audit", help="Audit an agent JSONL execution trace for loop patterns.")
106
+ audit_cmd.add_argument("file", help="Path to agent execution trace (.jsonl).")
107
+ audit_cmd.add_argument("--max-steps", type=int, default=30, help="Max step budget threshold.")
108
+ audit_cmd.add_argument("--max-cost", type=float, default=5.0, help="Max financial budget threshold.")
109
+ audit_cmd.add_argument("--repeat-limit", type=int, default=3, help="Consecutive repetition threshold.")
110
+ audit_cmd.add_argument("--json", action="store_true", help="Output audit report as formatted JSON.")
111
+
112
+ args = parser.parse_args(argv)
113
+
114
+ if args.command == "audit":
115
+ return audit_trace_file(
116
+ file_path=args.file,
117
+ max_steps=args.max_steps,
118
+ max_cost=args.max_cost,
119
+ repetition_thresh=args.repeat_limit,
120
+ output_json=args.json,
121
+ )
122
+
123
+ return 0
124
+
125
+
126
+ if __name__ == "__main__":
127
+ sys.exit(main())
@@ -0,0 +1,212 @@
1
+ """Algorithmic repetition, cycle oscillation, and error vortex detection engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
9
+ from loopcircuit.types import ActionRecord, ThrashType
10
+
11
+
12
+ def canonical_action_hash(tool_name: str, arguments: Dict[str, Any]) -> str:
13
+ """
14
+ Computes a deterministic, order-independent SHA256 hash for a tool call.
15
+ Sorts dictionary keys recursively to prevent false positives from parameter ordering.
16
+ """
17
+ def _normalize(val: Any) -> Any:
18
+ if isinstance(val, dict):
19
+ return {k: _normalize(v) for k, v in sorted(val.items())}
20
+ elif isinstance(val, (list, tuple)):
21
+ return [_normalize(x) for x in val]
22
+ elif isinstance(val, (int, float, str, bool)) or val is None:
23
+ return val
24
+ return str(val)
25
+
26
+ payload = {
27
+ "tool": tool_name.strip().lower(),
28
+ "args": _normalize(arguments)
29
+ }
30
+ encoded = json.dumps(payload, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode("utf-8")
31
+ return hashlib.sha256(encoded).hexdigest()[:16]
32
+
33
+
34
+ def normalize_error_signature(error: str) -> str:
35
+ """
36
+ Strips transient pointers, line numbers, memory addresses, and timestamps
37
+ to extract the structural root cause of an error.
38
+ """
39
+ if not error:
40
+ return ""
41
+ # Strip memory addresses (0x...)
42
+ s = re.sub(r'0x[0-9a-fA-F]+', '0xADDR', error)
43
+ # Strip line numbers and timestamps
44
+ s = re.sub(r'line \d+', 'line N', s, flags=re.IGNORECASE)
45
+ s = re.sub(r'\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?', 'TIMESTAMP', s)
46
+ # Strip excessive whitespace
47
+ s = re.sub(r'\s+', ' ', s).strip()
48
+ return s[:150]
49
+
50
+
51
+ class ThrashDetector:
52
+ """
53
+ High-performance, sliding-window detector for agent execution loops and stalls.
54
+ Evaluates cycles, error clustering, and stagnation with zero external dependencies.
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ repetition_threshold: int = 3,
60
+ oscillation_threshold: int = 2,
61
+ max_consecutive_errors: int = 3,
62
+ window_size: int = 12
63
+ ) -> None:
64
+ """
65
+ Args:
66
+ repetition_threshold: Number of consecutive identical actions to trip breaker (default: 3).
67
+ oscillation_threshold: Number of repeated multi-step cycles to trip breaker (default: 2).
68
+ max_consecutive_errors: Number of consecutive similar errors before triggering error vortex (default: 3).
69
+ window_size: Maximum sliding window of past steps maintained in memory (default: 12).
70
+ """
71
+ self.repetition_threshold = max(2, repetition_threshold)
72
+ self.oscillation_threshold = max(2, oscillation_threshold)
73
+ self.max_consecutive_errors = max(2, max_consecutive_errors)
74
+ self.window_size = window_size
75
+ self.history: List[ActionRecord] = []
76
+
77
+ def record_action(self, action: ActionRecord) -> None:
78
+ """Appends an immutable action record to sliding history window."""
79
+ self.history.append(action)
80
+ if len(self.history) > self.window_size:
81
+ self.history.pop(0)
82
+
83
+ def detect_thrash(self) -> Tuple[bool, Optional[ThrashType], str, Dict[str, Any]]:
84
+ """
85
+ Scans history window for failure patterns.
86
+ Returns: (has_thrashed: bool, thrash_type: Optional[ThrashType], reason: str, details: dict)
87
+ """
88
+ n = len(self.history)
89
+ if n < 2:
90
+ return False, None, "", {}
91
+
92
+ # 1. Error Vortex Check (Consecutive identical error signatures)
93
+ error_check = self._check_error_vortex()
94
+ if error_check[0]:
95
+ return error_check
96
+
97
+ # 2. Exact Repetition Check (Period = 1)
98
+ rep_check = self._check_exact_repetition()
99
+ if rep_check[0]:
100
+ return rep_check
101
+
102
+ # 3. Multi-Step Cycle Oscillation Check (Period = 2..4)
103
+ osc_check = self._check_cycle_oscillation()
104
+ if osc_check[0]:
105
+ return osc_check
106
+
107
+ # 4. Result Stagnation Check
108
+ stag_check = self._check_result_stagnation()
109
+ if stag_check[0]:
110
+ return stag_check
111
+
112
+ return False, None, "", {}
113
+
114
+ def _check_exact_repetition(self) -> Tuple[bool, Optional[ThrashType], str, Dict[str, Any]]:
115
+ n = len(self.history)
116
+ target_hash = self.history[-1].action_hash
117
+ tool = self.history[-1].tool_name
118
+ repeat_count = 1
119
+
120
+ for i in range(n - 2, -1, -1):
121
+ if self.history[i].action_hash == target_hash:
122
+ repeat_count += 1
123
+ else:
124
+ break
125
+
126
+ if repeat_count >= self.repetition_threshold:
127
+ return (
128
+ True,
129
+ ThrashType.EXACT_REPETITION,
130
+ f"Agent executed tool '{tool}' with identical arguments {repeat_count} times in a row.",
131
+ {"repeat_count": repeat_count, "tool_name": tool, "action_hash": target_hash}
132
+ )
133
+ return False, None, "", {}
134
+
135
+ def _check_cycle_oscillation(self) -> Tuple[bool, Optional[ThrashType], str, Dict[str, Any]]:
136
+ """
137
+ Detects periodic cycles of length 2, 3, or 4 (e.g. A-B-A-B or A-B-C-A-B-C).
138
+ """
139
+ hashes = [rec.action_hash for rec in self.history]
140
+ n = len(hashes)
141
+
142
+ for period in (2, 3, 4):
143
+ required_len = period * self.oscillation_threshold
144
+ if n < required_len:
145
+ continue
146
+
147
+ # Check if last (period * threshold) matches repeated cycle of length `period`
148
+ cycle_candidate = hashes[-period:]
149
+ matches_cycle = True
150
+
151
+ for offset in range(period, required_len, period):
152
+ segment = hashes[-offset - period : -offset]
153
+ if segment != cycle_candidate:
154
+ matches_cycle = False
155
+ break
156
+
157
+ if matches_cycle:
158
+ tools_in_cycle = [rec.tool_name for rec in self.history[-period:]]
159
+ thrash_type = ThrashType.SEMANTIC_OSCILLATION if period == 2 else ThrashType.CYCLIC_WANDERING
160
+ cycle_str = " -> ".join(tools_in_cycle)
161
+ return (
162
+ True,
163
+ thrash_type,
164
+ f"Agent is stuck in an oscillating loop of period {period}: [{cycle_str}] repeated {self.oscillation_threshold} times.",
165
+ {"period": period, "cycle_tools": tools_in_cycle, "repetitions": self.oscillation_threshold}
166
+ )
167
+
168
+ return False, None, "", {}
169
+
170
+ def _check_error_vortex(self) -> Tuple[bool, Optional[ThrashType], str, Dict[str, Any]]:
171
+ """Detects if agent is trapped encountering the same normalized error repeatedly."""
172
+ n = len(self.history)
173
+ latest_error = self.history[-1].error
174
+ if not latest_error:
175
+ return False, None, "", {}
176
+
177
+ latest_sig = normalize_error_signature(latest_error)
178
+ consecutive_errors = 1
179
+
180
+ for i in range(n - 2, -1, -1):
181
+ if self.history[i].error and normalize_error_signature(self.history[i].error) == latest_sig:
182
+ consecutive_errors += 1
183
+ else:
184
+ break
185
+
186
+ if consecutive_errors >= self.max_consecutive_errors:
187
+ tool = self.history[-1].tool_name
188
+ return (
189
+ True,
190
+ ThrashType.ERROR_VORTEX,
191
+ f"Agent trapped in error vortex: tool '{tool}' failed {consecutive_errors} consecutive times with error: '{latest_sig}'.",
192
+ {"consecutive_errors": consecutive_errors, "error_signature": latest_sig, "tool": tool}
193
+ )
194
+
195
+ return False, None, "", {}
196
+
197
+ def _check_result_stagnation(self) -> Tuple[bool, Optional[ThrashType], str, Dict[str, Any]]:
198
+ """Detects when 3+ actions produce completely identical non-empty outputs."""
199
+ if len(self.history) < 3:
200
+ return False, None, "", {}
201
+
202
+ last_3 = self.history[-3:]
203
+ res_strs = [str(r.result)[:200] for r in last_3 if r.result is not None]
204
+ if len(res_strs) == 3 and res_strs[0] == res_strs[1] == res_strs[2] and len(res_strs[0]) > 10:
205
+ return (
206
+ True,
207
+ ThrashType.STAGNANT_PROGRESS,
208
+ "Agent progress is stagnant: consecutive actions produced identical output with zero state delta.",
209
+ {"stagnant_steps": 3}
210
+ )
211
+
212
+ return False, None, "", {}
@@ -0,0 +1,44 @@
1
+ """Custom exception hierarchy for loopcircuit."""
2
+
3
+ from typing import Any, Dict, Optional
4
+
5
+
6
+ class LoopCircuitError(Exception):
7
+ """Base exception for all loopcircuit errors."""
8
+ pass
9
+
10
+
11
+ class CircuitTrippedError(LoopCircuitError):
12
+ """Raised when the agent circuit breaker trips and interrupts execution."""
13
+
14
+ def __init__(
15
+ self,
16
+ message: str,
17
+ reason: str,
18
+ metrics: Optional[Dict[str, Any]] = None,
19
+ recovery_prompt: Optional[str] = None
20
+ ) -> None:
21
+ super().__init__(message)
22
+ self.reason = reason
23
+ self.metrics = metrics or {}
24
+ self.recovery_prompt = recovery_prompt or ""
25
+
26
+
27
+ class ThrashDetectedError(CircuitTrippedError):
28
+ """Raised when repetitive loops or oscillation patterns are identified."""
29
+ pass
30
+
31
+
32
+ class BudgetExceededError(CircuitTrippedError):
33
+ """Raised when cumulative dollar spend or token limits are exceeded."""
34
+ pass
35
+
36
+
37
+ class MaxStepsExceededError(CircuitTrippedError):
38
+ """Raised when the loop exceeds maximum permissible execution steps."""
39
+ pass
40
+
41
+
42
+ class ErrorVortexError(CircuitTrippedError):
43
+ """Raised when an agent gets trapped repeatedly triggering the same error."""
44
+ pass
@@ -0,0 +1,74 @@
1
+ """Production governance decorators and iteration wrappers for agent loops."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import functools
7
+ import inspect
8
+ from typing import Any, Callable, Dict, Optional, Union
9
+
10
+ from loopcircuit.circuit import CircuitBreaker
11
+ from loopcircuit.types import Intervention
12
+
13
+
14
+ def governed(
15
+ max_steps: int = 30,
16
+ max_cost_usd: float = 5.00,
17
+ max_tokens: int = 200_000,
18
+ repetition_threshold: int = 3,
19
+ oscillation_threshold: int = 2,
20
+ max_consecutive_errors: int = 3,
21
+ on_trip: str = "raise",
22
+ breaker: Optional[CircuitBreaker] = None,
23
+ ) -> Callable:
24
+ """
25
+ Decorator that attaches an active CircuitBreaker governor to an agent loop or step executor.
26
+
27
+ If the wrapped function yields or returns tool executions or actions, the governor
28
+ intercepts them and records metrics automatically.
29
+
30
+ Args:
31
+ max_steps: Maximum allowed steps before halting.
32
+ max_cost_usd: Financial ceiling.
33
+ max_tokens: Token consumption threshold.
34
+ repetition_threshold: Consecutive repetition limit.
35
+ oscillation_threshold: Multi-step cycle limit.
36
+ max_consecutive_errors: Consecutively repeated error limit.
37
+ on_trip: Action policy on trip ("raise", "intervene", "warn", "silent").
38
+ breaker: Optional pre-configured CircuitBreaker instance.
39
+ """
40
+ active_breaker = breaker or CircuitBreaker(
41
+ max_steps=max_steps,
42
+ max_cost_usd=max_cost_usd,
43
+ max_tokens=max_tokens,
44
+ repetition_threshold=repetition_threshold,
45
+ oscillation_threshold=oscillation_threshold,
46
+ max_consecutive_errors=max_consecutive_errors,
47
+ on_trip=on_trip,
48
+ )
49
+
50
+ def decorator(fn: Callable) -> Callable:
51
+ # Check if function is async
52
+ if asyncio.iscoroutinefunction(fn):
53
+ @functools.wraps(fn)
54
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
55
+ active_breaker.reset()
56
+ # Inject breaker if the function accepts it as a parameter
57
+ sig = inspect.signature(fn)
58
+ if "breaker" in sig.parameters and "breaker" not in kwargs:
59
+ kwargs["breaker"] = active_breaker
60
+ return await fn(*args, **kwargs)
61
+ async_wrapper.breaker = active_breaker # type: ignore
62
+ return async_wrapper
63
+ else:
64
+ @functools.wraps(fn)
65
+ def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
66
+ active_breaker.reset()
67
+ sig = inspect.signature(fn)
68
+ if "breaker" in sig.parameters and "breaker" not in kwargs:
69
+ kwargs["breaker"] = active_breaker
70
+ return fn(*args, **kwargs)
71
+ sync_wrapper.breaker = active_breaker # type: ignore
72
+ return sync_wrapper
73
+
74
+ return decorator
@@ -0,0 +1,94 @@
1
+ """Context-aware recovery prompt synthesis and pattern-breaking interventions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional
6
+ from loopcircuit.types import ThrashType
7
+
8
+
9
+ def generate_recovery_prompt(thrash_type: ThrashType, details: Dict[str, Any]) -> str:
10
+ """
11
+ Synthesizes an authoritative, structured system intervention prompt designed
12
+ to break frontier LLMs out of cyclic loops, error traps, or oscillation.
13
+ """
14
+ header = "[SYSTEM GOVERNANCE · LOOP INTERVENTION TRIGGERED]"
15
+
16
+ if thrash_type == ThrashType.EXACT_REPETITION:
17
+ tool = details.get("tool_name", "the tool")
18
+ count = details.get("repeat_count", 3)
19
+ return (
20
+ f"{header}\n"
21
+ f"You have called tool '{tool}' with identical parameters {count} times in succession.\n"
22
+ f"ACTION MANDATE:\n"
23
+ f"1. Immediately STOP calling '{tool}' with these parameters.\n"
24
+ f"2. You must either try a completely different tool or strategy, or report the roadblock to the user.\n"
25
+ f"3. Do NOT repeat the previous action."
26
+ )
27
+
28
+ elif thrash_type == ThrashType.SEMANTIC_OSCILLATION:
29
+ cycle_tools = " -> ".join(details.get("cycle_tools", ["Action A", "Action B"]))
30
+ return (
31
+ f"{header}\n"
32
+ f"You are caught in an alternating ping-pong loop: [{cycle_tools}].\n"
33
+ f"ACTION MANDATE:\n"
34
+ f"1. Break the oscillation pattern immediately.\n"
35
+ f"2. Reflect on why the cycle is recurring instead of making progress.\n"
36
+ f"3. Switch to a non-cyclical strategy or ask the user for clarification."
37
+ )
38
+
39
+ elif thrash_type == ThrashType.CYCLIC_WANDERING:
40
+ cycle_tools = " -> ".join(details.get("cycle_tools", ["A", "B", "C"]))
41
+ return (
42
+ f"{header}\n"
43
+ f"You are wandering in a periodic multi-step loop: [{cycle_tools}].\n"
44
+ f"ACTION MANDATE:\n"
45
+ f"1. Halt this cycle. Re-evaluate your primary objective from first principles.\n"
46
+ f"2. Summarize what has failed so far and propose an alternative path."
47
+ )
48
+
49
+ elif thrash_type == ThrashType.ERROR_VORTEX:
50
+ tool = details.get("tool", "the tool")
51
+ err = details.get("error_signature", "unknown failure")
52
+ count = details.get("consecutive_errors", 3)
53
+ return (
54
+ f"{header}\n"
55
+ f"Tool '{tool}' has failed {count} times consecutively with the same error:\n"
56
+ f"'{err}'\n"
57
+ f"ACTION MANDATE:\n"
58
+ f"1. Do NOT retry this exact command or invocation.\n"
59
+ f"2. Diagnose why the error is persistent (e.g. invalid path, wrong syntax, or missing dependency).\n"
60
+ f"3. Pivot to an alternate diagnostic or reporting tool."
61
+ )
62
+
63
+ elif thrash_type == ThrashType.STAGNANT_PROGRESS:
64
+ return (
65
+ f"{header}\n"
66
+ f"Your last several actions produced identical output with zero state delta.\n"
67
+ f"ACTION MANDATE:\n"
68
+ f"1. Re-read the user instructions to ensure you are progressing toward the goal.\n"
69
+ f"2. Change your query or action parameters to produce meaningful forward progress."
70
+ )
71
+
72
+ elif thrash_type == ThrashType.BUDGET_EXCEEDED:
73
+ cost = details.get("cost_usd", 0.0)
74
+ max_cost = details.get("max_cost_usd", 0.0)
75
+ return (
76
+ f"{header}\n"
77
+ f"The allotted execution budget has been reached (${cost:.4f} spent / ${max_cost:.4f} cap).\n"
78
+ f"ACTION MANDATE:\n"
79
+ f"1. Cease all further expensive API and tool invocations immediately.\n"
80
+ f"2. Deliver your best current answer or summary of progress to the user now."
81
+ )
82
+
83
+ elif thrash_type == ThrashType.STEP_LIMIT_EXCEEDED:
84
+ steps = details.get("steps", 0)
85
+ max_steps = details.get("max_steps", 0)
86
+ return (
87
+ f"{header}\n"
88
+ f"Maximum step execution depth reached ({steps} / {max_steps} steps).\n"
89
+ f"ACTION MANDATE:\n"
90
+ f"1. Conclude your execution loop.\n"
91
+ f"2. Synthesize your findings and output your final result."
92
+ )
93
+
94
+ return f"{header}\nExecution loop detected. Please re-evaluate your plan and change strategy."
loopcircuit/py.typed ADDED
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561 typed package
loopcircuit/types.py ADDED
@@ -0,0 +1,105 @@
1
+ """Core enums, data models, and metrics for loopcircuit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import asdict, dataclass, field
7
+ from enum import Enum
8
+ from typing import Any, Dict, List, Optional
9
+
10
+
11
+ class CircuitState(str, Enum):
12
+ """Current state of the agent execution circuit breaker."""
13
+ CLOSED = "closed" # Healthy: normal agent execution
14
+ HALF_OPEN = "half_open" # Warning: probation mode following detected repetition
15
+ OPEN = "open" # Tripped: execution halted to prevent runaway spend/thrash
16
+ RECOVERING = "recovering" # Active: corrective recovery prompt injected into loop
17
+
18
+
19
+ class ThrashType(str, Enum):
20
+ """Categorization of agent loop failure patterns."""
21
+ EXACT_REPETITION = "exact_repetition" # Same tool + arguments executed consecutively
22
+ SEMANTIC_OSCILLATION = "semantic_oscillation" # Alternating between actions (A -> B -> A -> B)
23
+ CYCLIC_WANDERING = "cyclic_wandering" # Periodic loop cycle (e.g. A -> B -> C -> A -> B -> C)
24
+ ERROR_VORTEX = "error_vortex" # Same error pattern encountered repeatedly
25
+ STAGNANT_PROGRESS = "stagnant_progress" # Successive actions producing zero state entropy
26
+ STEP_LIMIT_EXCEEDED = "step_limit_exceeded" # Step execution depth limit reached
27
+ BUDGET_EXCEEDED = "budget_exceeded" # Financial cost or token threshold exceeded
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class ActionRecord:
32
+ """An immutable audit snapshot of a single agent step."""
33
+ step_index: int
34
+ tool_name: str
35
+ arguments: Dict[str, Any]
36
+ result: Any
37
+ error: Optional[str] = None
38
+ cost_usd: float = 0.0
39
+ tokens_used: int = 0
40
+ timestamp: float = 0.0
41
+ action_hash: str = ""
42
+
43
+ def to_dict(self) -> Dict[str, Any]:
44
+ return {
45
+ "step_index": self.step_index,
46
+ "tool_name": self.tool_name,
47
+ "arguments": self.arguments,
48
+ "result": str(self.result)[:200] if self.result is not None else None,
49
+ "error": self.error,
50
+ "cost_usd": self.cost_usd,
51
+ "tokens_used": self.tokens_used,
52
+ "timestamp": self.timestamp,
53
+ "action_hash": self.action_hash,
54
+ }
55
+
56
+
57
+ @dataclass
58
+ class Intervention:
59
+ """Actionable decision returned by the circuit breaker following an action record."""
60
+ should_trip: bool
61
+ is_warning: bool = False
62
+ thrash_type: Optional[ThrashType] = None
63
+ reason: str = ""
64
+ recovery_prompt: str = ""
65
+ confidence: float = 1.0
66
+ details: Dict[str, Any] = field(default_factory=dict)
67
+
68
+ def to_dict(self) -> Dict[str, Any]:
69
+ return {
70
+ "should_trip": self.should_trip,
71
+ "is_warning": self.is_warning,
72
+ "thrash_type": self.thrash_type.value if self.thrash_type else None,
73
+ "reason": self.reason,
74
+ "recovery_prompt": self.recovery_prompt,
75
+ "confidence": self.confidence,
76
+ "details": self.details,
77
+ }
78
+
79
+
80
+ @dataclass
81
+ class CircuitMetrics:
82
+ """Comprehensive performance and health telemetry for an agent loop."""
83
+ total_steps: int
84
+ total_cost_usd: float
85
+ total_tokens: int
86
+ thrash_events_count: int
87
+ interventions_count: int
88
+ state: CircuitState
89
+ history_length: int
90
+ violations: List[Dict[str, Any]] = field(default_factory=list)
91
+
92
+ def to_dict(self) -> Dict[str, Any]:
93
+ return {
94
+ "total_steps": self.total_steps,
95
+ "total_cost_usd": round(self.total_cost_usd, 5),
96
+ "total_tokens": self.total_tokens,
97
+ "thrash_events_count": self.thrash_events_count,
98
+ "interventions_count": self.interventions_count,
99
+ "state": self.state.value,
100
+ "history_length": self.history_length,
101
+ "violations": self.violations,
102
+ }
103
+
104
+ def to_json(self, indent: int = 2) -> str:
105
+ return json.dumps(self.to_dict(), indent=indent)
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: loopcircuit
3
+ Version: 0.1.0
4
+ Summary: Autonomous agent loop governor, circuit-breaker, and anti-thrashing engine for AI agents
5
+ Author: loopcircuit Contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/VikasPatel22/loopcircuit
8
+ Project-URL: Repository, https://github.com/VikasPatel22/loopcircuit.git
9
+ Keywords: agent,circuit-breaker,loop-detection,ai-safety,reliability,llm-governance
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+
21
+ # loopcircuit
22
+
23
+ Autonomous agent loop governor, circuit-breaker, and anti-thrashing engine for AI agents and LLM execution pipelines.
24
+
25
+ Zero hard dependencies. Framework-agnostic. Runs in sub-millisecond execution time.
26
+
27
+ ---
28
+
29
+ ## The Problem in 2026
30
+
31
+ Frontier AI agents (Claude Code, Cursor, AutoGen, CrewAI, or custom `while` loops) frequently suffer from **runaway execution traps**:
32
+ 1. **Exact Repetition**: Invoking the exact same broken tool with identical arguments 20 times in a row.
33
+ 2. **Ping-Pong Oscillation**: Flip-flopping between two tools (e.g. `edit_file` ➔ `run_test` ➔ `revert` ➔ `edit_file`) without making forward progress.
34
+ 3. **Error Vortices**: Trapped repeatedly hitting the same underlying exception.
35
+ 4. **Budget Blowouts**: Burning through $50+ in LLM API credits overnight while unsupervised.
36
+
37
+ `loopcircuit` provides a deterministic safety net and circuit breaker that halts runaway loops and dynamically injects surgical interventions to snap agents back on track.
38
+
39
+ ---
40
+
41
+ ## Key Capabilities
42
+
43
+ - **Cycle & Oscillation Detection**: Identifies periodic cycles of length 1 (repetition), length 2 (ping-pong), and length 3+ (wandering) via canonical argument hashing.
44
+ - **Error Vortex Recognition**: Normalizes stack traces (stripping memory addresses, line numbers, and timestamps) to detect recurring root causes.
45
+ - **Multi-Policy Actions**:
46
+ - `raise`: Immediately trips and raises structured exceptions (`ThrashDetectedError`, `BudgetExceededError`, `MaxStepsExceededError`).
47
+ - `intervene`: Injects a structured system intervention prompt directly into the agent's context to mandate a strategy change.
48
+ - `warn`: Half-opens the circuit, logging telemetry while allowing execution to proceed with probation.
49
+ - **Financial & Token Caps**: Hard limits on dollar costs and cumulative token consumption.
50
+ - **Drop-in `@governed` Decorator & Context Manager**: Works seamlessly across sync and async loops.
51
+
52
+ ---
53
+
54
+ ## Installation
55
+
56
+ ```bash
57
+ pip install loopcircuit
58
+ ```
59
+
60
+ ---
61
+
62
+ ## Quickstart
63
+
64
+ ### As an Interactive Circuit Breaker
65
+
66
+ ```python
67
+ from loopcircuit import CircuitBreaker
68
+
69
+ # Configure safety thresholds
70
+ breaker = CircuitBreaker(
71
+ max_steps=20,
72
+ max_cost_usd=2.00,
73
+ repetition_threshold=3,
74
+ on_trip="intervene" # Injects corrective prompt instead of crashing
75
+ )
76
+
77
+ for step in agent_execution:
78
+ # Record each tool invocation
79
+ intervention = breaker.record(
80
+ tool_name=step.tool,
81
+ arguments=step.args,
82
+ result=step.output,
83
+ cost_usd=step.cost
84
+ )
85
+
86
+ if intervention.is_warning:
87
+ # Feed the generated pattern-breaking prompt back to the LLM
88
+ step.inject_system_prompt(intervention.recovery_prompt)
89
+ ```
90
+
91
+ ---
92
+
93
+ ### As a Decorator
94
+
95
+ ```python
96
+ from loopcircuit import governed
97
+
98
+ @governed(max_steps=15, max_cost_usd=1.00, on_trip="raise")
99
+ def run_agent_loop(task: str, breaker=None):
100
+ while True:
101
+ action = planner(task)
102
+ result = execute(action)
103
+ breaker.record(action.tool, action.args, result=result)
104
+ ```
105
+
106
+ ---
107
+
108
+ ## CLI Trace Auditor
109
+
110
+ Replay and audit agent trace logs (`.jsonl`) to detect loops and calculate spend:
111
+
112
+ ```bash
113
+ loopcircuit audit agent_run.jsonl
114
+ loopcircuit audit agent_run.jsonl --max-cost 2.50 --json
115
+ ```
116
+
117
+ ---
118
+
119
+ ## License
120
+
121
+ MIT License.
@@ -0,0 +1,14 @@
1
+ loopcircuit/__init__.py,sha256=ZKmCBgMw26HGKAiOW0AyXKTQz0Ys9FcDmWQR-n_MdDQ,994
2
+ loopcircuit/circuit.py,sha256=ylYSaH1zi0ekJJT5YIew6tswKN14RaUtuPIDoDOg-MI,9689
3
+ loopcircuit/cli.py,sha256=gfe_rUim6eOlbq-pUz3hmw1h94sg0myOBgK7_e2uWqU,4409
4
+ loopcircuit/detector.py,sha256=q0R-tfeYgxFL_0RvI-behSO1IPe84VEJDnJqGw0uRng,8448
5
+ loopcircuit/exceptions.py,sha256=LfJEPsqtQg4sqC0Ra2HZjYE5fnIGcMsrajxFclfkx8c,1204
6
+ loopcircuit/governor.py,sha256=j29yUWYCBXtbm5b1s3YPvfvHkk-Rt2JikjoW7x9ruVQ,2845
7
+ loopcircuit/intervention.py,sha256=zBYF2cXvk47fS-gfZ9WivLaEP7RMuQJ9vj2zlEMzo8o,4300
8
+ loopcircuit/py.typed,sha256=2X_1X_HUbFbPMsgG85pQ4WTxzXDtgoxEZEPV1nHY9nw,40
9
+ loopcircuit/types.py,sha256=C3M-h9G-Zwcr2T-C1aZDLrLnNAgVEKglcEXOWyjwE-4,3931
10
+ loopcircuit-0.1.0.dist-info/METADATA,sha256=W3WIxri40KC-eNU95ZND-eU5Cv0l1ff52ccLZQiChNY,4155
11
+ loopcircuit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ loopcircuit-0.1.0.dist-info/entry_points.txt,sha256=fYZpt1Zyp2wPVUQeGsFtfMfp4BzxSaia6SqfoqFIjx0,53
13
+ loopcircuit-0.1.0.dist-info/top_level.txt,sha256=SBC17vdJ0TOWxDp6N5eA3zpVZSYEIs0OOYsgaDaBhxo,12
14
+ loopcircuit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ loopcircuit = loopcircuit.cli:main
@@ -0,0 +1 @@
1
+ loopcircuit