Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(api): keep discovery helpers sync under ASGI
cyh333a13e91ab3
diff --git a/tests/test_im_proxy_unification.py b/tests/test_im_proxy_unification.pyindex 65aa7de5b..a9f1a0e44 100644--- a/tests/test_im_proxy_unification.py+++ b/tests/test_im_proxy_unification.py@@ -271,6 +271,35 @@ def test_discord_api_get_via_aiohttp_raises_for_status() -> None:raise_for_status.assert_called_once()+def test_discord_api_get_sync_path_works_inside_active_event_loop() -> None:+ """Live discovery is sync code that may run on FastAPI's ASGI loop.++ The sync helper must not bridge through run_coroutine_blocking(), which+ intentionally raises inside an active loop.+ """+ import asyncio++ from unittest.mock import MagicMock++ from vibe import api as vibe_api++ fake_resp_cm = MagicMock()+ fake_resp_cm.__enter__ = MagicMock(+ return_value=MagicMock(read=MagicMock(return_value=b'[{"id":"c1","name":"general"}]'))+ )+ fake_resp_cm.__exit__ = MagicMock(return_value=None)+ fake_opener = MagicMock()+ fake_opener.open = MagicMock(return_value=fake_resp_cm)++ async def exercise():+ with patch("urllib.request.build_opener", return_value=fake_opener):+ return vibe_api._discord_api_get("bot-token", "guilds/g1/channels")++ result = asyncio.run(exercise())++ assert result == [{"id": "c1", "name": "general"}]++# ---------------------------------------------------------------------------# telegram_auth_test must call resolve_proxy() (regression for round-2 review)# ---------------------------------------------------------------------------@@ -370,25 +399,22 @@ def test_lark_auth_test_falls_back_to_system_proxy() -> None:assert captured["proxy_url"] == "socks5://system:1080"-def test_lark_tenant_token_uses_aiohttp_for_socks() -> None:- """SOCKS proxy_url branches into the aiohttp helper, not urllib."""- import asyncio-- from unittest.mock import AsyncMock+def test_lark_tenant_token_uses_sync_socks_helper_for_socks() -> None:+ """SOCKS proxy_url branches into the sync SOCKS helper, not urllib."""from vibe import api as vibe_api- aiohttp_called = {"hit": False}+ socks_called = {"hit": False}- async def fake_aiohttp(url, body, headers, proxy):- aiohttp_called["hit"] = True- aiohttp_called["proxy"] = proxy+ def fake_socks(proxy, url, *, method="GET", body=None, headers=None, timeout=10):+ socks_called["hit"] = True+ socks_called["proxy"] = proxyreturn {"code": 0, "tenant_access_token": "tok-from-socks"}def fail_urlopen(*args, **kwargs):raise AssertionError("urllib should not be used for SOCKS proxies")- with patch.object(vibe_api, "_lark_tenant_token_via_aiohttp", new=fake_aiohttp), patch(+ with patch.object(vibe_api, "_https_json_request_via_socks", new=fake_socks), patch("urllib.request.build_opener", side_effect=fail_urlopen):token = vibe_api._lark_tenant_token(@@ -396,11 +422,8 @@ def test_lark_tenant_token_uses_aiohttp_for_socks() -> None:)assert token == "tok-from-socks"- assert aiohttp_called["hit"] is True- assert aiohttp_called["proxy"] == "socks5://127.0.0.1:1080"- # touch asyncio so import is used in case lints flag it- assert asyncio.iscoroutinefunction(fake_aiohttp)- AsyncMock # unused-import guard+ assert socks_called["hit"] is True+ assert socks_called["proxy"] == "socks5://127.0.0.1:1080"def test_lark_tenant_token_uses_urllib_proxy_for_http() -> None:@@ -455,14 +478,39 @@ def test_lark_tenant_token_does_not_misroute_http_with_socks_hostname() -> None:fake_opener = MagicMock()fake_opener.open = MagicMock(return_value=fake_resp_cm)- def fail_aiohttp(*args, **kwargs):- raise AssertionError("aiohttp must not be used for HTTP proxies, even when hostname contains 'socks'")+ def fail_socks_helper(*args, **kwargs):+ raise AssertionError(+ "SOCKS helper must not be used for HTTP proxies, even when hostname contains 'socks'"+ )with patch("urllib.request.build_opener", return_value=fake_opener), patch.object(- vibe_api, "_lark_tenant_token_via_aiohttp", side_effect=fail_aiohttp+ vibe_api, "_https_json_request_via_socks", side_effect=fail_socks_helper):token = vibe_api._lark_tenant_token("cli_x", "secret", proxy_url="http://socks-gateway.corp:8080")assert token == "tok-via-http"+++def test_lark_tenant_token_sync_path_works_inside_active_event_loop() -> None:+ """Live Lark discovery is sync code and may run on FastAPI's ASGI loop."""+ import asyncio++ from unittest.mock import MagicMock++ from vibe import api as vibe_api++ fake_resp_cm = MagicMock()+ fake_resp_cm.__enter__ = MagicMock(+ return_value=MagicMock(read=MagicMock(return_value=b'{"code":0,"tenant_access_token":"tok-loop"}'))+ )+ fake_resp_cm.__exit__ = MagicMock(return_value=None)+ fake_opener = MagicMock()+ fake_opener.open = MagicMock(return_value=fake_resp_cm)++ async def exercise():+ with patch("urllib.request.build_opener", return_value=fake_opener):+ return vibe_api._lark_tenant_token("cli_x", "secret")++ assert asyncio.run(exercise()) == "tok-loop"diff --git a/vibe/api.py b/vibe/api.pyindex e8beae8e5..c30072a56 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -4,12 +4,15 @@ import loggingimport osimport reimport shutil+import sslimport subprocessimport sysimport threadingimport time+import urllib.parseimport urllib.requestimport uuid+from http.client import HTTPSConnectionfrom pathlib import Pathfrom typing import Any, Dict, List, Optional@@ -902,9 +905,29 @@ def opencode_options(cwd: str) -> dict:def _discord_api_get(bot_token: str, path: str, proxy_url: str | None = None) -> dict:- from vibe.async_bridge import run_coroutine_blocking+ import urllib.request++ from vibe.proxy import is_socks_proxy, resolve_proxy++ if not bot_token:+ raise ValueError("bot_token is required")+ url = f"https://discord.com/api/v10/{path.lstrip('/')}"+ headers = {"Authorization": f"Bot {bot_token}", "User-Agent": "vibe-remote"}++ proxy = resolve_proxy(proxy_url)+ if proxy and is_socks_proxy(proxy):+ return _https_json_request_via_socks(proxy, url, headers=headers)- return run_coroutine_blocking(_discord_api_get_async(bot_token, path, proxy_url=proxy_url))+ if proxy:+ opener = urllib.request.build_opener(+ urllib.request.ProxyHandler({"http": proxy, "https": proxy})+ )+ else:+ opener = urllib.request.build_opener()+ req = urllib.request.Request(url, headers=headers)+ with opener.open(req, timeout=10) as resp:+ payload = resp.read().decode("utf-8")+ return json.loads(payload)async def _discord_api_get_async(bot_token: str, path: str, proxy_url: str | None = None) -> dict:@@ -937,6 +960,40 @@ async def _discord_api_get_async(bot_token: str, path: str, proxy_url: str | Nonreturn await asyncio.to_thread(_request)+def _https_json_request_via_socks(+ proxy_url: str,+ url: str,+ *,+ method: str = "GET",+ body: bytes | None = None,+ headers: dict[str, str] | None = None,+ timeout: float = 10,+) -> dict:+ from python_socks.sync import Proxy++ parsed = urllib.parse.urlparse(url)+ if parsed.scheme != "https" or not parsed.hostname:+ raise ValueError("Only HTTPS URLs are supported")+ port = parsed.port or 443+ path = parsed.path or "/"+ if parsed.query:+ path = f"{path}?{parsed.query}"++ sock = Proxy.from_url(proxy_url).connect(parsed.hostname, port, timeout=timeout)+ tls_sock = ssl.create_default_context().wrap_socket(sock, server_hostname=parsed.hostname)+ conn = HTTPSConnection(parsed.hostname, port, timeout=timeout)+ conn.sock = tls_sock+ try:+ conn.request(method, path, body=body, headers=headers or {})+ resp = conn.getresponse()+ payload = resp.read().decode("utf-8")+ if resp.status < 200 or resp.status >= 300:+ raise urllib.error.HTTPError(url, resp.status, resp.reason, resp.headers, None)+ return json.loads(payload)+ finally:+ conn.close()++async def _discord_api_get_via_aiohttp(url: str, headers: dict, proxy: str) -> dict:import aiohttpfrom aiohttp_socks import ProxyConnector@@ -3750,11 +3807,36 @@ def _lark_tenant_token(domain: str = "feishu",proxy_url: str | None = None,) -> Optional[str]:- from vibe.async_bridge import run_coroutine_blocking+ import urllib.request- return run_coroutine_blocking(- _lark_tenant_token_async(app_id, app_secret, domain, proxy_url=proxy_url)- )+ from vibe.proxy import is_socks_proxy++ url = f"{_lark_api_base(domain)}/open-apis/auth/v3/tenant_access_token/internal"+ body = json.dumps({"app_id": app_id, "app_secret": app_secret}).encode()+ headers = {"Content-Type": "application/json"}++ if proxy_url and is_socks_proxy(proxy_url):+ result = _https_json_request_via_socks(+ proxy_url,+ url,+ method="POST",+ body=body,+ headers=headers,+ )+ else:+ if proxy_url:+ opener = urllib.request.build_opener(+ urllib.request.ProxyHandler({"http": proxy_url, "https": proxy_url})+ )+ else:+ opener = urllib.request.build_opener()+ req = urllib.request.Request(url, data=body, headers=headers)+ with opener.open(req, timeout=10) as resp:+ result = json.loads(resp.read().decode())++ if result.get("code") == 0:+ return result.get("tenant_access_token")+ return Noneasync def _lark_tenant_token_async(