Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix: CodeCheck清理

wangxiaolong100683329695988
diff --git a/jiuwenswarm/agents/harness/common/memory/manager.py b/jiuwenswarm/agents/harness/common/memory/manager.py
index 0601cb8065..6d4e3ee35a 100644
--- a/jiuwenswarm/agents/harness/common/memory/manager.py
+++ b/jiuwenswarm/agents/harness/common/memory/manager.py
@@ -444,7 +444,7 @@ class MemoryIndexManager:
try:
self._event_loop.call_soon_threadsafe(schedule_sync)
except Exception as e:
- logger.debug(f"Failed to schedule sync: {e}")
+ logger.debug("Failed to schedule sync: %s", e)
def _ensure_interval_sync(self) -> None:
"""Setup interval-based sync if configured."""
@@ -483,7 +483,7 @@ class MemoryIndexManager:
await self._run_reindex()
return
- logger.debug(f"Memory sync (reason: {reason or 'unknown'})...")
+ logger.debug("Memory sync (reason: %s)...", reason or 'unknown')
if "memory" in self.settings.sources and self.dirty:
await self._sync_memory_files()
@@ -579,7 +579,7 @@ class MemoryIndexManager:
"""
files = list_memory_files(self.workspace_dir, self.settings.extraPaths)
- logger.debug(f"Syncing {len(files)} memory files")
+ logger.debug("Syncing %d memory files", len(files))
active_paths = set()
@@ -615,7 +615,7 @@ class MemoryIndexManager:
if f.endswith(".jsonl"):
session_files.append(os.path.join(root, f))
- logger.debug(f"Syncing {len(session_files)} session files")
+ logger.debug("Syncing %d session files", len(session_files))
active_paths = set()
for session_file in session_files:
@@ -700,7 +700,7 @@ class MemoryIndexManager:
VALUES (?, ?, ?, ?, ?)
""", (chunk_rowid, chunk_id, file_path, source, chunk.text))
except Exception as e:
- logger.debug(f"Failed to insert into FTS: {e}")
+ logger.debug("Failed to insert into FTS: %s", e)
if self.vector_available and embedding and chunk_rowid:
try:
@@ -710,7 +710,7 @@ class MemoryIndexManager:
VALUES (?, vec_f32(?))
""", (chunk_rowid, vector_to_blob(embedding)))
except Exception as e:
- logger.debug(f"Failed to insert into vector table: {e}")
+ logger.debug("Failed to insert into vector table: %s", e)
def _remove_file_from_index(self, file_path: str) -> None:
"""Remove file from index."""
@@ -812,7 +812,7 @@ class MemoryIndexManager:
try:
keyword_results = await self._search_keyword(cleaned, candidates)
except Exception as e:
- logger.debug(f"Keyword search failed: {e}")
+ logger.debug("Keyword search failed: %s", e)
query_vec = await self._embed_query_with_timeout(cleaned)
has_vector = any(v != 0 for v in query_vec)
@@ -822,7 +822,7 @@ class MemoryIndexManager:
try:
vector_results = await self._search_vector(query_vec, candidates)
except Exception as e:
- logger.debug(f"Vector search failed: {e}")
+ logger.debug("Vector search failed: %s", e)
if not hybrid.get("enabled", True):
return [
@@ -908,7 +908,7 @@ class MemoryIndexManager:
return results
except Exception as e:
- logger.debug(f"Vector search with sqlite-vec failed: {e}")
+ logger.debug("Vector search with sqlite-vec failed: %s", e)
return await self._search_vector_fallback(query_vec, limit)
async def _search_vector_fallback(
@@ -1020,7 +1020,7 @@ class MemoryIndexManager:
return results
except Exception as e:
- logger.debug(f"Keyword search failed: {e}")
+ logger.debug("Keyword search failed: %s", e)
return []
def _build_source_filter(self) -> str:
diff --git a/jiuwenswarm/agents/harness/common/tools/browser-move/src/playwright_runtime/profiles.py b/jiuwenswarm/agents/harness/common/tools/browser-move/src/playwright_runtime/profiles.py
index 7ca7951db0..c2c57ead0a 100644
--- a/jiuwenswarm/agents/harness/common/tools/browser-move/src/playwright_runtime/profiles.py
+++ b/jiuwenswarm/agents/harness/common/tools/browser-move/src/playwright_runtime/profiles.py
@@ -7,10 +7,13 @@
from __future__ import annotations
import json
+import logging
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional
+logger = logging.getLogger(__name__)
+
@dataclass
class BrowserProfile:
@@ -63,7 +66,8 @@ class BrowserProfileStore:
return
try:
payload = json.loads(self.path.read_text(encoding="utf-8"))
- except Exception:
+ except (OSError, ValueError) as exc:
+ logger.warning("Failed to load browser profile store %s: %s", self.path, exc)
return
if not isinstance(payload, dict):
diff --git a/jiuwenswarm/agents/harness/common/tools/web_fetch_tools.py b/jiuwenswarm/agents/harness/common/tools/web_fetch_tools.py
index ecccabae54..8b38691ffa 100644
--- a/jiuwenswarm/agents/harness/common/tools/web_fetch_tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/web_fetch_tools.py
@@ -132,7 +132,7 @@ def _decode_response_text(response: requests.Response) -> str:
seen.add(enc)
try:
return raw.decode(enc, errors="strict")
- except Exception:
+ except (UnicodeDecodeError, LookupError):
continue
# Last-resort fallback.
diff --git a/jiuwenswarm/agents/harness/team/a2x/client/models.py b/jiuwenswarm/agents/harness/team/a2x/client/models.py
index 9253495232..fff2141922 100644
--- a/jiuwenswarm/agents/harness/team/a2x/client/models.py
+++ b/jiuwenswarm/agents/harness/team/a2x/client/models.py
@@ -8,9 +8,12 @@ yet declared (e.g. ``status``, ``endpoint``).
from __future__ import annotations
+import logging
from dataclasses import dataclass, field, fields
from typing import Any, TypeVar
+logger = logging.getLogger(__name__)
+
_T = TypeVar("_T", bound="_FromDictMixin")
@@ -136,7 +139,12 @@ class Reservation:
try:
self._client.release_reservation(self)
except Exception:
- pass # best-effort; lease will TTL-expire anyway
+ logger.warning(
+ "Reservation release on __exit__ failed for holder_id=%s; "
+ "lease will TTL-expire",
+ self.holder_id,
+ exc_info=True,
+ )
finally:
self._released = True
@@ -150,6 +158,11 @@ class Reservation:
try:
await self._client.release_reservation(self)
except Exception:
- pass
+ logger.warning(
+ "Reservation release on __aexit__ failed for holder_id=%s; "
+ "lease will TTL-expire",
+ self.holder_id,
+ exc_info=True,
+ )
finally:
self._released = True
diff --git a/jiuwenswarm/agents/harness/team/a2x/client/ownership.py b/jiuwenswarm/agents/harness/team/a2x/client/ownership.py
index d9d38de7f1..a4dd872487 100644
--- a/jiuwenswarm/agents/harness/team/a2x/client/ownership.py
+++ b/jiuwenswarm/agents/harness/team/a2x/client/ownership.py
@@ -184,7 +184,8 @@ class OwnershipStore:
)
def _save_to_disk(self) -> None:
- assert self._file_path is not None
+ if self._file_path is None:
+ raise RuntimeError("_save_to_disk called without a file_path")
path = self._file_path
with _file_lock(path):
existing = self._read_existing_locked(path)
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index 6b12806dd1..a059e7749d 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -58,7 +58,11 @@ def resolve_env_vars(value: Any) -> Any:
if is_need_decrypt and crypto:
current = crypto.decrypt(current)
except Exception:
- pass
+ logger.debug(
+ "Crypto provider unavailable while resolving env var %s; using raw value",
+ var_name,
+ exc_info=True,
+ )
# Bash: ${VAR:-default} uses default when VAR is unset OR empty.
# ${VAR} (no :-) keeps getenv behavior; unset -> "".
if default is not None:
@@ -798,7 +802,11 @@ def _decrypt_model_entries(entries: list[dict[str, Any]]) -> list[dict[str, Any]
try:
crypto = reg_mod.ExtensionRegistry.get_instance().get_crypto_provider()
except Exception:
- pass
+ logger.debug(
+ "Crypto provider unavailable while decrypting model entries; "
+ "api_key fields will be returned as stored",
+ exc_info=True,
+ )
for entry in result:
mcc = entry.get("model_client_config")
@@ -807,7 +815,10 @@ def _decrypt_model_entries(entries: list[dict[str, Any]]) -> list[dict[str, Any]
try:
mcc["api_key"] = crypto.decrypt(mcc["api_key"])
except Exception:
- pass
+ logger.warning(
+ "Failed to decrypt api_key for model entry; using raw value",
+ exc_info=True,
+ )
if "custom_headers" in mcc:
mcc["custom_headers"] = _parse_custom_headers(mcc["custom_headers"])
diff --git a/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/collectors/aggregator.py b/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/collectors/aggregator.py
index 36489a31e3..c1637ab929 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/collectors/aggregator.py
+++ b/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/collectors/aggregator.py
@@ -183,8 +183,8 @@ class DataAggregator:
},
}
- except Exception:
- pass
+ except Exception as e:
+ logging.warning(f"生成历史对比数据失败,返回已采集的部分结果: {e}", exc_info=True)
return comparison
diff --git a/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/collectors/email_collector.py b/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/collectors/email_collector.py
index c99f5f35de..de206f49df 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/collectors/email_collector.py
+++ b/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/collectors/email_collector.py
@@ -162,8 +162,8 @@ class EmailCollector:
if self._connection:
try:
self._connection.logout()
- except Exception:
- pass
+ except Exception as e:
+ logging.info(f"IMAP logout 失败(连接将直接释放): {e}", exc_info=True)
self._connection = None
def get_stats(self, date: Optional[str] = None) -> EmailStats:
diff --git a/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/generators/report_generator.py b/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/generators/report_generator.py
index bad07ee224..fbd8f35361 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/generators/report_generator.py
+++ b/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/generators/report_generator.py
@@ -11,6 +11,7 @@
import asyncio
import json
+import logging
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
@@ -96,7 +97,7 @@ class ReportGenerator:
try:
self.ai_analyzer = AIAnalyzer()
except Exception as e:
- print(f"[ReportGenerator] AI 分析器初始化失败: {e}")
+ logging.info(f"[ReportGenerator] AI 分析器初始化失败: {e}")
return None
try:
@@ -106,7 +107,7 @@ class ReportGenerator:
# 运行完整分析
return asyncio.run(self.ai_analyzer.analyze_full(data.to_dict(), pattern_data))
except Exception as e:
- print(f"[ReportGenerator] AI 分析失败: {e}")
+ logging.info(f"[ReportGenerator] AI 分析失败: {e}")
return None
def generate_weekly(self, end_date: Optional[str] = None) -> str:
@@ -485,7 +486,7 @@ def main():
import sys
if len(sys.argv) < 2:
- print("Usage: python report_generator.py <workspace_dir> [git_repo]")
+ logging.info("Usage: python report_generator.py <workspace_dir> [git_repo]")
sys.exit(1)
workspace_dir = sys.argv[1]
@@ -496,9 +497,9 @@ def main():
generator = ReportGenerator(aggregator)
# 生成日报
- print("=== 日报 ===\n")
+ logging.info("=== 日报 ===\n")
daily_report = generator.generate_daily()
- print(daily_report)
+ logging.info(daily_report)
if __name__ == "__main__":
diff --git a/scripts/build_python_packages.py b/scripts/build_python_packages.py
index f4bfc3abb4..bc1a0b5428 100644
--- a/scripts/build_python_packages.py
+++ b/scripts/build_python_packages.py
@@ -83,13 +83,21 @@ def build_tui_binary(target: str, clean: bool) -> None:
run(cmd, ROOT)
+class MissingJsDependenciesError(RuntimeError):
+ """Raised when TUI frontend node_modules is missing and auto-install is disabled."""
+
+
+class InvalidTargetError(ValueError):
+ """Raised when --target contains unknown TUI build target(s)."""
+
+
def ensure_js_dependencies(install: bool) -> None:
node_modules = TUI_ROOT / "node_modules"
if node_modules.exists():
return
if not install:
- raise SystemExit(
+ raise MissingJsDependenciesError(
"\n".join(
[
"missing JavaScript dependencies for jiuwenswarm/channels/tui/frontend",
@@ -121,7 +129,7 @@ def resolve_requested_targets(raw: str) -> list[str]:
unknown = [value for value in values if value not in TUI_TARGETS]
if unknown:
valid = ", ".join(["current", "all", *TUI_TARGETS.keys()])
- raise SystemExit(f"unknown target(s): {', '.join(unknown)}; valid: {valid}")
+ raise InvalidTargetError(f"unknown target(s): {', '.join(unknown)}; valid: {valid}")
return values
@@ -217,5 +225,7 @@ def main() -> None:
if __name__ == "__main__":
try:
main()
+ except (MissingJsDependenciesError, InvalidTargetError) as exc:
+ raise SystemExit(str(exc)) from exc
except subprocess.CalledProcessError as exc:
raise SystemExit(exc.returncode) from exc
\ No newline at end of file
diff --git a/scripts/build_tui.py b/scripts/build_tui.py
index ef0669be59..15f1fe2bca 100644
--- a/scripts/build_tui.py
+++ b/scripts/build_tui.py
@@ -2,10 +2,10 @@
from __future__ import annotations
import argparse
+import logging
import os
import shutil
import subprocess
-import sys
from pathlib import Path
@@ -35,7 +35,7 @@ def current_platform_key() -> str:
return f"macos-{machine}"
if system == "windows":
return f"windows-{machine}"
- raise SystemExit(f"unsupported platform for current target: {system}-{machine}")
+ raise ValueError(f"unsupported platform for current target: {system}-{machine}")
def output_binary_name(platform_key: str) -> str:
@@ -51,7 +51,7 @@ def resolve_requested_targets(raw: str) -> list[str]:
unknown = [value for value in values if value not in TARGETS]
if unknown:
valid = ", ".join(["current", "all", *TARGETS.keys()])
- raise SystemExit(f"unknown target(s): {', '.join(unknown)}; valid: {valid}")
+ raise ValueError(f"unknown target(s): {', '.join(unknown)}; valid: {valid}")
return values
@@ -123,11 +123,13 @@ def main() -> None:
built.append(build_target(target))
for path in built:
- print(path.relative_to(ROOT))
+ logging.info(path.relative_to(ROOT))
if __name__ == "__main__":
try:
main()
except subprocess.CalledProcessError as exc:
- raise SystemExit(exc.returncode) from exc
\ No newline at end of file
+ raise SystemExit(exc.returncode) from exc
+ except ValueError as exc:
+ raise SystemExit(str(exc)) from exc
\ No newline at end of file