Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 30 additions & 5 deletions limacharlie/sdk/ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
from .organization import Organization

_HIVE_SECRET_PREFIX = "hive://secret/"

# Fallback only. The real ai-sessions host is resolved per-org from the
# ``ai`` entry of ``orgs/{oid}/url`` (see :meth:`AI._get_ai_url`) because
# it differs by deployment -- e.g. staging orgs return
# ``ai-staging.limacharlie.io``.
_AI_SESSIONS_URL = "https://ai.limacharlie.io"


Expand All @@ -17,12 +22,32 @@ class AI:

def __init__(self, org: Organization) -> None:
self._org = org
self._ai_url: str | None = None

@property
def client(self) -> Any:
"""The underlying API client."""
return self._org.client

def _get_ai_url(self) -> str:
"""Resolve the ai-sessions base URL for this org.

The per-org service URLs (``orgs/{oid}/url``) carry an ``ai``
entry whose value depends on the deployment the org lives in
(production orgs resolve to ``ai.limacharlie.io``, staging orgs
to ``ai-staging.limacharlie.io``, etc.), so the host must not be
hardcoded. Mirrors the lazy, cached resolution used by
:class:`~limacharlie.sdk.search.Search`. Falls back to
:data:`_AI_SESSIONS_URL` only when the org URL set has no ``ai``
entry.
"""
if self._ai_url is None:
ai_url = self._org.get_urls().get("ai", "")
if ai_url and not ai_url.startswith(("http://", "https://")):
ai_url = "https://" + ai_url
self._ai_url = ai_url or _AI_SESSIONS_URL
return self._ai_url

def _resolve_secret(self, value: str) -> str:
"""Resolve a value that may be a hive://secret/ reference."""
if not value or not value.startswith(_HIVE_SECRET_PREFIX):
Expand Down Expand Up @@ -248,15 +273,15 @@ def start_session(self, definition_name: str, prompt: str | None = None,
raw_body=json.dumps(request_body).encode(),
content_type="application/json",
is_no_auth=True,
alt_root=_AI_SESSIONS_URL,
alt_root=self._get_ai_url(),
extra_headers=extra,
)

return self.client.request(
"POST", "v1/api/sessions",
raw_body=json.dumps(request_body).encode(),
content_type="application/json",
alt_root=_AI_SESSIONS_URL,
alt_root=self._get_ai_url(),
extra_headers=extra,
)

Expand Down Expand Up @@ -364,13 +389,13 @@ def _org_request(self, verb: str, path: str,
verb, path,
query_params=query_params,
is_no_auth=True,
alt_root=_AI_SESSIONS_URL,
alt_root=self._get_ai_url(),
extra_headers=extra,
)
return self.client.request(
verb, path,
query_params=query_params,
alt_root=_AI_SESSIONS_URL,
alt_root=self._get_ai_url(),
extra_headers=extra,
)

Expand Down Expand Up @@ -523,7 +548,7 @@ def _user_request(self, verb: str, path: str,
``claims.UID()`` alone; sending X-LC-OID is unnecessary here
and the routes don't accept raw API keys.
"""
kwargs: dict[str, Any] = {"alt_root": _AI_SESSIONS_URL}
kwargs: dict[str, Any] = {"alt_root": self._get_ai_url()}
if raw_body is not None:
kwargs["raw_body"] = raw_body
kwargs["content_type"] = "application/json"
Expand Down
10 changes: 6 additions & 4 deletions limacharlie/sdk/ai_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,13 @@ class SessionAttachment:
def __init__(self, ai: "AI", session_id: str, *,
read_only: bool = False,
base_url: str | None = None) -> None:
from .ai import _AI_SESSIONS_URL

self._ai = ai
self._session_id = session_id
self._read_only = read_only
self._base_url = base_url or _AI_SESSIONS_URL
# When no explicit override is supplied, resolve the per-org
# ai-sessions host lazily (in :meth:`url`) so we honour the org's
# deployment (prod vs staging) rather than a hardcoded host.
self._base_url = base_url
self._ws: Any = None
self._heartbeat_task: asyncio.Task | None = None

Expand All @@ -107,7 +108,8 @@ def read_only(self) -> bool:
return self._read_only

def url(self) -> str:
return _derive_ws_url(self._base_url, self._session_id, self._read_only)
base_url = self._base_url or self._ai._get_ai_url()
return _derive_ws_url(base_url, self._session_id, self._read_only)

# ------------------------------------------------------------------
# Connection lifecycle
Expand Down
55 changes: 55 additions & 0 deletions tests/unit/test_ai_session_attach.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,61 @@ def test_url_read_only_uses_org_endpoint(self):
)
assert att.url() == "wss://example.test/v1/ws/org/sessions/sid-42"

def test_url_resolves_from_org_ai_url_when_no_override(self):
"""With no explicit base_url, the attach URL is derived from the
org's resolved ai-sessions host (e.g. the staging deployment)
rather than a hardcoded production host.
"""
ai_stub = SimpleNamespace(
_get_ai_url=lambda: "https://ai-staging.limacharlie.io",
)
att = SessionAttachment(ai_stub, "sid-42")
assert att.url() == "wss://ai-staging.limacharlie.io/v1/ws/sessions/sid-42"


# ---------------------------------------------------------------------------
# Per-org ai-sessions URL resolution
# ---------------------------------------------------------------------------

class TestAiUrlResolution:
"""``AI._get_ai_url`` must read the per-org ``ai`` service URL from
``orgs/{oid}/url`` so staging/region deployments are honoured, and
must only fall back to the hardcoded production host when that entry
is absent.
"""

def _make_ai(self, urls: dict):
from limacharlie.sdk.ai import AI

calls = {"n": 0}

def get_urls():
calls["n"] += 1
return urls

org_stub = SimpleNamespace(get_urls=get_urls)
return AI(org_stub), calls

def test_uses_ai_entry_and_adds_https(self):
ai, _ = self._make_ai({"ai": "ai-staging.limacharlie.io"})
assert ai._get_ai_url() == "https://ai-staging.limacharlie.io"

def test_preserves_existing_scheme(self):
ai, _ = self._make_ai({"ai": "http://localhost:8080"})
assert ai._get_ai_url() == "http://localhost:8080"

def test_falls_back_when_ai_entry_missing(self):
from limacharlie.sdk.ai import _AI_SESSIONS_URL

ai, _ = self._make_ai({"search": "x.replay-search.limacharlie.io"})
assert ai._get_ai_url() == _AI_SESSIONS_URL

def test_result_is_cached(self):
ai, calls = self._make_ai({"ai": "ai.limacharlie.io"})
ai._get_ai_url()
ai._get_ai_url()
assert calls["n"] == 1


# ---------------------------------------------------------------------------
# Pretty-printer
Expand Down
3 changes: 3 additions & 0 deletions tests/unit/test_sdk_ai_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ def mock_org():
# MagicMock would auto-vivify a truthy _uid and leak an X-LC-UID
# header into every request.)
org.client._uid = None
# ai-sessions host is resolved per-org from orgs/{oid}/url; return the
# production host so the resolved alt_root matches _AI_SESSIONS_URL.
org.get_urls.return_value = {"ai": "ai.limacharlie.io"}
return org


Expand Down