From e5c7b0007389a3d4533fcf69d04c55a273810c1c Mon Sep 17 00:00:00 2001 From: Abhishek Mishra Date: Thu, 8 Oct 2026 04:05:06 +0530 Subject: [PATCH 1/3] test(integration): live SDK integration suite (smoke baseline + caller-context E2E) A common, env-gated live suite we run on every SDK change: a fully-automated smoke baseline (create/get/archive agent, list phone numbers) that proves the core surface still works, plus a caller-context end-to-end test (PRO-3560) that places a real call and asserts the crew read session.caller from the handshake (via the caller.probe event payload, not transcription). Uses the SDK for every step that has a method; flags the two that don't yet (crew deploy = CLI, make-build-live = REST) as gaps. See tests/integration/README.md. --- tests/integration/README.md | 49 ++++ tests/integration/test_caller_context_live.py | 221 ++++++++++++++++++ tests/integration/test_sdk_smoke_live.py | 62 +++++ 3 files changed, 332 insertions(+) create mode 100644 tests/integration/README.md create mode 100644 tests/integration/test_caller_context_live.py create mode 100644 tests/integration/test_sdk_smoke_live.py diff --git a/tests/integration/README.md b/tests/integration/README.md new file mode 100644 index 00000000..b5a50e1d --- /dev/null +++ b/tests/integration/README.md @@ -0,0 +1,49 @@ +# SDK live integration suite + +Real calls against a real environment — the common baseline we run on every SDK +change so we know the core surface still works, plus a feature test for the thing +we just shipped. No mocks, no WireMock. Gated by env vars, so the normal unit CI +skips it. + +Everything uses the **SDK** (not raw HTTP) wherever an SDK method exists. The two +spots that have no SDK method yet are flagged inline as gaps: crew code deploy +(only the `smallestai agent-crew` CLI) and making a crew build live +(`PATCH /sdk/agents/{id}/builds/{bid}`). + +## Setup + +```bash +export SMALLEST_API_KEY=sk_... # required +export SMALLEST_BASE=https://api.smallest.ai # optional; use https://api.dev.smallest.ai for dev +export SMALLEST_TEST_NUMBER=+91XXXXXXXXXX # a phone YOU can answer (caller-context test only) +``` + +## Run + +```bash +# Fast, fully automated — "nothing is broken" baseline (no telephony, no human): +poetry run pytest tests/integration/test_sdk_smoke_live.py -m integration -s + +# Caller context end-to-end (PRO-3560) — you must ANSWER the call it places: +poetry run pytest tests/integration/test_caller_context_live.py -m integration -s +# or just run it and watch the payload print: +poetry run python tests/integration/test_caller_context_live.py +``` + +## What each covers + +- **test_sdk_smoke_live.py** — create agent → get round-trip → archive; list phone + numbers. Catches a broken client / auth / response-shape regression. Add a case + here whenever a new core surface ships. +- **test_caller_context_live.py** — the full caller-context chain on a real call: + orchestrator forwards the caller block into `system.init` → SDK exposes it as + `session.caller` / `session.initial_variables` → crew reads it. The crew emits + what it read as a structured `caller.probe` event; the test reads that event's + **payload** (raw `session.caller` data, not the spoken/transcribed line) off the + conversation and asserts `user_number` / `agent_number` / `direction` / `call_id`. + +## Convention for a new SDK change + +1. Smoke stays green (nothing broke). +2. Add a focused live test for the new feature next to it (mirror the pattern: + gate on env, use the SDK, assert the observable behavior, clean up after). diff --git a/tests/integration/test_caller_context_live.py b/tests/integration/test_caller_context_live.py new file mode 100644 index 00000000..e06ed47b --- /dev/null +++ b/tests/integration/test_caller_context_live.py @@ -0,0 +1,221 @@ +"""Live end-to-end test for crew caller context (PRO-3560), driven through the SDK. + +Proves the whole chain on a real telephony call: the orchestrator forwards the +caller block into ``system.init`` -> the SDK surfaces it as ``session.caller`` / +``session.initial_variables`` -> crew code reads it. The crew emits what it read as +a structured ``caller.probe`` event (NOT a spoken/transcribed line), and this test +pulls that event's payload back off the conversation record and asserts the numbers. + +Everything that has an SDK method uses the SDK: ``agents.create_agent``, +``phone_numbers.list``, ``calls.start_outbound_call``, ``calls.get``, +``agents.archive_agent``. Two steps have no SDK method yet and are called out: +crew code deploy (the ``smallestai agent-crew`` CLI) and making a build live +(``PATCH /sdk/agents/{id}/builds/{bid}``) — both tracked as SDK gaps. + +Run it (you must answer the call): + + SMALLEST_API_KEY=sk_... SMALLEST_TEST_NUMBER=+91XXXXXXXXXX \ + poetry run python tests/integration/test_caller_context_live.py + +or under pytest: + + SMALLEST_API_KEY=sk_... SMALLEST_TEST_NUMBER=+91XXXXXXXXXX \ + poetry run pytest tests/integration/test_caller_context_live.py -m integration -s +""" + +import json +import os +import subprocess +import sys +import tempfile +import time +import urllib.request + +import pytest + +pytestmark = pytest.mark.integration + +API_KEY = os.environ.get("SMALLEST_API_KEY") +TEST_NUMBER = os.environ.get("SMALLEST_TEST_NUMBER") # a phone you can answer, E.164 +# Prod by default; override for dev, e.g. https://api.dev.smallest.ai +BASE = os.environ.get("SMALLEST_BASE", "https://api.smallest.ai").rstrip("/") + +PROBE_SERVER = '''\ +"""Caller-context probe crew: emit what the crew reads from session.caller as an event.""" +from loguru import logger + +from smallestai.atoms.crew.events import SDKAgentLogEvent +from smallestai.atoms.crew.nodes import OutputCrewNode +from smallestai.atoms.crew.server import AtomsCrewApp +from smallestai.atoms.crew.session import CrewSession + + +class Probe(OutputCrewNode): + def __init__(self, session: CrewSession): + super().__init__(name="probe") + self._session = session + + async def generate_response(self): + c = self._session.caller + payload = { + "user_number": c.user_number if c else None, + "agent_number": c.agent_number if c else None, + "direction": c.direction if c else None, + "call_id": c.call_id if c else None, + "variables": self._session.initial_variables, + } + logger.success(f"CALLER_PROBE {payload}") + await self.send_event(SDKAgentLogEvent(name="caller.probe", payload=payload)) + yield "Caller context probe recorded. Goodbye." + + +async def setup(session: CrewSession): + session.add_node(Probe(session)) + await session.start() + await session.wait_until_complete() + + +if __name__ == "__main__": + AtomsCrewApp(setup_handler=setup).run() +''' + + +def _client(): + from smallestai import SmallestAI + from smallestai.environment import SmallestAIEnvironment + + if "dev" in BASE: + env = SmallestAIEnvironment( + atoms=f"{BASE}/atoms/v1", waves=BASE, waves_ws=BASE.replace("http", "ws"), payment=BASE + ) + return SmallestAI(api_key=API_KEY, environment=env) + return SmallestAI(api_key=API_KEY) # Production + + +def _data(resp): + """Unwrap a {status, data} SDK response into the data dict.""" + d = getattr(resp, "data", resp) + if hasattr(d, "model_dump"): + d = d.model_dump() + return d + + +def _set_build_live(agent_id: str, build_id: str) -> None: + """Make a crew build live. SDK GAP: there is no SDK/CLI-scriptable method for + this yet (the CLI's `agent-crew builds` is interactive), so we hit the REST + endpoint directly. Tracked as a follow-up to add to the SDK.""" + req = urllib.request.Request( + f"{BASE}/atoms/v1/sdk/agents/{agent_id}/builds/{build_id}", + data=json.dumps({"isLive": True}).encode(), + headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, + method="PATCH", + ) + with urllib.request.urlopen(req, timeout=25) as r: + assert r.status == 200, f"make-live failed: {r.status}" + + +def _deploy_probe_crew(agent_id: str) -> str: + """Deploy the probe crew to `agent_id`. SDK GAP: crew code deploy only exists as + the `smallestai agent-crew` CLI, so we shell out to it. Returns the build id.""" + workdir = tempfile.mkdtemp(prefix="caller-probe-") + with open(os.path.join(workdir, "server.py"), "w") as f: + f.write(PROBE_SERVER) + with open(os.path.join(workdir, "requirements.txt"), "w") as f: + f.write("smallestai>=5.14.0\nloguru>=0.7.0\n") + env = {**os.environ, "SMALLEST_API_KEY": API_KEY} + if "dev" in BASE: + env["SMALLEST_BASE_URL"] = BASE + run = lambda *a: subprocess.run( + ["smallestai", *a], cwd=workdir, env=env, capture_output=True, text=True, timeout=600 + ) + assert run("auth", "login").returncode == 0 or True # login is idempotent + subprocess.run(["sh", "-c", f'echo "{API_KEY}" | smallestai auth login'], cwd=workdir, env=env, timeout=60) + init = run("agent-crew", "init", "--agent-id", agent_id) + assert init.returncode == 0, f"init failed: {init.stderr or init.stdout}" + dep = run("agent-crew", "deploy", "--entry-point", "server.py") + assert dep.returncode == 0 and "SUCCEEDED" in dep.stdout, f"deploy failed: {dep.stderr or dep.stdout}" + build_id = next(ln.split("Build ID:")[1].strip() for ln in dep.stdout.splitlines() if "Build ID:" in ln) + return build_id + + +def _unattached_from_product(client) -> str: + """A phone-number product not bound to an agent, to dial from.""" + for p in _data(client.atoms.phone_numbers.list()) or []: + p = p if isinstance(p, dict) else _data(p) + if not (p.get("agent") or p.get("agentId")): + return p["_id"] + raise AssertionError("no unattached phone-number product to dial from; attach a caller ID") + + +def run_live_caller_context_probe() -> dict: + """Create+deploy a probe crew, place an outbound call, return the caller.probe payload.""" + assert API_KEY, "set SMALLEST_API_KEY" + assert TEST_NUMBER, "set SMALLEST_TEST_NUMBER to a phone you can answer" + client = _client() + + stamp = str(int(time.time()))[-6:] + agent_id = _data(client.atoms.agents.create_agent(name=f"zzz-caller-probe-{stamp}", global_prompt="probe")) + agent_id = agent_id if isinstance(agent_id, str) else agent_id.get("_id") or agent_id.get("id") + print(f"created probe agent {agent_id}") + try: + build_id = _deploy_probe_crew(agent_id) + print(f"deployed build {build_id}; making live…") + _set_build_live(agent_id, build_id) + from_product = _unattached_from_product(client) + + call = _data( + client.atoms.calls.start_outbound_call( + agent_id=agent_id, phone_number=TEST_NUMBER, from_product_id=from_product + ) + ) + call_id = call.get("conversationId") or call.get("callId") + print(f"\n>>> CALL PLACED to {TEST_NUMBER} (call {call_id}). ANSWER IT. <<<\n") + + payload = None + for i in range(30): + rec = _data(client.atoms.calls.get(call_id)) + status = rec.get("status") + for e in rec.get("events") or []: + if str(e.get("name") or e.get("eventType") or "").lower() == "caller.probe": + payload = e.get("payload") + elif "caller.probe" in json.dumps(e): + inner = e.get("payload") or e.get("metadata") + if isinstance(inner, str): + inner = json.loads(inner) + payload = (inner or {}).get("payload", inner) + print(f" [{(i + 1) * 10}s] status={status} caller.probe={'FOUND' if payload else '-'}") + if payload: + break + if status in ("no_answer", "failed", "busy") and i > 0: + raise AssertionError(f"call {status} — answer the call next time") + time.sleep(10) + + assert payload, "no caller.probe event — the crew did not report session.caller (was the call answered?)" + return payload + finally: + try: + client.atoms.agents.archive_agent(agent_id) + print(f"cleaned up probe agent {agent_id}") + except Exception as exc: # cleanup is best-effort + print(f"cleanup skipped: {exc}") + + +@pytest.mark.skipif(not (API_KEY and TEST_NUMBER), reason="set SMALLEST_API_KEY + SMALLEST_TEST_NUMBER") +def test_caller_context_live(): + payload = run_live_caller_context_probe() + print("\n=== caller.probe payload (this is session.caller, not transcription) ===") + print(json.dumps(payload, indent=2)) + assert payload["user_number"], "session.caller.user_number was empty" + assert payload["agent_number"], "session.caller.agent_number was empty" + assert payload["direction"] in ("inbound", "outbound"), payload["direction"] + assert payload["call_id"], "session.caller.call_id was empty" + assert payload["user_number"] == TEST_NUMBER, "dialed number should be the caller user_number on outbound" + + +if __name__ == "__main__": + payload = run_live_caller_context_probe() + print("\n=== caller.probe payload (this is session.caller, not transcription) ===") + print(json.dumps(payload, indent=2)) + ok = bool(payload.get("user_number") and payload.get("direction") and payload.get("call_id")) + print("\nRESULT:", "PASS — session.caller delivered end to end" if ok else "FAIL") + sys.exit(0 if ok else 1) diff --git a/tests/integration/test_sdk_smoke_live.py b/tests/integration/test_sdk_smoke_live.py new file mode 100644 index 00000000..2c372c3e --- /dev/null +++ b/tests/integration/test_sdk_smoke_live.py @@ -0,0 +1,62 @@ +"""Fully-automated live smoke suite — the "nothing is broken" baseline. + +Runs real SDK calls against a real environment (no telephony, no human), so every +SDK change can prove the core surface still works before layering a new feature on +top. All through the SDK, no raw HTTP. + + SMALLEST_API_KEY=sk_... poetry run pytest tests/integration/test_sdk_smoke_live.py -m integration -s +""" + +import os +import time + +import pytest + +pytestmark = pytest.mark.integration + +API_KEY = os.environ.get("SMALLEST_API_KEY") +BASE = os.environ.get("SMALLEST_BASE", "https://api.smallest.ai").rstrip("/") + + +def _client(): + from smallestai import SmallestAI + from smallestai.environment import SmallestAIEnvironment + + if "dev" in BASE: + env = SmallestAIEnvironment( + atoms=f"{BASE}/atoms/v1", waves=BASE, waves_ws=BASE.replace("http", "ws"), payment=BASE + ) + return SmallestAI(api_key=API_KEY, environment=env) + return SmallestAI(api_key=API_KEY) + + +def _data(resp): + d = getattr(resp, "data", resp) + return d.model_dump() if hasattr(d, "model_dump") else d + + +pytestmark = [pytest.mark.integration, pytest.mark.skipif(not API_KEY, reason="set SMALLEST_API_KEY")] + + +def test_agent_create_read_roundtrip_and_archive(): + client = _client() + stamp = str(int(time.time()))[-6:] + created = _data(client.atoms.agents.create_agent(name=f"zzz-smoke-{stamp}", global_prompt="smoke")) + agent_id = created if isinstance(created, str) else created.get("_id") or created.get("id") + assert agent_id, f"create_agent returned no id: {created}" + try: + got = _data(client.atoms.agents.get_agent(agent_id)) + got_id = got.get("_id") or got.get("id") if isinstance(got, dict) else agent_id + assert str(got_id) == str(agent_id), "get_agent did not round-trip the agent id" + finally: + client.atoms.agents.archive_agent(agent_id) + + +def test_phone_numbers_list(): + client = _client() + nums = _data(client.atoms.phone_numbers.list()) + assert isinstance(nums, list), f"phone_numbers.list() should return a list, got {type(nums)}" + # Shape check on the first entry, if any. + if nums: + p = nums[0] if isinstance(nums[0], dict) else _data(nums[0]) + assert "_id" in p and "attributes" in p, f"unexpected phone-number shape: {list(p)[:6]}" From a27ce991bd0ba41fadc37a2c35cac2fc42fa6c9c Mon Sep 17 00:00:00 2001 From: Abhishek Mishra Date: Fri, 13 Nov 2026 09:30:18 +0530 Subject: [PATCH 2/3] fix(integration): by_alias dumps + mypy types (addresses crim + compile) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - _data() now model_dump(by_alias=True) in both files so camelCase wire keys (conversationId, callId, _id) survive — without it the suite only tested that KeyError still works (crim). - smoke: drop the duplicate scalar pytestmark (kept the list form) — fixes the list[MarkDecorator] vs MarkDecorator mypy error. - caller-context: type env as dict[str, str] (API_KEY or "") so subprocess.run's env arg type-checks. --- tests/integration/test_caller_context_live.py | 6 ++++-- tests/integration/test_sdk_smoke_live.py | 5 ++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/integration/test_caller_context_live.py b/tests/integration/test_caller_context_live.py index e06ed47b..0ce42cd1 100644 --- a/tests/integration/test_caller_context_live.py +++ b/tests/integration/test_caller_context_live.py @@ -96,7 +96,9 @@ def _data(resp): """Unwrap a {status, data} SDK response into the data dict.""" d = getattr(resp, "data", resp) if hasattr(d, "model_dump"): - d = d.model_dump() + # by_alias so camelCase wire keys (conversationId, callId, _id) survive — + # the SDK models alias them, and the assertions below key on the wire names. + d = d.model_dump(by_alias=True) return d @@ -122,7 +124,7 @@ def _deploy_probe_crew(agent_id: str) -> str: f.write(PROBE_SERVER) with open(os.path.join(workdir, "requirements.txt"), "w") as f: f.write("smallestai>=5.14.0\nloguru>=0.7.0\n") - env = {**os.environ, "SMALLEST_API_KEY": API_KEY} + env: dict[str, str] = {**os.environ, "SMALLEST_API_KEY": API_KEY or ""} if "dev" in BASE: env["SMALLEST_BASE_URL"] = BASE run = lambda *a: subprocess.run( diff --git a/tests/integration/test_sdk_smoke_live.py b/tests/integration/test_sdk_smoke_live.py index 2c372c3e..b0c61f7a 100644 --- a/tests/integration/test_sdk_smoke_live.py +++ b/tests/integration/test_sdk_smoke_live.py @@ -12,8 +12,6 @@ import pytest -pytestmark = pytest.mark.integration - API_KEY = os.environ.get("SMALLEST_API_KEY") BASE = os.environ.get("SMALLEST_BASE", "https://api.smallest.ai").rstrip("/") @@ -32,7 +30,8 @@ def _client(): def _data(resp): d = getattr(resp, "data", resp) - return d.model_dump() if hasattr(d, "model_dump") else d + # by_alias so camelCase wire keys (_id, etc.) survive the model dump. + return d.model_dump(by_alias=True) if hasattr(d, "model_dump") else d pytestmark = [pytest.mark.integration, pytest.mark.skipif(not API_KEY, reason="set SMALLEST_API_KEY")] From ed7631f4a8c9f29b822c0c1af2ae173539d2c29f Mon Sep 17 00:00:00 2001 From: Abhishek Mishra Date: Mon, 16 Nov 2026 15:55:09 +0530 Subject: [PATCH 3/3] fix: isolate live SDK probes and deploy the checkout under test --- tests/custom/test_live_integration_harness.py | 148 ++++++++++++++++++ tests/integration/README.md | 20 ++- tests/integration/_crew_cli.py | 23 +++ tests/integration/test_caller_context_live.py | 106 +++++++++---- tests/integration/test_sdk_smoke_live.py | 15 +- 5 files changed, 275 insertions(+), 37 deletions(-) create mode 100644 tests/custom/test_live_integration_harness.py create mode 100644 tests/integration/_crew_cli.py diff --git a/tests/custom/test_live_integration_harness.py b/tests/custom/test_live_integration_harness.py new file mode 100644 index 00000000..8c7fe4f6 --- /dev/null +++ b/tests/custom/test_live_integration_harness.py @@ -0,0 +1,148 @@ +"""Offline regressions for the live harness; never call the live tests.""" + +import importlib.util +import os +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace +from zipfile import ZipFile + +import httpx +import pytest + +ROOT = Path(__file__).resolve().parents[2] + + +def load_harness(name, monkeypatch): + monkeypatch.setenv("SMALLEST_API_KEY", "test-key") + spec = importlib.util.spec_from_file_location(name, ROOT / "tests/integration" / (name + ".py")) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.mark.parametrize("name", ["test_caller_context_live", "test_sdk_smoke_live"]) +@pytest.mark.parametrize( + "base", ["http://127.0.0.1:9999", "https://api.india.smallest.ai", "https://api.dev.smallest.ai"] +) +def test_sdk_targets_selected_host(name, base, monkeypatch): + monkeypatch.setenv("SMALLEST_BASE", base) + module = load_harness(name, monkeypatch) + seen = [] + real_client = httpx.Client + + def respond(request): + seen.append(request) + return httpx.Response(200, json={"status": "success", "data": []}) + + monkeypatch.setattr(httpx, "Client", lambda **kwargs: real_client(**kwargs, transport=httpx.MockTransport(respond))) + module._client().atoms.phone_numbers.list() + assert len(seen) == 1 + assert str(seen[0].url).startswith(base + "/atoms/v1/") + assert seen[0].headers["Authorization"] == "Bearer test-key" + + +def test_probe_bundle_installs_checkout_wheel(tmp_path, monkeypatch): + module = load_harness("test_caller_context_live", monkeypatch) + wheel_name = "smallestai-5.14.0-py3-none-any.whl" + + def build(args, **kwargs): + assert args[:7] == [sys.executable, "-m", "pip", "wheel", "--no-deps", "--no-build-isolation", "--wheel-dir"] + assert args[-1] == str(ROOT) + (tmp_path / wheel_name).write_bytes(b"wheel built from this checkout") + return SimpleNamespace(returncode=0) + + monkeypatch.setattr(module.subprocess, "run", build) + module._build_probe_package(tmp_path) + from smallestai.cli.utils import create_zip_from_directory + + with ZipFile(create_zip_from_directory(tmp_path)) as bundle: + import tomli + + project = tomli.loads(bundle.read("pyproject.toml").decode()) + assert project["tool"]["poetry"]["dependencies"]["smallestai"] == {"path": wheel_name} + assert "requirements.txt" not in bundle.namelist() + assert bundle.read(wheel_name) == b"wheel built from this checkout" + assert bundle.read("server.py").decode() == module.PROBE_SERVER + + +@pytest.mark.parametrize("stage", ["success", "init", "deploy"]) +def test_deploy_uses_same_host_and_no_login(stage, monkeypatch): + module = load_harness("test_caller_context_live", monkeypatch) + module.BASE = "https://api.india.smallest.ai" + monkeypatch.setenv("SMALLEST_BASE_URL", "https://unrelated.example") + monkeypatch.setattr(module, "_build_probe_package", lambda path: None) + seen = [] + + def run(args, **kwargs): + seen.append((args, kwargs)) + assert args[:2] == [sys.executable, str(ROOT / "tests/integration/_crew_cli.py")] + assert kwargs["env"]["SMALLEST_BASE_URL"] == module.BASE + assert kwargs["env"]["SMALLEST_API_KEY"] == "test-key" + assert kwargs["env"]["PYTHONPATH"] == str(ROOT / "src") + assert "test-key" not in " ".join(args) + assert "auth" not in args + return SimpleNamespace(returncode=int(args[2] == stage), stdout="Build ID: build-1\nSUCCEEDED", stderr="failed") + + monkeypatch.setattr(module.subprocess, "run", run) + if stage == "success": + assert module._deploy_probe_crew("agent-1") == "build-1" + else: + with pytest.raises(AssertionError, match=f"{stage} failed"): + module._deploy_probe_crew("agent-1") + assert not Path(seen[0][1]["cwd"]).exists() + + +def test_crew_runner_uses_real_cli_without_auth_files(tmp_path): + env = { + **os.environ, + "SMALLEST_API_KEY": "test-key", + "SMALLEST_BASE_URL": "https://api.example", + "PYTHONPATH": str(ROOT / "src"), + } + result = subprocess.run( + [sys.executable, str(ROOT / "tests/integration/_crew_cli.py"), "init", "--agent-id", "agent-1"], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stderr + assert "agent-1" in (tmp_path / ".smallestai/config.toml").read_text() + assert not (tmp_path / ".smallestai/credentials.json").exists() + + +def test_make_live_uses_selected_host(monkeypatch): + module = load_harness("test_caller_context_live", monkeypatch) + module.BASE = "http://127.0.0.1:9999" + from unittest.mock import MagicMock + + response = MagicMock() + response.__enter__.return_value.status = 200 + + def urlopen(request, timeout): + assert request.full_url == module.BASE + "/atoms/v1/sdk/agents/agent/builds/build" + assert request.method == "PATCH" + assert request.get_header("Authorization") == "Bearer test-key" + assert request.data == b'{"isLive": true}' + return response + + monkeypatch.setattr(module.urllib.request, "urlopen", urlopen) + module._set_build_live("agent", "build") + + +def test_wheel_failure_stops_deployment_and_cleans_up(monkeypatch): + module = load_harness("test_caller_context_live", monkeypatch) + seen = [] + + def fail(args, **kwargs): + seen.append(args) + raise subprocess.CalledProcessError(1, args) + + monkeypatch.setattr(module.subprocess, "run", fail) + with pytest.raises(subprocess.CalledProcessError): + module._deploy_probe_crew("agent") + assert len(seen) == 1 + assert seen[0][2:4] == ["pip", "wheel"] + assert not Path(seen[0][7]).exists() diff --git a/tests/integration/README.md b/tests/integration/README.md index b5a50e1d..fd4c5ad1 100644 --- a/tests/integration/README.md +++ b/tests/integration/README.md @@ -22,10 +22,10 @@ export SMALLEST_TEST_NUMBER=+91XXXXXXXXXX # a phone YOU can answer (caller-con ```bash # Fast, fully automated — "nothing is broken" baseline (no telephony, no human): -poetry run pytest tests/integration/test_sdk_smoke_live.py -m integration -s +poetry run pytest --noconftest tests/integration/test_sdk_smoke_live.py -m integration -s # Caller context end-to-end (PRO-3560) — you must ANSWER the call it places: -poetry run pytest tests/integration/test_caller_context_live.py -m integration -s +poetry run pytest --noconftest tests/integration/test_caller_context_live.py -m integration -s # or just run it and watch the payload print: poetry run python tests/integration/test_caller_context_live.py ``` @@ -47,3 +47,19 @@ poetry run python tests/integration/test_caller_context_live.py 1. Smoke stays green (nothing broke). 2. Add a focused live test for the new feature next to it (mirror the pattern: gate on env, use the SDK, assert the observable behavior, clean up after). + +## Reproducible caller probe + +The caller probe builds a wheel from the current checkout and includes it in the +uploaded crew bundle. A pyproject with a local wheel dependency selects the +backend build path that copies the whole bundle before installing dependencies. +The remote build installs that wheel and its declared +runtime dependencies, rather than a separately published SDK release. Before +running it, install the local build tools with `poetry run python -m pip install +pip poetry-core`. The test uses the same interpreter and checkout for crew CLI +commands, passes credentials in the environment, and never reads or updates your +saved CLI login. Temporary build files are removed on success and failure. + +`SMALLEST_BASE` is used consistently for SDK, crew CLI, and raw HTTP calls, +including regional and localhost hosts. `--noconftest` avoids the global wire-test +Docker fixture; these live tests do not use WireMock. diff --git a/tests/integration/_crew_cli.py b/tests/integration/_crew_cli.py new file mode 100644 index 00000000..4690db68 --- /dev/null +++ b/tests/integration/_crew_cli.py @@ -0,0 +1,23 @@ +"""Run the real crew commands without reading or writing a user's saved login.""" + +import os +from types import SimpleNamespace + +from smallestai.cli.agent_crew import initialise_agent_crew_app +from smallestai.cli.lib.atoms import AtomsAPIClient +from smallestai.cli.lib.project_config import ProjectConfig + + +def main(): + key = os.environ["SMALLEST_API_KEY"] + base = os.environ["SMALLEST_BASE_URL"] + app = initialise_agent_crew_app( + ProjectConfig(), + SimpleNamespace(get_credentials=lambda: {"access_token": key}), + AtomsAPIClient(base_url=base), + ) + app() + + +if __name__ == "__main__": + main() diff --git a/tests/integration/test_caller_context_live.py b/tests/integration/test_caller_context_live.py index 0ce42cd1..7373ea6c 100644 --- a/tests/integration/test_caller_context_live.py +++ b/tests/integration/test_caller_context_live.py @@ -20,7 +20,7 @@ or under pytest: SMALLEST_API_KEY=sk_... SMALLEST_TEST_NUMBER=+91XXXXXXXXXX \ - poetry run pytest tests/integration/test_caller_context_live.py -m integration -s + poetry run pytest --noconftest tests/integration/test_caller_context_live.py -m integration -s """ import json @@ -30,6 +30,7 @@ import tempfile import time import urllib.request +from pathlib import Path import pytest @@ -84,12 +85,13 @@ def _client(): from smallestai import SmallestAI from smallestai.environment import SmallestAIEnvironment - if "dev" in BASE: - env = SmallestAIEnvironment( - atoms=f"{BASE}/atoms/v1", waves=BASE, waves_ws=BASE.replace("http", "ws"), payment=BASE - ) - return SmallestAI(api_key=API_KEY, environment=env) - return SmallestAI(api_key=API_KEY) # Production + env = SmallestAIEnvironment( + atoms=f"{BASE}/atoms/v1", + waves=BASE, + waves_ws=BASE.replace("https://", "wss://", 1).replace("http://", "ws://", 1), + payment=BASE, + ) + return SmallestAI(api_key=API_KEY, environment=env) def _data(resp): @@ -116,28 +118,76 @@ def _set_build_live(agent_id: str, build_id: str) -> None: assert r.status == 200, f"make-live failed: {r.status}" -def _deploy_probe_crew(agent_id: str) -> str: - """Deploy the probe crew to `agent_id`. SDK GAP: crew code deploy only exists as - the `smallestai agent-crew` CLI, so we shell out to it. Returns the build id.""" - workdir = tempfile.mkdtemp(prefix="caller-probe-") - with open(os.path.join(workdir, "server.py"), "w") as f: - f.write(PROBE_SERVER) - with open(os.path.join(workdir, "requirements.txt"), "w") as f: - f.write("smallestai>=5.14.0\nloguru>=0.7.0\n") - env: dict[str, str] = {**os.environ, "SMALLEST_API_KEY": API_KEY or ""} - if "dev" in BASE: - env["SMALLEST_BASE_URL"] = BASE - run = lambda *a: subprocess.run( - ["smallestai", *a], cwd=workdir, env=env, capture_output=True, text=True, timeout=600 +def _build_probe_package(workdir: Path) -> None: + """Ship a wheel of this checkout, including its declared runtime dependencies.""" + repo = Path(__file__).resolve().parents[2] + subprocess.run( + [ + sys.executable, + "-m", + "pip", + "wheel", + "--no-deps", + "--no-build-isolation", + "--wheel-dir", + str(workdir), + str(repo), + ], + check=True, + capture_output=True, + text=True, + timeout=120, ) - assert run("auth", "login").returncode == 0 or True # login is idempotent - subprocess.run(["sh", "-c", f'echo "{API_KEY}" | smallestai auth login'], cwd=workdir, env=env, timeout=60) - init = run("agent-crew", "init", "--agent-id", agent_id) - assert init.returncode == 0, f"init failed: {init.stderr or init.stdout}" - dep = run("agent-crew", "deploy", "--entry-point", "server.py") - assert dep.returncode == 0 and "SUCCEEDED" in dep.stdout, f"deploy failed: {dep.stderr or dep.stdout}" - build_id = next(ln.split("Build ID:")[1].strip() for ln in dep.stdout.splitlines() if "Build ID:" in ln) - return build_id + wheels = list(workdir.glob("smallestai-*.whl")) + if len(wheels) != 1: + raise AssertionError("expected exactly one wheel built from the SDK checkout") + # The backend copies the whole bundle before `pip install .` for pyproject + # builds. Its requirements-only path copies just requirements.txt first, + # which would leave a bundled wheel unavailable during installation. + (workdir / "pyproject.toml").write_text( + f'''[tool.poetry] +name = "smallestai-caller-probe" +version = "0.0.0" +description = "Live caller-context probe" +authors = [] +packages = [{{include = "server.py"}}] + +[tool.poetry.dependencies] +python = ">=3.9" +smallestai = {{path = "{wheels[0].name}"}} + +[build-system] +requires = ["poetry-core>=1.0.0"] +build-backend = "poetry.core.masonry.api" +''', + encoding="utf-8", + ) + (workdir / "server.py").write_text(PROBE_SERVER, encoding="utf-8") + + +def _deploy_probe_crew(agent_id: str) -> str: + """Run the checkout's crew CLI with in-memory auth and a local SDK wheel.""" + repo = Path(__file__).resolve().parents[2] + env = {**os.environ, "SMALLEST_API_KEY": API_KEY or "", "SMALLEST_BASE_URL": BASE, "PYTHONPATH": str(repo / "src")} + with tempfile.TemporaryDirectory(prefix="caller-probe-") as directory: + workdir = Path(directory) + _build_probe_package(workdir) + + def run(*args): + return subprocess.run( + [sys.executable, str(Path(__file__).with_name("_crew_cli.py")), *args], + cwd=workdir, + env=env, + capture_output=True, + text=True, + timeout=600, + ) + + init = run("init", "--agent-id", agent_id) + assert init.returncode == 0, f"init failed: {init.stderr or init.stdout}" + dep = run("deploy", "--entry-point", "server.py") + assert dep.returncode == 0 and "SUCCEEDED" in dep.stdout, f"deploy failed: {dep.stderr or dep.stdout}" + return next(ln.split("Build ID:")[1].strip() for ln in dep.stdout.splitlines() if "Build ID:" in ln) def _unattached_from_product(client) -> str: diff --git a/tests/integration/test_sdk_smoke_live.py b/tests/integration/test_sdk_smoke_live.py index b0c61f7a..181c75e4 100644 --- a/tests/integration/test_sdk_smoke_live.py +++ b/tests/integration/test_sdk_smoke_live.py @@ -4,7 +4,7 @@ SDK change can prove the core surface still works before layering a new feature on top. All through the SDK, no raw HTTP. - SMALLEST_API_KEY=sk_... poetry run pytest tests/integration/test_sdk_smoke_live.py -m integration -s + SMALLEST_API_KEY=sk_... poetry run pytest --noconftest tests/integration/test_sdk_smoke_live.py -m integration -s """ import os @@ -20,12 +20,13 @@ def _client(): from smallestai import SmallestAI from smallestai.environment import SmallestAIEnvironment - if "dev" in BASE: - env = SmallestAIEnvironment( - atoms=f"{BASE}/atoms/v1", waves=BASE, waves_ws=BASE.replace("http", "ws"), payment=BASE - ) - return SmallestAI(api_key=API_KEY, environment=env) - return SmallestAI(api_key=API_KEY) + env = SmallestAIEnvironment( + atoms=f"{BASE}/atoms/v1", + waves=BASE, + waves_ws=BASE.replace("https://", "wss://", 1).replace("http://", "ws://", 1), + payment=BASE, + ) + return SmallestAI(api_key=API_KEY, environment=env) def _data(resp):