diff --git a/ci/test_tier2_build_errors.py b/ci/test_tier2_build_errors.py index e4f2106f73..4cc4e0d0eb 100644 --- a/ci/test_tier2_build_errors.py +++ b/ci/test_tier2_build_errors.py @@ -149,6 +149,32 @@ def test_recovery_preserves_first_failure_and_keeps_one_retry(self): fields = output.read_text() if output.exists() else '' self.assertEqual('cache-healthy=false' in fields, bool(daemon_status)) + def test_mcp_plugin_child_inherits_uncached_recovery(self): + # The main retry succeeds, then validate.sh launches mcp-tests.sh. + # Its plugin builds must keep bypassing the daemon that just failed. + for daemon_status, expected in ((0, "unset"), (1, "1")): + with self.subTest(daemon_status=daemon_status), tempfile.TemporaryDirectory() as directory: + prefix = """ +cmake() { + if [ ! -f "$build.calls" ]; then + echo 1 > "$build.calls" + echo 'FAILED: [code=125] first.o' + return 1 + fi + echo 2 > "$build.calls" + return 0 +} +""" + child = "\nbash -c 'printf \"MCP cache bypass: %s\\n\" \"${ZCCACHE_DISABLE:-unset}\"'\n" + result = subprocess.run( + ['bash', '-euo', 'pipefail', '-c', prefix + self.recovery_script() + child], + env={**os.environ, 'SRC': str(ROOT), 'build': directory + '/build', + **self.zccache_stub(directory, str(daemon_status))}, + capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('MCP cache bypass: ' + expected, result.stdout) + self.assertEqual(Path(directory, 'build.calls').read_text().strip(), '2') + def test_recovery_clears_the_daemon_cool_down(self): # zccache 1.15.5 keeps the cache root in its recovery cool-down after # `zccache stop`, and the launcher then refuses even with diff --git a/ci/test_vcam_av_sync_mcp.py b/ci/test_vcam_av_sync_mcp.py new file mode 100644 index 0000000000..90deed5d68 --- /dev/null +++ b/ci/test_vcam_av_sync_mcp.py @@ -0,0 +1,91 @@ +#!/usr/bin/env -S uv run --script +"""MCP probe transport tests, without devices, GUI or optional numerical packages.""" +import asyncio +import importlib.util +import json +from pathlib import Path +import sys +import unittest +from unittest.mock import AsyncMock, Mock, patch + +# Numerical analysis is not exercised by these transport tests. +spec = importlib.util.spec_from_file_location("vcam_probe_under_test", Path(__file__).with_name("vcam_av_sync.py")) +probe = importlib.util.module_from_spec(spec) +with patch.dict(sys.modules, {"numpy": Mock()}): + spec.loader.exec_module(probe) +McpSession = probe.McpSession + +class Reader: + def __init__(self, reply): self.reply = reply + async def readline(self): return json.dumps(self.reply).encode() + b"\n" +class Writer: + def __init__(self): self.data = b"" + def write(self, data): self.data += data + async def drain(self): pass + +class McpProbeTransportTest(unittest.IsolatedAsyncioTestCase): + async def test_structured_reply_and_wire_request(self): + writer = Writer() + session = McpSession(Reader({"jsonrpc":"2.0", "id":1, "result":{"structuredContent":{"active":True}}}), writer) + self.assertEqual(await session.call("vcam_start", {"wait":True}), {"active":True}) + request = json.loads(writer.data) + self.assertEqual(request["params"], {"name":"vcam_start", "arguments":{"wait":True}}) + + async def test_domain_failure_and_wrong_id_are_errors(self): + for reply in [ + {"jsonrpc":"2.0", "id":1, "result":{"isError":True, "structuredContent":{"code":207, "message":"not ready"}}}, + {"jsonrpc":"2.0", "id":9, "result":{}}, + ]: + with self.assertRaises(RuntimeError): + await McpSession(Reader(reply), Writer()).call("vcam_start") + + async def test_probe_waits_and_always_removes_its_own_source(self): + async def reply(name, arguments=None): + return {"scene_get_current": {"name":"program"}, "screenshot":{"width":1280,"height":720}, + "vmic_status":{"active":True}, "wait_for":{"satisfied":True}}.get(name, {}) + session = Mock() + session.call = AsyncMock(side_effect=reply) + session.writer.wait_closed = AsyncMock() + recorder = Mock(returncode=0) + recorder.poll.return_value = 0 + args = Mock(mcp_socket="/test/socket", seconds=0, device="/dev/test", source="test-mic") + with patch.object(probe, "connect_mcp", AsyncMock(return_value=session)), \ + patch.object(probe.subprocess, "Popen", return_value=recorder), \ + patch.object(probe.asyncio, "sleep", AsyncMock()), \ + patch.object(probe, "analyze", return_value={"av_offset_ms":0}): + result = await probe.measure_mcp(args, Path("probe.mkv"), Path("capture.mkv")) + calls = session.call.await_args_list + names = [call.args[0] for call in calls] + self.assertLess(names.index("wait_for"), names.index("media_restart")) + self.assertEqual(names[-1], "source_remove") + created = next(call.args[1]["name"] for call in calls if call.args[0] == "source_create") + self.assertEqual(calls[-1].args[1]["name"], created) + self.assertEqual(result["transport"], "mcp") + session.writer.close.assert_called_once() + + async def test_auto_falls_back_only_when_websocket_connection_is_absent(self): + import tempfile + args = Mock(transport="auto", url="ws://absent") + websocket = Mock(connect=AsyncMock(side_effect=ConnectionRefusedError())) + with tempfile.TemporaryDirectory() as directory, \ + patch.dict(sys.modules, {"websockets":websocket}), \ + patch.object(probe.tempfile, "mkdtemp", return_value=directory), \ + patch.object(probe, "write_clip"), \ + patch.object(probe, "measure_mcp", AsyncMock(return_value={"transport":"mcp"})) as fallback: + self.assertEqual(await probe.measure(args), {"transport":"mcp"}) + fallback.assert_awaited_once() + args.transport = "websocket" + with self.assertRaises(ConnectionRefusedError): + await probe.measure(args) + + async def test_capture_that_ignores_sigint_is_killed_and_reaped(self): + recorder = Mock() + recorder.poll.return_value = None + with patch.object(probe.asyncio, "to_thread", AsyncMock(side_effect=[probe.subprocess.TimeoutExpired("ffmpeg", 10), 0])) as wait: + await probe.stop_capture(recorder) + recorder.send_signal.assert_called_once_with(probe.signal.SIGINT) + recorder.kill.assert_called_once() + self.assertEqual(wait.await_count, 2) + self.assertEqual([entry.kwargs for entry in wait.await_args_list], [{"timeout":10}, {"timeout":5}]) + +if __name__ == "__main__": unittest.main() diff --git a/ci/vcam_av_sync.py b/ci/vcam_av_sync.py index b4094938d6..ec7eb1e611 100644 --- a/ci/vcam_av_sync.py +++ b/ci/vcam_av_sync.py @@ -4,7 +4,7 @@ # /// """A/V sync of the Linux Virtual Camera and its OBS Virtual Microphone. -Drives a running OBS over obs-websocket (no clicks, no computer use): +Drives OBS over a private MCP socket or obs-websocket (no clicks, no computer use): uv run --script ci/vcam_av_sync.py measure [--seconds 12] [--url ws://127.0.0.1:4455] uv run --script ci/vcam_av_sync.py analyze @@ -31,6 +31,9 @@ import argparse import asyncio import json +import os +import stat +import uuid import signal import subprocess import sys @@ -155,14 +158,153 @@ async def obs_request(ws, kind: str, data: dict | None = None) -> dict: return msg["d"].get("responseData") or {} -async def measure(args: argparse.Namespace) -> dict: - import websockets +class McpSession: + """Bounded newline JSON-RPC exchange over an existing OBS socket.""" + + def __init__(self, reader, writer): + self.reader, self.writer = reader, writer + self.next_id = 0 + + async def rpc(self, method: str, params: dict) -> dict: + self.next_id += 1 + request = {"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params} + self.writer.write(json.dumps(request).encode() + b"\n") + await self.writer.drain() + line = await asyncio.wait_for(self.reader.readline(), timeout=310) + if not line: + raise RuntimeError("MCP socket closed before response") + reply = json.loads(line) + if reply.get("jsonrpc") != "2.0" or reply.get("id") != self.next_id: + raise RuntimeError("MCP response version/ID mismatch") + if "error" in reply: + raise RuntimeError(f"MCP protocol error: {reply['error']}") + if "result" not in reply: + raise RuntimeError("MCP response has no result") + return reply["result"] + + async def call(self, name: str, arguments: dict | None = None) -> dict: + result = await self.rpc("tools/call", {"name": name, "arguments": arguments or {}}) + if result.get("isError"): + raise RuntimeError(f"{name}: {result.get('structuredContent', result)}") + if "structuredContent" not in result: + raise RuntimeError(f"{name}: missing structuredContent") + return result["structuredContent"] + + +async def connect_mcp(socket_path: str | None): + """Attach without spawning a GUI or a second OBS.""" + if socket_path is None: + runtime = os.environ.get("XDG_RUNTIME_DIR") + if not runtime: + raise RuntimeError("XDG_RUNTIME_DIR is unset; use --mcp-socket") + socket_path = str(Path(runtime) / "obs-studio-rust/control.sock") + metadata = Path(socket_path).lstat() + if not stat.S_ISSOCK(metadata.st_mode) or metadata.st_uid != os.geteuid() or metadata.st_mode & 0o077: + raise RuntimeError("MCP endpoint must be a private socket owned by this user") + reader, writer = await asyncio.open_unix_connection(socket_path, limit=32 * 1024 * 1024) + session = McpSession(reader, writer) + try: + await session.rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "vcam-av-sync", "version": "1"}}) + writer.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}).encode() + b"\n") + await writer.drain() + return session + except BaseException: + writer.close() + await writer.wait_closed() + raise + + +async def stop_capture(recorder) -> None: + """Stop and reap a capture even when a device ignores SIGINT.""" + if recorder.poll() is not None: + return + recorder.send_signal(signal.SIGINT) + try: + await asyncio.to_thread(recorder.wait, timeout=10) + except subprocess.TimeoutExpired: + recorder.kill() + await asyncio.to_thread(recorder.wait, timeout=5) + +async def measure_mcp(args: argparse.Namespace, clip: Path, capture: Path) -> dict: + session = await connect_mcp(args.mcp_socket) + recorder = None + created = False + # A unique name prevents modifying or removing a user's existing source. + name = f"{SOURCE_NAME}-{uuid.uuid4().hex[:12]}" + try: + scene = (await session.call("scene_get_current"))["name"] + if not scene: + scene = f"vcam-av-sync-scene-{uuid.uuid4().hex[:12]}" + await session.call("scene_create", {"name": scene}) + video = await session.call("screenshot", {"source": scene}) + await session.call("vcam_start", {"wait": True, "timeout_ms": 5000, "audio_enabled": True}) + mic = await session.call("vmic_status") + if mic.get("active") is not True: + raise RuntimeError(f"virtual microphone is not active: {mic}") + await session.call("source_create", {"scene": scene, "kind": "ffmpeg_source", "name": name, + "settings": {"is_local_file": True, "local_file": str(clip), "looping": True, + "restart_on_activate": True, "close_when_inactive": False}}) + created = True + await session.call("scene_item_set_transform", {"scene": scene, "source": name, + "position": {"x": 0.0, "y": 0.0}, + "scale": {"x": video["width"] / 640.0, "y": video["height"] / 360.0}}) + state = await session.call("wait_for", {"condition": {"type": "media_state", "name": name, "state": "playing"}, + "timeout_ms": 10000}) + if not state["satisfied"]: + raise RuntimeError(f"probe did not start: {state}") + await session.call("stats_reset") + recorder = subprocess.Popen( + ["ffmpeg", "-loglevel", "error", "-y", "-f", "v4l2", "-ts", "abs", "-i", args.device, + "-f", "pulse", "-wallclock", "1", "-fragment_size", "1920", "-i", args.source, + "-map", "0:v", "-map", "1:a", "-c:v", "ffv1", "-c:a", "pcm_f32le", "-copyts", str(capture)]) + # Capture must already be listening before the known media timeline begins. + await asyncio.sleep(1.0) + await session.call("media_restart", {"name": name}) + restarted = time.time() + await asyncio.sleep(args.seconds) + await stop_capture(recorder) + if recorder.returncode not in (0, 255): + raise RuntimeError(f"ffmpeg capture failed: {recorder.returncode}") + snapshot = await session.call("stats_get") + finally: + original_error = sys.exception() + try: + if created: + await session.call("source_remove", {"name": name}) + except Exception as cleanup_error: + if original_error is None: + raise + original_error.add_note(f"probe cleanup also failed: {cleanup_error}") + finally: + try: + if recorder is not None: + await stop_capture(recorder) + finally: + session.writer.close() + await session.writer.wait_closed() + result = analyze(capture, EVENTS, restarted) + result.update({"capture": str(capture), "transport": "mcp", "stats": snapshot, + "measured_from": "independent ffmpeg v4l2/PulseAudio capture of flash/beep probe"}) + return result + + +async def measure(args: argparse.Namespace) -> dict: work = Path(tempfile.mkdtemp(prefix="vcam-av-sync-")) clip = work / "probe.mkv" write_clip(clip) capture = work / "capture.mkv" - async with websockets.connect(args.url, subprotocols=["obswebsocket.json"]) as ws: + if args.transport == "mcp": + return await measure_mcp(args, clip, capture) + import websockets + try: + ws = await websockets.connect(args.url, subprotocols=["obswebsocket.json"], open_timeout=5) + except (OSError, TimeoutError): + if args.transport == "auto": + return await measure_mcp(args, clip, capture) + raise + try: await ws.recv() await ws.send(json.dumps({"op": 1, "d": {"rpcVersion": 1}})) await ws.recv() @@ -199,7 +341,10 @@ async def measure(args: argparse.Namespace) -> dict: await asyncio.to_thread(recorder.wait) finally: await obs_request(ws, "RemoveInput", {"inputName": SOURCE_NAME}) + finally: + await ws.close() result = analyze(capture, EVENTS, restarted) + result["transport"] = "websocket" result["capture"] = str(capture) return result @@ -224,6 +369,8 @@ def main(argv: list[str]) -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = parser.add_subparsers(dest="cmd", required=True) m = sub.add_parser("measure") + m.add_argument("--transport", choices=("auto", "websocket", "mcp"), default="auto") + m.add_argument("--mcp-socket", default=None) m.add_argument("--url", default="ws://127.0.0.1:4455") m.add_argument("--device", default="/dev/video9") m.add_argument("--source", default="obs_virtual_microphone") diff --git a/docs/features.md b/docs/features.md index b6bdc8a63a..48070941a0 100644 --- a/docs/features.md +++ b/docs/features.md @@ -3075,3 +3075,7 @@ area. - **Control socket** (#4456): private Unix MCP endpoint, `--mcp-attach` stdio proxy, and an in-app frontend module that controls the existing OBS instance. + +- **Typed control client and probe** (#4457): fluent Rust socket client and + `ci/vcam_av_sync.py --transport mcp` with automatic fallback when the websocket + service is absent, bounded capture shutdown, typed waits and probe cleanup. diff --git a/docs/rust-port/control-api.md b/docs/rust-port/control-api.md index ec5d238380..69f3f66b55 100644 --- a/docs/rust-port/control-api.md +++ b/docs/rust-port/control-api.md @@ -72,3 +72,24 @@ Keep its stdin open for the test's lifetime; EOF stops the socket and libobs. The attached backend resolves frontend scenes and output names on each call, preserves coordinate settings, and queues scene changes through the graphics thread so the frontend's UI mutation path cannot block shutdown. + +## Clients and the A/V probe + +```rust,ignore +let obs = obs_mcp::client::Client::attach(Default::default())?; +obs.vcam().start(obs_mcp::tools::control::StartInput { + wait: true, ..Default::default() +})?; +obs.wait_for(condition).timeout_ms(5000).call()?; +``` + +`uv run --script ci/vcam_av_sync.py measure --transport mcp --mcp-socket PATH` +creates a uniquely named media probe in the program scene, waits for playback, +starts independent ffmpeg v4l2/PulseAudio capture, restarts the clip and reports +A/V offset, per-path latency and `stats_get`. `source_remove` cleans up the probe. +`--transport auto` (default) falls back to MCP only when the websocket connection +cannot be opened. `--transport websocket` preserves the original path. Auth and +protocol failures are surfaced rather than retried with a second transport. +Capture timing is relative to the media restart response wall clock; the server +keeps end-to-end offset null until an independent capture probe measures it. +Run actual device capture only inside bosn. No GUI interaction is required. diff --git a/docs/rust-port/control-api.schema.json b/docs/rust-port/control-api.schema.json index cc60c0a65a..5f6e40f4bc 100644 --- a/docs/rust-port/control-api.schema.json +++ b/docs/rust-port/control-api.schema.json @@ -1,5 +1,5 @@ { - "toolError": {"$defs":{"ErrorCategory":{"description":"Domain failure category, using obs-websocket v5 status ranges.","oneOf":[{"const":"not_ready","description":"A resource is absent or not ready (ResourceNotFound/NotReady).","type":"string"},{"const":"wrong_state","description":"The current state prevents the operation (6xx).","type":"string"},{"const":"processing","description":"OBS failed to process the operation (7xx).","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A domain failure, distinct from a JSON-RPC fault.","properties":{"category":{"$ref":"#/$defs/ErrorCategory","description":"Stable machine-readable category."},"code":{"description":"obs-websocket v5 RequestStatus code.","format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"message":{"description":"Human-readable context.","type":"string"},"retryable":{"description":"Whether a later retry may succeed.","type":"boolean"}},"required":["code","category","message","retryable"],"title":"ToolError","type":"object"}, + "toolError": {"$defs":{"ErrorCategory":{"description":"Domain failure category, using obs-websocket v5 status ranges.","oneOf":[{"const":"not_ready","description":"A resource is absent or not ready (ResourceNotFound/NotReady).","type":"string"},{"const":"wrong_state","description":"The current state prevents the operation (6xx).","type":"string"},{"const":"processing","description":"OBS failed to process the operation (7xx).","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"A domain failure, distinct from a JSON-RPC fault.","properties":{"category":{"$ref":"#/$defs/ErrorCategory","description":"Stable machine-readable category."},"code":{"description":"obs-websocket v5 RequestStatus code.","format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"message":{"description":"Human-readable context.","type":"string"},"retryable":{"description":"Whether a later retry may succeed.","type":"boolean"}},"required":["code","category","message","retryable"],"title":"ToolError","type":"object"}, "tools": [ {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_restart","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_status","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, @@ -18,6 +18,7 @@ {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"scenes_list","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Scene listing.","properties":{"scenes":{"description":"Scene names in display order.","items":{"type":"string"},"type":"array"}},"required":["scenes"],"title":"ScenesOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Screenshot selection and requested size.","properties":{"height":{"description":"Height in pixels.","format":"uint32","minimum":0,"type":["integer","null"]},"source":{"description":"Source to capture; omit for program output.","type":["string","null"]},"width":{"description":"Width in pixels.","format":"uint32","minimum":0,"type":["integer","null"]}},"title":"CaptureInput","type":"object"},"name":"screenshot","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Captured PNG and its dimensions.","properties":{"data":{"description":"PNG bytes encoded in base64.","type":"string"},"height":{"description":"Height in pixels.","format":"uint32","minimum":0,"type":"integer"},"source":{"description":"Source name, or null for program output.","type":["string","null"]},"width":{"description":"Width in pixels.","format":"uint32","minimum":0,"type":"integer"}},"required":["data","width","height"],"title":"CaptureOutput","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Source creation, optionally placing it in a scene.","properties":{"kind":{"description":"Source kind id.","type":"string"},"name":{"description":"Unique name.","type":"string"},"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"Initial position (requires scene)."},"scene":{"description":"Scene receiving the source.","type":["string","null"]},"settings":{"additionalProperties":true,"description":"Kind-specific settings.","type":"object"}},"required":["kind","name","settings"],"title":"CreateInput","type":"object"},"name":"source_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Created source.","properties":{"item":{"description":"Created item id.","format":"int64","type":["integer","null"]},"kind":{"description":"Source kind.","type":"string"},"name":{"description":"Source name.","type":"string"},"scene":{"description":"Scene receiving the new item.","type":["string","null"]}},"required":["name","kind"],"title":"CreateOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Remove a source by name.","properties":{"name":{"type":"string"}},"required":["name"],"title":"RemoveInput","type":"object"},"name":"source_remove","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Updated source name.","properties":{"name":{"description":"Source name.","type":"string"}},"required":["name"],"title":"NameOutput","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Settings update.","properties":{"name":{"description":"Source name.","type":"string"},"settings":{"additionalProperties":true,"description":"Kind-specific settings to merge.","type":"object"}},"required":["name","settings"],"title":"SettingsInput","type":"object"},"name":"source_set_settings","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Updated source name.","properties":{"name":{"description":"Source name.","type":"string"}},"required":["name"],"title":"NameOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"sources_list","outputSchema":{"$defs":{"SourceInfo":{"description":"A source as listed by [`SourceBackend::sources`].","properties":{"kind":{"description":"The source kind id, such as `color_source`.","type":"string"},"name":{"description":"The source's unique name.","type":"string"}},"required":["name","kind"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Source listing.","properties":{"sources":{"description":"Sources in stable order.","items":{"$ref":"#/$defs/SourceInfo"},"type":"array"}},"required":["sources"],"title":"SourcesOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_get","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"generation":{"description":"Counter generation, when the provider exposes one.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index 47c8260e0b..814cc7a38d 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -316,6 +316,23 @@ impl SceneBackend for ObsBackend { } impl SourceBackend for ObsBackend { + fn remove_source( + &self, + request: crate::tools::sources::RemoveInput, + ) -> Result { + let source = Source::by_name(&request.name).ok_or_else(|| { + crate::server::ToolError::not_found(format!("no source named '{}'", request.name)) + })?; + if source.is_scene() { + return Err(crate::server::ToolError::wrong_state( + "use scene_remove for scenes", + )); + } + source.remove(); + self.owned.borrow_mut().remove(&request.name); + Ok(crate::tools::sources::NameOutput { name: request.name }) + } + fn sources(&self) -> Vec { sorted(ffi::inputs()) .into_iter() diff --git a/rust/obs-mcp/src/client.rs b/rust/obs-mcp/src/client.rs new file mode 100644 index 0000000000..cb56c6d257 --- /dev/null +++ b/rust/obs-mcp/src/client.rs @@ -0,0 +1,261 @@ +//! Synchronous typed client for an existing OBS control socket. +pub use crate::tools::control::{MediaInput, StartInput, StatsSnapshot, VcamStatus, VmicStatus}; +pub use crate::tools::waiting::Condition; +use crate::{ + platform::{self, Connection, EndpointOptions}, + server::ToolError, + tools::{self, EmptyInput as Empty}, +}; +use serde::{Serialize, de::DeserializeOwned}; +use serde_json::{Value, json}; +use std::{ + fmt, + io::{self, Write}, + sync::Mutex, +}; +/// Connection, protocol or structured domain failure. +#[derive(Debug)] +pub enum Error { + Io(io::Error), + Protocol(String), + Domain(ToolError), +} +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Io(e) => e.fmt(f), + Self::Protocol(e) => f.write_str(e), + Self::Domain(e) => e.fmt(f), + } + } +} +impl std::error::Error for Error {} +impl From for Error { + fn from(e: io::Error) -> Self { + Self::Io(e) + } +} +fn protocol(e: impl fmt::Display) -> Error { + Error::Protocol(e.to_string()) +} +struct State { + connection: Connection, + next_id: u64, +} +impl State { + fn request(&mut self, method: &str, params: Value) -> Result { + self.next_id = self + .next_id + .checked_add(1) + .ok_or_else(|| protocol("request ID exhausted"))?; + let id = self.next_id; + serde_json::to_writer( + &mut self.connection.writer, + &json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}), + ) + .map_err(protocol)?; + self.connection.writer.write_all(b"\n")?; + self.connection.writer.flush()?; + let mut line = Vec::new(); + // Bound reads even for a peer that never sends a newline. + loop { + let buffer = self.connection.reader.fill_buf()?; + if buffer.is_empty() { + return Err(protocol("control socket closed before response")); + } + let count = buffer + .iter() + .position(|b| *b == b'\n') + .map_or(buffer.len(), |n| n + 1); + if line.len().saturating_add(count) > 32 * 1024 * 1024 { + return Err(protocol("control response exceeds 32 MiB")); + } + line.extend_from_slice(&buffer[..count]); + self.connection.reader.consume(count); + if line.last() == Some(&b'\n') { + break; + } + } + let response: Value = serde_json::from_slice(&line).map_err(protocol)?; + if response["jsonrpc"] != "2.0" || response["id"] != id { + return Err(protocol("invalid JSON-RPC version or response ID")); + } + if let Some(error) = response.get("error") { + return Err(protocol(format!("JSON-RPC error: {error}"))); + } + response + .get("result") + .cloned() + .ok_or_else(|| protocol("response has no result")) + } +} +/// Fluent, synchronous client. A mutex serializes requests and response IDs. +pub struct Client { + state: Mutex, +} +impl Client { + /// Connect to an existing instance. This never spawns OBS. + /// # Errors + /// Returns endpoint, handshake or protocol failures. + pub fn attach(options: EndpointOptions) -> Result { + Self::from_connection(platform::connect(&options)?) + } + /// Initialize an already-connected byte stream (also useful for embedded peers). + /// # Errors + /// Returns handshake or I/O failures. + pub fn from_connection(connection: Connection) -> Result { + let mut state = State { + connection, + next_id: 0, + }; + state.request("initialize",json!({"protocolVersion":crate::server::PROTOCOL_VERSION,"capabilities":{},"clientInfo":{"name":"obs-mcp-rust","version":env!("CARGO_PKG_VERSION")}}))?; + serde_json::to_writer( + &mut state.connection.writer, + &json!({"jsonrpc":"2.0","method":"notifications/initialized"}), + ) + .map_err(protocol)?; + state.connection.writer.write_all(b"\n")?; + state.connection.writer.flush()?; + Ok(Self { + state: Mutex::new(state), + }) + } + fn call(&self, name: &str, input: I) -> Result { + let params = + json!({"name":name,"arguments":serde_json::to_value(input).map_err(protocol)?}); + let result = self + .state + .lock() + .map_err(protocol)? + .request("tools/call", params)?; + let content = result + .get("structuredContent") + .ok_or_else(|| protocol("tool response has no structuredContent"))?; + if result["isError"] == true { + return Err(Error::Domain( + serde_json::from_value(content.clone()).map_err(protocol)?, + )); + } + serde_json::from_value(content.clone()).map_err(protocol) + } + #[must_use] + pub fn vcam(&self) -> Vcam<'_> { + Vcam(self) + } + #[must_use] + pub fn vmic(&self) -> Vmic<'_> { + Vmic(self) + } + #[must_use] + pub fn media(&self) -> Media<'_> { + Media(self) + } + #[must_use] + pub fn stats(&self) -> Stats<'_> { + Stats(self) + } + /// Build a typed wait with the default five-second deadline. + #[must_use] + pub fn wait_for(&self, condition: tools::waiting::Condition) -> Wait<'_> { + Wait { + client: self, + input: tools::waiting::WaitInput { + condition, + timeout_ms: tools::waiting::DEFAULT_TIMEOUT_MS, + }, + } + } + /// Read the complete control pipeline. + /// # Errors + /// Returns a peer or domain failure. + pub fn pipeline_dump(&self) -> Result { + self.call("pipeline_dump", Empty {}) + } + /// A no-side-effect transport probe. + /// # Errors + /// Returns a protocol or I/O failure. + pub fn ping(&self) -> Result<(), Error> { + self.state + .lock() + .map_err(protocol)? + .request("ping", json!({}))?; + Ok(()) + } +} +pub struct Vcam<'a>(&'a Client); +impl Vcam<'_> { + /// # Errors + /// Returns a peer or domain failure. + pub fn start( + &self, + input: tools::control::StartInput, + ) -> Result { + self.0.call("vcam_start", input) + } + /// # Errors + /// Returns a peer or domain failure. + pub fn stop(&self) -> Result { + self.0.call("vcam_stop", Empty {}) + } + /// # Errors + /// Returns a peer or domain failure. + pub fn status(&self) -> Result { + self.0.call("vcam_status", Empty {}) + } +} +pub struct Vmic<'a>(&'a Client); +impl Vmic<'_> { + /// # Errors + /// Returns a peer or domain failure. + pub fn status(&self) -> Result { + self.0.call("vmic_status", Empty {}) + } +} +pub struct Media<'a>(&'a Client); +impl Media<'_> { + /// # Errors + /// Returns a peer or domain failure. + pub fn restart( + &self, + input: tools::control::MediaInput, + ) -> Result { + self.0.call("media_restart", input) + } + /// # Errors + /// Returns a peer or domain failure. + pub fn status( + &self, + input: tools::control::MediaInput, + ) -> Result { + self.0.call("media_status", input) + } +} +pub struct Stats<'a>(&'a Client); +impl Stats<'_> { + /// # Errors + /// Returns a peer or domain failure. + pub fn get(&self) -> Result { + self.0.call("stats_get", Empty {}) + } + /// # Errors + /// Returns a peer or domain failure. + pub fn reset(&self) -> Result { + self.0.call("stats_reset", Empty {}) + } +} +pub struct Wait<'a> { + client: &'a Client, + input: tools::waiting::WaitInput, +} +impl Wait<'_> { + #[must_use] + pub fn timeout_ms(mut self, timeout_ms: u64) -> Self { + self.input.timeout_ms = timeout_ms; + self + } + /// # Errors + /// Returns a peer or domain failure. Timeout is a normal unsatisfied response. + pub fn call(self) -> Result { + self.client.call("wait_for", self.input) + } +} diff --git a/rust/obs-mcp/src/lib.rs b/rust/obs-mcp/src/lib.rs index 5279e4f382..1dacb1937e 100644 --- a/rust/obs-mcp/src/lib.rs +++ b/rust/obs-mcp/src/lib.rs @@ -41,4 +41,5 @@ pub fn serve(reader: R, writer: W) -> io::Result<()> { server::Server::new().serve(reader, writer) } +pub mod client; pub mod platform; diff --git a/rust/obs-mcp/src/server/typed.rs b/rust/obs-mcp/src/server/typed.rs index d1f3d5a4e0..b271048290 100644 --- a/rust/obs-mcp/src/server/typed.rs +++ b/rust/obs-mcp/src/server/typed.rs @@ -51,7 +51,6 @@ pub enum ErrorCategory { } /// A domain failure, distinct from a JSON-RPC fault. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] -#[serde(deny_unknown_fields)] pub struct ToolError { /// obs-websocket v5 RequestStatus code. pub code: u16, diff --git a/rust/obs-mcp/src/tools/sources.rs b/rust/obs-mcp/src/tools/sources.rs index b246af156e..39de929365 100644 --- a/rust/obs-mcp/src/tools/sources.rs +++ b/rust/obs-mcp/src/tools/sources.rs @@ -67,6 +67,15 @@ pub struct Transform { /// Methods take `&self`: libobs owns the state, so implementations use their /// own interior mutability. pub trait SourceBackend { + /// Remove an owned or application source, including its scene references. + /// # Errors + /// Reports a missing source or unsupported removal. + fn remove_source(&self, _request: RemoveInput) -> Result { + Err(ToolError::processing( + "source removal is not supported by this backend", + )) + } + /// Typed `ListSources` backend operation. /// # Errors /// Reports invalid state, a missing resource or processing failure. @@ -289,6 +298,12 @@ pub struct CreateOutput { #[serde(default, skip_serializing_if = "Option::is_none")] pub item: Option, } +/// Remove a source by name. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct RemoveInput { + pub name: String, +} /// Settings update. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] @@ -466,6 +481,16 @@ typed_tool!( "Create a source of the given kind with a name and settings. Give `scene` (and optionally `position`) to also add it to that scene as an item.", |backend, input| { backend.create_source(input) } ); +typed_tool!( + RemoveSource, + "source_remove", + SourceBackend, + RemoveInput, + NameOutput, + MUTATING, + "Remove a source and its references from scenes.", + |backend, input| { backend.remove_source(input) } +); typed_tool!( SetSettings, "source_set_settings", @@ -516,7 +541,7 @@ typed_tool!( "Set the position, scale and/or rotation of a scene item, named by `item` (id from scene_items_list) or `source`.", |backend, input| { backend.update_transform(input) } ); -/// Registers seven typed source tools. +/// Registers typed source tools, including probe cleanup. pub fn register(registry: &mut ToolRegistry, backend: &Rc) { registry.register(Box::new(ListSources { backend: Rc::clone(backend), @@ -524,6 +549,9 @@ pub fn register(registry: &mut ToolRegistry, backend: &Rc) { registry.register(Box::new(CreateSource { backend: Rc::clone(backend), })); + registry.register(Box::new(RemoveSource { + backend: Rc::clone(backend), + })); registry.register(Box::new(SetSettings { backend: Rc::clone(backend), })); @@ -547,6 +575,7 @@ pub fn schemas() -> Vec { vec![ crate::server::tool_schema::(), crate::server::tool_schema::(), + crate::server::tool_schema::(), crate::server::tool_schema::(), crate::server::tool_schema::(), crate::server::tool_schema::(), diff --git a/rust/obs-mcp/tests/mcp/client.rs b/rust/obs-mcp/tests/mcp/client.rs new file mode 100644 index 0000000000..713bc51fbe --- /dev/null +++ b/rust/obs-mcp/tests/mcp/client.rs @@ -0,0 +1,73 @@ +use obs_mcp::{ + client::{Client, Error}, + platform::Connection, + tools::control::StartInput, +}; +use serde_json::{Value, json}; +use std::{ + io::{self, Write}, + sync::{Arc, Mutex}, +}; +#[derive(Clone, Default)] +struct Captured(Arc>>); +impl Write for Captured { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} +fn connection(reply: Value) -> (Connection, Captured) { + let output = Captured::default(); + let data = format!("{}\n{reply}\n", json!({"jsonrpc":"2.0","id":1,"result":{}})); + ( + Connection { + reader: Box::new(io::Cursor::new(data.into_bytes())), + writer: Box::new(output.clone()), + }, + output, + ) +} +#[test] +fn client_reuses_typed_inputs_and_structured_outputs() { + let (connection, written) = connection( + json!({"jsonrpc":"2.0","id":2,"result":{"structuredContent":{"configured":true,"active":true,"vmic_active":true}}}), + ); + let client = Client::from_connection(connection).unwrap(); + assert!( + client + .vcam() + .start(StartInput { + wait: true, + ..Default::default() + }) + .unwrap() + .active + ); + let bytes = written.0.lock().unwrap(); + let requests: Vec = std::str::from_utf8(&bytes) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!(requests[2]["params"]["name"], "vcam_start"); + assert_eq!(requests[2]["params"]["arguments"]["wait"], true); +} +#[test] +fn client_preserves_domain_error_and_rejects_wrong_id() { + let (stream, _) = connection( + json!({"jsonrpc":"2.0","id":2,"result":{"isError":true,"structuredContent":{"code":207,"category":"not_ready","message":"video unavailable","retryable":true,"future_context":{"stage":"render"}}}}), + ); + let client = Client::from_connection(stream).unwrap(); + assert!( + matches!(client.vcam().start(StartInput::default()),Err(Error::Domain(error)) if error.code==207 && error.retryable) + ); + let (stream, _) = connection(json!({"jsonrpc":"2.0","id":99,"result":{}})); + let client = Client::from_connection(stream).unwrap(); + assert!(matches!( + client.vcam().start(StartInput::default()), + Err(Error::Protocol(_)) + )); +} diff --git a/rust/obs-mcp/tests/mcp/main.rs b/rust/obs-mcp/tests/mcp/main.rs index 91c270fa13..bbc6bf40e4 100644 --- a/rust/obs-mcp/tests/mcp/main.rs +++ b/rust/obs-mcp/tests/mcp/main.rs @@ -30,4 +30,5 @@ mod control; mod waiting; +mod client; mod transport; diff --git a/rust/obs-mcp/tests/mcp/sources.rs b/rust/obs-mcp/tests/mcp/sources.rs index 12ce475169..85d0acaf50 100644 --- a/rust/obs-mcp/tests/mcp/sources.rs +++ b/rust/obs-mcp/tests/mcp/sources.rs @@ -44,6 +44,18 @@ impl Fake { } impl SourceBackend for Fake { + fn remove_source( + &self, + request: obs_mcp::tools::sources::RemoveInput, + ) -> Result { + if !self.has(&request.name) { + return Err(obs_mcp::server::ToolError::not_found("source absent")); + } + self.sources + .borrow_mut() + .retain(|(source, _)| source.name != request.name); + Ok(obs_mcp::tools::sources::NameOutput { name: request.name }) + } fn sources(&self) -> Vec { self.sources .borrow() @@ -170,7 +182,7 @@ fn with_source(name: &str) -> (Rc, Server) { } #[test] -fn lists_seven_tools_with_object_schemas() { +fn lists_source_tools_with_object_schemas() { let mut s = server(&Rc::new(Fake::default())); let r = rpc(&mut s, "tools/list", &json!({})); let tools = r["result"]["tools"].as_array().unwrap(); @@ -184,6 +196,7 @@ fn lists_seven_tools_with_object_schemas() { "scene_item_set_visible", "scene_items_list", "source_create", + "source_remove", "source_set_settings", "sources_list" ] @@ -220,6 +233,26 @@ fn lists_seven_tools_with_object_schemas() { assert_eq!(xf["rotation"]["type"], json!(["number", "null"])); } +#[test] +fn probe_source_can_be_removed_through_the_typed_wire_call() { + let fake = Rc::new(Fake::default()); + let mut server = server(&fake); + assert!( + !call( + &mut server, + "source_create", + &json!({"name":"probe","kind":"color_source","settings":{}}) + ) + .0 + ); + assert_eq!( + call(&mut server, "source_remove", &json!({"name":"probe"})), + (false, json!({"name":"probe"})) + ); + assert!(fake.sources.borrow().is_empty()); + assert!(call(&mut server, "source_remove", &json!({"name":"probe"})).0); +} + #[test] fn create_and_list() { let mut s = server(&Rc::new(Fake::default())); diff --git a/rust/tools/linux-validate/validate.sh b/rust/tools/linux-validate/validate.sh index 672dfdf50c..322feb4a24 100755 --- a/rust/tools/linux-validate/validate.sh +++ b/rust/tools/linux-validate/validate.sh @@ -263,10 +263,10 @@ else echo 'cache-healthy=false' >>"$GITHUB_OUTPUT" fi fi - ( - if [ "$daemon_unavailable" = 1 ]; then export ZCCACHE_DISABLE=1; fi - cmake --build "$build" --target "${tier2_targets[@]}" -- -k 0 - ) >"$build.build.log" 2>&1 || + # Later MCP plugin builds run in a child shell too: keep the bypass + # in this validation process when the daemon cannot be recovered. + if [ "$daemon_unavailable" = 1 ]; then export ZCCACHE_DISABLE=1; fi + cmake --build "$build" --target "${tier2_targets[@]}" -- -k 0 >"$build.build.log" 2>&1 || { uv run --no-project "$SRC"/rust/tools/linux-validate/build_errors.py "$build.build.log"; exit 1; } else uv run --no-project "$SRC"/rust/tools/linux-validate/build_errors.py "$build.build.log"