chore: collapse multi-line argument definitions into single lines across multiple modules

This commit is contained in:
2025-11-04 07:10:37 +00:00
parent e9ced4a493
commit d58e2b56f2
44 changed files with 163 additions and 469 deletions
+1 -3
View File
@@ -40,9 +40,7 @@ class AdvancedContextManager:
words = re.findall(r"\b\w+\b", content.lower())
unique_words.update(words)
vocabulary_richness = (
len(unique_words) / total_length if total_length > 0 else 0
)
vocabulary_richness = len(unique_words) / total_length if total_length > 0 else 0
# Simple complexity score based on length and richness
complexity = min(1.0, (avg_length / 100) + vocabulary_richness)
+3 -9
View File
@@ -9,9 +9,7 @@ from pr.core.context import auto_slim_messages
logger = logging.getLogger("pr")
def call_api(
messages, model, api_url, api_key, use_tools, tools_definition, verbose=False
):
def call_api(messages, model, api_url, api_key, use_tools, tools_definition, verbose=False):
try:
messages = auto_slim_messages(messages, verbose=verbose)
@@ -65,13 +63,9 @@ def call_api(
msg = choice["message"]
logger.debug(f"Response role: {msg.get('role', 'N/A')}")
if "content" in msg and msg["content"]:
logger.debug(
f"Response content length: {len(msg['content'])} chars"
)
logger.debug(f"Response content length: {len(msg['content'])} chars")
if "tool_calls" in msg:
logger.debug(
f"Response contains {len(msg['tool_calls'])} tool call(s)"
)
logger.debug(f"Response contains {len(msg['tool_calls'])} tool call(s)")
logger.debug("=== API CALL END ===")
return result
+15 -45
View File
@@ -76,9 +76,7 @@ logger = logging.getLogger("pr")
logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(LOG_FILE)
file_handler.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
)
file_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
logger.addHandler(file_handler)
@@ -93,9 +91,7 @@ class Assistant:
if self.debug:
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(
logging.Formatter("%(levelname)s: %(message)s")
)
console_handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger.addHandler(console_handler)
logger.debug("Debug mode enabled")
self.api_key = os.environ.get("OPENROUTER_API_KEY", "")
@@ -210,13 +206,9 @@ class Assistant:
session_name = event.get("session_name", "unknown")
if event_type == "session_started":
print(
f" {Colors.GREEN}{Colors.RESET} Session '{session_name}' started"
)
print(f" {Colors.GREEN}{Colors.RESET} Session '{session_name}' started")
elif event_type == "session_ended":
print(
f" {Colors.YELLOW}{Colors.RESET} Session '{session_name}' ended"
)
print(f" {Colors.YELLOW}{Colors.RESET} Session '{session_name}' ended")
elif event_type == "output_received":
lines = len(event.get("new_output", {}).get("stdout", []))
print(
@@ -241,9 +233,7 @@ class Assistant:
except Exception as e:
if self.debug:
print(
f"{Colors.RED}Error checking background updates: {e}{Colors.RESET}"
)
print(f"{Colors.RED}Error checking background updates: {e}{Colors.RESET}")
def execute_tool_calls(self, tool_calls):
results = []
@@ -263,14 +253,10 @@ class Assistant:
"run_command": lambda **kw: run_command(**kw),
"tail_process": lambda **kw: tail_process(**kw),
"kill_process": lambda **kw: kill_process(**kw),
"start_interactive_session": lambda **kw: start_interactive_session(
**kw
),
"start_interactive_session": lambda **kw: start_interactive_session(**kw),
"send_input_to_session": lambda **kw: send_input_to_session(**kw),
"read_session_output": lambda **kw: read_session_output(**kw),
"close_interactive_session": lambda **kw: close_interactive_session(
**kw
),
"close_interactive_session": lambda **kw: close_interactive_session(**kw),
"read_file": lambda **kw: read_file(**kw, db_conn=self.db_conn),
"write_file": lambda **kw: write_file(**kw, db_conn=self.db_conn),
"list_directory": lambda **kw: list_directory(**kw),
@@ -286,9 +272,7 @@ class Assistant:
**kw, python_globals=self.python_globals
),
"index_source_directory": lambda **kw: index_source_directory(**kw),
"search_replace": lambda **kw: search_replace(
**kw, db_conn=self.db_conn
),
"search_replace": lambda **kw: search_replace(**kw, db_conn=self.db_conn),
"open_editor": lambda **kw: open_editor(**kw),
"editor_insert_text": lambda **kw: editor_insert_text(
**kw, db_conn=self.db_conn
@@ -304,15 +288,11 @@ class Assistant:
"display_edit_summary": lambda **kw: display_edit_summary(),
"display_edit_timeline": lambda **kw: display_edit_timeline(**kw),
"clear_edit_tracker": lambda **kw: clear_edit_tracker(),
"start_interactive_session": lambda **kw: start_interactive_session(
**kw
),
"start_interactive_session": lambda **kw: start_interactive_session(**kw),
"send_input_to_session": lambda **kw: send_input_to_session(**kw),
"read_session_output": lambda **kw: read_session_output(**kw),
"list_active_sessions": lambda **kw: list_active_sessions(**kw),
"close_interactive_session": lambda **kw: close_interactive_session(
**kw
),
"close_interactive_session": lambda **kw: close_interactive_session(**kw),
"create_agent": lambda **kw: create_agent(**kw),
"list_agents": lambda **kw: list_agents(**kw),
"execute_agent_task": lambda **kw: execute_agent_task(**kw),
@@ -321,16 +301,10 @@ class Assistant:
"add_knowledge_entry": lambda **kw: add_knowledge_entry(**kw),
"get_knowledge_entry": lambda **kw: get_knowledge_entry(**kw),
"search_knowledge": lambda **kw: search_knowledge(**kw),
"get_knowledge_by_category": lambda **kw: get_knowledge_by_category(
**kw
),
"update_knowledge_importance": lambda **kw: update_knowledge_importance(
**kw
),
"get_knowledge_by_category": lambda **kw: get_knowledge_by_category(**kw),
"update_knowledge_importance": lambda **kw: update_knowledge_importance(**kw),
"delete_knowledge_entry": lambda **kw: delete_knowledge_entry(**kw),
"get_knowledge_statistics": lambda **kw: get_knowledge_statistics(
**kw
),
"get_knowledge_statistics": lambda **kw: get_knowledge_statistics(**kw),
}
if func_name in func_map:
@@ -356,9 +330,7 @@ class Assistant:
{
"tool_call_id": tool_id,
"role": "tool",
"content": json.dumps(
{"status": "error", "error": error_msg}
),
"content": json.dumps({"status": "error", "error": error_msg}),
}
)
@@ -405,9 +377,7 @@ class Assistant:
self.autonomous_mode = False
sys.exit(0)
else:
print(
f"\n{Colors.YELLOW}Press Ctrl+C again to force exit{Colors.RESET}"
)
print(f"\n{Colors.YELLOW}Press Ctrl+C again to force exit{Colors.RESET}")
return
self.interrupt_count += 1
+3 -9
View File
@@ -21,9 +21,7 @@ class AutonomousInteractions:
self.llm_callback = llm_callback
if self.interaction_thread is None:
self.active = True
self.interaction_thread = threading.Thread(
target=self._interaction_loop, daemon=True
)
self.interaction_thread = threading.Thread(target=self._interaction_loop, daemon=True)
self.interaction_thread.start()
def stop(self):
@@ -55,9 +53,7 @@ class AutonomousInteractions:
if not sessions:
return # No active sessions
sessions_needing_attention = self._identify_sessions_needing_attention(
sessions
)
sessions_needing_attention = self._identify_sessions_needing_attention(sessions)
if sessions_needing_attention and self.llm_callback:
# Format session updates for LLM
@@ -84,9 +80,7 @@ class AutonomousInteractions:
continue
# 2. High output volume (potential completion or error)
total_lines = (
output_summary["stdout_lines"] + output_summary["stderr_lines"]
)
total_lines = output_summary["stdout_lines"] + output_summary["stderr_lines"]
if total_lines > 50: # Arbitrary threshold
needing_attention.append(session_name)
continue
+6 -19
View File
@@ -18,9 +18,7 @@ class BackgroundMonitor:
"""Start the background monitoring thread."""
if self.monitor_thread is None:
self.active = True
self.monitor_thread = threading.Thread(
target=self._monitor_loop, daemon=True
)
self.monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
self.monitor_thread.start()
def stop(self):
@@ -105,21 +103,14 @@ class BackgroundMonitor:
old_stderr_lines = old_state["output_summary"]["stderr_lines"]
new_stderr_lines = new_state["output_summary"]["stderr_lines"]
if (
new_stdout_lines > old_stdout_lines
or new_stderr_lines > old_stderr_lines
):
if new_stdout_lines > old_stdout_lines or new_stderr_lines > old_stderr_lines:
# Get the new output
mux = get_multiplexer(session_name)
if mux:
all_output = mux.get_all_output()
new_output = {
"stdout": all_output["stdout"].split("\n")[
old_stdout_lines:
],
"stderr": all_output["stderr"].split("\n")[
old_stderr_lines:
],
"stdout": all_output["stdout"].split("\n")[old_stdout_lines:],
"stderr": all_output["stderr"].split("\n")[old_stderr_lines:],
}
events.append(
@@ -167,9 +158,7 @@ class BackgroundMonitor:
output_summary = state["output_summary"]
# Heuristic: High output volume might indicate completion or error
total_lines = (
output_summary["stdout_lines"] + output_summary["stderr_lines"]
)
total_lines = output_summary["stdout_lines"] + output_summary["stderr_lines"]
if total_lines > 100: # Arbitrary threshold
events.append(
{
@@ -193,9 +182,7 @@ class BackgroundMonitor:
# Heuristic: Sessions that might be waiting for input
# This would be enhanced with prompt detection in later phases
if self._might_be_waiting_for_input(session_name, state):
events.append(
{"type": "possible_input_needed", "session_name": session_name}
)
events.append({"type": "possible_input_needed", "session_name": session_name})
return events
+13 -37
View File
@@ -41,15 +41,11 @@ def truncate_tool_result(result, max_length=None):
if "data" in result_copy and isinstance(result_copy["data"], str):
if len(result_copy["data"]) > max_length:
result_copy["data"] = (
result_copy["data"][:max_length] + f"\n... [truncated]"
)
result_copy["data"] = result_copy["data"][:max_length] + f"\n... [truncated]"
if "error" in result_copy and isinstance(result_copy["error"], str):
if len(result_copy["error"]) > max_length // 2:
result_copy["error"] = (
result_copy["error"][: max_length // 2] + "... [truncated]"
)
result_copy["error"] = result_copy["error"][: max_length // 2] + "... [truncated]"
return result_copy
@@ -111,9 +107,7 @@ Shell Commands:
system_message = "\n\n".join(context_parts)
if len(system_message) > max_context_size * 3:
system_message = (
system_message[: max_context_size * 3] + "\n... [system message truncated]"
)
system_message = system_message[: max_context_size * 3] + "\n... [system message truncated]"
return {"role": "system", "content": system_message}
@@ -198,18 +192,14 @@ def trim_message_content(message, max_length):
if isinstance(content, str) and len(content) > max_length:
trimmed_msg["content"] = (
content[:max_length]
+ f"\n... [trimmed {len(content) - max_length} chars]"
content[:max_length] + f"\n... [trimmed {len(content) - max_length} chars]"
)
elif isinstance(content, list):
trimmed_content = []
for item in content:
if isinstance(item, dict):
trimmed_item = item.copy()
if (
"text" in trimmed_item
and len(trimmed_item["text"]) > max_length
):
if "text" in trimmed_item and len(trimmed_item["text"]) > max_length:
trimmed_item["text"] = (
trimmed_item["text"][:max_length] + f"\n... [trimmed]"
)
@@ -236,8 +226,7 @@ def trim_message_content(message, max_length):
and len(parsed["output"]) > MAX_TOOL_RESULT_LENGTH // 2
):
parsed["output"] = (
parsed["output"][: MAX_TOOL_RESULT_LENGTH // 2]
+ f"\n... [truncated]"
parsed["output"][: MAX_TOOL_RESULT_LENGTH // 2] + f"\n... [truncated]"
)
if (
"content" in parsed
@@ -245,8 +234,7 @@ def trim_message_content(message, max_length):
and len(parsed["content"]) > MAX_TOOL_RESULT_LENGTH // 2
):
parsed["content"] = (
parsed["content"][: MAX_TOOL_RESULT_LENGTH // 2]
+ f"\n... [truncated]"
parsed["content"][: MAX_TOOL_RESULT_LENGTH // 2] + f"\n... [truncated]"
)
trimmed_msg["content"] = json.dumps(parsed)
except:
@@ -259,24 +247,18 @@ def intelligently_trim_messages(messages, target_tokens, keep_recent=3):
if estimate_tokens(messages) <= target_tokens:
return messages
system_msg = (
messages[0] if messages and messages[0].get("role") == "system" else None
)
system_msg = messages[0] if messages and messages[0].get("role") == "system" else None
start_idx = 1 if system_msg else 0
recent_messages = (
messages[-keep_recent:] if len(messages) > keep_recent else messages[start_idx:]
)
middle_messages = (
messages[start_idx:-keep_recent] if len(messages) > keep_recent else []
)
middle_messages = messages[start_idx:-keep_recent] if len(messages) > keep_recent else []
trimmed_middle = []
for msg in middle_messages:
if msg.get("role") == "tool":
trimmed_middle.append(
trim_message_content(msg, MAX_TOOL_RESULT_LENGTH // 2)
)
trimmed_middle.append(trim_message_content(msg, MAX_TOOL_RESULT_LENGTH // 2))
elif msg.get("role") in ["user", "assistant"]:
trimmed_middle.append(trim_message_content(msg, CONTENT_TRIM_LENGTH))
else:
@@ -313,9 +295,7 @@ def auto_slim_messages(messages, verbose=False):
print(
f"{Colors.YELLOW}⚠️ Token limit approaching: ~{estimated_tokens} tokens (limit: {MAX_TOKENS_LIMIT}){Colors.RESET}"
)
print(
f"{Colors.YELLOW}🔧 Intelligently trimming message content...{Colors.RESET}"
)
print(f"{Colors.YELLOW}🔧 Intelligently trimming message content...{Colors.RESET}")
result = intelligently_trim_messages(
messages, MAX_TOKENS_LIMIT, keep_recent=EMERGENCY_MESSAGES_TO_KEEP
@@ -339,17 +319,13 @@ def auto_slim_messages(messages, verbose=False):
f"{Colors.GREEN} Token estimate: {estimated_tokens}{final_tokens} (~{estimated_tokens - final_tokens} saved){Colors.RESET}"
)
if removed_count > 0:
print(
f"{Colors.GREEN} Removed {removed_count} older messages{Colors.RESET}"
)
print(f"{Colors.GREEN} Removed {removed_count} older messages{Colors.RESET}")
return result
def emergency_reduce_messages(messages, target_tokens, verbose=False):
system_msg = (
messages[0] if messages and messages[0].get("role") == "system" else None
)
system_msg = messages[0] if messages and messages[0].get("role") == "system" else None
start_idx = 1 if system_msg else 0
keep_count = 2
+6 -16
View File
@@ -63,9 +63,7 @@ class EnhancedAssistant:
logger.info("Enhanced Assistant initialized with all features")
def _execute_tool_for_workflow(
self, tool_name: str, arguments: Dict[str, Any]
) -> Any:
def _execute_tool_for_workflow(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
if self.tool_cache:
cached_result = self.tool_cache.get(tool_name, arguments)
if cached_result is not None:
@@ -119,9 +117,7 @@ class EnhancedAssistant:
if self.tool_cache:
content = result.get("content", "")
try:
parsed_content = (
json.loads(content) if isinstance(content, str) else content
)
parsed_content = json.loads(content) if isinstance(content, str) else content
self.tool_cache.set(tool_name, arguments, parsed_content)
except Exception:
pass
@@ -164,9 +160,7 @@ class EnhancedAssistant:
if self.api_cache and CACHE_ENABLED and "error" not in response:
token_count = response.get("usage", {}).get("total_tokens", 0)
self.api_cache.set(
self.base.model, messages, 0.7, 4096, response, token_count
)
self.api_cache.set(self.base.model, messages, 0.7, 4096, response, token_count)
return response
@@ -197,10 +191,8 @@ class EnhancedAssistant:
self.knowledge_store.add_entry(entry)
if self.context_manager and ADVANCED_CONTEXT_ENABLED:
enhanced_messages, context_info = (
self.context_manager.create_enhanced_context(
self.base.messages, user_message, include_knowledge=True
)
enhanced_messages, context_info = self.context_manager.create_enhanced_context(
self.base.messages, user_message, include_knowledge=True
)
if self.base.verbose:
@@ -261,9 +253,7 @@ class EnhancedAssistant:
orchestrator_id = self.agent_manager.create_agent("orchestrator")
return self.agent_manager.collaborate_agents(orchestrator_id, task, agent_roles)
def search_knowledge(
self, query: str, limit: int = KNOWLEDGE_SEARCH_LIMIT
) -> List[Any]:
def search_knowledge(self, query: str, limit: int = KNOWLEDGE_SEARCH_LIMIT) -> List[Any]:
return self.knowledge_store.search_entries(query, top_k=limit)
def get_cache_statistics(self) -> Dict[str, Any]:
+1 -3
View File
@@ -16,9 +16,7 @@ def setup_logging(verbose=False):
if logger.handlers:
logger.handlers.clear()
file_handler = RotatingFileHandler(
LOG_FILE, maxBytes=10 * 1024 * 1024, backupCount=5
)
file_handler = RotatingFileHandler(LOG_FILE, maxBytes=10 * 1024 * 1024, backupCount=5)
file_handler.setLevel(logging.DEBUG)
file_formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s",
+3 -9
View File
@@ -64,13 +64,9 @@ class UsageTracker:
self._save_to_history(model, input_tokens, output_tokens, cost)
logger.debug(
f"Tracked request: {model}, tokens: {total_tokens}, cost: ${cost:.4f}"
)
logger.debug(f"Tracked request: {model}, tokens: {total_tokens}, cost: ${cost:.4f}")
def _calculate_cost(
self, model: str, input_tokens: int, output_tokens: int
) -> float:
def _calculate_cost(self, model: str, input_tokens: int, output_tokens: int) -> float:
if model not in MODEL_COSTS:
base_model = model.split("/")[0] if "/" in model else model
if base_model not in MODEL_COSTS:
@@ -85,9 +81,7 @@ class UsageTracker:
return input_cost + output_cost
def _save_to_history(
self, model: str, input_tokens: int, output_tokens: int, cost: float
):
def _save_to_history(self, model: str, input_tokens: int, output_tokens: int, cost: float):
try:
history = []
if os.path.exists(USAGE_DB_FILE):
+1 -3
View File
@@ -16,9 +16,7 @@ def validate_file_path(path: str, must_exist: bool = False) -> str:
return os.path.abspath(path)
def validate_directory_path(
path: str, must_exist: bool = False, create: bool = False
) -> str:
def validate_directory_path(path: str, must_exist: bool = False, create: bool = False) -> str:
if not path:
raise ValidationError("Directory path cannot be empty")