diff --git a/capiscio_sdk/connect.py b/capiscio_sdk/connect.py index c731027..2186d13 100644 --- a/capiscio_sdk/connect.py +++ b/capiscio_sdk/connect.py @@ -285,21 +285,24 @@ def connect(self) -> AgentIdentity: def _ensure_agent(self) -> Dict[str, Any]: """Find existing agent or create new one.""" - if self.agent_id: - # Fetch specific agent - resp = self._client.get(f"/v1/agents/{self.agent_id}") - if resp.status_code == 200: - data = resp.json() - return data.get("data", data) - elif resp.status_code == 404: - raise ValueError(f"Agent {self.agent_id} not found") - else: - raise RuntimeError(f"Failed to fetch agent: {resp.text}") - - # List agents and find by name or use first one - resp = self._client.get("/v1/agents") - if resp.status_code != 200: - raise RuntimeError(f"Failed to list agents: {resp.text}") + try: + if self.agent_id: + # Fetch specific agent + resp = self._client.get(f"/v1/agents/{self.agent_id}") + if resp.status_code == 200: + data = resp.json() + return data.get("data", data) + elif resp.status_code == 404: + raise ValueError(f"Agent {self.agent_id} not found") + else: + raise RuntimeError(f"Failed to fetch agent (status {resp.status_code})") + + # List agents and find by name or use first one + resp = self._client.get("/v1/agents") + if resp.status_code != 200: + raise RuntimeError(f"Failed to list agents (status {resp.status_code})") + except httpx.RequestError as e: + raise RuntimeError(f"Network error connecting to server: {type(e).__name__}") from e data = resp.json() agents = data.get("data", data) if isinstance(data.get("data", data), list) else [] @@ -321,13 +324,16 @@ def _create_agent(self) -> Dict[str, Any]: """Create a new agent.""" name = self.name or f"Agent-{os.urandom(4).hex()}" - resp = self._client.post("/v1/agents", json={ - "name": name, - "protocol": "a2a", - }) + try: + resp = self._client.post("/v1/agents", json={ + "name": name, + "protocol": "a2a", + }) + except httpx.RequestError as e: + raise RuntimeError(f"Network error creating agent: {type(e).__name__}") from e if resp.status_code not in (200, 201): - raise RuntimeError(f"Failed to create agent: {resp.text}") + raise RuntimeError(f"Failed to create agent (status {resp.status_code})") data = resp.json() logger.info(f"Created new agent: {name}") diff --git a/tests/unit/test_connect.py b/tests/unit/test_connect.py index 5ffdc8e..07f4a1c 100644 --- a/tests/unit/test_connect.py +++ b/tests/unit/test_connect.py @@ -2,6 +2,7 @@ import os import pytest +import httpx from pathlib import Path from unittest.mock import MagicMock, patch @@ -568,6 +569,40 @@ def test_create_agent_failure(self): with pytest.raises(RuntimeError, match="Failed to create agent"): connector._create_agent() + def test_ensure_agent_network_error(self): + """Test _ensure_agent handles network errors gracefully.""" + connector = _Connector( + api_key="sk_test", + name=None, + agent_id="some-agent", + server_url="https://test.server.com", + keys_dir=None, + auto_badge=True, + dev_mode=False, + ) + + connector._client.get = MagicMock(side_effect=httpx.ConnectError("Connection refused")) + + with pytest.raises(RuntimeError, match="Network error connecting to server"): + connector._ensure_agent() + + def test_create_agent_network_error(self): + """Test _create_agent handles network errors gracefully.""" + connector = _Connector( + api_key="sk_test", + name="Test", + agent_id=None, + server_url="https://test.server.com", + keys_dir=None, + auto_badge=True, + dev_mode=False, + ) + + connector._client.post = MagicMock(side_effect=httpx.TimeoutException("Timeout")) + + with pytest.raises(RuntimeError, match="Network error creating agent"): + connector._create_agent() + def test_connect_full_flow(self, tmp_path): """Test connect() executes full flow.""" connector = _Connector(