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清理
wangxiaolong100d91b11fb8404
diff --git a/jiuwenswarm/agents/harness/common/tools/browser-move/examples/controller_usage_example.py b/jiuwenswarm/agents/harness/common/tools/browser-move/examples/controller_usage_example.pydeleted file mode 100644index 2a7aea2b89..0000000000--- a/jiuwenswarm/agents/harness/common/tools/browser-move/examples/controller_usage_example.py+++ /dev/null@@ -1,101 +0,0 @@-#!/usr/bin/env python-# coding: utf-8-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.--"""Example usage of the playwright_runtime custom action registry.--Shows how to:- 1. Register your own action handlers.- 2. Call run_action directly (e.g. from tests or scripts).- 3. Use the MCP tools browser_custom_action and browser_list_custom_actions- when the runtime MCP server is running.--Run from repo root:- uv run examples/controller_usage_example.py- uv run python src/playwright_runtime/controller.py # minimal demo-"""--from __future__ import annotations--import asyncio-import json-import sys-from pathlib import Path-from typing import Any, Dict--# Allow importing playwright_runtime when run from repo root-_REPO_ROOT = Path(__file__).resolve().parents[1]-_SRC = _REPO_ROOT / "src"-if _SRC.exists() and str(_SRC) not in sys.path:- sys.path.insert(0, str(_SRC))-if str(_REPO_ROOT) not in sys.path:- sys.path.insert(0, str(_REPO_ROOT))---async def example_register_and_call() -> None:- """Example: register a custom action and invoke it via the custom action API."""- from playwright_runtime.controller import (- list_actions,- register_action,- register_example_actions,- run_action,- )-- # Optional: register built-in examples (ping, echo)- register_example_actions()-- # Register your own action- async def my_uppercase(- session_id: str = "",- request_id: str = "",- text: str = "",- **kwargs: Any,- ) -> Dict[str, Any]:- return {"uppercased": (text or "").upper(), "session_id": session_id}-- register_action("uppercase", my_uppercase)-- print("Registered actions:", list_actions())-- # Call built-in examples- out = await run_action("ping", session_id="s1", request_id="r1")- print("run_action('ping', ...):", json.dumps(out, indent=2))-- out = await run_action("echo", session_id="s1", text="hello controller")- print("run_action('echo', text='hello controller'):", json.dumps(out, indent=2))-- # Call your custom action- out = await run_action("uppercase", session_id="s1", text="hello")- print("run_action('uppercase', text='hello'):", json.dumps(out, indent=2))-- # Unknown action- out = await run_action("nonexistent")- print("run_action('nonexistent'):", json.dumps(out, indent=2))---async def example_via_mcp_tools() -> None:- """- When the Playwright runtime MCP server is running, clients can call:-- - browser_list_custom_actions() -> {"ok": true, "actions": ["ping", "echo", ...]}- - browser_custom_action(action="ping", session_id="...", request_id="...")- - browser_custom_action(action="echo", params={"text": "hello"})-- The server registers register_example_actions() in its lifespan, so- "ping" and "echo" are available by default. Add your own in a startup- hook or by calling register_action() before the server starts.- """- print(- "To use from an MCP client: call browser_custom_action with action='ping' or 'echo', "- "or register your own actions and call browser_list_custom_actions to see them."- )---def main() -> None:- asyncio.run(example_register_and_call())- print()- asyncio.run(example_via_mcp_tools())---if __name__ == "__main__":- main()diff --git a/jiuwenswarm/agents/harness/common/tools/browser-move/examples/test_with_mcp.py b/jiuwenswarm/agents/harness/common/tools/browser-move/examples/test_with_mcp.pydeleted file mode 100644index ac0afd2fb4..0000000000--- a/jiuwenswarm/agents/harness/common/tools/browser-move/examples/test_with_mcp.py+++ /dev/null@@ -1,520 +0,0 @@-#!/usr/bin/env python-# coding: utf-8-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.--"""-Test script for Main Agent + MCP tools and browser sub-agent.--How to run the MCP servers (each in its own terminal; SSE = default, ports match below):-- # Browser (required for browser_cdp_sub)- uv run -m src.super_agent.tool.mcp_servers.browser_use_mcp_server_cdp --host 127.0.0.1 --port 8930-- # Reasoning (port 8934)- uv run -m src.super_agent.tool.mcp_servers.reasoning_mcp_server --transport sse --host 127.0.0.1 --port 8934-- # Searching (port 8936)- uv run -m src.super_agent.tool.mcp_servers.searching_mcp_server --transport sse --host 127.0.0.1 --port 8936-- # Vision (port 8932)- uv run -m src.super_agent.tool.mcp_servers.vision_mcp_server --transport sse --host 127.0.0.1 --port 8932--Then run this test: uv run -m src.super_agent.test.test_with_mcp-"""-from __future__ import annotations--import sys-import os-import time-import json-import asyncio-from pathlib import Path-from typing import Any, Dict, Optional--from dotenv import load_dotenv--# =============================================================================-# Force using repo openjiuwen (same as your current test.py)-# =============================================================================-REPO_ROOT = Path(__file__).resolve().parents[3]-sys.path.insert(0, str(REPO_ROOT))--# Load environment variables from .env (so you don't have to export them manually)-load_dotenv()--# ------------------------------# openjiuwen imports-# ------------------------------from openjiuwen.core.runner import Runner-from openjiuwen.core.foundation.tool import Tool, ToolCard, McpServerConfig-from openjiuwen.core.single_agent.agents.react_agent import ReActAgent, ReActAgentConfig-from openjiuwen.core.single_agent.schema.agent_card import AgentCard-from openjiuwen.core.session.session import Session, BaseSession---# =============================================================================-# Minimal Session (same idea as your original file)-# =============================================================================-class _DummyBaseSession(BaseSession):- def __init__(self, sid: str):- self._sid = sid-- def config(self):- return None-- def state(self):- return None-- def tracer(self) -> Any:- return None-- def stream_writer_manager(self):- return None-- def callback_manager(self):- return None-- def session_id(self) -> str:- return self._sid-- def checkpointer(self):- return None---class DemoSession(Session):- def __init__(self, sid: Optional[str] = None):- self._sid = sid or f"demo-{int(time.time() * 1000)}"- self._exec_id = f"exec-{self._sid}"- self._state: Dict[str, Any] = {}- self._global_state: Dict[str, Any] = {}- self._base = _DummyBaseSession(self._sid)-- def base(self) -> BaseSession:- return self._base-- def session_id(self) -> str:- return self._sid-- def exec_id(self) -> str:- return self._exec_id-- def get(self, key: str, default=None):- return self._state.get(key, default)-- def set(self, key: str, value: Any) -> None:- self._state[key] = value-- def get_global(self, key: str, default=None):- return self._global_state.get(key, default)-- def set_global(self, key: str, value: Any) -> None:- self._global_state[key] = value---# =============================================================================-# A simple local Tool-# =============================================================================-class AddLocalTool(Tool):- def __init__(self):- super().__init__(- card=ToolCard(- id="tool.add_local",- name="add_local",- description="(Local) Add two numbers and return the sum.",- input_params={- "type": "object",- "properties": {- "a": {"type": "number", "description": "first number"},- "b": {"type": "number", "description": "second number"},- },- "required": ["a", "b"],- },- )- )-- async def invoke(self, a: float, b: float, **kwargs) -> str:- return str(a + b)---# =============================================================================-# MCP Server Registry - Configure YOUR MCP servers here-# =============================================================================-# Only this server is exposed as a sub-agent; all other enabled servers are main-agent tools.-BROWSER_MCP_KEY = "browser_cdp"--# Add/remove servers based on what you have running-# Format: (server_name, default_port, description, system_prompt_snippet)-AVAILABLE_MCP_SERVERS = {- "browser_cdp": {- "server_name": "browser-use-cdp-server",- "port": 8930,- "description": "Browser automation using CDP. Input: {'query': string with browser task}.",- "prompt": (- "You are a browser automation sub-agent.\n"- "You have access to browser MCP tools for web interaction.\n"- "When given a browser task:\n"- "1. Use the available MCP tools to complete it\n"- "2. Return clear, concise results about what you observed\n"- ),- "enabled": True, # Set to False to disable- },- "vision": {- "server_name": "vision-mcp-server",- "port": 8932,- "description": "Vision/VQA for image analysis. Input: {'query': string with image path/url and question}.",- "prompt": (- "You are a vision analysis sub-agent.\n"- "You can analyze images and answer questions about visual content.\n"- "Provide detailed descriptions and insights.\n"- ),- "enabled": False, # Enable if server is running- },- "reasoning": {- "server_name": "reasoning-mcp-server",- "port": 8934,- "description": "Complex reasoning tasks. Input: {'query': string with problem}.",- "prompt": (- "You are a reasoning sub-agent.\n"- "You can perform complex multi-step reasoning and problem solving.\n"- "Break down problems and solve them systematically.\n"- ),- "enabled": True,- },- "searching": {- "server_name": "searching-mcp-server",- "port": 8936,- "description": "Web search. Input: {'query': string with search query}.",- "prompt": (- "You are a web search sub-agent.\n"- "You can search the web and retrieve relevant information.\n"- "Provide comprehensive and accurate search results.\n"- ),- "enabled": True,- },-}---# =============================================================================-# Sub-agent builder for MCP servers-# =============================================================================-def build_mcp_sub_agent(- agent_id: str,- agent_name: str,- description: str,- system_prompt: str,- provider: str,- api_key: str,- api_base: str,- model_name: str,- mcp_cfg: McpServerConfig-) -> ReActAgent:- """- Build a sub-agent that uses MCP tools from a specific server.- """- card = AgentCard(- id=agent_id,- name=agent_name,- description=description,- input_params={},- )-- return ReActAgent(card=card).configure(- ReActAgentConfig()- .configure_model_client(- provider=provider,- api_key=api_key,- api_base=api_base,- model_name=model_name,- )- .configure_max_iterations(8)- .configure_prompt_template(- [- {- "role": "system",- "content": system_prompt,- }- ]- )- )---# =============================================================================-# MCP config helper (supports different McpServerConfig field names)-# =============================================================================-def make_mcp_config(- server_id: str,- server_name: str,- host: str,- port: int,- transport: str = "sse",-) -> McpServerConfig:- fields = getattr(McpServerConfig, "model_fields", None) or getattr(McpServerConfig, "__fields__", {})- def has(k: str) -> bool:- try:- return k in fields- except Exception:- return False-- base_http = f"http://{host}:{port}"- sse_url = f"{base_http}/sse"-- payload: Dict[str, Any] = {}- if has("server_id"):- payload["server_id"] = server_id- elif has("id"):- payload["id"] = server_id-- if has("name"):- payload["name"] = server_name-- if has("transport"):- payload["transport"] = transport-- # required in your env: server_path- if has("server_path"):- payload["server_path"] = sse_url-- # compat fields (if exist)- if has("url"):- payload["url"] = sse_url- if has("base_url"):- payload["base_url"] = base_http- if has("host"):- payload["host"] = host- if has("port"):- payload["port"] = port- if has("server_name") and "server_name" not in payload:- payload["server_name"] = server_name- if has("client_type"):- payload["client_type"] = transport # "sse" for SSE endpoints-- # filter unknown fields for pydantic v1/v2- try:- payload = {k: v for k, v in payload.items() if has(k)}- except Exception:- pass-- return McpServerConfig(**payload)---async def register_mcp_server_to_resource_mgr(mcp_cfg: McpServerConfig, tag: str):- """Register MCP server to ResourceManager.-- Returns the Result from add_mcp_server. Caller should check .is_ok() and only- add to ability_manager when True (so failed servers are not offered as tools).- """- rm = Runner.resource_mgr- if not hasattr(rm, "add_mcp_server"):- raise RuntimeError("Runner.resource_mgr has no method add_mcp_server() in this version.")- return await rm.add_mcp_server(mcp_cfg, tag=tag)---# =============================================================================-# Main Agent: registers local tool + MCP sub-agents-# =============================================================================-async def build_main_agent_with_mcp_subs(- provider: str,- api_key: str,- api_base: str,- model_name: str,- mcp_host: str = "127.0.0.1",-) -> ReActAgent:- """Build main agent with direct MCP tools (non-browser) and one browser sub-agent."""-- # Direct MCP tools on main agent (all enabled except browser)- main_agent_mcp = [- f"- {key}: {info['description']}"- for key, info in AVAILABLE_MCP_SERVERS.items()- if info["enabled"] and key != BROWSER_MCP_KEY- ]- main_mcp_desc = "\n".join(main_agent_mcp) if main_agent_mcp else " (none enabled)"- # Sub-agent: only browser- sub_agent_desc = (- "- browser_cdp_sub: Browser automation. For browser tasks, call this sub-agent."- if AVAILABLE_MCP_SERVERS.get(BROWSER_MCP_KEY, {}).get("enabled")- else " (none)"- )-- main_card = AgentCard(- id="agent.main",- name="main_agent",- description="Main agent with local tools, MCP tools, and browser sub-agent.",- input_params={},- )-- agent = ReActAgent(card=main_card).configure(- ReActAgentConfig()- .configure_model_client(- provider=provider,- api_key=api_key,- api_base=api_base,- model_name=model_name,- )- .configure_max_iterations(10)- .configure_prompt_template(- [- {- "role": "system",- "content": (- "You are a main orchestrator agent with multiple capabilities:\n\n"- "Local tools:\n"- "- add_local: Add two numbers\n\n"- "MCP tools (use these directly):\n"- f"{main_mcp_desc}\n\n"- "Sub-agent (delegate browser tasks only):\n"- f"{sub_agent_desc}\n\n"- "For browser tasks, call the browser_cdp_sub sub-agent."- " For other tasks, use the MCP tools or add_local.\n"- "Then provide a final natural language answer to the user.\n"- ),- }- ]- )- )-- # Register local tool- add_local = AddLocalTool()- Runner.resource_mgr.add_tool(add_local, tag=agent.card.id)- agent.ability_manager.add(add_local.card)-- # Register enabled MCP servers: browser as sub-agent, rest as main-agent tools- for key, config in AVAILABLE_MCP_SERVERS.items():- if not config["enabled"]:- continue-- mcp_cfg = make_mcp_config(- server_id=key,- server_name=config["server_name"],- host=mcp_host,- port=config["port"],- )-- if key == BROWSER_MCP_KEY:- # Browser: sub-agent only- print(f" Registering sub-agent {key}_sub at port {config['port']} (browser)...")- await register_mcp_server_to_resource_mgr(mcp_cfg, tag=f"agent.{key}_sub")- sub_agent = build_mcp_sub_agent(- agent_id=f"agent.{key}_sub",- agent_name=f"{key}_sub",- description=config["description"],- system_prompt=config["prompt"],- provider=provider,- api_key=api_key,- api_base=api_base,- model_name=model_name,- mcp_cfg=mcp_cfg,- )- sub_agent.ability_manager.add(mcp_cfg)- Runner.resource_mgr.add_agent(sub_agent.card, lambda a=sub_agent: a, tag=agent.card.id)- agent.ability_manager.add(sub_agent.card)- else:- # Non-browser: main agent MCP tools (only add to ability_manager if registration succeeded)- print(f" Registering MCP tools for main agent: {key} at port {config['port']}...")- result = await register_mcp_server_to_resource_mgr(mcp_cfg, tag=agent.card.id)- if result is not None and getattr(result, "is_ok", lambda: False)():- agent.ability_manager.add(mcp_cfg)- else:- err = getattr(result, "value", result) if result is not None else "connection failed"- print(f" [WARN] Skipping {key} (MCP server not available): {err}")-- return agent---# =============================================================================-# Run (assumes MCP servers are started manually)-# =============================================================================-async def main():- # Start the runner first (required for MCP resource manager)- await Runner.start()-- # Get credentials from environment (OpenRouter or OpenAI)- # When MODEL_PROVIDER=openrouter, use OpenRouter key/base; otherwise OpenAI.- model_provider = (os.getenv("MODEL_PROVIDER") or "OpenAI").strip().lower()- if model_provider == "openrouter":- api_key = (os.getenv("OPENROUTER_API_KEY") or os.getenv("OPENAI_API_KEY") or "").strip()- api_base = (os.getenv("OPENROUTER_BASE_URL") or "https://openrouter.ai/api/v1").strip()- model_name = (os.getenv("MODEL_NAME") or "anthropic/claude-sonnet-4").strip()- # openjiuwen Model only accepts OpenAI, SiliconFlow, DashScope; OpenRouter is OpenAI-compatible- provider = "OpenAI"- else:- api_key = (os.getenv("OPENAI_API_KEY") or "").strip()- api_base = (os.getenv("OPENAI_BASE_URL") or "https://api.openai.com/v1").strip()- model_name = (os.getenv("MODEL_NAME") or "gpt-4o-mini").strip()- provider = "OpenAI"-- # MCP server host- mcp_host = os.getenv("MCP_SERVER_HOST", "127.0.0.1")-- print(f"\n{'='*70}")- print(f"Testing Main Agent + MCP Sub-Agents")- print(f"{'='*70}")- print(f"Backend: {model_provider} (client provider: {provider})")- print(f"Model: {model_name}")- print(f"MCP Host: {mcp_host}")- if not api_key:- raise RuntimeError(- "No API key found. Set OPENROUTER_API_KEY (for OpenRouter) or OPENAI_API_KEY (for OpenAI) in .env"- )- print(f"\nEnabled MCP Servers:")- for key, info in AVAILABLE_MCP_SERVERS.items():- if not info["enabled"]:- print(f" ⏭️ {key:15} @ port {info['port']} - disabled")- elif key == BROWSER_MCP_KEY:- print(f" ✅ {key:15} @ port {info['port']} - sub-agent (browser)")- else:- print(f" ✅ {key:15} @ port {info['port']} - main agent tools")- print(f"{'='*70}\n")-- # Build main agent (direct MCP tools + browser sub-agent)- print("Building main agent (MCP tools + browser sub-agent)...")- agent = await build_main_agent_with_mcp_subs(- provider=provider,- api_key=api_key,- api_base=api_base,- model_name=model_name,- mcp_host=mcp_host,- )-- print("\nDiscovering available tools and sub-agents...")- tools = await agent.ability_manager.list_tool_info()- print(f"✅ Main agent has {len(tools)} capabilities\n")-- # Show available capabilities- print("Main agent capabilities:")- for tool in tools:- tool_name = getattr(tool, 'name', 'unknown')- tool_desc = getattr(tool, 'description', '')[:100]- print(f" - {tool_name}: {tool_desc}")- print()-- # Default: main agent uses an MCP tool directly (reasoning or search), not a local tool.- # Override with EXAMPLE_QUERY env var- # (e.g. for browser sub-agent: "Open https://example.com and tell me the title").- query = (- "Use the reasoning tool to solve: if 3x + 5 = 14, what is x? Reply with the value of x.\n"- "Use that value of x to open https://www.roastful.com/top-roasters#top-50"- " and find the position of the roaster on the list.\n"- "Reply with the name of the roaster that sits in that position."- )- print(f"Test Query: {query}\n")- print("Running main agent (will call MCP tools or delegate to sub-agent as needed)...\n")-- result = await agent.invoke({"query": query}, session=None)-- print("\n" + "=" * 70)- print("FINAL RESULT")- print("=" * 70)- print(result)- print("=" * 70)---if __name__ == "__main__":- try:- asyncio.run(main())- except RuntimeError as e:- # Swallow the specific MCP/anyio shutdown bug so tests can continue- if "Attempted to exit cancel scope in a different task than it was entered in" in str(e):- print(f"Ignoring MCP shutdown error: {e}", file=sys.stderr)- else:- # Re-raise anything else so real errors still fail- raisediff --git a/jiuwenswarm/agents/harness/common/tools/browser_start_client.py b/jiuwenswarm/agents/harness/common/tools/browser_start_client.pyindex 642002f9b0..4ccb68b52c 100644--- a/jiuwenswarm/agents/harness/common/tools/browser_start_client.py+++ b/jiuwenswarm/agents/harness/common/tools/browser_start_client.py@@ -28,6 +28,7 @@ import osimport platformimport shutilimport subprocess+import sysfrom pathlib import Pathfrom typing import Any@@ -281,8 +282,8 @@ def start_browser(*, dry_run: bool = False, config_file: str = "") -> int:kwargs["start_new_session"] = Trueif dry_run:- print("Dry run: browser launch command prepared.")- print(" ".join(args))+ logger.info("Dry run: browser launch command prepared.")+ logger.info(" ".join(args))return 0logger.info(@@ -298,9 +299,9 @@ def start_browser(*, dry_run: bool = False, config_file: str = "") -> int:user_data_dir=user_data_dir,profile_directory=profile_directory,)- print(f"Chrome started (pid={proc.pid}) at {host}:{port}")- print(f"Executable: {chrome_exec}")- print(f"Profile dir: {user_data_dir}")+ logger.info(f"Chrome started (pid={proc.pid}) at {host}:{port}")+ logger.info(f"Executable: {chrome_exec}")+ logger.info(f"Profile dir: {user_data_dir}")return 0@@ -320,7 +321,7 @@ def main() -> int:try:return start_browser(dry_run=args.dry_run, config_file=args.config)except Exception as exc:- print(f"Failed to start Chrome: {exc}", file=sys.stderr)+ logger.info(f"Failed to start Chrome: {exc}", file=sys.stderr)return 1diff --git a/jiuwenswarm/init_workspace.py b/jiuwenswarm/init_workspace.pyindex 1a96026d82..bbd98ac307 100644--- a/jiuwenswarm/init_workspace.py+++ b/jiuwenswarm/init_workspace.py@@ -54,18 +54,18 @@ def run_init(force: bool = False, name: Optional[str] = None) -> int:if name:validation_error = validate_instance_name(name)if validation_error:- print(f"[jiuwenswarm-init] ERROR: {validation_error}")+ logging.info(f"[jiuwenswarm-init] ERROR: {validation_error}")return 1# 2. Determine target workspace path and set env varif name:workspace_path = get_instance_workspace_path(name)- print(f"[jiuwenswarm-init] Creating instance: {name}")- print(f"[jiuwenswarm-init] Workspace: {workspace_path}")+ logging.info(f"[jiuwenswarm-init] Creating instance: {name}")+ logging.info(f"[jiuwenswarm-init] Workspace: {workspace_path}")else:workspace_path = get_user_home() / ".jiuwenswarm"- print(f"[jiuwenswarm-init] Initializing default workspace")- print(f"[jiuwenswarm-init] Workspace: {workspace_path}")+ logging.info(f"[jiuwenswarm-init] Initializing default workspace")+ logging.info(f"[jiuwenswarm-init] Workspace: {workspace_path}")# 3. Check if instance is running (for named instances, always check)if name:@@ -79,15 +79,15 @@ def run_init(force: bool = False, name: Optional[str] = None) -> int:status = get_instance_status(config)if status.running:- print(f"[jiuwenswarm-init] ERROR: Instance '{name}' is running (PID={status.pid}).")- print(f"[jiuwenswarm-init] Stop it first with: jiuwenswarm-start --stop {name}")+ logging.info(f"[jiuwenswarm-init] ERROR: Instance '{name}' is running (PID={status.pid}).")+ logging.info(f"[jiuwenswarm-init] Stop it first with: jiuwenswarm-start --stop {name}")return 1elif force:# For default instance, use get_default_instance_status which includes port detectionstatus = get_default_instance_status()if status.running:- print(f"[jiuwenswarm-init] ERROR: Default instance is running (PID={status.pid or '-'}).")- print(f"[jiuwenswarm-init] Stop it first with: jiuwenswarm-start --stop default")+ logging.info(f"[jiuwenswarm-init] ERROR: Default instance is running (PID={status.pid or '-'}).")+ logging.info(f"[jiuwenswarm-init] Stop it first with: jiuwenswarm-start --stop default")return 1# 4. Call init_user_workspace with workspace path@@ -106,14 +106,14 @@ def run_init(force: bool = False, name: Optional[str] = None) -> int:# Create bootstrap .env with the same portsconfig = InstanceConfig(name=name, workspace=workspace_path, ports=ports)create_bootstrap_env(config)-- print(f"[jiuwenswarm-init] Instance '{name}' initialized successfully.")+ logging.info(f"[jiuwenswarm-init] Instance '{name}' initialized successfully.")return 0if target == "cancelled":return 1- print(f"[jiuwenswarm-init] initialized: {target}")+ logging.info(f"[jiuwenswarm-init] initialized: {target}")+return 0diff --git a/jiuwenswarm/start_services.py b/jiuwenswarm/start_services.pyindex 5fe34bdc84..3797ec088b 100644--- a/jiuwenswarm/start_services.py+++ b/jiuwenswarm/start_services.py@@ -15,6 +15,7 @@ Multi-instance management commands:from __future__ import annotationsimport argparse+import loggingimport osimport signalimport subprocess@@ -108,14 +109,15 @@ class InstanceCommand:# Validate instance nameerror = validate_instance_name(self.name)if error:- print(f"[start_services] ERROR: {error}")+ logging.info(f"[start_services] ERROR: {error}")return 1# Load instance config from instances.yamlself.config = get_instance_config(self.name)if self.config is None:- print(f"[start_services] ERROR: Instance '{self.name}' not found in instances.yaml")- print(f"[start_services] Run 'jiuwenswarm-init --name {self.name}' to create it.")+ logging.info(f"[start_services] ERROR: Instance '{self.name}' not found in instances.yaml")+ logging.info(f"[start_services] Run 'jiuwenswarm-init --name {self.name}' to create it.")+return 1# Get current status@@ -131,8 +133,9 @@ class InstanceCommand:if self.config is None:return 1if not self.config.workspace.exists():- print(f"[start_services] ERROR: Workspace directory not found: {self.config.workspace}")- print(f"[start_services] Run 'jiuwenswarm-init --name {self.name}' to create it.")+ logging.info(f"[start_services] ERROR: Workspace directory not found: {self.config.workspace}")+ logging.info(f"[start_services] Run 'jiuwenswarm-init --name {self.name}' to create it.")+return 1return None@@ -155,18 +158,18 @@ class InstanceCommand:if self.config is None:return 1- print(f"[start_services] Checking ports for instance '{self.name}'...")+ logging.info(f"[start_services] Checking ports for instance '{self.name}'...")conflicts = []for port_type, port in self.config.ports.items():if not is_port_available("127.0.0.1", port):conflicts.append((port_type, port))- print(f" ✗ {port_type}: {port} - already in use")+ logging.info(f" ✗ {port_type}: {port} - already in use")else:- print(f" ✓ {port_type}: {port} - available")+ logging.info(f" ✓ {port_type}: {port} - available")if conflicts:- print("[start_services] ERROR: Port conflicts detected, cannot start instance.")+ logging.info("[start_services] ERROR: Port conflicts detected, cannot start instance.")return 1return None@@ -178,19 +181,20 @@ def print_instance_details(status: InstanceStatus) -> None:Args:status: InstanceStatus to display"""- print(f"Instance: {status.name}")- print(f"Status: {'running' if status.running else 'stopped'}")- print(f"PID: {status.pid or '-'}")- print(f"Workspace: {status.workspace}")- print("Ports:")+ logging.info(f"Instance: {status.name}")+ logging.info(f"Status: {'running' if status.running else 'stopped'}")+ logging.info(f"PID: {status.pid or '-'}")+ logging.info(f"Workspace: {status.workspace}")+ logging.info("Ports:")+for port_type in PORT_TYPES:port = status.ports.get(port_type, 0)- print(f" {port_type}: {port}")+ logging.info(f" {port_type}: {port}")if status.started_at:from datetime import datetimestarted_dt = datetime.fromtimestamp(status.started_at)- print(f"Started at: {started_dt.isoformat()}")+ logging.info(f"Started at: {started_dt.isoformat()}")def do_stop_instance(cmd: InstanceCommand) -> int:@@ -206,7 +210,7 @@ def do_stop_instance(cmd: InstanceCommand) -> int:return 1pid = cmd.status.pid- print(f"[start_services] Stopping instance '{cmd.name}' (PID={pid})...")+ logging.info(f"[start_services] Stopping instance '{cmd.name}' (PID={pid})...")if cmd.is_default:success = stop_process_by_pid(pid, timeout=10.0)@@ -214,10 +218,10 @@ def do_stop_instance(cmd: InstanceCommand) -> int:success = stop_instance_process(cmd.config, timeout=10.0)if success:- print(f"[start_services] Instance '{cmd.name}' stopped.")+ logging.info(f"[start_services] Instance '{cmd.name}' stopped.")return 0else:- print(f"[start_services] Failed to stop instance '{cmd.name}'.")+ logging.info(f"[start_services] Failed to stop instance '{cmd.name}'.")return 1@@ -238,7 +242,7 @@ def _run_instance_with_pid(commands: list[tuple[str, list[str], Path]],processes[cmd_name] = _start_process(cmd_name, cmd_args, cwd)write_pid_file(config, os.getpid(), time.time())- print(f"[start_services] Instance '{config.name}' started")+ logging.info(f"[start_services] Instance '{config.name}' started")_wait_for_services_ready(config.ports, processes)@@ -246,12 +250,12 @@ def _run_instance_with_pid(commands: list[tuple[str, list[str], Path]],for cmd_name, proc in processes.items():code = proc.poll()if code is not None:- print(f"[start_services] {cmd_name} exited with code {code}")+ logging.info(f"[start_services] {cmd_name} exited with code {code}")return codetime.sleep(0.5)except KeyboardInterrupt:- print("\n[start_services] Keyboard interrupt received, shutting down...")+ logging.info("\n[start_services] Keyboard interrupt received, shutting down...")return 130finally:_terminate_processes(processes)@@ -300,7 +304,7 @@ def _build_commands(mode: str, dotenv_path: Path | None = None) -> list[tuple[stdef _start_process(name: str, cmd: list[str], cwd: Path) -> subprocess.Popen[bytes]:"""Start a single subprocess."""import json- print(f"[start_services] starting {name}: {' '.join(cmd)} (cwd={cwd})")+ logging.info(f"[start_services] starting {name}: {' '.join(cmd)} (cwd={cwd})")env = os.environ.copy()env["JIUWENSWARM_START_CMD"] = json.dumps(sys.argv[:])return subprocess.Popen(cmd, cwd=str(cwd), env=env)@@ -310,7 +314,7 @@ def _terminate_processes(processes: dict[str, subprocess.Popen[bytes]]) -> None:"""Terminate all running processes gracefully."""for name, proc in processes.items():if proc.poll() is None:- print(f"[start_services] terminating {name} (pid={proc.pid})")+ logging.info(f"[start_services] terminating {name} (pid={proc.pid})")proc.terminate()deadline = time.time() + 8@@ -321,7 +325,7 @@ def _terminate_processes(processes: dict[str, subprocess.Popen[bytes]]) -> None:for name, proc in processes.items():if proc.poll() is None:- print(f"[start_services] killing {name} (pid={proc.pid})")+ logging.info(f"[start_services] killing {name} (pid={proc.pid})")proc.kill()@@ -358,9 +362,9 @@ def _wait_for_services_ready(ports: dict[str, int], processes: dict[str, subprocpath_suffix = "/ws" if port_key == "web" else ""if _check_port(port):- print(f"[start_services] ✓ {svc_name} ready at {url_prefix}127.0.0.1:{port}{path_suffix}")+ logging.info(f"[start_services] ✓ {svc_name} ready at {url_prefix}127.0.0.1:{port}{path_suffix}")else:- print(f"[start_services] ⏳ {svc_name} starting... (port {port})")+ logging.info(f"[start_services] ⏳ {svc_name} starting... (port {port})")def _run_processes(commands: list[tuple[str, list[str], Path]]) -> int:@@ -381,11 +385,11 @@ def _run_processes(commands: list[tuple[str, list[str], Path]]) -> int:for name, proc in processes.items():code = proc.poll()if code is not None:- print(f"[start_services] {name} exited with code {code}")+ logging.info(f"[start_services] {name} exited with code {code}")return codetime.sleep(0.5)except KeyboardInterrupt:- print("\n[start_services] keyboard interrupt received, shutting down...")+ logging.info("\n[start_services] keyboard interrupt received, shutting down...")return 130finally:_terminate_processes(processes)@@ -395,7 +399,7 @@ def _run(mode: str) -> int:"""Run default instance (existing behavior)."""commands = _build_commands(mode)if not commands:- print(f"[start_services] no commands to run for mode: {mode}")+ logging.info(f"[start_services] no commands to run for mode: {mode}")return 2return _run_processes(commands)@@ -409,16 +413,17 @@ def _action_list() -> int:statuses = list_all_instances(include_default=True)if not statuses:- print("[start_services] No instances configured.")- print("[start_services] Run 'jiuwenswarm-init' to initialize default instance.")+ logging.info("[start_services] No instances configured.")+ logging.info("[start_services] Run 'jiuwenswarm-init' to initialize default instance.")+return 0# Print table header- print("INSTANCE STATUS PID WORKSPACE PORTS")- print("-" * 80)+ logging.info("INSTANCE STATUS PID WORKSPACE PORTS")+ logging.info("-" * 80)for status in statuses:- print(format_status_line(status))+ logging.info(format_status_line(status))return 0@@ -459,7 +464,7 @@ def _action_stop(name: str) -> int:if running is None:return 1if not running:- print(f"[start_services] Instance '{name}' is not running.")+ logging.info(f"[start_services] Instance '{name}' is not running.")return 0# Execute stop@@ -476,7 +481,7 @@ def _action_restart(name: str, mode: str = "all") -> int:Returns:Exit code"""- print(f"[start_services] Restarting instance '{name}'...")+ logging.info(f"[start_services] Restarting instance '{name}'...")# Validate and load first (common check for both stop and start)cmd = InstanceCommand(name)@@ -488,7 +493,7 @@ def _action_restart(name: str, mode: str = "all") -> int:if cmd.check_running():stop_result = do_stop_instance(cmd)if stop_result != 0:- print("[start_services] Restart aborted: stop failed.")+ logging.info("[start_services] Restart aborted: stop failed.")return stop_result# Wait for process to fully exittime.sleep(1)@@ -500,10 +505,10 @@ def _action_restart(name: str, mode: str = "all") -> int:start_result = _start_named_instance(name, mode)if start_result != 0:- print("[start_services] Restart failed: start failed.")+ logging.info("[start_services] Restart failed: start failed.")return start_result- print(f"[start_services] Instance '{name}' restarted.")+ logging.info(f"[start_services] Instance '{name}' restarted.")return 0@@ -523,7 +528,7 @@ def _start_named_instance(name: str, mode: str) -> int:if cmd.check_workspace_exists():return 1if cmd.check_running():- print(f"[start_services] ERROR: Instance '{cmd.name}' is already running (PID={cmd.status.pid})")+ logging.info(f"[start_services] ERROR: Instance '{cmd.name}' is already running (PID={cmd.status.pid})")return 1if cmd.check_ports_available():return 1@@ -535,15 +540,15 @@ def _start_named_instance(name: str, mode: str) -> int:# Acquire startup lock to prevent concurrent startslock = InstanceLock(config)if not lock.acquire(timeout=5.0):- print(f"[start_services] ERROR: Instance '{name}' startup in progress by another process")- print(f"[start_services] Wait a few seconds or check if another terminal is starting this instance.")+ logging.info(f"[start_services] ERROR: Instance '{name}' startup in progress by another process")+ logging.info(f"[start_services] Wait a few seconds or check if another terminal is starting this instance.")return 1try:dotenv_path = create_bootstrap_env(config)commands = _build_commands(mode, dotenv_path)if not commands:- print(f"[start_services] ERROR: No commands for mode: {mode}")+ logging.info(f"[start_services] ERROR: No commands for mode: {mode}")return 2return _run_instance_with_pid(commands, config)@@ -606,7 +611,7 @@ def _validate_args(args: argparse.Namespace) -> int | None:# Additional validation: --restart needs valid modeif args.restart and args.mode not in ("all", "app", "web"):- print(f"[start_services] ERROR: Invalid mode '{args.mode}' for --restart")+ logging.info(f"[start_services] ERROR: Invalid mode '{args.mode}' for --restart")return 1return None