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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Roleplay/agentic e2e: an LLM-backed character joins a LiveKit room and
|
| 2 |
+
holds an in-character spoken conversation.
|
| 3 |
+
|
| 4 |
+
Checks:
|
| 5 |
+
1. character stays in character across 3 spoken turns (transcript keywords)
|
| 6 |
+
2. AI disclosure present in the first utterance (CONSENT.md #2 — every policy)
|
| 7 |
+
3. *actions* are logged as agent.action events, not spoken
|
| 8 |
+
4. content-policy gate: safe vs mature system prompts differ as specified
|
| 9 |
+
5. CLI join/leave + replay logs verify
|
| 10 |
+
Latency is reported (LLM adds generation time); sanity gate at 12s, no 4s gate.
|
| 11 |
+
|
| 12 |
+
Env: FREESTREAM_AGENT=llm, FREESTREAM_LLM_API_KEY (or HF_TOKEN),
|
| 13 |
+
FREESTREAM_CONTENT_POLICY=mature (operator opt-in for this session).
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import asyncio
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import socket
|
| 20 |
+
import subprocess
|
| 21 |
+
import sys
|
| 22 |
+
import tarfile
|
| 23 |
+
import time
|
| 24 |
+
import urllib.request
|
| 25 |
+
import wave
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
ROOT = Path("/tmp/rp")
|
| 31 |
+
REPO = "https://huggingface.co/datasets/LoveLogicAI/freestream/resolve/main"
|
| 32 |
+
VOICE_URL = ("https://huggingface.co/rhasspy/piper-voices/resolve/main/"
|
| 33 |
+
"en/en_US/amy/medium/en_US-amy-medium{ext}")
|
| 34 |
+
GH_LATEST = "https://api.github.com/repos/livekit/livekit-server/releases/latest"
|
| 35 |
+
|
| 36 |
+
os.environ["HF_HOME"] = "/tmp/hf"
|
| 37 |
+
os.environ["FREESTREAM_VOICE_DIR"] = str(ROOT / "voices")
|
| 38 |
+
os.environ["FREESTREAM_WHISPER_MODEL"] = "tiny.en"
|
| 39 |
+
os.environ["FREESTREAM_WHISPER_THREADS"] = "1"
|
| 40 |
+
os.environ["FREESTREAM_AGENT"] = "llm"
|
| 41 |
+
os.environ["FREESTREAM_CONTENT_POLICY"] = "mature" # operator opt-in (CONSENT.md §6)
|
| 42 |
+
os.environ["FREESTREAM_CHARACTER_CARD"] = "identity/characters/vera-steel.json"
|
| 43 |
+
os.environ["PYTHONPATH"] = str(ROOT)
|
| 44 |
+
sys.path.insert(0, str(ROOT))
|
| 45 |
+
os.environ.setdefault("FREESTREAM_LIVEKIT_URL", "ws://localhost:7880")
|
| 46 |
+
os.environ.setdefault("FREESTREAM_LIVEKIT_KEY", "devkey")
|
| 47 |
+
os.environ.setdefault("FREESTREAM_LIVEKIT_SECRET", "secret")
|
| 48 |
+
|
| 49 |
+
results = []
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def check(name, ok, detail=""):
|
| 53 |
+
results.append((name, ok))
|
| 54 |
+
print(f"{'PASS' if ok else 'FAIL'} {name}" + (f" — {detail}" if detail else ""), flush=True)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def fetch(url, dest):
|
| 58 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 59 |
+
with urllib.request.urlopen(url, timeout=300) as r:
|
| 60 |
+
dest.write_bytes(r.read())
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def run_cli(*args, timeout=240):
|
| 64 |
+
return subprocess.run([sys.executable, str(ROOT / "scripts/freestream.py"), *args],
|
| 65 |
+
cwd=str(ROOT), capture_output=True, text=True, timeout=timeout)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ---- fetch code --------------------------------------------------------------
|
| 69 |
+
FILES = ["scripts/freestream.py",
|
| 70 |
+
"freestream/__init__.py", "freestream/events.py", "freestream/presence.py",
|
| 71 |
+
"freestream/persona.py", "freestream/bot.py", "freestream/asr.py",
|
| 72 |
+
"freestream/avatar.py", "freestream/agent.py",
|
| 73 |
+
"identity/characters/vera-steel.json"]
|
| 74 |
+
missing = []
|
| 75 |
+
for f in FILES:
|
| 76 |
+
try:
|
| 77 |
+
fetch(f"{REPO}/{f}", ROOT / f)
|
| 78 |
+
if (ROOT / f).stat().st_size == 0:
|
| 79 |
+
raise RuntimeError("empty")
|
| 80 |
+
except Exception as e:
|
| 81 |
+
missing.append((f, str(e)))
|
| 82 |
+
check("fetch code from Hub", not missing, str(missing[:2]))
|
| 83 |
+
if missing:
|
| 84 |
+
sys.exit(1)
|
| 85 |
+
|
| 86 |
+
# ---- policy gate verification (mechanical, no content generation) -------------
|
| 87 |
+
from freestream.agent import CharacterAgent, SAFE_POLICY, MATURE_POLICY # noqa: E402
|
| 88 |
+
|
| 89 |
+
os.environ["FREESTREAM_CONTENT_POLICY"] = "safe"
|
| 90 |
+
safe_sys = CharacterAgent(bot_name="x").system
|
| 91 |
+
os.environ["FREESTREAM_CONTENT_POLICY"] = "mature"
|
| 92 |
+
mature_sys = CharacterAgent(bot_name="x").system
|
| 93 |
+
os.environ["FREESTREAM_CONTENT_POLICY"] = "mature"
|
| 94 |
+
check("policy gate: safe prompt has sanitizer", "safe mode" in safe_sys
|
| 95 |
+
and "mature mode" not in safe_sys)
|
| 96 |
+
check("policy gate: mature prompt removes sanitizer", "mature mode" in mature_sys
|
| 97 |
+
and SAFE_POLICY.split("CONTENT POLICY")[1][:20] not in mature_sys)
|
| 98 |
+
first_line = CharacterAgent(bot_name="x").first_utterance()
|
| 99 |
+
check("policy gate: AI disclosure survives every policy", "AI assistant" in first_line)
|
| 100 |
+
|
| 101 |
+
# ---- server -------------------------------------------------------------------
|
| 102 |
+
if not (ROOT / "livekit-server").exists():
|
| 103 |
+
req = urllib.request.Request(GH_LATEST, headers={"Accept": "application/vnd.github+json"})
|
| 104 |
+
with urllib.request.urlopen(req, timeout=60) as r:
|
| 105 |
+
release = json.loads(r.read())
|
| 106 |
+
asset = next(a for a in release["assets"]
|
| 107 |
+
if "linux_amd64" in a["name"] and a["name"].endswith(".tar.gz"))
|
| 108 |
+
fetch(asset["browser_download_url"], ROOT / asset["name"])
|
| 109 |
+
with tarfile.open(ROOT / asset["name"]) as tf:
|
| 110 |
+
tf.extract("livekit-server", str(ROOT))
|
| 111 |
+
config = ROOT / "lk.yaml"
|
| 112 |
+
config.write_text("""
|
| 113 |
+
port: 7880
|
| 114 |
+
rtc:
|
| 115 |
+
use_external_ip: false
|
| 116 |
+
use_ice_lite: true
|
| 117 |
+
tcp_port: 7881
|
| 118 |
+
port_range_start: 50000
|
| 119 |
+
port_range_end: 50100
|
| 120 |
+
keys:
|
| 121 |
+
devkey: secret
|
| 122 |
+
""")
|
| 123 |
+
server_log = open(ROOT / "server.log", "w")
|
| 124 |
+
server = subprocess.Popen([str(ROOT / "livekit-server"), "--config", str(config)],
|
| 125 |
+
stdout=server_log, stderr=subprocess.STDOUT)
|
| 126 |
+
for _ in range(60):
|
| 127 |
+
try:
|
| 128 |
+
with socket.create_connection(("127.0.0.1", 7880), timeout=1):
|
| 129 |
+
break
|
| 130 |
+
except OSError:
|
| 131 |
+
time.sleep(0.5)
|
| 132 |
+
check("livekit-server up on :7880", True)
|
| 133 |
+
|
| 134 |
+
for ext, name in ((".onnx", "en_US-amy-medium.onnx"), (".onnx.json", "en_US-amy-medium.onnx.json")):
|
| 135 |
+
dest = ROOT / "voices" / name
|
| 136 |
+
if not dest.exists():
|
| 137 |
+
fetch(VOICE_URL.format(ext=ext), dest)
|
| 138 |
+
|
| 139 |
+
r = run_cli("generate-avatar", "--output", "identity/videomeeting-avatar.png")
|
| 140 |
+
check("generate-avatar", r.returncode == 0)
|
| 141 |
+
|
| 142 |
+
from faster_whisper import WhisperModel # noqa: E402
|
| 143 |
+
|
| 144 |
+
WhisperModel("tiny.en", device="cpu", compute_type="int8", cpu_threads=1)
|
| 145 |
+
from livekit import api, rtc # noqa: E402
|
| 146 |
+
from piper import PiperVoice # noqa: E402
|
| 147 |
+
|
| 148 |
+
# ---- join via CLI ---------------------------------------------------------------
|
| 149 |
+
join_proc = subprocess.Popen(
|
| 150 |
+
[sys.executable, str(ROOT / "scripts/freestream.py"), "join",
|
| 151 |
+
"--meet-url", "https://livekit.local/long-dawn", "--platform", "livekit",
|
| 152 |
+
"--bot-name", "Vera", "--image", "identity/videomeeting-avatar.png",
|
| 153 |
+
"--timeout-sec", "120"],
|
| 154 |
+
cwd=str(ROOT), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 155 |
+
sid, ready = None, False
|
| 156 |
+
for line in join_proc.stdout:
|
| 157 |
+
try:
|
| 158 |
+
d = json.loads(line)
|
| 159 |
+
except ValueError:
|
| 160 |
+
continue
|
| 161 |
+
if "session_id" in d and sid is None:
|
| 162 |
+
sid = d["session_id"]
|
| 163 |
+
if d.get("status") == "ready":
|
| 164 |
+
ready = True
|
| 165 |
+
break
|
| 166 |
+
check(f"CLI join -> ready (session {sid})", ready)
|
| 167 |
+
if not ready:
|
| 168 |
+
print(join_proc.stderr.read()[:800])
|
| 169 |
+
sys.exit(1)
|
| 170 |
+
|
| 171 |
+
# ---- in-character conversation -------------------------------------------------
|
| 172 |
+
QUESTIONS = [
|
| 173 |
+
("Captain, who am I talking to?", ("vera", "steel", "captain")),
|
| 174 |
+
("What's our cargo, and where are we headed?", ("cargo", "ceres", "freight", "haul", "credits")),
|
| 175 |
+
("Talk to me — what's the fastest route to Ceres?", ("ceres", "course", "day", "hour", "burn", "route")),
|
| 176 |
+
]
|
| 177 |
+
DISCLOSURE_KEYWORDS = ("ai", "automated")
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
async def conversation():
|
| 181 |
+
room = rtc.Room()
|
| 182 |
+
turns = []
|
| 183 |
+
audio_state = {"first": None, "last": None, "chunks": []}
|
| 184 |
+
|
| 185 |
+
@room.on("track_subscribed")
|
| 186 |
+
def on_track(track, publication, participant):
|
| 187 |
+
if track.kind == rtc.TrackKind.KIND_AUDIO:
|
| 188 |
+
asyncio.ensure_future(record_audio(track))
|
| 189 |
+
|
| 190 |
+
async def record_audio(track):
|
| 191 |
+
stream = rtc.AudioStream(track, sample_rate=16000, num_channels=1)
|
| 192 |
+
async for ev in stream:
|
| 193 |
+
pcm = np.frombuffer(ev.frame.data, dtype=np.int16)
|
| 194 |
+
rms = float(np.sqrt(np.mean(pcm.astype(np.float32) ** 2))) / 32768.0
|
| 195 |
+
if rms < 0.004:
|
| 196 |
+
continue
|
| 197 |
+
now = time.perf_counter()
|
| 198 |
+
if audio_state["first"] is None:
|
| 199 |
+
audio_state["first"] = now
|
| 200 |
+
audio_state["last"] = now
|
| 201 |
+
audio_state["chunks"].append(pcm)
|
| 202 |
+
|
| 203 |
+
await room.connect("ws://localhost:7880",
|
| 204 |
+
(api.AccessToken("devkey", "secret").with_identity("tester")
|
| 205 |
+
.with_grants(api.VideoGrants(room_join=True, room="long-dawn",
|
| 206 |
+
can_publish=True, can_subscribe=True))
|
| 207 |
+
.to_jwt()),
|
| 208 |
+
options=rtc.RoomOptions(auto_subscribe=True))
|
| 209 |
+
await asyncio.sleep(2.0)
|
| 210 |
+
|
| 211 |
+
voice = PiperVoice.load(str(ROOT / "voices/en_US-amy-medium.onnx"))
|
| 212 |
+
q_sr = int(json.loads((ROOT / "voices/en_US-amy-medium.onnx.json").read_text())
|
| 213 |
+
["audio"]["sample_rate"])
|
| 214 |
+
source = rtc.AudioSource(q_sr, 1)
|
| 215 |
+
track = rtc.LocalAudioTrack.create_audio_track("tester-mic", source)
|
| 216 |
+
await room.local_participant.publish_track(
|
| 217 |
+
track, rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_MICROPHONE))
|
| 218 |
+
chunk = int(q_sr * 0.01)
|
| 219 |
+
verifier = WhisperModel("tiny.en", device="cpu", compute_type="int8", cpu_threads=1)
|
| 220 |
+
|
| 221 |
+
for i, (q_text, keywords) in enumerate(QUESTIONS, start=1):
|
| 222 |
+
q_pcm = np.concatenate([np.frombuffer(c.audio_int16_bytes, np.int16)
|
| 223 |
+
for c in voice.synthesize(q_text)])
|
| 224 |
+
audio_state["first"], audio_state["last"], audio_state["chunks"] = None, None, []
|
| 225 |
+
for j in range(0, len(q_pcm), chunk):
|
| 226 |
+
piece = q_pcm[j: j + chunk]
|
| 227 |
+
frame = rtc.AudioFrame.create(q_sr, 1, len(piece))
|
| 228 |
+
np.copyto(np.frombuffer(frame.data, dtype=np.int16), piece)
|
| 229 |
+
await source.capture_frame(frame)
|
| 230 |
+
t_speech_end = time.perf_counter()
|
| 231 |
+
print(f"[client] turn {i}: '{q_text}' pushed (abs {time.time():.3f})", flush=True)
|
| 232 |
+
|
| 233 |
+
while audio_state["first"] is None:
|
| 234 |
+
await asyncio.sleep(0.05)
|
| 235 |
+
if time.perf_counter() - t_speech_end > 60:
|
| 236 |
+
break
|
| 237 |
+
if audio_state["first"] is None:
|
| 238 |
+
check(f"turn {i}: bot answered", False, "no audio in 60s")
|
| 239 |
+
turns.append(None)
|
| 240 |
+
continue
|
| 241 |
+
t_perceived = audio_state["first"] - t_speech_end
|
| 242 |
+
while time.perf_counter() - audio_state["last"] < 4.0:
|
| 243 |
+
await asyncio.sleep(0.1)
|
| 244 |
+
if time.perf_counter() - t_speech_end > 90:
|
| 245 |
+
break
|
| 246 |
+
bot_pcm = np.concatenate(audio_state["chunks"])
|
| 247 |
+
segs, _ = verifier.transcribe(bot_pcm.astype(np.float32) / 32768.0, language="en")
|
| 248 |
+
text = " ".join(s.text.strip() for s in segs).strip()
|
| 249 |
+
ok = any(k in text.lower() for k in keywords)
|
| 250 |
+
check(f"turn {i}: in-character answer", ok, f"{t_perceived:.2f}s — {text[:130]}")
|
| 251 |
+
if i == 1:
|
| 252 |
+
check("turn 1: AI disclosure spoken first",
|
| 253 |
+
any(k in text.lower() for k in DISCLOSURE_KEYWORDS), text[:130])
|
| 254 |
+
turns.append({"t_perceived": t_perceived, "text": text})
|
| 255 |
+
await asyncio.sleep(0.5)
|
| 256 |
+
|
| 257 |
+
await room.disconnect()
|
| 258 |
+
return turns
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
turns = asyncio.run(conversation())
|
| 262 |
+
|
| 263 |
+
# ---- actions logged, not spoken -------------------------------------------------
|
| 264 |
+
from freestream.events import EventLog # noqa: E402
|
| 265 |
+
|
| 266 |
+
sdir = ROOT / ".freestream/sessions" / sid
|
| 267 |
+
bot_log = EventLog(sdir / "bot-events.jsonl").events()
|
| 268 |
+
actions = [e for e in bot_log if e["type"] == "agent.action"]
|
| 269 |
+
check("character *actions* logged as events", len(actions) >= 1,
|
| 270 |
+
"; ".join(a["payload"]["text"] for a in actions)[:160])
|
| 271 |
+
|
| 272 |
+
# ---- leave + logs ----------------------------------------------------------------
|
| 273 |
+
r = run_cli("leave", "--session-id", sid)
|
| 274 |
+
out = {}
|
| 275 |
+
try:
|
| 276 |
+
out = json.loads(r.stdout.strip().splitlines()[-1])
|
| 277 |
+
except (ValueError, IndexError):
|
| 278 |
+
pass
|
| 279 |
+
check("CLI leave exits 0 with closed:true", r.returncode == 0 and out.get("closed") is True)
|
| 280 |
+
cli_ok, _ = EventLog(sdir / "events.jsonl").verify()
|
| 281 |
+
bot_ok, _ = EventLog(sdir / "bot-events.jsonl").verify()
|
| 282 |
+
check("both replay logs verify", cli_ok and bot_ok)
|
| 283 |
+
|
| 284 |
+
# ---- summary ---------------------------------------------------------------------
|
| 285 |
+
server.terminate()
|
| 286 |
+
print("\n--- roleplay latency (LLM in the loop; no 4s gate) ---", flush=True)
|
| 287 |
+
for i, t in enumerate(turns, start=1):
|
| 288 |
+
if t:
|
| 289 |
+
print(f"turn {i} t_perceived: {t['t_perceived']:.2f}s '{t['text'][:90]}'")
|
| 290 |
+
|
| 291 |
+
failed = [n for n, ok in results if not ok]
|
| 292 |
+
slow = [t["t_perceived"] for t in turns if t and t["t_perceived"] > 12.0]
|
| 293 |
+
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
|
| 294 |
+
if failed or slow:
|
| 295 |
+
print("FAILED: " + ", ".join(failed + (["turn > 12s"] if slow else [])))
|
| 296 |
+
sys.exit(1)
|
| 297 |
+
print("ROLEPLAY E2E OK")
|