chore: fix 154 f-strings, simplify getattr/URL patterns, remove dead code (#3119)

Three categories of cleanup, all zero-behavioral-change:

1. F-strings without placeholders (154 fixes across 29 files)
   - Converted f'...' to '...' where no {expression} was present
   - Heaviest files: run_agent.py (24), cli.py (20), honcho_integration/cli.py (34)

2. Simplify defensive patterns in run_agent.py
   - Added explicit self._is_anthropic_oauth = False in __init__ (before
     the api_mode branch that conditionally sets it)
   - Replaced 7x getattr(self, '_is_anthropic_oauth', False) with direct
     self._is_anthropic_oauth (attribute always initialized now)
   - Added _is_openrouter_url() and _is_anthropic_url() helper methods
   - Replaced 3 inline 'openrouter' in self._base_url_lower checks

3. Remove dead code in small files
   - hermes_cli/claw.py: removed unused 'total' computation
   - tools/fuzzy_match.py: removed unused strip_indent() function and
     pattern_stripped variable

Full test suite: 6184 passed, 0 failures
E2E PTY: banner clean, tool calls work, zero garbled ANSI
This commit is contained in:
Teknium
2026-03-25 19:47:58 -07:00
committed by GitHub
parent 08d3be0412
commit cbf195e806
30 changed files with 173 additions and 170 deletions

View File

@@ -1073,7 +1073,7 @@ def browser_navigate(url: str, task_id: Optional[str] = None) -> str:
_run_browser_command(effective_task_id, "open", ["about:blank"], timeout=10)
return json.dumps({
"success": False,
"error": f"Blocked: redirect landed on a private/internal address",
"error": "Blocked: redirect landed on a private/internal address",
})
response = {

View File

@@ -505,7 +505,7 @@ class CheckpointManager:
# Get the hash of the commit at the cutoff point
ok, cutoff_hash, _ = _run_git(
["rev-list", "--reverse", "HEAD", "--skip=0",
f"--max-count=1"],
"--max-count=1"],
shadow_repo, working_dir,
)
@@ -542,7 +542,7 @@ def format_checkpoint_list(checkpoints: List[Dict], directory: str) -> str:
lines.append(f" {i}. {cp['short_hash']} {ts} {cp['reason']}{stat}")
lines.append(f"\n /rollback <N> restore to checkpoint N")
lines.append(f" /rollback diff <N> preview changes since checkpoint N")
lines.append(f" /rollback <N> <file> restore a single file from checkpoint N")
lines.append("\n /rollback <N> restore to checkpoint N")
lines.append(" /rollback diff <N> preview changes since checkpoint N")
lines.append(" /rollback <N> <file> restore a single file from checkpoint N")
return "\n".join(lines)

View File

@@ -187,11 +187,6 @@ def _strategy_indentation_flexible(content: str, pattern: str) -> List[Tuple[int
Strips all leading whitespace from lines before matching.
"""
def strip_indent(s):
return '\n'.join(line.lstrip() for line in s.split('\n'))
pattern_stripped = strip_indent(pattern)
content_lines = content.split('\n')
content_stripped_lines = [line.lstrip() for line in content_lines]
pattern_lines = [line.lstrip() for line in pattern.split('\n')]

View File

@@ -156,7 +156,7 @@ async def _redirect_to_browser(auth_url: str) -> None:
try:
if _can_open_browser():
webbrowser.open(auth_url)
print(f" Opened browser for authorization...")
print(" Opened browser for authorization...")
else:
print(f"\n Open this URL to authorize:\n {auth_url}\n")
except Exception:

View File

@@ -466,7 +466,7 @@ if __name__ == "__main__":
# Show current configuration
config = get_moa_configuration()
print(f"\n⚙️ Current Configuration:")
print("\n⚙️ Current Configuration:")
print(f" 🤖 Reference models ({len(config['reference_models'])}): {', '.join(config['reference_models'])}")
print(f" 🧠 Aggregator model: {config['aggregator_model']}")
print(f" 🌡️ Reference temperature: {config['reference_temperature']}")
@@ -506,7 +506,7 @@ if __name__ == "__main__":
print(f" - Optimized temperatures: {REFERENCE_TEMPERATURE} for reference models, {AGGREGATOR_TEMPERATURE} for aggregation")
print(" - Token-efficient: only returns final aggregated response")
print(" - Resilient: continues with partial model failures")
print(f" - Configurable: easy to modify models and settings at top of file")
print(" - Configurable: easy to modify models and settings at top of file")
print(" - State-of-the-art results on challenging benchmarks")
print("\nDebug mode:")

View File

@@ -456,7 +456,7 @@ async def _monitor_training_run(run_state: RunState):
if run_state.api_process and run_state.api_process.poll() is not None:
run_state.status = "failed"
run_state.error_message = f"API server exited unexpectedly"
run_state.error_message = "API server exited unexpectedly"
_stop_training_run(run_state)
break
@@ -1233,11 +1233,11 @@ async def rl_test_inference(
print(f"\n ❌ Error: {model_results['error']}")
# Print last few lines of stderr for debugging
if stderr_lines:
print(f" Last errors:")
print(" Last errors:")
for line in stderr_lines[-5:]:
print(f" {line}")
else:
print(f"\n ✅ Process completed successfully")
print("\n ✅ Process completed successfully")
print(f" Output file: {output_file}")
print(f" File exists: {output_file.exists()}")
@@ -1272,7 +1272,7 @@ async def rl_test_inference(
except asyncio.TimeoutError:
model_results["error"] = "Process timed out after 10 minutes"
print(f" Timeout!")
print(" Timeout!")
except Exception as e:
model_results["error"] = str(e)
print(f" Error: {e}")

View File

@@ -2021,8 +2021,8 @@ class LobeHubSource(SkillSource):
"metadata:",
" hermes:",
f" tags: [{', '.join(str(t) for t in tag_list)}]",
f" lobehub:",
f" source: lobehub",
" lobehub:",
" source: lobehub",
"---",
]

View File

@@ -1252,7 +1252,7 @@ if __name__ == "__main__":
print("=" * 50)
config = _get_env_config()
print(f"\nCurrent Configuration:")
print("\nCurrent Configuration:")
print(f" Environment type: {config['env_type']}")
print(f" Docker image: {config['docker_image']}")
print(f" Modal image: {config['modal_image']}")

View File

@@ -634,7 +634,7 @@ def check_command_security(command: str) -> dict:
logger.warning("tirith timed out after %ds", timeout)
if fail_open:
return {"action": "allow", "findings": [], "summary": f"tirith timed out ({timeout}s)"}
return {"action": "block", "findings": [], "summary": f"tirith timed out (fail-closed)"}
return {"action": "block", "findings": [], "summary": "tirith timed out (fail-closed)"}
# Map exit code to action
exit_code = result.returncode

View File

@@ -797,7 +797,7 @@ if __name__ == "__main__":
except ImportError:
return False
print(f"\nProvider availability:")
print("\nProvider availability:")
print(f" Edge TTS: {'installed' if _check(_import_edge_tts, 'edge') else 'not installed (pip install edge-tts)'}")
print(f" ElevenLabs: {'installed' if _check(_import_elevenlabs, 'el') else 'not installed (pip install elevenlabs)'}")
print(f" API Key: {'set' if os.getenv('ELEVENLABS_API_KEY') else 'not set'}")

View File

@@ -1665,7 +1665,7 @@ if __name__ == "__main__":
print(" # - Final processed results")
print(" # Logs saved to: ./logs/web_tools_debug_UUID.json")
print(f"\n📝 Run 'python test_web_tools_llm.py' to test LLM processing capabilities")
print("\n📝 Run 'python test_web_tools_llm.py' to test LLM processing capabilities")
# ---------------------------------------------------------------------------