Wire Unity editor snapshots into Brokkr
This commit is contained in:
parent
16adc98447
commit
2b8a247087
16 changed files with 690 additions and 26 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -1,6 +1,7 @@
|
|||
target/
|
||||
.brokkr/
|
||||
.brokkr-smoke/
|
||||
BrokkrUnitySmoke/
|
||||
*.user
|
||||
*.suo
|
||||
Library/
|
||||
|
|
@ -12,4 +13,3 @@ Logs/
|
|||
UserSettings/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
|
|
|
|||
14
README.md
14
README.md
|
|
@ -42,3 +42,17 @@ cargo run -p brokkr-daemon -- provider
|
|||
The first smoke prints the typed provider advertisement. That is deliberately
|
||||
small: discovery shape first, live sockets second.
|
||||
|
||||
## Unity Smoke
|
||||
|
||||
```powershell
|
||||
cargo run -p brokkr-daemon -- serve
|
||||
```
|
||||
|
||||
Add the Unity package by local path:
|
||||
|
||||
```json
|
||||
"com.gamecult.brokkr": "file:E:/Projects/Brokkr/surfaces/unity/Packages/com.gamecult.brokkr"
|
||||
```
|
||||
|
||||
Then open `GameCult > Brokkr` in Unity and publish a snapshot to the local
|
||||
daemon.
|
||||
|
|
|
|||
|
|
@ -8,4 +8,3 @@ publish = false
|
|||
anyhow = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,14 @@
|
|||
use anyhow::Result;
|
||||
use serde::Serialize;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
const PROVIDER_SCHEMA: &str = "gamecult.brokkr.provider_advertisement.v0";
|
||||
const PROVIDER_ID: &str = "brokkr.creative_tool_broker";
|
||||
const CULTMESH_BASE_URI: &str = "cultmesh://brokkr";
|
||||
const DEFAULT_BIND: &str = "127.0.0.1:8798";
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
|
@ -72,16 +77,69 @@ struct CommandPolicy {
|
|||
notes: Vec<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ToolHostSnapshot {
|
||||
schema: String,
|
||||
provider_id: String,
|
||||
tool_kind: String,
|
||||
project_path: String,
|
||||
observed_at: String,
|
||||
unity_version: Option<String>,
|
||||
product_name: Option<String>,
|
||||
active_scene_path: Option<String>,
|
||||
open_scene_count: Option<u32>,
|
||||
selected_object_names: Vec<String>,
|
||||
asset_count: Option<u32>,
|
||||
capabilities: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct BrokerState {
|
||||
unity_snapshot: Option<ToolHostSnapshot>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct HealthResponse<'a> {
|
||||
ok: bool,
|
||||
provider_id: &'a str,
|
||||
version: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct HostSnapshotsResponse {
|
||||
unity: Option<ToolHostSnapshot>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SnapshotReceipt<'a> {
|
||||
schema: &'a str,
|
||||
provider_id: &'a str,
|
||||
tool_kind: &'a str,
|
||||
accepted_at: String,
|
||||
status: &'a str,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let command = std::env::args()
|
||||
.nth(1)
|
||||
.unwrap_or_else(|| "provider".to_string());
|
||||
let mut args = std::env::args().skip(1);
|
||||
let command = args.next().unwrap_or_else(|| "provider".to_string());
|
||||
|
||||
match command.as_str() {
|
||||
"provider" => print_provider(),
|
||||
"smoke" => print_provider(),
|
||||
"serve" => {
|
||||
let bind = match args.next().as_deref() {
|
||||
Some("--bind") => args.next().unwrap_or_else(|| DEFAULT_BIND.to_string()),
|
||||
Some(value) => value.to_string(),
|
||||
None => DEFAULT_BIND.to_string(),
|
||||
};
|
||||
serve(&bind)
|
||||
}
|
||||
_ => {
|
||||
eprintln!("usage: brokkr-daemon [provider|smoke]");
|
||||
eprintln!("usage: brokkr-daemon [provider|smoke|serve [--bind] [addr]]");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
|
|
@ -93,6 +151,172 @@ fn print_provider() -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn serve(bind: &str) -> Result<()> {
|
||||
let listener =
|
||||
TcpListener::bind(bind).with_context(|| format!("failed to bind Brokkr on {bind}"))?;
|
||||
let state = Arc::new(Mutex::new(BrokerState::default()));
|
||||
eprintln!("Brokkr listening on http://{bind}");
|
||||
|
||||
for stream in listener.incoming() {
|
||||
let stream = stream.context("failed to accept connection")?;
|
||||
let state = Arc::clone(&state);
|
||||
if let Err(error) = handle_connection(stream, state) {
|
||||
eprintln!("request failed: {error:#}");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_connection(mut stream: TcpStream, state: Arc<Mutex<BrokerState>>) -> Result<()> {
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
let request = read_http_request(&mut stream)?;
|
||||
|
||||
let response = match (request.method.as_str(), request.path.as_str()) {
|
||||
("GET", "/health") => json_response(
|
||||
200,
|
||||
&HealthResponse {
|
||||
ok: true,
|
||||
provider_id: PROVIDER_ID,
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
},
|
||||
)?,
|
||||
("GET", "/provider") => json_response(200, &build_provider_advertisement())?,
|
||||
("GET", "/hosts") => {
|
||||
let state = state.lock().expect("broker state poisoned");
|
||||
json_response(
|
||||
200,
|
||||
&HostSnapshotsResponse {
|
||||
unity: state.unity_snapshot.clone(),
|
||||
},
|
||||
)?
|
||||
}
|
||||
("POST", "/hosts/unity/snapshot") => {
|
||||
let snapshot: ToolHostSnapshot = serde_json::from_slice(&request.body)
|
||||
.context("invalid Unity host snapshot JSON")?;
|
||||
validate_unity_snapshot(&snapshot)?;
|
||||
let receipt = SnapshotReceipt {
|
||||
schema: "gamecult.brokkr.snapshot_receipt.v0",
|
||||
provider_id: "brokkr.unity_editor",
|
||||
tool_kind: "unity-editor",
|
||||
accepted_at: unix_millis_timestamp(),
|
||||
status: "accepted",
|
||||
};
|
||||
state.lock().expect("broker state poisoned").unity_snapshot = Some(snapshot);
|
||||
json_response(202, &receipt)?
|
||||
}
|
||||
_ => text_response(404, "not found"),
|
||||
};
|
||||
|
||||
stream.write_all(response.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_unity_snapshot(snapshot: &ToolHostSnapshot) -> Result<()> {
|
||||
if snapshot.schema != "gamecult.brokkr.tool_host_snapshot.v0" {
|
||||
bail!("unexpected snapshot schema: {}", snapshot.schema);
|
||||
}
|
||||
if snapshot.provider_id != "brokkr.unity_editor" {
|
||||
bail!("unexpected provider id: {}", snapshot.provider_id);
|
||||
}
|
||||
if snapshot.tool_kind != "unity-editor" {
|
||||
bail!("unexpected tool kind: {}", snapshot.tool_kind);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct HttpRequest {
|
||||
method: String,
|
||||
path: String,
|
||||
body: Vec<u8>,
|
||||
}
|
||||
|
||||
fn read_http_request(stream: &mut TcpStream) -> Result<HttpRequest> {
|
||||
let mut buffer = Vec::new();
|
||||
let mut chunk = [0_u8; 4096];
|
||||
let header_end;
|
||||
|
||||
loop {
|
||||
let bytes_read = stream.read(&mut chunk)?;
|
||||
if bytes_read == 0 {
|
||||
bail!("connection closed before headers");
|
||||
}
|
||||
buffer.extend_from_slice(&chunk[..bytes_read]);
|
||||
if let Some(index) = find_header_end(&buffer) {
|
||||
header_end = index;
|
||||
break;
|
||||
}
|
||||
if buffer.len() > 64 * 1024 {
|
||||
bail!("request headers too large");
|
||||
}
|
||||
}
|
||||
|
||||
let header_text = std::str::from_utf8(&buffer[..header_end]).context("headers not utf-8")?;
|
||||
let mut lines = header_text.lines();
|
||||
let request_line = lines.next().context("missing request line")?;
|
||||
let mut parts = request_line.split_whitespace();
|
||||
let method = parts.next().context("missing method")?.to_string();
|
||||
let path = parts.next().context("missing path")?.to_string();
|
||||
|
||||
let mut content_length = 0_usize;
|
||||
for line in lines {
|
||||
if let Some(value) = line.strip_prefix("Content-Length:") {
|
||||
content_length = value.trim().parse().context("bad Content-Length")?;
|
||||
} else if let Some(value) = line.strip_prefix("content-length:") {
|
||||
content_length = value.trim().parse().context("bad Content-Length")?;
|
||||
}
|
||||
}
|
||||
|
||||
let body_start = header_end + 4;
|
||||
while buffer.len() < body_start + content_length {
|
||||
let bytes_read = stream.read(&mut chunk)?;
|
||||
if bytes_read == 0 {
|
||||
bail!("connection closed before body");
|
||||
}
|
||||
buffer.extend_from_slice(&chunk[..bytes_read]);
|
||||
}
|
||||
|
||||
Ok(HttpRequest {
|
||||
method,
|
||||
path,
|
||||
body: buffer[body_start..body_start + content_length].to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
fn find_header_end(buffer: &[u8]) -> Option<usize> {
|
||||
buffer.windows(4).position(|window| window == b"\r\n\r\n")
|
||||
}
|
||||
|
||||
fn json_response<T: Serialize>(status: u16, value: &T) -> Result<String> {
|
||||
let body = serde_json::to_string_pretty(value)?;
|
||||
Ok(http_response(status, "application/json", &body))
|
||||
}
|
||||
|
||||
fn text_response(status: u16, body: &str) -> String {
|
||||
http_response(status, "text/plain; charset=utf-8", body)
|
||||
}
|
||||
|
||||
fn http_response(status: u16, content_type: &str, body: &str) -> String {
|
||||
let reason = match status {
|
||||
200 => "OK",
|
||||
202 => "Accepted",
|
||||
404 => "Not Found",
|
||||
_ => "OK",
|
||||
};
|
||||
format!(
|
||||
"HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
fn unix_millis_timestamp() -> String {
|
||||
let millis = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis();
|
||||
format!("unix-ms:{millis}")
|
||||
}
|
||||
|
||||
fn build_provider_advertisement() -> ProviderAdvertisement {
|
||||
ProviderAdvertisement {
|
||||
schema: PROVIDER_SCHEMA,
|
||||
|
|
@ -109,11 +333,18 @@ fn build_provider_advertisement() -> ProviderAdvertisement {
|
|||
presentation_owner: "Eve/CultUI lowers Brokkr surfaces without owning editor truth.",
|
||||
discovery_owner: "Odin discovers Brokkr through CultMesh provider advertisements.",
|
||||
},
|
||||
transports: vec![Transport {
|
||||
kind: "cultmesh",
|
||||
base_uri: CULTMESH_BASE_URI,
|
||||
status: "scaffold",
|
||||
}],
|
||||
transports: vec![
|
||||
Transport {
|
||||
kind: "cultmesh",
|
||||
base_uri: CULTMESH_BASE_URI,
|
||||
status: "scaffold",
|
||||
},
|
||||
Transport {
|
||||
kind: "http-local",
|
||||
base_uri: "http://127.0.0.1:8798",
|
||||
status: "active-local-adapter",
|
||||
},
|
||||
],
|
||||
tool_surfaces: vec![
|
||||
ToolSurface {
|
||||
id: "brokkr.unity_editor",
|
||||
|
|
|
|||
|
|
@ -7,11 +7,11 @@ daemon, beginning with Unity and Blender plugin surfaces.
|
|||
|
||||
## Current Mechanism
|
||||
|
||||
Brokkr starts as a Rust daemon skeleton that can emit a provider advertisement.
|
||||
Unity and Blender each have a thin plugin scaffold with host-local metadata and
|
||||
connection settings. The live transport is intentionally not claimed yet; the
|
||||
first contract establishes owner, inputs, outputs, command policy, and surface
|
||||
names.
|
||||
Brokkr starts as a Rust daemon that emits a provider advertisement and exposes a
|
||||
local HTTP adapter lane for tool plugins. Unity can capture a host snapshot from
|
||||
the editor and publish it to `POST /hosts/unity/snapshot`; Brokkr validates and
|
||||
retains that snapshot for `GET /hosts`. Blender still has a thin plugin scaffold
|
||||
with host-local metadata and connection settings.
|
||||
|
||||
## Invariants
|
||||
|
||||
|
|
@ -55,6 +55,7 @@ Outputs:
|
|||
- `gamecult.brokkr.tool_host_snapshot.v0`
|
||||
- `gamecult.brokkr.command_request.v0`
|
||||
- `gamecult.brokkr.command_receipt.v0`
|
||||
- local adapter receipts for accepted host snapshots
|
||||
- Eve/CultUI surface documents for host status, selection, assets, scene/object
|
||||
trees, command palette, and receipt history.
|
||||
|
||||
|
|
@ -83,4 +84,3 @@ Deletion Line:
|
|||
|
||||
If a plugin grows its own command policy, provider advertisement, or durable
|
||||
state ledger, cut it back into an adapter and move the authority into Brokkr.
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ Provider id: `brokkr.creative_tool_broker`
|
|||
|
||||
CultMesh base URI: `cultmesh://brokkr`
|
||||
|
||||
Local adapter HTTP endpoint: `http://127.0.0.1:8798`
|
||||
|
||||
Primary Eve surface id: `brokkr.eve.tool_broker.v0`
|
||||
|
||||
## Tool Kinds
|
||||
|
|
@ -25,3 +27,12 @@ The scaffold advertises command execution as policy-gated. No host command
|
|||
should execute unless the host plugin recognizes the command family and Brokkr
|
||||
has issued a command request with a receipt id.
|
||||
|
||||
## Local Adapter Endpoints
|
||||
|
||||
- `GET /health`
|
||||
- `GET /provider`
|
||||
- `GET /hosts`
|
||||
- `POST /hosts/unity/snapshot`
|
||||
|
||||
The HTTP lane is a local adapter transport. It is not the canonical public
|
||||
Verse contract.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,57 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using GameCult.Brokkr;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GameCult.Brokkr.Editor
|
||||
{
|
||||
internal static class BrokkrBrokerClient
|
||||
{
|
||||
internal static string GetHealth(string endpoint)
|
||||
{
|
||||
return Send(endpoint, "/health", "GET", null);
|
||||
}
|
||||
|
||||
internal static BrokkrSnapshotReceipt PublishUnitySnapshot(string endpoint, BrokkrHostSnapshot snapshot)
|
||||
{
|
||||
var json = JsonUtility.ToJson(snapshot);
|
||||
var response = Send(endpoint, "/hosts/unity/snapshot", "POST", json);
|
||||
return JsonUtility.FromJson<BrokkrSnapshotReceipt>(response);
|
||||
}
|
||||
|
||||
private static string Send(string endpoint, string path, string method, string body)
|
||||
{
|
||||
var request = (HttpWebRequest)WebRequest.Create(endpoint.TrimEnd('/') + path);
|
||||
request.Method = method;
|
||||
request.Timeout = 2500;
|
||||
request.ReadWriteTimeout = 2500;
|
||||
request.Accept = "application/json";
|
||||
|
||||
if (body != null)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(body);
|
||||
request.ContentType = "application/json";
|
||||
request.ContentLength = bytes.Length;
|
||||
using var requestStream = request.GetRequestStream();
|
||||
requestStream.Write(bytes, 0, bytes.Length);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var response = (HttpWebResponse)request.GetResponse();
|
||||
using var responseStream = response.GetResponseStream();
|
||||
using var reader = new StreamReader(responseStream ?? Stream.Null);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
catch (WebException error) when (error.Response != null)
|
||||
{
|
||||
using var responseStream = error.Response.GetResponseStream();
|
||||
using var reader = new StreamReader(responseStream ?? Stream.Null);
|
||||
throw new InvalidOperationException(reader.ReadToEnd());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -7,12 +7,24 @@ namespace GameCult.Brokkr.Editor
|
|||
internal const string ProviderId = "brokkr.unity_editor";
|
||||
internal const string ToolKind = "unity-editor";
|
||||
internal const string DefaultBrokerUri = "cultmesh://brokkr";
|
||||
internal const string DefaultHttpEndpoint = "http://127.0.0.1:8798";
|
||||
|
||||
internal static string BrokerUri
|
||||
{
|
||||
get => EditorPrefs.GetString("GameCult.Brokkr.BrokerUri", DefaultBrokerUri);
|
||||
set => EditorPrefs.SetString("GameCult.Brokkr.BrokerUri", value);
|
||||
}
|
||||
|
||||
internal static string HttpEndpoint
|
||||
{
|
||||
get => EditorPrefs.GetString("GameCult.Brokkr.HttpEndpoint", DefaultHttpEndpoint);
|
||||
set => EditorPrefs.SetString("GameCult.Brokkr.HttpEndpoint", value.TrimEnd('/'));
|
||||
}
|
||||
|
||||
internal static bool AutoPublish
|
||||
{
|
||||
get => EditorPrefs.GetBool("GameCult.Brokkr.AutoPublish", false);
|
||||
set => EditorPrefs.SetBool("GameCult.Brokkr.AutoPublish", value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,42 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using GameCult.Brokkr;
|
||||
using UnityEditor;
|
||||
using UnityEditor.SceneManagement;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GameCult.Brokkr.Editor
|
||||
{
|
||||
internal static class BrokkrUnitySnapshotBuilder
|
||||
{
|
||||
private static readonly string[] Capabilities =
|
||||
{
|
||||
"host.status.read",
|
||||
"scene.tree.read",
|
||||
"selection.read",
|
||||
"asset.catalog.read",
|
||||
"command.palette.read",
|
||||
"command.execute",
|
||||
"receipt.read"
|
||||
};
|
||||
|
||||
internal static BrokkrHostSnapshot Capture()
|
||||
{
|
||||
return new BrokkrHostSnapshot
|
||||
{
|
||||
projectPath = Application.dataPath.Replace("/Assets", ""),
|
||||
observedAt = DateTime.UtcNow.ToString("O"),
|
||||
unityVersion = Application.unityVersion,
|
||||
productName = Application.productName,
|
||||
activeScenePath = EditorSceneManager.GetActiveScene().path,
|
||||
openSceneCount = EditorSceneManager.sceneCount,
|
||||
selectedObjectNames = Selection.objects
|
||||
.Where(item => item != null)
|
||||
.Select(item => item.name)
|
||||
.ToArray(),
|
||||
assetCount = AssetDatabase.GetAllAssetPaths().Length,
|
||||
capabilities = Capabilities
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
using System;
|
||||
using GameCult.Brokkr;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
|
|
@ -6,6 +8,11 @@ namespace GameCult.Brokkr.Editor
|
|||
public sealed class BrokkrWindow : EditorWindow
|
||||
{
|
||||
private string brokerUri = BrokkrSettings.DefaultBrokerUri;
|
||||
private string httpEndpoint = BrokkrSettings.DefaultHttpEndpoint;
|
||||
private bool autoPublish;
|
||||
private BrokkrHostSnapshot lastSnapshot;
|
||||
private string lastReceipt = "No snapshot published yet.";
|
||||
private MessageType lastMessageType = MessageType.Info;
|
||||
|
||||
[MenuItem("GameCult/Brokkr")]
|
||||
public static void Open()
|
||||
|
|
@ -16,6 +23,18 @@ namespace GameCult.Brokkr.Editor
|
|||
private void OnEnable()
|
||||
{
|
||||
brokerUri = BrokkrSettings.BrokerUri;
|
||||
httpEndpoint = BrokkrSettings.HttpEndpoint;
|
||||
autoPublish = BrokkrSettings.AutoPublish;
|
||||
Selection.selectionChanged += Repaint;
|
||||
EditorSceneManagerBridge.SceneDirtied += OnEditorSignal;
|
||||
EditorApplication.playModeStateChanged += OnPlayModeChanged;
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
Selection.selectionChanged -= Repaint;
|
||||
EditorSceneManagerBridge.SceneDirtied -= OnEditorSignal;
|
||||
EditorApplication.playModeStateChanged -= OnPlayModeChanged;
|
||||
}
|
||||
|
||||
private void OnGUI()
|
||||
|
|
@ -23,17 +42,111 @@ namespace GameCult.Brokkr.Editor
|
|||
EditorGUILayout.LabelField("Provider", BrokkrSettings.ProviderId);
|
||||
EditorGUILayout.LabelField("Tool Kind", BrokkrSettings.ToolKind);
|
||||
brokerUri = EditorGUILayout.TextField("Broker URI", brokerUri);
|
||||
httpEndpoint = EditorGUILayout.TextField("HTTP Endpoint", httpEndpoint);
|
||||
autoPublish = EditorGUILayout.Toggle("Auto Publish", autoPublish);
|
||||
|
||||
if (GUILayout.Button("Save Settings"))
|
||||
{
|
||||
BrokkrSettings.BrokerUri = brokerUri;
|
||||
BrokkrSettings.HttpEndpoint = httpEndpoint;
|
||||
BrokkrSettings.AutoPublish = autoPublish;
|
||||
SetStatus("Settings saved.", MessageType.Info);
|
||||
}
|
||||
|
||||
EditorGUILayout.Space();
|
||||
EditorGUILayout.HelpBox(
|
||||
"Scaffold only: this adapter should publish Unity editor observations to Brokkr and execute admitted broker commands with receipts.",
|
||||
MessageType.Info);
|
||||
using (new EditorGUILayout.HorizontalScope())
|
||||
{
|
||||
if (GUILayout.Button("Capture Snapshot"))
|
||||
{
|
||||
CaptureSnapshot();
|
||||
}
|
||||
|
||||
if (GUILayout.Button("Publish Snapshot"))
|
||||
{
|
||||
PublishSnapshot();
|
||||
}
|
||||
}
|
||||
|
||||
if (GUILayout.Button("Ping Brokkr"))
|
||||
{
|
||||
PingBroker();
|
||||
}
|
||||
|
||||
EditorGUILayout.Space();
|
||||
EditorGUILayout.HelpBox(lastReceipt, lastMessageType);
|
||||
|
||||
if (lastSnapshot != null)
|
||||
{
|
||||
EditorGUILayout.LabelField("Observed At", lastSnapshot.observedAt);
|
||||
EditorGUILayout.LabelField("Project", lastSnapshot.productName);
|
||||
EditorGUILayout.LabelField("Path", lastSnapshot.projectPath);
|
||||
EditorGUILayout.LabelField("Active Scene", lastSnapshot.activeScenePath);
|
||||
EditorGUILayout.LabelField("Open Scenes", lastSnapshot.openSceneCount.ToString());
|
||||
EditorGUILayout.LabelField("Assets", lastSnapshot.assetCount.ToString());
|
||||
EditorGUILayout.LabelField("Selection", string.Join(", ", lastSnapshot.selectedObjectNames));
|
||||
}
|
||||
}
|
||||
|
||||
private void CaptureSnapshot()
|
||||
{
|
||||
lastSnapshot = BrokkrUnitySnapshotBuilder.Capture();
|
||||
SetStatus("Captured Unity editor host snapshot.", MessageType.Info);
|
||||
}
|
||||
|
||||
private void PublishSnapshot()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (lastSnapshot == null)
|
||||
{
|
||||
lastSnapshot = BrokkrUnitySnapshotBuilder.Capture();
|
||||
}
|
||||
|
||||
var receipt = BrokkrBrokerClient.PublishUnitySnapshot(httpEndpoint, lastSnapshot);
|
||||
SetStatus($"Snapshot {receipt.status}: {receipt.acceptedAt}", MessageType.Info);
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
SetStatus(error.Message, MessageType.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void PingBroker()
|
||||
{
|
||||
try
|
||||
{
|
||||
var health = BrokkrBrokerClient.GetHealth(httpEndpoint);
|
||||
SetStatus(health, MessageType.Info);
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
SetStatus(error.Message, MessageType.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnEditorSignal()
|
||||
{
|
||||
if (autoPublish)
|
||||
{
|
||||
CaptureSnapshot();
|
||||
PublishSnapshot();
|
||||
}
|
||||
else
|
||||
{
|
||||
Repaint();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPlayModeChanged(PlayModeStateChange _)
|
||||
{
|
||||
OnEditorSignal();
|
||||
}
|
||||
|
||||
private void SetStatus(string message, MessageType messageType)
|
||||
{
|
||||
lastReceipt = message;
|
||||
lastMessageType = messageType;
|
||||
Repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,39 @@
|
|||
using System;
|
||||
using UnityEditor.SceneManagement;
|
||||
using UnityEngine.SceneManagement;
|
||||
|
||||
namespace GameCult.Brokkr.Editor
|
||||
{
|
||||
internal static class EditorSceneManagerBridge
|
||||
{
|
||||
internal static event Action SceneDirtied;
|
||||
|
||||
static EditorSceneManagerBridge()
|
||||
{
|
||||
EditorSceneManager.activeSceneChangedInEditMode += OnActiveSceneChanged;
|
||||
EditorSceneManager.sceneSaved += OnSceneSaved;
|
||||
EditorSceneManager.sceneOpened += OnSceneOpened;
|
||||
EditorSceneManager.sceneClosed += OnSceneClosed;
|
||||
}
|
||||
|
||||
private static void OnActiveSceneChanged(Scene previous, Scene next)
|
||||
{
|
||||
SceneDirtied?.Invoke();
|
||||
}
|
||||
|
||||
private static void OnSceneSaved(Scene scene)
|
||||
{
|
||||
SceneDirtied?.Invoke();
|
||||
}
|
||||
|
||||
private static void OnSceneOpened(Scene scene, OpenSceneMode mode)
|
||||
{
|
||||
SceneDirtied?.Invoke();
|
||||
}
|
||||
|
||||
private static void OnSceneClosed(Scene scene)
|
||||
{
|
||||
SceneDirtied?.Invoke();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"name": "GameCult.Brokkr.Editor",
|
||||
"rootNamespace": "GameCult.Brokkr.Editor",
|
||||
"references": [
|
||||
"GameCult.Brokkr"
|
||||
],
|
||||
"includePlatforms": [
|
||||
"Editor"
|
||||
],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": false,
|
||||
"precompiledReferences": [],
|
||||
"autoReferenced": true,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
|
|
@ -10,6 +10,22 @@ namespace GameCult.Brokkr
|
|||
public string toolKind = "unity-editor";
|
||||
public string projectPath = "";
|
||||
public string observedAt = "";
|
||||
public string unityVersion = "";
|
||||
public string productName = "";
|
||||
public string activeScenePath = "";
|
||||
public int openSceneCount;
|
||||
public string[] selectedObjectNames = Array.Empty<string>();
|
||||
public int assetCount;
|
||||
public string[] capabilities = Array.Empty<string>();
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class BrokkrSnapshotReceipt
|
||||
{
|
||||
public string schema = "";
|
||||
public string providerId = "";
|
||||
public string toolKind = "";
|
||||
public string acceptedAt = "";
|
||||
public string status = "";
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"name": "GameCult.Brokkr",
|
||||
"rootNamespace": "GameCult.Brokkr",
|
||||
"references": [],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": false,
|
||||
"precompiledReferences": [],
|
||||
"autoReferenced": true,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
|
||||
39
surfaces/unity/README.md
Normal file
39
surfaces/unity/README.md
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
# Brokkr Unity Adapter
|
||||
|
||||
This package lets the Unity Editor publish a host snapshot to the local Brokkr
|
||||
daemon.
|
||||
|
||||
## Install By Local Path
|
||||
|
||||
Add this package to a Unity project's `Packages/manifest.json`:
|
||||
|
||||
```json
|
||||
"com.gamecult.brokkr": "file:E:/Projects/Brokkr/surfaces/unity/Packages/com.gamecult.brokkr"
|
||||
```
|
||||
|
||||
Then open `GameCult > Brokkr`.
|
||||
|
||||
## Local Smoke
|
||||
|
||||
Start the daemon:
|
||||
|
||||
```powershell
|
||||
cargo run -p brokkr-daemon -- serve
|
||||
```
|
||||
|
||||
In Unity:
|
||||
|
||||
1. Open `GameCult > Brokkr`.
|
||||
2. Leave HTTP endpoint as `http://127.0.0.1:8798`.
|
||||
3. Click `Ping Brokkr`.
|
||||
4. Click `Capture Snapshot`.
|
||||
5. Click `Publish Snapshot`.
|
||||
|
||||
The daemon should retain the latest Unity snapshot at:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:8798/hosts
|
||||
```
|
||||
|
||||
The Unity plugin is still an adapter. Brokkr owns the Verse-facing provider and
|
||||
receipt lane; Unity owns Unity editor truth.
|
||||
|
|
@ -1,12 +1,70 @@
|
|||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Assert-NativeSuccess {
|
||||
param([string]$Label)
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "$Label failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
|
||||
Push-Location (Split-Path -Parent $PSScriptRoot)
|
||||
try {
|
||||
cargo fmt --check
|
||||
Assert-NativeSuccess "cargo fmt"
|
||||
cargo test --workspace
|
||||
Assert-NativeSuccess "cargo test"
|
||||
cargo run -p brokkr-daemon -- provider | Out-Null
|
||||
Assert-NativeSuccess "cargo provider smoke"
|
||||
cargo build -p brokkr-daemon | Out-Null
|
||||
Assert-NativeSuccess "cargo build"
|
||||
|
||||
$smokeRoot = Join-Path (Get-Location) ".brokkr-smoke"
|
||||
New-Item -ItemType Directory -Force -Path $smokeRoot | Out-Null
|
||||
|
||||
$log = Join-Path $smokeRoot "brokkr-daemon.log"
|
||||
$out = Join-Path $smokeRoot "brokkr-daemon.out.log"
|
||||
Remove-Item $log, $out -ErrorAction SilentlyContinue
|
||||
|
||||
$daemon = Start-Process `
|
||||
-FilePath (Join-Path (Get-Location) "target\debug\brokkr-daemon.exe") `
|
||||
-ArgumentList @("serve", "--bind", "127.0.0.1:8798") `
|
||||
-WorkingDirectory (Get-Location) `
|
||||
-RedirectStandardError $log `
|
||||
-RedirectStandardOutput $out `
|
||||
-WindowStyle Hidden `
|
||||
-PassThru
|
||||
|
||||
try {
|
||||
Start-Sleep -Milliseconds 500
|
||||
$healthText = curl.exe -s http://127.0.0.1:8798/health
|
||||
Assert-NativeSuccess "health request"
|
||||
$health = $healthText | ConvertFrom-Json
|
||||
if ($health.ok -ne $true) {
|
||||
throw "Brokkr health smoke failed: $health"
|
||||
}
|
||||
|
||||
$snapshotPath = Join-Path $smokeRoot "unity-snapshot.json"
|
||||
$snapshot = '{"schema":"gamecult.brokkr.tool_host_snapshot.v0","providerId":"brokkr.unity_editor","toolKind":"unity-editor","projectPath":"E:/Projects/StreamPixelsUnity","observedAt":"2026-06-12T12:00:00.0000000Z","unityVersion":"smoke","productName":"StreamPixelsUnity","activeScenePath":"Assets/Scenes/SampleScene.unity","openSceneCount":1,"selectedObjectNames":["SmokeObject"],"assetCount":42,"capabilities":["host.status.read","scene.tree.read","selection.read","asset.catalog.read","command.palette.read","command.execute","receipt.read"]}'
|
||||
[System.IO.File]::WriteAllText($snapshotPath, $snapshot, [System.Text.UTF8Encoding]::new($false))
|
||||
|
||||
$receiptText = curl.exe -s -X POST http://127.0.0.1:8798/hosts/unity/snapshot -H "Content-Type: application/json" --data-binary "@$snapshotPath"
|
||||
Assert-NativeSuccess "Unity snapshot request"
|
||||
$receipt = $receiptText | ConvertFrom-Json
|
||||
if ($receipt.status -ne "accepted") {
|
||||
throw "Unity snapshot smoke failed: $receipt"
|
||||
}
|
||||
|
||||
$hostsText = curl.exe -s http://127.0.0.1:8798/hosts
|
||||
Assert-NativeSuccess "Unity host readback request"
|
||||
$hosts = $hostsText | ConvertFrom-Json
|
||||
if ($hosts.unity.providerId -ne "brokkr.unity_editor") {
|
||||
throw "Unity host readback smoke failed: $hosts"
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Stop-Process -Id $daemon.Id -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue