diff --git a/.gitignore b/.gitignore index d772650..8d7aa6c 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ __pycache__/ node_modules/ state/scratch-compaction-*.md experiments/images/ +target/ diff --git a/AGENTS.md b/AGENTS.md index f937d36..a9b1e76 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,20 +35,20 @@ inside another project. ## Important Paths -- Project root: `E:\Projects\Ghostlight` -- Canonical map: `E:\Projects\Ghostlight\state\map.yaml` -- Scratch surface: `E:\Projects\Ghostlight\state\scratch.md` -- Distilled evidence ledger: `E:\Projects\Ghostlight\state\evidence.jsonl` -- Branch ledger: `E:\Projects\Ghostlight\state\branches.json` -- Handoff summary: `E:\Projects\Ghostlight\notes\fresh-workspace-handoff.md` -- System map: `E:\Projects\Ghostlight\notes\ghostlight-current-system-map.md` -- Implementation plan: `E:\Projects\Ghostlight\notes\ghostlight-implementation-plan.md` -- Architecture rationale: `E:\Projects\Ghostlight\notes\architecture-rationale.md` -- State CLI: `E:\Projects\Ghostlight\tools\ghostlight_state.py` -- CultCache state seam: `E:\Projects\Ghostlight\tools\ghostlight_state_store.py` -- CultCache-Py submodule: `E:\Projects\Ghostlight\vendor\cultcache-py` -- CultCache state store: `E:\Projects\Ghostlight\state\ghostlight-state.cultcache.jsonl` -- Pre-compaction helper: `E:\Projects\Ghostlight\tools\ghostlight_prepare_compaction.py` +- Project root: `F:\Projects\Ghostlight` +- Canonical map: `F:\Projects\Ghostlight\state\map.yaml` +- Scratch surface: `F:\Projects\Ghostlight\state\scratch.md` +- Distilled evidence ledger: `F:\Projects\Ghostlight\state\evidence.jsonl` +- Branch ledger: `F:\Projects\Ghostlight\state\branches.json` +- Handoff summary: `F:\Projects\Ghostlight\notes\fresh-workspace-handoff.md` +- System map: `F:\Projects\Ghostlight\notes\ghostlight-current-system-map.md` +- Implementation plan: `F:\Projects\Ghostlight\notes\ghostlight-implementation-plan.md` +- Architecture rationale: `F:\Projects\Ghostlight\notes\architecture-rationale.md` +- State CLI: `F:\Projects\Ghostlight\tools\ghostlight_state.py` +- CultCache state seam: `F:\Projects\Ghostlight\tools\ghostlight_state_store.py` +- CultCache-Py submodule: `F:\Projects\Ghostlight\vendor\cultcache-py` +- CultCache state store: `F:\Projects\Ghostlight\state\ghostlight-state.cultcache.jsonl` +- Pre-compaction helper: `F:\Projects\Ghostlight\tools\ghostlight_prepare_compaction.py` ## Useful Commands diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-compiler-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-compiler-smoke.rs new file mode 100644 index 0000000..811c64c --- /dev/null +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-compiler-smoke.rs @@ -0,0 +1,51 @@ +#[cfg(not(windows))] +fn main() -> anyhow::Result<()> { + anyhow::bail!("the live compiler smoke uses Starfire's DPAPI credential") +} + +#[cfg(windows)] +#[tokio::main] +async fn main() -> anyhow::Result<()> { + use ghostlight_dungeon::{ + compiler::{CustomStart, WorldCompiler}, + model::{DeepSeekPort, ModelPort}, + vault::VoidBotMcpVault, + }; + use std::{path::PathBuf, sync::Arc}; + + let secret = std::env::var_os("GHOSTLIGHT_DEEPSEEK_BLOB") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(r"F:\GameCult\GhostlightDungeon\secrets\deepseek.dpapi")); + let model: Arc = Arc::new(DeepSeekPort::from_machine_dpapi(secret)?); + let compiler = WorldCompiler::new( + Arc::new(VoidBotMcpVault::starfire_loopback()), + model, + "deepseek-v4-pro", + ); + let (preview, receipt) = compiler.compile_custom(CustomStart { + campaign_name: "Compiler acceptance smoke".into(), + who: "A low-status maintenance worker with local access but no institutional authority".into(), + where_: "an obscure inhabited Aetheria location supported by the retrieved sources".into(), + when: "a source-supported pre-Elysium period".into(), + goal: "prevent an approaching institutional failure without inventing expertise or geography".into(), + }).await?; + println!( + "{}", + serde_json::to_string_pretty(&serde_json::json!({ + "schema":"ghostlight.world_compile_smoke.v1", + "title":preview.title, + "location_count":preview.campaign.locations.len(), + "actor_count":preview.campaign.actors.len(), + "institution_count":preview.campaign.institutions.len(), + "clock_count":preview.campaign.clocks.len(), + "evidence_receipt_count":preview.evidence_receipts.len(), + "evidence_witness_count":preview.evidence_receipts.iter().map(|r|r.witnesses.len()).sum::(), + "gaps":preview.gaps, + "branch_assumptions":preview.branch_assumptions, + "requires_approval":preview.requires_approval, + "campaign_revision":preview.campaign.revision, + "model_receipt":receipt + }))? + ); + Ok(()) +} diff --git a/crates/ghostlight-dungeon/src/compiler.rs b/crates/ghostlight-dungeon/src/compiler.rs new file mode 100644 index 0000000..14efae1 --- /dev/null +++ b/crates/ghostlight-dungeon/src/compiler.rs @@ -0,0 +1,507 @@ +use crate::{ + domain::{ + ActorState, BranchOrigin, Campaign, FactScope, InstitutionState, Location, + VaultEvidenceReceipt, WorldClock, WorldCompilePreview, WorldFact, + }, + model::{ModelPort, ModelStageReceipt, ModelStageRequest, run_validated_stage}, + vault::{VaultProvider, VaultQuery}, +}; +use anyhow::{Result, anyhow}; +use chrono::{DateTime, Utc}; +use schemars::{JsonSchema, schema_for}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; +use uuid::Uuid; + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct OpeningRequest { + pub setting: String, + pub constraints: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct OpeningSuggestion { + pub id: String, + pub title: String, + pub era: String, + pub place: String, + pub pressure: String, + pub player_hook: String, + pub evidence_receipt_ids: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct RoleSuggestion { + pub id: String, + pub name: String, + pub premise: String, + pub capabilities: Vec, + pub obligations: Vec, + pub evidence_receipt_ids: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct CustomStart { + pub campaign_name: String, + pub who: String, + pub where_: String, + pub when: String, + pub goal: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +pub struct SelectedStart { + pub campaign_name: String, + pub opening: OpeningSuggestion, + pub role: RoleSuggestion, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct SuggestedOpenings { + pub openings: Vec, + pub evidence_receipts: Vec, + pub model_receipt: ModelStageReceipt, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct SuggestedRoles { + pub roles: Vec, + pub evidence_receipts: Vec, + pub model_receipt: ModelStageReceipt, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +struct OpeningSet { + openings: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +struct RoleSet { + roles: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] +struct CompiledSeed { + title: String, + canon_cutoff: String, + world_time: DateTime, + tick_hours: u32, + player: ActorState, + locations: Vec, + actors: Vec, + institutions: Vec, + clocks: Vec, + facts: Vec, + gaps: Vec, + branch_assumptions: Vec, + opening_narration: String, +} + +pub struct WorldCompiler { + vault: Arc, + model: Arc, + compiler_model: String, +} + +impl WorldCompiler { + pub fn new( + vault: Arc, + model: Arc, + compiler_model: impl Into, + ) -> Self { + Self { + vault, + model, + compiler_model: compiler_model.into(), + } + } + + pub async fn suggest_openings(&self, request: OpeningRequest) -> Result { + let queries = [ + format!("{} history eras locations institutions", request.setting), + format!("{} conflicts pressures ordinary life", request.setting), + format!("{} travel geography routes", request.setting), + ]; + let receipts = self.retrieve_all(&queries, "all", 8).await?; + let evidence = evidence_text(&receipts); + let output = self.structured("world_openings", "opening-suggestions", &format!("Generate exactly three source-grounded openings. They must use distinct eras, places, and pressures. Do not fill material evidence gaps with invention. REQUEST:\n{}\nEVIDENCE:\n{}", serde_json::to_string(&request)?, evidence), serde_json::to_value(schema_for!(OpeningSet))?, receipt_ids(&receipts)).await?; + let parsed: OpeningSet = serde_json::from_value(output.0)?; + if parsed.openings.len() != 3 { + return Err(anyhow!("world compiler must return exactly three openings")); + } + ensure_distinct_openings(&parsed.openings)?; + Ok(SuggestedOpenings { + openings: parsed.openings, + evidence_receipts: receipts, + model_receipt: output.1, + }) + } + + pub async fn suggest_roles(&self, opening: &OpeningSuggestion) -> Result { + let queries = [ + format!( + "{} {} people occupations institutions", + opening.era, opening.place + ), + format!( + "{} capabilities obligations {}", + opening.place, opening.pressure + ), + ]; + let receipts = self.retrieve_all(&queries, &opening.era, 8).await?; + let output = self.structured("world_roles", &format!("roles:{}", opening.id), &format!("Generate exactly three materially distinct player roles grounded in this opening and evidence. OPENING:\n{}\nEVIDENCE:\n{}", serde_json::to_string(opening)?, evidence_text(&receipts)), serde_json::to_value(schema_for!(RoleSet))?, receipt_ids(&receipts)).await?; + let parsed: RoleSet = serde_json::from_value(output.0)?; + if parsed.roles.len() != 3 { + return Err(anyhow!("world compiler must return exactly three roles")); + } + Ok(SuggestedRoles { + roles: parsed.roles, + evidence_receipts: receipts, + model_receipt: output.1, + }) + } + + pub async fn compile_custom( + &self, + start: CustomStart, + ) -> Result<(WorldCompilePreview, ModelStageReceipt)> { + let queries = [ + format!( + "{} {} geography routes containment", + start.where_, start.when + ), + format!("{} {} people institutions powers", start.where_, start.when), + format!("{} capabilities mechanics {}", start.who, start.goal), + ]; + let receipts = self.retrieve_all(&queries, &start.when, 10).await?; + let output = self.structured("world_compile", "custom-start", &format!("Compile a bounded playable region and institutional pressure graph. Emit only supported canon facts; mark reversible texture provisional_local and list material gaps. The player location and every actor location must exist. Every route destination must exist, travel time must be positive, clocks need positive thresholds, and the player id must be unique. START:\n{}\nEVIDENCE:\n{}", serde_json::to_string(&start)?, evidence_text(&receipts)), serde_json::to_value(schema_for!(CompiledSeed))?, receipt_ids(&receipts)).await?; + let seed: CompiledSeed = serde_json::from_value(output.0)?; + let campaign = seed_to_campaign(seed.clone(), &receipts)?; + validate_campaign_seed(&campaign)?; + Ok(( + WorldCompilePreview { + schema: "ghostlight.world_compile_preview.v1".into(), + title: seed.title, + campaign, + evidence_receipts: receipts, + gaps: seed.gaps, + branch_assumptions: seed.branch_assumptions, + requires_approval: true, + }, + output.1, + )) + } + + pub async fn compile_selected( + &self, + start: SelectedStart, + ) -> Result<(WorldCompilePreview, ModelStageReceipt)> { + self.compile_custom(CustomStart { + campaign_name: start.campaign_name, + who: format!("{} — {}", start.role.name, start.role.premise), + where_: start.opening.place, + when: start.opening.era, + goal: format!("{}; {}", start.opening.player_hook, start.opening.pressure), + }) + .await + } + + async fn retrieve_all( + &self, + queries: &[String], + temporal_scope: &str, + limit: u8, + ) -> Result> { + let mut receipts = Vec::new(); + for query in queries { + receipts.push( + self.vault + .search(&VaultQuery { + query: query.clone(), + authority_lanes: vec!["Aetheria".into(), "AetheriaLore".into()], + temporal_scope: temporal_scope.into(), + limit, + }) + .await?, + ); + } + if receipts.iter().all(|r| r.witnesses.is_empty()) { + return Err(anyhow!("Vault returned no evidence; compilation refused")); + } + Ok(receipts) + } + + async fn structured( + &self, + stage: &str, + binding: &str, + prompt: &str, + schema: serde_json::Value, + sources: Vec, + ) -> Result<(serde_json::Value, ModelStageReceipt)> { + let prompt = format!( + "{prompt}\n\nOUTPUT JSON SCHEMA (follow exactly):\n{}", + serde_json::to_string_pretty(&schema)? + ); + let out = run_validated_stage( + self.model.as_ref(), + &ModelStageRequest { + stage: stage.into(), + model: self.compiler_model.clone(), + snapshot_binding: binding.into(), + lived_stream: prompt, + output_schema: Some(schema), + source_receipt_ids: sources, + }, + ) + .await?; + Ok(( + out.structured + .ok_or_else(|| anyhow!("compiler returned no structured output"))?, + out.receipt, + )) + } +} + +fn evidence_text(receipts: &[VaultEvidenceReceipt]) -> String { + receipts + .iter() + .flat_map(|r| r.witnesses.iter()) + .map(|w| { + format!( + "[{} | {} | {}] {}", + w.source_id, w.exact_locator, w.content_hash, w.excerpt + ) + }) + .collect::>() + .join("\n\n") +} +fn receipt_ids(receipts: &[VaultEvidenceReceipt]) -> Vec { + receipts.iter().map(|r| r.id.clone()).collect() +} +fn ensure_distinct_openings(items: &[OpeningSuggestion]) -> Result<()> { + let eras: BTreeSet<_> = items.iter().map(|x| x.era.trim().to_lowercase()).collect(); + let places: BTreeSet<_> = items + .iter() + .map(|x| x.place.trim().to_lowercase()) + .collect(); + let pressures: BTreeSet<_> = items + .iter() + .map(|x| x.pressure.trim().to_lowercase()) + .collect(); + if eras.len() != 3 || places.len() != 3 || pressures.len() != 3 { + Err(anyhow!( + "openings are not distinct across era, place, and pressure" + )) + } else { + Ok(()) + } +} + +fn seed_to_campaign(seed: CompiledSeed, receipts: &[VaultEvidenceReceipt]) -> Result { + let id = Uuid::new_v4(); + let player_id = seed.player.id.clone(); + let now = Utc::now(); + let mut actors: BTreeMap<_, _> = seed.actors.into_iter().map(|x| (x.id.clone(), x)).collect(); + if actors.insert(player_id.clone(), seed.player).is_some() { + return Err(anyhow!("player id duplicates an NPC")); + } + Ok(Campaign { + schema: "ghostlight.campaign.v1".into(), + id, + name: seed.title, + revision: 0, + branch_origin: BranchOrigin { + canon_cutoff: seed.canon_cutoff, + evidence_receipt_ids: receipt_ids(receipts), + }, + world_time: seed.world_time, + tick_hours: seed.tick_hours, + player_actor_id: player_id, + locations: seed + .locations + .into_iter() + .map(|x| (x.id.clone(), x)) + .collect(), + actors, + institutions: seed + .institutions + .into_iter() + .map(|x| (x.id.clone(), x)) + .collect(), + clocks: seed.clocks.into_iter().map(|x| (x.id.clone(), x)).collect(), + facts: seed + .facts + .into_iter() + .map(|mut x| { + if x.scope == FactScope::CanonBaseline && x.evidence_receipt_ids.is_empty() { + x.scope = FactScope::ProvisionalLocal + }; + (x.id.clone(), x) + }) + .collect(), + transcript: vec![crate::domain::NarrativeTurn { + revision: 0, + at: now, + speaker: "world".into(), + text: seed.opening_narration, + }], + last_player_activity: now, + pending_ticks: 0, + }) +} + +pub fn validate_campaign_seed(c: &Campaign) -> Result<()> { + if c.tick_hours == 0 { + return Err(anyhow!("strategic tick duration must be positive")); + } + if !c.actors.contains_key(&c.player_actor_id) { + return Err(anyhow!("player actor is missing")); + } + for actor in c.actors.values() { + if !c.locations.contains_key(&actor.location_id) { + return Err(anyhow!( + "actor {} occupies unknown location {}", + actor.id, + actor.location_id + )); + } + } + for location in c.locations.values() { + if let Some(parent) = &location.container_id { + if parent == &location.id || !c.locations.contains_key(parent) { + return Err(anyhow!("location {} has invalid container", location.id)); + } + } + for route in location.routes.values() { + if route.travel_minutes == 0 || !c.locations.contains_key(&route.destination_id) { + return Err(anyhow!("location {} has invalid route", location.id)); + } + } + } + for clock in c.clocks.values() { + if clock.threshold == 0 || clock.progress > clock.threshold { + return Err(anyhow!("clock {} is invalid", clock.id)); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{domain::SourceWitness, model::ModelPort, vault::FixtureVault}; + use async_trait::async_trait; + + struct CompilerModel { + invalid_route: bool, + } + #[async_trait] + impl ModelPort for CompilerModel { + async fn run(&self, request: &ModelStageRequest) -> Result { + Ok(match request.stage.as_str() { + "world_openings" => serde_json::json!({"openings":[ + {"id":"a","title":"Ash","era":"early","place":"ring","pressure":"strike","player_hook":"work","evidence_receipt_ids":[]}, + {"id":"b","title":"Glass","era":"middle","place":"moon","pressure":"siege","player_hook":"survive","evidence_receipt_ids":[]}, + {"id":"c","title":"Rain","era":"late","place":"station","pressure":"election","player_hook":"choose","evidence_receipt_ids":[]} + ]}).to_string(), + "world_compile" => { + let destination = if self.invalid_route { "missing" } else { "yard" }; + serde_json::json!({ + "title":"Grounded test", "canon_cutoff":"fixture", "world_time":"2026-01-01T00:00:00Z", "tick_hours":6, + "player":{"id":"player","name":"Tester","location_id":"yard","capabilities":[],"knowledge":[],"equipment":[],"conditions":[],"obligations":[],"relationships":{},"goals":["learn"]}, + "locations":[{"id":"yard","name":"Yard","container_id":null,"routes":{"out":{"destination_id":destination,"distance":"near","travel_minutes":5}},"persistent_features":["same yard"]}], + "actors":[],"institutions":[],"clocks":[{"id":"shift","label":"Shift ends","progress":0,"threshold":4,"consequence":"night"}], + "facts":[{"id":"f","statement":"A witnessed fact","scope":"canon_baseline","evidence_receipt_ids":["fixture"]}], + "gaps":[],"branch_assumptions":[],"opening_narration":"The yard persists." + }).to_string() + } + _ => return Err(anyhow!("unexpected stage")), + }) + } + fn provider(&self) -> &'static str { + "compiler-fixture" + } + } + + fn vault() -> Arc { + Arc::new(FixtureVault { + witnesses: vec![SourceWitness { + source_id: "AetheriaLore:test.md".into(), + exact_locator: "test.md:1-2".into(), + content_hash: "sha256:test".into(), + excerpt: "A stable witnessed place.".into(), + authority_lane: "AetheriaLore".into(), + temporal_scope: "fixture".into(), + }], + }) + } + + #[tokio::test] + async fn opening_stage_requires_three_distinct_axes() { + let compiler = WorldCompiler::new( + vault(), + Arc::new(CompilerModel { + invalid_route: false, + }), + "pro", + ); + let output = compiler + .suggest_openings(OpeningRequest { + setting: "Aetheria".into(), + constraints: vec![], + }) + .await + .unwrap(); + assert_eq!(output.openings.len(), 3); + assert_eq!(output.evidence_receipts.len(), 3); + } + + #[tokio::test] + async fn compile_returns_approval_preview_without_committing() { + let compiler = WorldCompiler::new( + vault(), + Arc::new(CompilerModel { + invalid_route: false, + }), + "pro", + ); + let (preview, _) = compiler + .compile_custom(CustomStart { + campaign_name: "Test".into(), + who: "worker".into(), + where_: "yard".into(), + when: "fixture".into(), + goal: "learn".into(), + }) + .await + .unwrap(); + assert!(preview.requires_approval); + assert_eq!(preview.campaign.revision, 0); + assert_eq!(preview.campaign.locations.len(), 1); + } + + #[tokio::test] + async fn compiler_refuses_dream_route_to_unknown_location() { + let compiler = WorldCompiler::new( + vault(), + Arc::new(CompilerModel { + invalid_route: true, + }), + "pro", + ); + let result = compiler + .compile_custom(CustomStart { + campaign_name: "Test".into(), + who: "worker".into(), + where_: "yard".into(), + when: "fixture".into(), + goal: "learn".into(), + }) + .await; + assert!(result.unwrap_err().to_string().contains("invalid route")); + } +} diff --git a/crates/ghostlight-dungeon/src/domain.rs b/crates/ghostlight-dungeon/src/domain.rs index 807debf..4a2f7ef 100644 --- a/crates/ghostlight-dungeon/src/domain.rs +++ b/crates/ghostlight-dungeon/src/domain.rs @@ -114,6 +114,7 @@ pub struct ActionIntent { pub enum WorldCommand { CreateCampaign { campaign: Campaign, + evidence_receipts: Vec, }, Speak { expected_revision: u64, diff --git a/crates/ghostlight-dungeon/src/kernel.rs b/crates/ghostlight-dungeon/src/kernel.rs index a4986a9..ab05386 100644 --- a/crates/ghostlight-dungeon/src/kernel.rs +++ b/crates/ghostlight-dungeon/src/kernel.rs @@ -78,14 +78,18 @@ fn execute( assessments: &mut BTreeMap, command: WorldCommand, ) -> Result { - if let WorldCommand::CreateCampaign { campaign } = command { + if let WorldCommand::CreateCampaign { + campaign, + evidence_receipts, + } = command + { + if !store.keys("campaign.v1").map_err(persist)?.is_empty() { + return Err(KernelError::Invalid("campaign already exists".into())); + } + crate::compiler::validate_campaign_seed(&campaign) + .map_err(|error| KernelError::Invalid(error.to_string()))?; store - .insert( - "campaign.v1", - "ghostlight.campaign.v1", - &campaign.id.to_string(), - &campaign, - ) + .create_campaign(&campaign, &evidence_receipts) .map_err(persist)?; return Ok(CommandResult::Created { campaign }); } @@ -351,6 +355,7 @@ mod tests { kernel .command(WorldCommand::CreateCampaign { campaign: seed.clone(), + evidence_receipts: vec![], }) .await .unwrap(); @@ -385,6 +390,7 @@ mod tests { kernel .command(WorldCommand::CreateCampaign { campaign: seed.clone(), + evidence_receipts: vec![], }) .await .unwrap(); diff --git a/crates/ghostlight-dungeon/src/lib.rs b/crates/ghostlight-dungeon/src/lib.rs index d98e10b..edd41d3 100644 --- a/crates/ghostlight-dungeon/src/lib.rs +++ b/crates/ghostlight-dungeon/src/lib.rs @@ -1,3 +1,4 @@ +pub mod compiler; pub mod d20; pub mod domain; pub mod kernel; diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index 4220707..ef3f991 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -9,10 +9,12 @@ use axum::{ use ghostlight_dungeon::windows_secret::unprotect_machine_utf8; use ghostlight_dungeon::{ WorldKernel, - domain::{Campaign, WorldCommand}, - model::{DeepSeekPort, ModelStageRequest, run_validated_stage}, + compiler::{CustomStart, OpeningRequest, OpeningSuggestion, SelectedStart, WorldCompiler}, + domain::{Campaign, WorldCommand, WorldCompilePreview}, + model::{DeepSeekPort, ModelPort, ModelStageRequest, run_validated_stage}, persistence::CampaignStore, surface::player_surface, + vault::VoidBotMcpVault, }; use serde::Serialize; use std::{ @@ -32,6 +34,8 @@ struct AppState { invites: Arc>>, sessions: Arc>>, deepseek_status: String, + compiler: Option>, + compile_previews: Arc>>, } #[tokio::main] @@ -45,13 +49,6 @@ async fn main() -> anyhow::Result<()> { std::fs::create_dir_all(runtime_root.join("campaigns/default"))?; let store = CampaignStore::open(runtime_root.join("campaigns/default/campaign.cc"))?; let kernel = WorldKernel::start(store.clone()); - if store.keys("campaign.v1")?.is_empty() { - kernel - .command(WorldCommand::CreateCampaign { - campaign: seed_campaign(), - }) - .await?; - } let invite_blob = runtime_root.join("secrets/invites.dpapi"); #[cfg(windows)] let invite_material = if invite_blob.is_file() { @@ -78,10 +75,11 @@ async fn main() -> anyhow::Result<()> { )); } let secret_path = runtime_root.join("secrets/deepseek.dpapi"); - let deepseek_status = if secret_path.is_file() { - let provider = DeepSeekPort::from_machine_dpapi(&secret_path)?; + let (deepseek_status, compiler) = if secret_path.is_file() { + let provider: Arc = + Arc::new(DeepSeekPort::from_machine_dpapi(&secret_path)?); let probe = run_validated_stage( - &provider, + provider.as_ref(), &ModelStageRequest { stage: "startup_probe".into(), model: "deepseek-v4-flash".into(), @@ -92,9 +90,16 @@ async fn main() -> anyhow::Result<()> { }, ) .await?; - format!("ready:{}", probe.receipt.output_hash) + ( + format!("ready:{}", probe.receipt.output_hash), + Some(Arc::new(WorldCompiler::new( + Arc::new(VoidBotMcpVault::starfire_loopback()), + provider, + "deepseek-v4-pro", + ))), + ) } else { - "missing-secret".into() + ("missing-secret".into(), None) }; let state = AppState { kernel, @@ -102,6 +107,8 @@ async fn main() -> anyhow::Result<()> { invites: Arc::new(Mutex::new(invite_tokens)), sessions: Arc::new(Mutex::new(BTreeSet::new())), deepseek_status, + compiler, + compile_previews: Arc::new(Mutex::new(BTreeMap::new())), }; let release_web_root = std::env::current_exe()? .parent() @@ -113,6 +120,11 @@ async fn main() -> anyhow::Result<()> { .route("/health", get(health)) .route("/invite/{token}", get(invite)) .route("/api/surface", get(surface)) + .route("/api/compiler/openings", post(compile_openings)) + .route("/api/compiler/roles", post(compile_roles)) + .route("/api/compiler/selected", post(compile_selected)) + .route("/api/compiler/custom", post(compile_custom)) + .route("/api/compiler/approve/{preview_id}", post(approve_preview)) .route("/api/command", post(command)) .fallback_service(ServeDir::new(web_root).append_index_html_on_directories(true)) .with_state(state); @@ -152,7 +164,159 @@ async fn surface(headers: HeaderMap, State(state): State) -> Response } match load_campaign(&state.store) { Ok(campaign) => Json(player_surface(&campaign)).into_response(), - Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), + Err(_) => Json(serde_json::json!({"schema":"gamecult.eve.surface.v1","surface_id":"ghostlight.compiler","version":0,"title":"Compile a world","layout":{"kind":"stack","children":[]}})).into_response(), + } +} + +async fn compile_openings( + headers: HeaderMap, + State(state): State, + Json(request): Json, +) -> Response { + if !authorized(&headers, &state).await { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Some(compiler) = &state.compiler else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + "DeepSeek credential is unavailable", + ) + .into_response(); + }; + match compiler.suggest_openings(request).await { + Ok(value) => Json(value).into_response(), + Err(error) => (StatusCode::BAD_GATEWAY, error.to_string()).into_response(), + } +} + +async fn compile_custom( + headers: HeaderMap, + State(state): State, + Json(request): Json, +) -> Response { + if !authorized(&headers, &state).await { + return StatusCode::UNAUTHORIZED.into_response(); + } + if !state + .store + .keys("campaign.v1") + .unwrap_or_default() + .is_empty() + { + return (StatusCode::CONFLICT, "campaign already exists").into_response(); + } + let Some(compiler) = &state.compiler else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + "DeepSeek credential is unavailable", + ) + .into_response(); + }; + match compiler.compile_custom(request).await { + Ok((preview, receipt)) => { + let id = uuid::Uuid::new_v4().to_string(); + state + .compile_previews + .lock() + .await + .insert(id.clone(), preview.clone()); + Json(serde_json::json!({"preview_id":id,"preview":preview,"model_receipt":receipt})) + .into_response() + } + Err(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response(), + } +} + +async fn compile_roles( + headers: HeaderMap, + State(state): State, + Json(opening): Json, +) -> Response { + if !authorized(&headers, &state).await { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Some(compiler) = &state.compiler else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + "DeepSeek credential is unavailable", + ) + .into_response(); + }; + match compiler.suggest_roles(&opening).await { + Ok(value) => Json(value).into_response(), + Err(error) => (StatusCode::BAD_GATEWAY, error.to_string()).into_response(), + } +} + +async fn compile_selected( + headers: HeaderMap, + State(state): State, + Json(request): Json, +) -> Response { + if !authorized(&headers, &state).await { + return StatusCode::UNAUTHORIZED.into_response(); + } + if !state + .store + .keys("campaign.v1") + .unwrap_or_default() + .is_empty() + { + return (StatusCode::CONFLICT, "campaign already exists").into_response(); + } + let Some(compiler) = &state.compiler else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + "DeepSeek credential is unavailable", + ) + .into_response(); + }; + store_preview(&state, compiler.compile_selected(request).await).await +} + +async fn store_preview( + state: &AppState, + result: anyhow::Result<( + WorldCompilePreview, + ghostlight_dungeon::model::ModelStageReceipt, + )>, +) -> Response { + match result { + Ok((preview, receipt)) => { + let id = uuid::Uuid::new_v4().to_string(); + state + .compile_previews + .lock() + .await + .insert(id.clone(), preview.clone()); + Json(serde_json::json!({"preview_id":id,"preview":preview,"model_receipt":receipt})) + .into_response() + } + Err(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response(), + } +} + +async fn approve_preview( + Path(preview_id): Path, + headers: HeaderMap, + State(state): State, +) -> Response { + if !authorized(&headers, &state).await { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Some(preview) = state.compile_previews.lock().await.remove(&preview_id) else { + return (StatusCode::NOT_FOUND, "preview missing or already consumed").into_response(); + }; + match state + .kernel + .command(WorldCommand::CreateCampaign { + campaign: preview.campaign, + evidence_receipts: preview.evidence_receipts, + }) + .await + { + Ok(value) => Json(value).into_response(), + Err(error) => (StatusCode::CONFLICT, error.to_string()).into_response(), } } @@ -209,6 +373,7 @@ struct ErrorBody { error: String, } +#[allow(dead_code)] fn seed_campaign() -> Campaign { let id = uuid::Uuid::new_v4(); let location = ghostlight_dungeon::domain::Location { diff --git a/crates/ghostlight-dungeon/src/persistence.rs b/crates/ghostlight-dungeon/src/persistence.rs index 1801c68..edd441e 100644 --- a/crates/ghostlight-dungeon/src/persistence.rs +++ b/crates/ghostlight-dungeon/src/persistence.rs @@ -1,3 +1,4 @@ +use crate::domain::{Campaign, VaultEvidenceReceipt}; use anyhow::{Context, Result, anyhow}; use chrono::Utc; use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; @@ -60,6 +61,32 @@ impl CampaignStore { Ok(row) } + pub fn create_campaign( + &self, + campaign: &Campaign, + receipts: &[VaultEvidenceReceipt], + ) -> Result { + let campaign_row = envelope( + "campaign.v1", + "ghostlight.campaign.v1", + &campaign.id.to_string(), + campaign, + )?; + let mut rows = vec![campaign_row.clone()]; + for receipt in receipts { + rows.push(envelope( + "vault_evidence_receipt.v1", + "ghostlight.vault_evidence_receipt.v1", + &receipt.id, + receipt, + )?); + } + if !self.inner.compare_and_swap_batch(&[], rows)? { + return Err(anyhow!("campaign store is not empty")); + } + Ok(campaign_row) + } + pub fn replace( &self, expected: &CultCacheEnvelope, diff --git a/crates/ghostlight-dungeon/src/vault.rs b/crates/ghostlight-dungeon/src/vault.rs index 0ff48dd..396c52a 100644 --- a/crates/ghostlight-dungeon/src/vault.rs +++ b/crates/ghostlight-dungeon/src/vault.rs @@ -17,6 +17,8 @@ pub struct VaultQuery { #[async_trait] pub trait VaultProvider: Send + Sync { async fn search(&self, query: &VaultQuery) -> Result; + async fn surrounding_context(&self, source_id: &str, chunk_index: u32) + -> Result; async fn exact_document(&self, source_id: &str) -> Result; fn provider_id(&self) -> &'static str; } @@ -45,6 +47,9 @@ impl VaultProvider for FixtureVault { .cloned() .ok_or_else(|| anyhow!("fixture source not found")) } + async fn surrounding_context(&self, source_id: &str, _: u32) -> Result { + self.exact_document(source_id).await + } fn provider_id(&self) -> &'static str { "fixture" } @@ -56,24 +61,108 @@ pub struct VoidBotMcpVault { endpoint: String, } impl VoidBotMcpVault { - pub fn starfire_loopback() -> Self { + pub fn new(endpoint: impl Into) -> Self { Self { client: Client::new(), - endpoint: "http://127.0.0.1:17875/mcp".into(), + endpoint: endpoint.into(), } } + pub fn starfire_loopback() -> Self { + Self::new("http://127.0.0.1:17875/mcp") + } + + async fn call_tool( + &self, + name: &str, + arguments: serde_json::Value, + ) -> Result { + let text = self.client.post(&self.endpoint) + .header("accept", "application/json, text/event-stream") + .json(&serde_json::json!({"jsonrpc":"2.0","id":"ghostlight-vault","method":"tools/call","params":{"name":name,"arguments":arguments}})) + .send().await?.error_for_status()?.text().await?; + let payload = text + .lines() + .find_map(|line| line.strip_prefix("data: ")) + .ok_or_else(|| anyhow!("VoidBot MCP returned no event payload"))?; + Ok(serde_json::from_str(payload)?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::{Router, response::IntoResponse, routing::post}; + + #[tokio::test] + async fn voidbot_search_results_become_exact_evidence_witnesses() { + let app=Router::new().route("/mcp",post(||async { ([("content-type","text/event-stream")], "event: message\ndata: {\"result\":{\"structuredContent\":{\"results\":[{\"sourceId\":\"AetheriaLore:place.md\",\"path\":\"place.md\",\"lineStart\":7,\"lineEnd\":9,\"text\":\"The route takes six hours.\"}]}}}\n\n").into_response() })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let vault = VoidBotMcpVault::new(format!("http://{address}/mcp")); + let result = vault + .search(&VaultQuery { + query: "route".into(), + authority_lanes: vec!["AetheriaLore".into()], + temporal_scope: "era".into(), + limit: 3, + }) + .await + .unwrap(); + assert_eq!(result.witnesses[0].exact_locator, "place.md:7-9"); + assert!(result.witnesses[0].content_hash.starts_with("sha256:")); + assert_eq!(result.witnesses[0].authority_lane, "AetheriaLore"); + } } #[async_trait] impl VaultProvider for VoidBotMcpVault { async fn search(&self, query: &VaultQuery) -> Result { - let response: serde_json::Value = self.client.post(&self.endpoint).json(&serde_json::json!({"jsonrpc":"2.0","id":"ghostlight-vault","method":"tools/call","params":{"name":"search_sources","arguments":{"query":query.query,"limit":query.limit}}})).send().await?.error_for_status()?.json().await?; - let witnesses = response - .pointer("/result/structuredContent/witnesses") - .cloned() - .and_then(|v| serde_json::from_value(v).ok()) - .ok_or_else(|| anyhow!("VoidBot MCP returned no typed witnesses"))?; + let response = self + .call_tool( + "search_sources", + serde_json::json!({"query":query.query,"limit":query.limit}), + ) + .await?; + let results = response + .pointer("/result/structuredContent/results") + .and_then(|v| v.as_array()) + .ok_or_else(|| anyhow!("VoidBot MCP returned no typed search results"))?; + let witnesses = results + .iter() + .map(|item| witness_from_result(item, query)) + .collect::>>()?; Ok(receipt(self.provider_id(), query, witnesses)) } + async fn surrounding_context( + &self, + source_id: &str, + chunk_index: u32, + ) -> Result { + let response = self + .call_tool( + "get_source_context", + serde_json::json!({"sourceId":source_id,"chunkIndex":chunk_index}), + ) + .await?; + let value = response + .pointer("/result/structuredContent") + .ok_or_else(|| anyhow!("VoidBot MCP returned no source context"))?; + let excerpt = value + .get("text") + .and_then(|v| v.as_str()) + .or_else(|| value.get("context").and_then(|v| v.as_str())) + .ok_or_else(|| anyhow!("VoidBot source context contained no text"))?; + Ok(SourceWitness { + source_id: source_id.into(), + exact_locator: format!("{source_id}#chunk={chunk_index}"), + content_hash: format!("sha256:{:x}", Sha256::digest(excerpt.as_bytes())), + excerpt: excerpt.into(), + authority_lane: "source_context".into(), + temporal_scope: "unspecified".into(), + }) + } async fn exact_document(&self, _source_id: &str) -> Result { Err(anyhow!( "exact-document VoidBot adapter awaits restored trusted crossing contract verification" @@ -84,6 +173,33 @@ impl VaultProvider for VoidBotMcpVault { } } +fn witness_from_result(item: &serde_json::Value, query: &VaultQuery) -> Result { + let source_id = item + .get("sourceId") + .and_then(|v| v.as_str()) + .ok_or_else(|| anyhow!("search result missing sourceId"))?; + let excerpt = item + .get("text") + .and_then(|v| v.as_str()) + .ok_or_else(|| anyhow!("search result missing text"))?; + let locator = match ( + item.get("path").and_then(|v| v.as_str()), + item.get("lineStart").and_then(|v| v.as_u64()), + item.get("lineEnd").and_then(|v| v.as_u64()), + ) { + (Some(path), Some(start), Some(end)) => format!("{path}:{start}-{end}"), + _ => source_id.into(), + }; + Ok(SourceWitness { + source_id: source_id.into(), + exact_locator: locator, + content_hash: format!("sha256:{:x}", Sha256::digest(excerpt.as_bytes())), + excerpt: excerpt.into(), + authority_lane: query.authority_lanes.join(","), + temporal_scope: query.temporal_scope.clone(), + }) +} + fn receipt( provider: &str, query: &VaultQuery, diff --git a/docs/architecture/ghostlight-dungeon-mvp.md b/docs/architecture/ghostlight-dungeon-mvp.md index 7269c36..31d29a6 100644 --- a/docs/architecture/ghostlight-dungeon-mvp.md +++ b/docs/architecture/ghostlight-dungeon-mvp.md @@ -15,6 +15,31 @@ core world, Persona, and Vault contracts remain setting-neutral. Ghostlight's existing v0 schemas and Pallas, Lucent, and Corvid fixtures are evidence and regression scenarios. They do not own runtime state or commits. +## Implementation frontier + +The Rust runtime now contains the first honest world-compiler seam: + +- `VaultProvider` search results become exact, hashed evidence witnesses from + VoidBot's live streamable MCP response shape; +- opening generation requires exactly three distinct eras, places, and + pressures; +- role generation requires exactly three grounded roles; +- custom compilation emits a bounded typed campaign, evidence receipts, gaps, + branch assumptions, and an approval-required preview; +- deterministic seed validation rejects missing occupancy, dangling or + zero-time routes, invalid containment, invalid clocks, and missing players; +- approval alone submits `CreateCampaign`, which atomically stores the campaign + and the exact Vault receipts in the campaign `.cc` store. + +This is not yet the complete MVP compiler. The browser compiler flow, selected +opening/role compilation path, material-gap approval controls, exact-document +retrieval beyond bounded source context, on-demand destination compilation, + canon-candidate persistence remain. A live custom-start acceptance run on + 2026-08-16 consumed 30 VoidBot witnesses across three exact receipts and + produced three locations, three actors, two institutions, two clocks, + explicit gaps, and branch assumptions. It remained an uncommitted revision-0 + preview with `requires_approval: true`. + ## Body and faculty map | Faculty | Owner | Body | Authority | diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 66531ca..7d63a5a 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -33,9 +33,17 @@ per-campaign WorldKernel mailbox is the sole canonical writer. Ghostlight owns the generalized Projector → Persona → Interpreter organ; Epiphany retains her canonical Persona mind and will consume the shared organ through an adapter. -The immediate next action is to map Epiphany's existing projection machinery -into move/stay/split/delete ownership before continuing the Rust scaffold. -Existing Ghostlight fixtures remain regression evidence. +The Epiphany extraction map is complete. The active bounded organ is the world +compiler. Its Rust seam now retrieves hashed VoidBot witnesses, generates +distinct openings and roles, compiles approval-gated custom starts, rejects +invalid topology, and atomically admits campaign plus evidence only on +approval. The browser now exposes generated opening/role selection and custom +starts. A live DeepSeek plus VoidBot custom compilation passed with 30 witnessed +source chunks and remained an uncommitted approval preview. Next, prove browser +session/invite flow plus approval persistence against a disposable campaign +store, then add material-gap decisions, on-demand destination compilation, and +canon-candidate persistence. Existing Ghostlight fixtures remain regression +evidence. ## Prior research pipeline focus diff --git a/notes/ghostlight-current-system-map.md b/notes/ghostlight-current-system-map.md index 884c889..3e7e226 100644 --- a/notes/ghostlight-current-system-map.md +++ b/notes/ghostlight-current-system-map.md @@ -203,6 +203,9 @@ paths as active state surfaces. ## Missing Or Incomplete Organs +- World compiler browser flow, selected-opening/role path, live provider + acceptance, material-gap approval, on-demand destination expansion, and + canon-candidate persistence - Deterministic speaker-local input slicer - Full prompt renderer - Classifier/appraiser pipeline diff --git a/notes/ghostlight-dungeon.md b/notes/ghostlight-dungeon.md new file mode 100644 index 0000000..9d32f8b --- /dev/null +++ b/notes/ghostlight-dungeon.md @@ -0,0 +1,171 @@ +# GhostlightDungeon MVP — Starfire-Hosted AI Dungeon Master + +## Summary + +Build `GhostlightDungeon` inside `GameCult/Ghostlight`: a persistent, Vault-grounded, single-player narrative simulation with a private web chat interface for two testers. + +The runtime will be a Rust daemon on Starfire. It will own world compilation, typed CultCache state, d20 resolution, NPC Persona loops, offscreen simulation, narration, and Eve/CultUI publication. A thin TypeScript browser client will lower the Eve surface and submit typed commands. + +Ghostlight’s existing v0 schemas and training fixtures remain evidence and regression material; they do not become runtime authorities. + +## Authority and invariants + +- The per-campaign `WorldKernel` is the sole owner of canonical state and revision numbers. +- Player commands, NPC actions, scheduled ticks, travel, waits, imports, and reloads all enter the same `WorldCommand → validate → atomic commit` path. +- Projectors, Personas, Interpreters, retrieval, initiative, narration, news generation, dice previews, and the browser may propose or project state; none may commit it. +- Scenes are derived from persistent occupancy, topology, perception, and current events. Leaving a location does not delete it. +- RAG evidence remains owned by the Vault provider. For Aetheria, Ghostlight consumes VoidBot’s canonical retrieval service and stores only exact evidence receipts used by each campaign—never a rival semantic index. +- Every campaign branches from canon at creation. Later historical records describe the baseline trajectory, not an outcome the player must be railroaded into. +- Improvised facts are explicitly branch-local. Broadly useful gaps become reviewable canon candidates, never silent Vault edits. +- Player text describes an attempt, not a completed fact. Impossible actions do not receive a roll. +- Model failures, malformed outputs, stale projections, or retrieval outages produce no partial world mutation. + +## Implementation changes + +### Runtime and persistence + +- Add a Rust 2024 workspace using Tokio/Axum, the Rust CultCache/redb backend, CultMesh/CultNet publication, and a provider-neutral model port. +- Store service state under `F:\GameCult\GhostlightDungeon`: + - service/control and schema catalog `.cc`; + - one row-oriented `.cc` store per campaign; + - exact Vault evidence receipts; + - private model-stage records and commit receipts; + - exported campaign and canon-candidate bundles. +- Route all writers through an in-process campaign mailbox. Background ticks and HTTP commands cannot race or repair each other afterward. +- Publish the player surface, operator inspector, health, scheduler pressure, model receipts, and command results through CultMesh/Eve. HTTP health remains a probe of that state, not separate truth. + +### Vault and world compiler + +- Define a generic `VaultProvider` contract for source search, surrounding context, source witnesses, authority lanes, temporal scope, and exact-document retrieval. +- Implement the bundled Aetheria adapter against VoidBot’s streamable MCP endpoint at Starfire loopback. +- At campaign creation: + 1. Retrieve broad Aetheria evidence and generate three distinct suggested openings across different eras, places, and pressures. + 2. For the selected opening, generate three source-grounded player roles plus a custom-role path. + 3. Alternatively compile a fully custom who/where/when/goal description. + 4. Produce an approval preview containing the initial topology, cast, institutions, capabilities, clocks, evidence coverage, gaps, and branch-local assumptions. + 5. Commit only after approval. +- Materialize a bounded playable region and surrounding institutional pressure graph, not the entire universe. New destinations compile on demand and attach to stable containment, route, distance, and travel-time records. +- Automatically improvise reversible local texture as provisional branch fact. Material gaps in geography, mechanics, institutions, or extraordinary abilities require approval before the world seed or action is admitted. +- Store useful gaps as `CanonCandidate` records with originating campaign, evidence, conflicts, proposed wording, and affected Vault sources. The lab can review and export Markdown plus `.cc` evidence; it cannot edit AetheriaLore or open PRs. + +### Persona and world action loop + +Ghostlight owns its own generalized projection machinery: + +1. Projector converts the actor’s permitted typed slice, memories, perceived events, relationships, goals, and retrieved knowledge into a private lived narrative stream. +2. Persona receives only that narrative stream and responds naturally—no schemas, action DSL, or raw state. +3. Interpreter extracts typed private deltas, explicit speech, reaction priority, and `WorldActionProposal` candidates. +4. WorldKernel validates spatial reach, knowledge, custody, resources, capability, opposition, and state version before committing anything. + +All affected scene participants appraise a committed event in parallel. Actor-private deltas commit against their own snapshot versions; initiative then chooses compatible reactions or actions for world resolution. This ensures present characters continue perceiving and reacting even when another character currently holds conversational focus. + +Use DeepSeek’s current API directly: + +- `deepseek-v4-flash`, non-thinking: Projectors, Interpreters, retrieval planning/reranking, verification, and offscreen actors. +- `deepseek-v4-pro`, non-thinking for live work: world compilation, action assessment, live Personas, and narration. +- Structured stages use JSON Output followed by local schema validation. Empty or malformed output receives one same-snapshot retry, then fails without mutation. +- Record provider, model, request hash, source receipts, latency, output hash, validation result, and state version. Never persist or display `reasoning_content`. + +DeepSeek currently documents both V4 model IDs, streaming, and JSON output through its OpenAI-compatible Chat Completions API. [Models](https://api-docs.deepseek.com/quick_start/pricing), [Chat API](https://api-docs.deepseek.com/api/create-chat-completion), [JSON Output](https://api-docs.deepseek.com/guides/json_mode/). + +### Fiction-first d20 resolution + +- Provide separate `Assess` and `Attempt` commands. Assessment never becomes visible to NPCs or changes state. +- An assessment contains: + - normalized intent and intended effect; + - admissibility or the missing permission; + - DC on the 5/10/15/20/25/30 resistance scale; + - itemized contextual modifiers with state or evidence references; + - modifier total capped at ±10; + - effect ceiling; + - success, mixed-result, and failure stakes; + - campaign revision and expiring assessment digest. +- Contextual modifiers come from capabilities, knowledge, tools, access, assistance, leverage, position, opposition, injuries, and conditions. There are no base attributes. +- Confirmation checks the assessment revision, obtains a server-side OS-random d20, and atomically stores the roll receipt and world transition. +- Outcomes: + - total ≥ DC + 10: strong success; + - total ≥ DC: success; + - total within 5 below DC: mixed result; + - lower: failure with the previewed consequence. +- Natural 20/1 moves one outcome band, but cannot make an impossible action possible or exceed its effect ceiling. +- Stale assessments are recompiled rather than rebased. +- Overreach returns explicit sacrifices or bargains that could admit a new assessment. +- Speech and its intended effect are separated: the character may successfully say something while failing to persuade, deceive, or intimidate. + +### Away-time world agency + +- The daemon owns a five-minute scheduler pulse. Campaigns enter away simulation after fifteen minutes without player activity. +- Each real hour awards one strategic tick, capped at eight pending ticks per absence. The compiled campaign chooses the in-world tick duration; default is six hours. +- Background simulation affects remote actors, institutions, resources, movement, bargains, investigations, preparation, recruitment, obstruction, and clocks. The absent player is never puppeted or directly harmed. +- The scheduler and return-time catch-up invoke the same `AdvanceStrategicTick` command. Catch-up processes missed ticks before accepting the next player action. +- Live play has inference priority; background work stops launching new calls while a player turn is active. +- Offscreen events generate information-channel-aware news leads. On return, the player may receive newspapers, reports, messages, or rumors only when the character has access to them; the news layer cannot reveal omniscient state. + +### Web laboratory and hosting + +- Build the interface as a Ghostlight-owned `gamecult.eve.surface.v1` document and lower it with Eve’s pinned browser renderer. +- Provide: + - generated-opening and custom-start compiler; + - narrative transcript and composer; + - Assess, Attempt, confirm-roll, revise, and Wait controls; + - character ledger for capabilities, equipment, conditions, obligations, relationships, and known facts; + - location/time/pressure display; + - news and rumor drawer; + - named campaign creation, fork, reset, and `.cc` export; + - optional operator inspector for evidence, topology, state versions, model receipts, rejected proposals, and private spoiler traces. +- Do not expose model chain-of-thought or secrets. +- Serve the embedded web bundle on TCP `8831`. Firewall access is limited to Starfire’s private LAN and `10.77.0.0/24`; no public listener or Yggdrasil web gateway is added. +- Use two single-use invite links that establish separate HttpOnly sessions. Campaigns are single-player; simultaneous co-op is outside the MVP. +- Install `GhostlightDungeon` as an automatic Windows service under a dedicated virtual service identity. ACL the runtime root to administrators and the service identity. +- Read the DeepSeek key from stdin during setup, protect it with machine-scoped DPAPI plus file ACLs, and never place it in source, arguments, logs, or environment projections. +- Build immutable release directories from the exact Git commit, switch the active release atomically, record provenance in CultCache, and configure service restart recovery. + +### Repository and operational documentation + +- Implement on `codex/ghostlight-dungeon-mvp`, with coherent foundation, runtime, interface, and deployment commits pushed to GitHub. +- Add the authoritative GhostlightDungeon architecture/build document and update Ghostlight’s system map, implementation plan, handoff, state map, and evidence ledger. +- Keep Starfire service/firewall/tunnel ownership in `gamecult-ops`, with a deployment and rollback runbook. +- Before live VoidBot integration, resolve the current Yggdrasil inventory/DNS split and independently verify the offered SSH host fingerprint. Then repair the tunnel task’s stale `E:\Projects` path to `F:\Projects`, restore `127.0.0.1:17875/mcp`, and update ops truth. Never bypass host-key verification or revive Starfire’s retired VoidBot/Qdrant writers. + +## Public contracts + +- `ghostlight.vault_manifest.v1`, `vault_evidence_receipt.v1`, `world_compile_preview.v1` +- `campaign.v1`, `world_fact.v1`, `location.v1`, `actor_state.v1`, `institution_state.v1`, `relationship_state.v1`, `world_clock.v1`, `event.v1` +- `player_action_assessment.v1`, `roll_receipt.v1`, `world_commit_receipt.v1` +- `persona_stage_receipt.v1`, `actor_state_delta.v1`, `world_action_proposal.v1` +- `strategic_tick.v1`, `news_issue.v1`, `canon_candidate.v1` +- Existing `gamecult.eve.surface.v1` and `gamecult.eve.command.v1` + +Publish JSON Schema only as the schema catalog. Runtime documents and exports use MessagePack-backed CultCache `.cc`; JSON exists only at browser, MCP, and model-provider boundaries. + +## Test and acceptance plan + +- Unit-test every schema, redb/CultCache round trip, optimistic commit, topology invariant, knowledge gate, DC/modifier rule, outcome band, roll receipt, branch fact, and scheduler budget. +- Use injected clocks, RNG, Vault provider, DeepSeek transport, and persistence ports. +- Prove malformed/empty DeepSeek JSON, timeout, retrieval loss, daemon restart, stale assessment, stale Persona output, and concurrent scheduler/player commands cannot partially mutate state. +- Run existing Pallas, Lucent, and Corvid fixtures as regression scenarios, even though hosted opening suggestions are generated. +- Acceptance scenarios: + - compile an obscure Aetheria time/place or return an honest evidence-gap preview; + - leave a location, advance the world, and return to the same geometry and inhabitants; + - show reactions from every affected present actor; + - prevent an NPC from acquiring unearned knowledge or expertise; + - reject impossible action claims and offer explicit bargains; + - preview and confirm a fully receipted d20 action; + - observe institutions exploiting, resisting, or redirecting the protagonist; + - produce material offscreen changes and accessible news after absence; + - reload/fork/export a campaign without losing continuity; + - verify two invite sessions and rejection of unauthenticated access. +- Performance targets under a healthy provider: + - first progress update within 300 ms; + - all actor stages execute in parallel waves; + - a four-actor live turn completes within 20 seconds; + - background inference yields immediately to live work. +- Final deployment smoke verifies service restart, LAN and WireGuard access, blocked public access, DeepSeek inference, VoidBot-grounded retrieval, scheduler continuation, state persistence, CultMesh/Eve publication, and exact deployed commit provenance. + +## Assumptions and exclusions + +- Aetheria is the only bundled Vault adapter, but no compiler logic is Aetheria-specific. +- Generated suggestions plus unrestricted custom compilation replace fixed featured openings. +- No D&D classes, spell slots, six-ability statistics, or 5e sheet are canonical in the MVP. The typed character ledger remains sufficient for later D&D-shaped projections. +- No arbitrary Vault upload/import UI, multiplayer campaign, voice, image generation, direct canon mutation, or public internet exposure. +- The live deployment requires a DeepSeek key and restoration of the trusted VoidBot retrieval crossing; fixture-backed development may proceed before those two setup gates. diff --git a/notes/ghostlight-implementation-plan.md b/notes/ghostlight-implementation-plan.md index 1a03e71..cf9697b 100644 --- a/notes/ghostlight-implementation-plan.md +++ b/notes/ghostlight-implementation-plan.md @@ -8,12 +8,19 @@ architecture and ownership map is pipeline and fixtures remain regression evidence; they do not become hosted runtime authorities. -The first required cut is documentation and extraction mapping: inventory the -Projector → Persona → Interpreter machinery currently embedded in Epiphany, -classify move/stay/split/delete ownership, and only then continue runtime code. +The Epiphany Projector → Persona → Interpreter extraction map is complete. Ghostlight owns the generalized projection organ. Epiphany keeps her canonical Persona mind and consumes the shared organ through a narrow adapter. +The active implementation cut is the world compiler. The first Rust seam now +owns Vault witness conversion, distinct opening and role proposals, +approval-gated custom compilation, deterministic seed validation, atomic +campaign-plus-evidence admission, and the browser opening/role/custom flow. A +live DeepSeek plus VoidBot custom compilation passed without committing. Prove +invite/session plus approval persistence against a disposable campaign store, +then implement material-gap decisions, on-demand destination compilation, and +canon-candidate persistence before moving to the action/Persona loop. + ## Prior research-program phase Build a reliable data-generation loop for socially persistent Aetheria agents. diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 86a807f..35dd16f 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -69,4 +69,5 @@ {"note": "GhostlightDungeon ownership map accepted: Ghostlight owns generalized Projector-Persona-Interpreter machinery; consuming Personas such as Epiphany retain canonical mind and commit authority through narrow adapters. WorldKernel is the sole campaign writer.", "status": "accepted", "ts": "2026-08-16T14:26:32+00:00", "type": "architecture"} {"note": "Epiphany extraction map grounded in persona_turn.rs, persona_executor.rs, persona-service, conversation, and Discord crossing: shared orchestration moves to Ghostlight; Epiphany Mind/state/mouth stay; narrow slicer, transport, receipt, schema, and permit ports split; strict v1 removes second-channel state from Persona turn.", "status": "accepted", "ts": "2026-08-16T14:28:19+00:00", "type": "architecture"} {"note": "DeepSeek credential validated and migrated from plaintext ops ingress to machine-scoped DPAPI at the runtime root; native Rust DPAPI loading and live deepseek-v4-flash startup probe passed without persisting or displaying secret or reasoning content. Service ACL and protected invite generation remain in the elevated ops install.", "status": "ok", "ts": "2026-08-16T14:46:04+00:00", "type": "verification"} -{"ts": "2026-08-16T15:00:31+00:00", "type": "deployment", "status": "ok", "note": "GhostlightDungeon MVP deployed on Starfire as a normal detached operator process, not a Windows service. Exact release 747b27e9 listens on 8831, DeepSeek DPAPI startup inference is ready, unauthenticated surface access returns 401, PID/executable/log witnesses are recorded, and the obsolete stopped service was deleted."} +{"note": "GhostlightDungeon MVP deployed on Starfire as a normal detached operator process, not a Windows service. Exact release 747b27e9 listens on 8831, DeepSeek DPAPI startup inference is ready, unauthenticated surface access returns 401, PID/executable/log witnesses are recorded, and the obsolete stopped service was deleted.", "status": "ok", "ts": "2026-08-16T15:00:31+00:00", "type": "deployment"} +{"ts": "2026-08-16T18:12:28+00:00", "type": "implementation", "status": "ok", "note": "World compiler live acceptance passed on 2026-08-16: DeepSeek v4 Pro consumed 30 hashed VoidBot witnesses across three receipts, emitted three locations, three actors, two institutions, two clocks, explicit gaps and branch assumptions, and remained an uncommitted revision-0 approval preview. Deterministic tests reject dangling routes and malformed typed seeds."} diff --git a/state/ghostlight-state.cultcache.jsonl b/state/ghostlight-state.cultcache.jsonl index 3b7bf30..a57e97a 100644 --- a/state/ghostlight-state.cultcache.jsonl +++ b/state/ghostlight-state.cultcache.jsonl @@ -71,3 +71,4 @@ {"key": "2026-08-16T142819Z0000-0069-97f4de27c74a", "payload": "eyJub3RlIjogIkVwaXBoYW55IGV4dHJhY3Rpb24gbWFwIGdyb3VuZGVkIGluIHBlcnNvbmFfdHVybi5ycywgcGVyc29uYV9leGVjdXRvci5ycywgcGVyc29uYS1zZXJ2aWNlLCBjb252ZXJzYXRpb24sIGFuZCBEaXNjb3JkIGNyb3NzaW5nOiBzaGFyZWQgb3JjaGVzdHJhdGlvbiBtb3ZlcyB0byBHaG9zdGxpZ2h0OyBFcGlwaGFueSBNaW5kL3N0YXRlL21vdXRoIHN0YXk7IG5hcnJvdyBzbGljZXIsIHRyYW5zcG9ydCwgcmVjZWlwdCwgc2NoZW1hLCBhbmQgcGVybWl0IHBvcnRzIHNwbGl0OyBzdHJpY3QgdjEgcmVtb3ZlcyBzZWNvbmQtY2hhbm5lbCBzdGF0ZSBmcm9tIFBlcnNvbmEgdHVybi4iLCAic3RhdHVzIjogImFjY2VwdGVkIiwgInRzIjogIjIwMjYtMDgtMTZUMTQ6Mjg6MTkrMDA6MDAiLCAidHlwZSI6ICJhcmNoaXRlY3R1cmUifQ==", "stored_at": "2026-08-16T14:28:19.728049+00:00", "type": "ghostlight.evidence_record.v0"} {"key": "2026-08-16T144604Z0000-0070-b7d6330d1d5c", "payload": "eyJub3RlIjogIkRlZXBTZWVrIGNyZWRlbnRpYWwgdmFsaWRhdGVkIGFuZCBtaWdyYXRlZCBmcm9tIHBsYWludGV4dCBvcHMgaW5ncmVzcyB0byBtYWNoaW5lLXNjb3BlZCBEUEFQSSBhdCB0aGUgcnVudGltZSByb290OyBuYXRpdmUgUnVzdCBEUEFQSSBsb2FkaW5nIGFuZCBsaXZlIGRlZXBzZWVrLXY0LWZsYXNoIHN0YXJ0dXAgcHJvYmUgcGFzc2VkIHdpdGhvdXQgcGVyc2lzdGluZyBvciBkaXNwbGF5aW5nIHNlY3JldCBvciByZWFzb25pbmcgY29udGVudC4gU2VydmljZSBBQ0wgYW5kIHByb3RlY3RlZCBpbnZpdGUgZ2VuZXJhdGlvbiByZW1haW4gaW4gdGhlIGVsZXZhdGVkIG9wcyBpbnN0YWxsLiIsICJzdGF0dXMiOiAib2siLCAidHMiOiAiMjAyNi0wOC0xNlQxNDo0NjowNCswMDowMCIsICJ0eXBlIjogInZlcmlmaWNhdGlvbiJ9", "stored_at": "2026-08-16T14:46:04.295343+00:00", "type": "ghostlight.evidence_record.v0"} {"key": "2026-08-16T150031Z0000-0071-f1b3502e505f", "payload": "eyJub3RlIjogIkdob3N0bGlnaHREdW5nZW9uIE1WUCBkZXBsb3llZCBvbiBTdGFyZmlyZSBhcyBhIG5vcm1hbCBkZXRhY2hlZCBvcGVyYXRvciBwcm9jZXNzLCBub3QgYSBXaW5kb3dzIHNlcnZpY2UuIEV4YWN0IHJlbGVhc2UgNzQ3YjI3ZTkgbGlzdGVucyBvbiA4ODMxLCBEZWVwU2VlayBEUEFQSSBzdGFydHVwIGluZmVyZW5jZSBpcyByZWFkeSwgdW5hdXRoZW50aWNhdGVkIHN1cmZhY2UgYWNjZXNzIHJldHVybnMgNDAxLCBQSUQvZXhlY3V0YWJsZS9sb2cgd2l0bmVzc2VzIGFyZSByZWNvcmRlZCwgYW5kIHRoZSBvYnNvbGV0ZSBzdG9wcGVkIHNlcnZpY2Ugd2FzIGRlbGV0ZWQuIiwgInN0YXR1cyI6ICJvayIsICJ0cyI6ICIyMDI2LTA4LTE2VDE1OjAwOjMxKzAwOjAwIiwgInR5cGUiOiAiZGVwbG95bWVudCJ9", "stored_at": "2026-08-16T15:00:31.447772+00:00", "type": "ghostlight.evidence_record.v0"} +{"key": "2026-08-16T181228Z0000-0072-4445afe2af66", "payload": "eyJub3RlIjogIldvcmxkIGNvbXBpbGVyIGxpdmUgYWNjZXB0YW5jZSBwYXNzZWQgb24gMjAyNi0wOC0xNjogRGVlcFNlZWsgdjQgUHJvIGNvbnN1bWVkIDMwIGhhc2hlZCBWb2lkQm90IHdpdG5lc3NlcyBhY3Jvc3MgdGhyZWUgcmVjZWlwdHMsIGVtaXR0ZWQgdGhyZWUgbG9jYXRpb25zLCB0aHJlZSBhY3RvcnMsIHR3byBpbnN0aXR1dGlvbnMsIHR3byBjbG9ja3MsIGV4cGxpY2l0IGdhcHMgYW5kIGJyYW5jaCBhc3N1bXB0aW9ucywgYW5kIHJlbWFpbmVkIGFuIHVuY29tbWl0dGVkIHJldmlzaW9uLTAgYXBwcm92YWwgcHJldmlldy4gRGV0ZXJtaW5pc3RpYyB0ZXN0cyByZWplY3QgZGFuZ2xpbmcgcm91dGVzIGFuZCBtYWxmb3JtZWQgdHlwZWQgc2VlZHMuIiwgInN0YXR1cyI6ICJvayIsICJ0cyI6ICIyMDI2LTA4LTE2VDE4OjEyOjI4KzAwOjAwIiwgInR5cGUiOiAiaW1wbGVtZW50YXRpb24ifQ==", "stored_at": "2026-08-16T18:12:28.266343+00:00", "type": "ghostlight.evidence_record.v0"} diff --git a/state/map.yaml b/state/map.yaml index 8a10d39..c412ee7 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -254,5 +254,5 @@ data_flow: - If state grows faster than understanding, cut it back. current_status: - summary: GhostlightDungeon is the active MVP program. Its authority map assigns canonical campaign state and revision ownership to a per-campaign WorldKernel mailbox, preserves existing fixtures as regression evidence, and assigns the generalized Projector-Persona-Interpreter organ to Ghostlight while each consuming Persona retains its own canonical mind and commit authority. - next_action: Map Epiphany's current Persona projection implementation in plain language and source references, classify every part as move to Ghostlight, stay in Epiphany, split at a narrow port, or delete, then revise the inert Rust scaffold against that map before continuing implementation. + summary: GhostlightDungeon is the active MVP program. The world-compiler seam retrieves hashed VoidBot witnesses, generates distinct openings and roles, compiles approval-gated custom starts, rejects invalid typed topology, and admits campaign plus evidence through the WorldKernel only after approval. Its browser flow is built and a live DeepSeek plus VoidBot custom compilation passed with 30 witnessed chunks while remaining uncommitted. The broader hosted MVP remains incomplete. + next_action: Prove invite/session and approval persistence through the HTTP harness against a disposable campaign store, then implement material-gap decisions, on-demand destination compilation, and canon-candidate persistence before moving to the action and Persona loop. diff --git a/web/dist/assets/index-CmB__dez.js b/web/dist/assets/index-CmB__dez.js deleted file mode 100644 index 85310da..0000000 --- a/web/dist/assets/index-CmB__dez.js +++ /dev/null @@ -1,153 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))i(o);new MutationObserver(o=>{for(const a of o)if(a.type==="childList")for(const s of a.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&i(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const a={};return o.integrity&&(a.integrity=o.integrity),o.referrerPolicy&&(a.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?a.credentials="include":o.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(o){if(o.ep)return;o.ep=!0;const a=n(o);fetch(o.href,a)}})();const K=new WeakMap,pt=20;function Vt(t,e,n,i,o,a,s,l){const f=te(t.canvas);if(!f)return!1;const c=f.gl;if(!ee(f,a,s))return K.set(t.canvas,null),!1;const r=Jt(e,n,i,o,l);c.bindFramebuffer(c.FRAMEBUFFER,f.framebuffer),c.viewport(0,0,a,s),c.disable(c.DEPTH_TEST),c.disable(c.CULL_FACE),c.enable(c.BLEND),c.blendFunc(c.ONE,c.ONE),c.clearColor(0,0,0,1),c.clear(c.COLOR_BUFFER_BIT),r.gravity.length>0&&(c.useProgram(f.splatProgram),c.uniform4f(c.getUniformLocation(f.splatProgram,"u_viewport"),o.minX,o.minY,o.maxX,o.maxY),c.uniform1f(c.getUniformLocation(f.splatProgram,"u_time"),_(e.simulationTimeSeconds,0)),c.bindBuffer(c.ARRAY_BUFFER,f.splatBuffer),c.bufferData(c.ARRAY_BUFFER,r.gravity,c.DYNAMIC_DRAW),Ct(c,f.splatProgram),c.drawArrays(c.TRIANGLES,0,r.gravity.length/pt)),c.bindFramebuffer(c.FRAMEBUFFER,f.tintFramebuffer),c.clearColor(0,0,0,0),c.clear(c.COLOR_BUFFER_BIT),r.tint.length>0&&(c.useProgram(f.splatProgram),c.uniform4f(c.getUniformLocation(f.splatProgram,"u_viewport"),o.minX,o.minY,o.maxX,o.maxY),c.uniform1f(c.getUniformLocation(f.splatProgram,"u_time"),_(e.simulationTimeSeconds,0)),c.bindBuffer(c.ARRAY_BUFFER,f.splatBuffer),c.bufferData(c.ARRAY_BUFFER,r.tint,c.DYNAMIC_DRAW),Ct(c,f.splatProgram),c.drawArrays(c.TRIANGLES,0,r.tint.length/pt)),c.disable(c.BLEND),c.bindFramebuffer(c.FRAMEBUFFER,null),c.viewport(0,0,a,s),c.useProgram(f.shadeProgram),c.activeTexture(c.TEXTURE0),c.bindTexture(c.TEXTURE_2D,f.fieldTexture),c.uniform1i(c.getUniformLocation(f.shadeProgram,"u_field"),0),c.activeTexture(c.TEXTURE1),c.bindTexture(c.TEXTURE_2D,f.tintTexture),c.uniform1i(c.getUniformLocation(f.shadeProgram,"u_tint"),1),c.uniform2f(c.getUniformLocation(f.shadeProgram,"u_resolution"),a,s),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_time"),_(n.simulationTimeSeconds,_(e.simulationTimeSeconds,0))),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineInterval"),_(e.lineInterval,_(e.scalarFieldLineInterval,_(e.depthRange,228.79605)/20))),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineOffset"),_(e.lineOffset,_(e.startDepth,2.310401))),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineWidth"),_(e.lineWidth,.3)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineFade"),_(e.lineFade,5)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_angleWidth"),_(e.angleWidth,.05)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_angleFade"),_(e.angleFade,1.15)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_dangerSteepness"),_(e.dangerSteepness,1.5)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_scale"),_(e.isolineScale,2.6924083)),V(c,f.shadeProgram,"u_baseColor",q(e.scalarFieldBaseColor,[.002,.006,.012])),V(c,f.shadeProgram,"u_fieldGlowColor",q(e.scalarFieldGlowColor,[.018,.05,.075])),V(c,f.shadeProgram,"u_lineLowColor",q(e.scalarFieldLowLineColor,[0,.34,.52])),V(c,f.shadeProgram,"u_lineHighColor",q(e.scalarFieldHighLineColor,[1.45,.3,.05])),V(c,f.shadeProgram,"u_angleLowColor",q(e.scalarFieldLowAngleColor,[.06,.16,.24])),V(c,f.shadeProgram,"u_angleHighColor",q(e.scalarFieldHighAngleColor,[1.1,.24,.04])),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_tintScale"),_(e.vectorFieldTintScale,.45)),c.bindBuffer(c.ARRAY_BUFFER,f.quadBuffer);const d=c.getAttribLocation(f.shadeProgram,"a_position");return c.enableVertexAttribArray(d),c.vertexAttribPointer(d,2,c.FLOAT,!1,0,0),c.drawArrays(c.TRIANGLES,0,6),t.drawImage(f.canvas,0,0,a,s),!0}function Jt(t,e,n,i,o){const a=[],s=[];return Zt(a,t,e,n),Qt(s,t,o),{gravity:new Float32Array(a),tint:new Float32Array(s)}}function Zt(t,e,n,i,o){const a=_(n.terrainRadius,_(e.terrainRadius,1200)),s=_(n.terrainDepth,_(e.terrainDepth,-8));s!==0&&at(t,0,0,Math.max(1,a*2),Math.max(1,a*2),-s,0,0,1,Math.max(1e-4,_(n.terrainDepthExponent,_(e.terrainDepthExponent,1.2))),0,1,0,0);for(const l of i)at(t,l.x,l.y,Math.max(1,l.radius),Math.max(1,l.radius),-l.depth,0,0,1,Math.max(1e-4,l.exponent),0,1,0,0),l.waveRadius>0&&l.waveDepth!==0&&at(t,l.x,l.y,l.waveRadius,l.waveRadius,-l.waveDepth,0,0,1,8,4,_(n.terrainWaveFrequency,_(e.terrainWaveFrequency,.6)),l.waveSpeed,0)}function Qt(t,e,n){const i=ne(n?.splats),o=Array.isArray(n?.layers)?n.layers:[],a=new Set,s=re(e.vectorFieldLayer,e.tintFieldLayer,"fog.tint");o.forEach((E,H)=>{const tt=ie(E?.layerKey,"");_(E?.channel,-1)===4&&tt===s&&a.add(H)});const l=Math.max(0,oe(i.count,0));if(l<=0||a.size===0)return;const f=k(i.centerX),c=k(i.centerY),r=k(i.halfExtentX),d=k(i.halfExtentY),u=k(i.rotationCos),h=k(i.rotationSin),y=k(i.channel),b=k(i.falloff),v=k(i.valueR),C=k(i.valueG),A=k(i.valueB),N=k(i.valueA),O=k(i.sourceKind),W=k(i.frequencyX),Y=k(i.animationSpeed),j=k(i.sourceFlags),z=k(i.layerIndex);for(let E=0;ENumber(i));if(n.length>=3&&n.slice(0,3).every(Number.isFinite))return[n[0],n[1],n[2]]}if(typeof t=="string"){const n=t.split(/[,\s]+/).map(i=>Number(i)).filter(Number.isFinite);if(n.length>=3)return[n[0],n[1],n[2]]}return e}function V(t,e,n,i){t.uniform3f(t.getUniformLocation(e,n),i[0],i[1],i[2])}function k(t){return Array.isArray(t)?t.map(e=>_(e,0)):[]}function ne(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function ie(t,e){return t==null?e:String(t)}function re(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e;if(typeof e=="number"&&Number.isFinite(e))return String(e)}return""}function oe(t,e){const n=Number(t);return Number.isFinite(n)?Math.max(0,Math.floor(n)):e}const ae=`#version 300 es -in vec2 a_corner; -in vec2 a_center; -in vec2 a_half; -in vec2 a_rot; -in vec4 a_meta; -in vec4 a_source; -in vec4 a_value; -uniform vec4 u_viewport; -out vec2 v_local; -out vec4 v_meta; -out vec4 v_source; -out vec4 v_value; -void main() { - vec2 scaled = a_corner * a_half; - vec2 world = a_center + vec2( - scaled.x * a_rot.x - scaled.y * a_rot.y, - scaled.x * a_rot.y + scaled.y * a_rot.x - ); - vec2 clip = vec2( - ((world.x - u_viewport.x) / max(0.0001, u_viewport.z - u_viewport.x)) * 2.0 - 1.0, - ((world.y - u_viewport.y) / max(0.0001, u_viewport.w - u_viewport.y)) * 2.0 - 1.0 - ); - gl_Position = vec4(clip, 0.0, 1.0); - v_local = a_corner; - v_meta = a_meta; - v_source = a_source; - v_value = a_value; -}`,ce=`#version 300 es -precision highp float; -in vec2 v_local; -in vec4 v_meta; -in vec4 v_source; -in vec4 v_value; -uniform float u_time; -out vec4 outColor; -float hash21(vec2 p) { - p = fract(p * vec2(123.34, 456.21)); - p += dot(p, p + 45.32); - return fract(p.x * p.y); -} -float valueNoise(vec2 p) { - vec2 i = floor(p); - vec2 f = fract(p); - float a = hash21(i); - float b = hash21(i + vec2(1.0, 0.0)); - float c = hash21(i + vec2(0.0, 1.0)); - float d = hash21(i + vec2(1.0, 1.0)); - vec2 u = f * f * (3.0 - 2.0 * f); - return mix(mix(a, b, u.x), mix(c, d, u.x), u.y) * 2.0 - 1.0; -} -float powerPulse(float x, float power) { - x = clamp(abs(x), 0.0, 1.0); - return pow((x + 1.0) * (1.0 - x), max(0.0001, power)); -} -void main() { - float d = length(v_local); - if (d > 1.0) discard; - float alpha = powerPulse(d, v_meta.x); - if (alpha <= 0.0001) discard; - float source = 1.0; - if (v_source.x > 0.5 && v_source.x < 2.5) { - float timeOffset = v_source.x > 1.5 ? u_time * v_source.z : 0.0; - source = valueNoise(v_local * v_source.y + timeOffset); - if (v_source.w != 0.0) source = abs(source); - } else if (v_source.x > 3.5) { - source = cos(pow(d * 2.0, 1.25) * v_source.y + u_time * v_source.z); - } - outColor = v_value * alpha * source; -}`,se=`#version 300 es -in vec2 a_position; -out vec2 v_uv; -void main() { - v_uv = a_position * 0.5 + 0.5; - gl_Position = vec4(a_position, 0.0, 1.0); -}`,le=`#version 300 es -precision highp float; -uniform sampler2D u_field; -uniform sampler2D u_tint; -uniform vec2 u_resolution; -uniform float u_time; -uniform float u_lineInterval; -uniform float u_lineOffset; -uniform float u_lineWidth; -uniform float u_lineFade; -uniform float u_angleWidth; -uniform float u_angleFade; -uniform float u_dangerSteepness; -uniform float u_scale; -uniform vec3 u_baseColor; -uniform vec3 u_fieldGlowColor; -uniform vec3 u_lineLowColor; -uniform vec3 u_lineHighColor; -uniform vec3 u_angleLowColor; -uniform vec3 u_angleHighColor; -uniform float u_tintScale; -in vec2 v_uv; -out vec4 outColor; -vec2 calcGrad(vec2 uv, float me) { - vec2 texel = 1.0 / max(vec2(1.0), u_resolution); - float n = -texture(u_field, vec2(uv.x, uv.y + texel.y)).r; - float e = -texture(u_field, vec2(uv.x + texel.x, uv.y)).r; - return vec2(e - me, n - me); -} -void main() { - float height = -texture(u_field, v_uv).r; - vec4 tint = texture(u_tint, v_uv); - vec2 plan = calcGrad(v_uv, height); - float slope = max(length(plan), 0.00001); - vec3 color = u_baseColor; - float fieldGlow = smoothstep(0.0, u_lineInterval * 7.0, abs(height)); - color += u_fieldGlowColor * fieldGlow; - color += tint.rgb * clamp(tint.a, 0.0, 1.0) * u_tintScale; - - float dangerBlend = smoothstep(0.0, u_dangerSteepness, pow(slope / max(0.0001, u_scale), 2.0)); - vec3 baseLine = mix(u_lineLowColor, u_lineHighColor, dangerBlend); - vec3 angleLine = mix(u_angleLowColor, u_angleHighColor, dangerBlend) * clamp(slope / max(0.0001, u_scale), 0.0, 1.0); - - vec3 lines = vec3(0.0); - float interval = max(0.0001, abs(u_lineInterval)); - float nearestLine = abs(fract((height + u_lineOffset) / interval) - 0.5) * interval; - float lineDistance = nearestLine / slope; - float line = 1.0 - smoothstep(u_lineWidth, u_lineWidth * u_lineFade, lineDistance); - lines += line * baseLine; - - float angle = atan(plan.y, plan.x) / 3.1415926536 + 1.0; - float nearestAngle = abs(fract(angle * 6.0) - 0.5) / 6.0; - float angleMask = smoothstep(interval * 0.25, interval * 1.5, abs(height)); - float angleLineAmount = 1.0 - smoothstep(u_angleWidth, u_angleWidth * u_angleFade, nearestAngle); - lines += angleLineAmount * angleMask * angleLine; - - color += clamp(lines, 0.0, 1.7); - outColor = vec4(color, 1.0); -}`,Ut=new Set(["gamecult.fields.splats.v1","gamecult.fields.gravity.v1","gamecult.fields.objects.v1"]),de={pluginId:"fields.surface",capabilities:["field.surface2d","gravity.surface","field.scalar","field.vector","field.objects"],componentKinds:["field.surface2d","gravity.surface"],schemas:[...Ut],normalizeDocument:ht,renderComponent:ue};function ue(t,e,n,i,o,a){const s=document.createElement("canvas");s.className="cultui-gravity-surface",t.id&&(s.id=t.id),s.setAttribute("role","img"),s.setAttribute("aria-label",Ne(e.label,"gravity surface")),s.style.display="block",s.style.width="100%",s.style.height="100%",s.style.pointerEvents="none",a.applyGeneratedLayout(s,n,i);let l=!1;const f={},c=()=>pe(s,e,f,a.resolveAssetUrl),r=()=>{!s.isConnected||l||(l=!0,requestAnimationFrame(()=>{l=!1,s.isConnected&&c()}))};s.addEventListener("cultui:asset-loaded",r);let d=0,u;const h=()=>{d&&window.clearInterval(d),u?.disconnect(),s.removeEventListener("cultui:asset-loaded",r)},y=()=>{if(!s.isConnected){h();return}fe(t,e,o,a.providerId,f).then(v=>{v&&s.isConnected&&r()}).catch(v=>{f.lastError=v instanceof Error?v.message:String(v)})};typeof ResizeObserver<"u"&&(u=new ResizeObserver(r),u.observe(s)),r();const b=Math.max(33,Math.min(1e3,Be(e.stateRefreshMs,100)));return d=window.setInterval(y,b),queueMicrotask(y),window.setTimeout(r,300),window.setTimeout(r,1e3),s}async function fe(t,e,n,i,o){if(o.loading)return!1;const a=[ft(t,e,"renderSplats","renderSplatsDocumentId","renderSplatsSchemaId"),ft(t,e,"gravity","gravityDocumentId","gravitySchemaId"),ft(t,e,"objects","objectsDocumentId","objectsSchemaId")].filter(s=>!!s?.documentId);if(a.length===0)return!1;o.loading=!0;try{let s=!1;for(const l of a){const f=await n.documentResolver?.(l,t);let c=lt(ht(f?.schemaId||l.schemaId,f?.document));if(Object.keys(c).length===0&&(c=lt(ht(l.schemaId,await me(l,i||n.provider?.providerId)))),Object.keys(c).length===0)continue;const r=l.slotId==="renderSplats"?"renderSplats":l.slotId==="gravity"?"gravity":"objects",d=yt(o[r]?.frameId,-1),u=yt(c.frameId,d);o[r]=c,s||=u!==d}return o.lastLoadedAt=Date.now(),s}finally{o.loading=!1}}async function me(t,e){if(typeof fetch!="function"||typeof window>"u"||!e)return;const n=new URLSearchParams({documentId:t.documentId});t.schemaId&&n.set("schemaId",t.schemaId),t.slotId&&n.set("slotId",t.slotId);const i=await fetch(`/eir/document/${encodeURIComponent(e)}?${n.toString()}`,{cache:"no-store",headers:{Accept:"application/json"}});if(i.ok)return lt(await i.json()).document}function ft(t,e,n,i,o){const a=(t.embeddedDocuments||[]).find(l=>String(l?.slotId||"")===n),s=T(e[i],a?.documentId);if(s)return{documentId:s,schemaId:T(e[o],a?.schemaId),presentationKind:T(a?.presentationKind)||"data",slotId:n}}function ht(t,e){const n=Array.isArray(e)?e:void 0,i=n?n[0]:e?.schema,o=String(t||i||"");return!n||!Ut.has(o)?e:o==="gamecult.fields.splats.v1"?Ee(n):o==="gamecult.fields.gravity.v1"?Ce(n):Te(n)}function pe(t,e,n,i){const o=t.getBoundingClientRect(),a=Math.max(1,Math.floor(o.width||t.clientWidth||1)),s=Math.max(1,Math.floor(o.height||t.clientHeight||1)),l=Math.max(1,Math.min(2,window.devicePixelRatio||1)),f=Math.max(1,Math.floor(a*l)),c=Math.max(1,Math.floor(s*l));(t.width!==f||t.height!==c)&&(t.width=f,t.height=c);const r=t.getContext("2d");if(!r)return;r.setTransform(l,0,0,l,0,0),r.clearRect(0,0,a,s);const d=_e(Ae(e),a,s),u=$t(n?.gravity),h=Se(n?.gravity)||xe(T(e.bodies,"")),y=Ie(n?.objects)||we(T(e.objects,""));Vt(r,e,u,h,d,a,s,n?.renderSplats)||he(r,e,a,s,"field.surface2d requires WebGL2 float render targets"),ge(r,h,e,d,a,s,i),be(r,y,e,d,a,s,i)}function he(t,e,n,i,o){t.save(),t.fillStyle=T(e.failureBackground,"rgba(0, 0, 0, 0.72)"),t.fillRect(0,0,n,i),t.font=T(e.failureFont,"700 13px Cascadia Mono, Consolas, monospace"),t.fillStyle=T(e.failureColor,"rgba(255, 184, 79, 0.95)"),t.fillText(o,16,28),t.restore()}function ge(t,e,n,i,o,a,s){for(const l of e){const f=zt(i,l.x,l.y,o,a),c=Math.max(18,Math.min(190,l.radius/Math.max(1,i.maxX-i.minX)*o*.32)),r=s(l.icon),d=l.kind.toLowerCase().includes("sun")?Math.max(I(n.sunIconMinPx,34),c*I(n.sunIconScale,.72)):Math.max(I(n.bodyIconMinPx,24),c*I(n.bodyIconScale,.48)),u=l.iconSize>0?l.iconSize:d;r&&ye(t,r,f.x,f.y,u,.92),l.key&&Wt(t,n,l.key.replace(/^local\./,""),f.x+c*.44,f.y-c*.48,T(n.bodyLabelColor,"rgba(226, 244, 255, 0.82)"))}}const st=new Map;function ye(t,e,n,i,o,a){let s=st.get(e);s||(s=new Image,s.decoding="async",s.onload=()=>requestAnimationFrame(()=>{t.canvas.dispatchEvent(new CustomEvent("cultui:asset-loaded"))}),s.src=e,st.set(e,s)),!(!s.complete||s.naturalWidth===0)&&(t.save(),t.globalAlpha=a,t.drawImage(s,n-o/2,i-o/2,o,o),t.restore())}function be(t,e,n,i,o,a,s){for(const l of e){const f=zt(i,l.x,l.y,o,a);if(f.x<-40||f.x>o+40||f.y<-40||f.y>a+40)continue;const c=l.kind.toLowerCase().includes("station")?I(n.stationIconSizePx,34):l.controlled?I(n.shipIconSizePx,22):I(n.remoteShipIconSizePx,18),r=ve(n,l.faction,l.controlled,l.visibility),d=s(l.icon);t.save(),t.globalAlpha=Math.max(.25,Math.min(1,l.visibility)),t.translate(f.x,f.y);const u=Math.atan2(l.directionY,l.directionX)+Math.PI/2;if(l.kind.toLowerCase().includes("ship")&&t.rotate(u),d){const h=st.get(d);if(h)h.complete&&h.naturalWidth>0&&t.drawImage(h,-c/2,-c/2,c,c);else{const y=new Image;y.decoding="async",y.onload=()=>t.canvas.dispatchEvent(new CustomEvent("cultui:asset-loaded")),y.src=d,st.set(d,y)}}t.restore(),Wt(t,n,l.label,f.x+c*.55,f.y-c*.45,r)}}function Wt(t,e,n,i,o,a){n&&(t.save(),t.font=T(e.objectLabelFont,"700 12px Ubuntu, system-ui, sans-serif"),t.textBaseline="middle",t.lineWidth=I(e.objectLabelStrokeWidth,3),t.strokeStyle=T(e.objectLabelStroke,"rgba(0, 0, 0, 0.72)"),t.fillStyle=a,t.strokeText(n,i,o),t.fillText(n,i,o),t.restore())}function ve(t,e,n,i){const o=Math.max(.25,Math.min(1,i));if(n)return et(T(t.objectControlledColor,"rgba(122, 240, 255, {alpha})"),o);const a=e.toLowerCase();return a.includes("raider")?et(T(t.objectRaiderColor,"rgba(255, 143, 74, {alpha})"),o):a.includes("neutral")?et(T(t.objectNeutralColor,"rgba(232, 232, 224, {alpha})"),o):et(T(t.objectDefaultColor,"rgba(214, 244, 255, {alpha})"),o)}function et(t,e){return t.replaceAll("{alpha}",String(e))}function xe(t){return t.split(";").map(e=>e.trim()).filter(Boolean).map(e=>{const n=e.split("|");return{key:n[0]??"",kind:n[1]??"",x:Number(n[2])||0,y:Number(n[3])||0,radius:Math.max(1,Number(n[4])||1),depth:Number(n[5])||0,exponent:Number(n[6])||1,waveRadius:Number(n[7])||0,waveDepth:Number(n[8])||0,waveSpeed:Number(n[9])||0,icon:n[10]??"",iconSize:Number(n[12])||0,tint:n[11]??""}})}function we(t){return t.split(";").map(e=>e.trim()).filter(Boolean).map(e=>{const n=e.split("|");return{key:n[0]??"",kind:n[1]??"",label:n[2]??"",x:Number(n[3])||0,y:Number(n[4])||0,directionX:Number(n[5])||0,directionY:Number(n[6])||1,faction:n[7]??"",controlled:n[8]==="1"||n[8]==="true",visibility:Number(n[9])||1,icon:n[10]??""}})}function Se(t){const e=Array.isArray(t?.gravityInfluences)?t.gravityInfluences:[],n=Array.isArray(t?.bodies)?t.bodies:[];if(e.length===0&&n.length===0)return;const i=new Map;for(const o of n){const a=T(o.bodyKey,o.name,"");a&&i.set(a,o)}return(e.length>0?e:n).map(o=>{const a=T(o.bodyKey,o.name,"body"),s=i.get(a),l=T(o.kind,"Body");return{key:a,kind:l,x:I(o.x,0),y:I(o.y,0),radius:Math.max(1,I(o.radius,80)),depth:I(o.gravityDepth,0),exponent:I(o.gravityDepthExponent,1),waveRadius:I(o.waveRadius,0),waveDepth:I(o.waveDepth,0),waveSpeed:I(o.waveSpeed,0),icon:gt(o.iconAsset)||gt(s?.iconAsset),iconSize:I(s?.iconSize,I(o.iconSize,0)),tint:""}})}function Ie(t){const e=Array.isArray(t?.objects)?t.objects:[];if(e.length!==0)return e.map(n=>{const i=T(n.kind,"object");return{key:T(n.entityKey,String(n.entityIndex??""),"object"),kind:i,label:T(n.displayName,n.entityKey,"object"),x:I(n.x,0),y:I(n.y,0),directionX:I(n.directionX,1),directionY:I(n.directionY,0),faction:T(n.factionKey,""),controlled:De(n.controlled),visibility:I(n.visibility,1),icon:gt(n.iconAsset)}})}function gt(t){const e=$t(t);return T(e.uri,"")}function Ae(t){const e=Math.max(1,I(t.viewRadius,Math.max(1200,I(t.terrainRadius,1200))));return{minX:I(t.minX,-e),minY:I(t.minY,-e),maxX:I(t.maxX,e),maxY:I(t.maxY,e)}}function _e(t,e,n){const i=Math.max(1e-4,t.maxX-t.minX),o=Math.max(1e-4,t.maxY-t.minY),a=Math.max(1e-4,e/Math.max(1,n)),s=i/o,l=(t.minX+t.maxX)*.5,f=(t.minY+t.maxY)*.5;if(a>s){const r=o*a;return{minX:l-r*.5,maxX:l+r*.5,minY:t.minY,maxY:t.maxY}}const c=i/a;return{minX:t.minX,maxX:t.maxX,minY:f-c*.5,maxY:f+c*.5}}function zt(t,e,n,i,o){return{x:(e-t.minX)/Math.max(1,t.maxX-t.minX)*i,y:(n-t.minY)/Math.max(1,t.maxY-t.minY)*o}}function Ee(t){const e=L(t[9]);return{schema:t[0],frameId:t[1],publishedAtUtc:t[2],simulationTimeSeconds:t[3],runId:t[4],zoneIndex:t[5],zoneName:t[6],viewport:vt(t[7]),layers:L(t[8]).map(Re),splats:{count:e[0]??0,centerX:e[1]||[],centerY:e[2]||[],halfExtentX:e[3]||[],halfExtentY:e[4]||[],rotationCos:e[5]||[],rotationSin:e[6]||[],channel:e[7]||[],falloff:e[8]||[],valueR:e[9]||[],valueG:e[10]||[],valueB:e[11]||[],valueA:e[12]||[],sourceKey:e[13]||[],layerIndex:e[14]||[],sourceKind:e[15]||[],frequencyX:e[16]||[],frequencyY:e[17]||[],phaseX:e[18]||[],phaseY:e[19]||[],animationSpeed:e[20]||[],sourceFlags:e[21]||[]}}}function Ce(t){return{schema:t[0],frameId:t[1],publishedAtUtc:t[2],simulationTimeSeconds:t[3],runId:t[4],zoneIndex:t[5],zoneName:t[6],viewport:vt(t[7]),gravityInfluences:L(t[8]).map(Fe),bodies:L(t[9]).map(Pe),terrainRadius:t[10],terrainDepth:t[11],terrainDepthExponent:t[12],terrainWaveFrequency:t[13]}}function Te(t){return{schema:t[0],frameId:t[1],publishedAtUtc:t[2],simulationTimeSeconds:t[3],runId:t[4],zoneIndex:t[5],zoneName:t[6],currentEntityKey:t[7],viewport:vt(t[8]),controlledEntityIndices:L(t[9]),objects:L(t[10]).map(ke)}}function vt(t){const e=L(t);return e.length?{minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}:t}function Re(t){const e=L(t);return e.length?{layerKey:e[0],displayName:e[1],channel:e[2],blendMode:e[3],graphicsFormat:e[4],clearBeforeDraw:e[5],clearR:e[6],clearG:e[7],clearB:e[8],clearA:e[9]}:t}function Fe(t){const e=L(t);return e.length?{bodyKey:e[0],orbitKey:e[1],kind:e[2],x:e[3],y:e[4],radius:e[5],gravityDepth:e[6],gravityDepthExponent:e[7],waveRadius:e[8],waveDepth:e[9],waveSpeed:e[10]}:t}function Pe(t){const e=L(t);return e.length?{bodyKey:e[0],orbitKey:e[1],name:e[2],kind:e[3],x:e[4],y:e[5],radius:e[6],isAsteroidBelt:e[7],body:e[8],iconAsset:xt(e[9])}:t}function ke(t){const e=L(t);return e.length?{entityIndex:e[0],entityKey:e[1],displayName:e[2],kind:e[3],factionKey:e[4],x:e[5],y:e[6],z:e[7],directionX:e[8],directionY:e[9],velocityX:e[10],velocityY:e[11],controlled:e[12],targetEntityIndex:e[13],isActive:e[14],visibility:e[15],status:Me(e[16]),inventory:L(e[17]).map(Le),iconAsset:xt(e[18])}:t}function Me(t){const e=L(t);return e.length?{hull:e[0],shield:e[1],heat:e[2]}:t||{}}function Le(t){const e=L(t);return e.length?{source:e[0],itemKey:e[1],quantity:e[2],quality:e[3],durability:e[4],enabled:e[5],sourceIndex:e[6],x:e[7],y:e[8],iconAsset:xt(e[9])}:t}function xt(t){const e=L(t);return e.length?{assetKey:e[0],kind:e[1],uri:e[2],transport:e[3],contentHash:e[4],mimeType:e[5],metadata:e[6]||{}}:t||{}}function L(t){return Array.isArray(t)?t:[]}function lt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function T(...t){for(const e of t)if(typeof e=="string"&&e.trim())return e.trim();return""}function Ne(t,e){return typeof t=="string"&&t?t:e}function Be(t,e){const n=Number(t);return Number.isFinite(n)&&n>0?Math.floor(n):e}function yt(t,e){const n=Number(t);return Number.isFinite(n)?n:e}const $t=lt,I=yt;function De(t){return typeof t=="boolean"?t:typeof t=="number"?t!==0:typeof t=="string"&&["1","true","yes","on"].includes(t.trim().toLowerCase())}const Ue=[de],We={"--bg":"#020909","--bg-top":"#020909","--bg-mid":"#020909","--bg-bottom":"#020909","--shell-top":"#010707","--shell-bottom":"#010707","--panel":"#071918","--panel-2":"#0a2423","--line":"rgba(103, 240, 228, 0.28)","--line-deep":"rgba(103, 240, 228, 0.18)","--text":"#e7f1f1","--text-bright":"#e7f1f1","--quiet":"#8ba5a3","--accent":"#ffb84f","--accent-strong":"#ffb84f","--corner-accent":"#ffb84f","--cyan":"#8efcff","--shadow":"rgba(0, 0, 0, 0.35)","--pixel-grid":"rgba(142, 252, 255, 0.04)","--border-width":"1px","--border-bottom-width":"1px","--corner-accent-size":"0","--font-body":'"M PLUS 1", "Ubuntu Sans", Ubuntu, "Noto Sans JP", system-ui, sans-serif',"--font-title":'"Montserrat", "Zen Kaku Gothic New", "M PLUS 1", "Ubuntu Sans", system-ui, sans-serif',"--font-mono":'"Ubuntu Sans Mono", "M PLUS 1 Code", "Cascadia Mono", Consolas, monospace'};let nt,Kt=wt(void 0),Z,U={};const Ft=new WeakMap;function ze(t,e,n={}){if(Ft.get(e)?.dispose(),Z=t,U=n,Kt=wt(t.surface?.styles),globalThis.__eveCurrentMesh=t.mesh,on(t.surface?.styles,n.body??document.body),n.body&&(n.body.dataset.provider=t.providerId||n.provider?.providerId||""),n.statusElement&&(n.statusElement.textContent=`${t.title||t.surface?.title||"surface"}${n.source?` (${n.source})`:""}`),t.surface?.root){if(e.replaceChildren(P(t.surface.root,n)),n.stateBindingResolver){const i=new Ke(t,e,n);Ft.set(e,i),i.start()}}else e.replaceChildren(X("No surface root"));return e}function $e(t,e,n){const i=e.targetProp.split(".").filter(Boolean);if(i.length===0)throw new Error("Eve state binding targetProp must not be empty.");t.props||={};let o=t.props;for(const a of i.slice(0,-1)){const s=o[a];(!s||typeof s!="object"||Array.isArray(s))&&(o[a]={}),o=o[a]}o[i[i.length-1]]=n}class Ke{surface;host;options;disposed=!1;unsubscribers=[];constructor(e,n,i){this.surface=e,this.host=n,this.options=i}async start(){const e=this.options.stateBindingResolver,n=this.surface.surface?.root;if(!(!e||!n))for(const i of Gt(n))for(const o of i.stateBindings||[]){if(this.disposed)return;const a=await e(o,i);if(!a||this.disposed)continue;const s=l=>{this.disposed||($e(i,o,l),this.renderCanonicalProjection())};if(s(await a.latest()),this.disposed)return;this.unsubscribers.push(a.watch(s))}}dispose(){this.disposed=!0;for(const e of this.unsubscribers.splice(0))e()}renderCanonicalProjection(){const e=this.surface.surface?.root;e&&this.host.replaceChildren(P(e,this.options))}}function*Gt(t){yield t;for(const e of t.children||[])yield*Gt(e)}function P(t,e=U){const n=t.kind||"panel",i=x(t.props),o=x(t.layout),a=x(t.style),s=t.children||[],l=t.embeddedDocuments||[];if(n==="surface"||n==="cockpit"||n==="dashboard"){const r=m("section","cultui-surface-root eve-surface");w(r,t),typeof o.direction=="string"?r.dataset.direction=o.direction:typeof i.layout=="object"&&i.layout&&typeof i.layout.direction=="string"&&(r.dataset.direction=String(i.layout.direction)),n!=="surface"&&(r.dataset.surfaceKind=n),S(r,o,a);for(const d of s)r.append(P(d,e));return r}if(n==="column"||n==="row"||n==="form"||n==="rail"){const r=m("div",`cultui-partition eve-${n}`);w(r,t),r.dataset.direction=n==="row"||n==="rail"?"horizontal":"vertical",n==="rail"&&(r.dataset.overflow="x"),rt(r,{...o,...i}),S(r,o,a);for(const d of s)r.append(P(d,e));return r}if(n==="grid"){const r=m("section","cultui-grid"),d=B(i.columns,0);d>0?r.style.gridTemplateColumns=`repeat(${d}, minmax(0, 1fr))`:typeof i.columns=="string"&&(r.style.gridTemplateColumns=i.columns);const u=B(i.rows,0);u>0&&(r.style.gridTemplateRows=`repeat(${u}, minmax(0, auto))`),S(r,o,a);for(const h of s)r.append(P(h,e));return r}if(n==="partition"){const r=m("section",`cultui-partition split-${g(i.split,"none")}`);w(r,t),rt(r,i),S(r,o,a),r.style.minWidth="0",g(i.split,"none")==="x"&&!p(i.flexWrap,o.flexWrap,"")&&(r.style.flexWrap="wrap"),typeof i.role=="string"&&(r.dataset.role=i.role);for(const d of s)r.append(P(d,e));return r}if(n==="input.binding-map")return tn(t,i,e);if(n==="inventory.drag_session")return qe(t,i,o,a);if(n==="inventory.grid")return Ve(t,i,o,a,e);if(n==="inventory.item")return Je(t,i,o,a);const f=(e.pluginAdapters||Ue).find(r=>r.componentKinds.includes(n));if(f?.renderComponent)return f.renderComponent(t,i,o,a,e,{applyGeneratedLayout:S,providerId:Z?.providerId||e.provider?.providerId,resolveAssetUrl:J});if(n==="world.scene3d"||n==="world.scene2d")return Xe(t,i,o,a,e);if(n==="image.background"){const r=m("div","cultui-background"),d=J(p(i.src,i.assetUri,i.assetRef,""));return d&&(r.style.backgroundImage=`url("${d}")`),r.setAttribute("aria-label",g(i.label,"background")),r}if(n==="image.sprite"){const r=m("figure",`cultui-sprite ${g(i.slot,"center")}`);w(r,t);const d=J(p(i.src,i.assetUri,i.assetRef,""));if(d){const u=m("img");u.src=d,u.alt=g(i.alt,g(i.actor,g(i.label,""))),r.append(u)}return r}if(n==="avatar"){const r=m("figure","cultui-avatar-card");w(r,t);const d=J(p(i.src,i.assetUri,i.assetRef,""));if(d){const b=m("img");b.src=d,b.alt=g(i.alt,g(i.text,g(i.label,""))),r.append(b)}else r.append(m("div","cultui-avatar-fallback",yn(p(i.text,i.label,i.actor,"?"))));const u=p(i.text,i.label,i.actor,"");u&&r.append(m("figcaption","cultui-avatar-name",u));const h=p(i.status,"");h&&r.append(m("div","cultui-avatar-status",h));const y=p(i.detail,"");return y&&r.append(m("div","cultui-avatar-detail",y)),r}if(n==="pane"||n==="panel"){const r=m("section","pane cultui-pane");w(r,t);const d=g(i.span,"");d&&(r.dataset.span=d);const u=g(i.density,"");u&&(r.dataset.density=u);const h=g(i.title,t.text||"");h&&r.append(m("h2","",h));for(const y of s)r.append(P(y,e));return r}if(n==="list"||n.endsWith(".roster")){const r=m("section","cultui-list");w(r,t),r.dataset.componentKind=n;const d=g(i.title,"");d&&r.append(m("h3","cultui-list-title",d));for(const[u,h]of hn(i.items).entries())r.append(P({id:`${t.id||"list"}-item-${u}`,kind:"list.item",props:{...h}},e));for(const u of s)r.append(P(u,e));return r}if(n==="list.item"||n.endsWith(".item")){const r=Xt(t),d=m("article","cultui-list-item");w(d,t),d.dataset.componentKind=n;const u=m("div","cultui-list-item-heading");if(u.append(m("strong","cultui-list-item-label",r.label)),r.status&&u.append(m("span","cultui-list-item-status",r.status)),d.append(u),r.detail&&d.append(m("div","cultui-list-item-detail",r.detail)),r.badges.length){const h=m("div","cultui-list-item-badges");for(const y of r.badges)h.append(m("span","cultui-list-item-badge",y));d.append(h)}for(const h of s)d.append(P(h,e));return d}if(n==="bar"){const r=m("div","cultui-meter");w(r,t);const d=g(i.label,""),u=g(i.value,"");if(d||u){const b=m("div","cultui-meter-head");b.append(m("span","",d)),b.append(m("strong","",u)),r.append(b)}const h=m("div","cultui-meter-track"),y=m("span","cultui-meter-fill");return y.style.width=`${Bt(i.percent)}%`,h.append(y),r.append(h),r}if(n==="card"){const r=Lt(i,t),d=r?m("button","card cultui-card cultui-card-button"):m("article","card cultui-card");w(d,t),S(d,o,a),d instanceof HTMLButtonElement&&(d.type="button");const u=g(i.title,t.text||"");u&&d.append(m("div","card-title",u));for(const h of s)d.append(P(h,e));return r&&Nt(d,t,r,i,e),d}if(n==="control.button"){const r=m("button","cultui-button eve-control-button",g(i.label,"Action"));return w(r,t),r.type="button",S(r,o,a),Nt(r,t,Lt(i,t),i,e),r}if(n==="control.popup"){const r=m("button","cultui-button eve-control-popup",g(i.label,"Open"));return w(r,t),r.type="button",S(r,o,a),r.addEventListener("click",d=>{en(t,e,r,d.clientX,d.clientY)}),r}if(n==="text.dialogue"||n==="text"||n==="text.title"||n==="text.subtitle"||n==="label"){const r=m("div",dn(n,i),g(i.value,g(i.text,t.text||"")));return w(r,t),rt(r,i),S(r,o,a),r}if(n==="metric"){const r=m("dl","metric cultui-reactive-metric eve-metric");return w(r,t),S(r,o,a),r.append(m("dt","",g(i.label,"Metric"))),r.append(m("dd","metric-value",g(i.value,""))),r}if(n==="progress"){const r=m("div","cultui-meter eve-progress");w(r,t),S(r,o,a);const d=g(i.label,""),u=g(i.value,""),h=Number(i.min??0),y=Number(i.max??1),b=Number(i.value??0),v=Number.isFinite(b)&&Number.isFinite(h)&&Number.isFinite(y)&&y!==h?(b-h)/(y-h)*100:Bt(i.percent);if(d||u){const N=m("div","cultui-meter-head");N.append(m("span","",d)),N.append(m("strong","",u)),r.append(N)}const C=m("div","cultui-meter-track"),A=m("span","cultui-meter-fill");return A.style.width=`${Math.max(0,Math.min(100,v))}%`,C.append(A),r.append(C),r}if(n==="modal"){const r=m("section","cultui-modal-surface");w(r,t),S(r,o,a);const d=g(i.title,"");d&&r.append(m("h2","cultui-modal-surface-title",d));for(const u of s)r.append(P(u,e));return r}if(n==="options"){const r=m("section","cultui-options");w(r,t),S(r,o,a);const d=g(i.label,"");d&&r.append(m("h3","cultui-list-title",d));for(const u of s)r.append(P(u,e));return s.length===0&&r.append(X("waiting for options")),r}if(n==="image.preview"){const r=m("figure","cultui-image-preview");w(r,t);const d=m("div","cultui-image-frame"),u=J(p(i.src,i.assetUri,i.assetRef,""));if(u){const h=m("img");h.src=u,h.alt=g(i.label,""),h.style.imageRendering=g(i.imageRendering,"auto"),i.zoom!==void 0&&(h.style.transform=`scale(${i.zoom})`,h.style.transformOrigin=g(i.crop,"50% 50%")),d.append(h)}else d.append(m("span","",g(i.label,"image")));return r.append(d),i.label&&r.append(m("figcaption","",String(i.label))),r}if(n==="canvas.preview"||n==="canvas.editor"){const r=m("div",`cultui-canvas-placeholder ${n==="canvas.editor"?"editor":"preview"}`);return w(r,t),r.append(m("div","viz-label",g(i.label,"Canvas"))),r.append(m("div","cultui-canvas-grid",i.state==="empty"?"waiting for pixels":g(i.state,""))),r}if(n==="surface.slot"){const r=m("section","cultui-embedded-slot");w(r,t),S(r,o,a),r.dataset.slotId=g(i.slotId,g(l[0]?.slotId,"")),r.dataset.documentId=g(i.documentId,g(l[0]?.documentId,"")),r.dataset.schemaId=g(i.schemaId,g(l[0]?.schemaId,"")),r.dataset.presentationKind=g(i.presentationKind,g(l[0]?.presentationKind,""));const d=l.map(h=>x(h.surface)).find(h=>x(h.root).kind||h.root),u=i.modal===!0||r.dataset.presentationKind.includes("modal");if((d||r.dataset.documentId)&&u){const h=m("button","cultui-button cultui-modal-trigger",g(i.label,r.dataset.slotId||"Configure"));h.type="button",h.addEventListener("click",()=>jt(bt(t,e),e)),r.append(h)}else if(d||r.dataset.documentId){const h=m("div","cultui-embedded-slot-body");h.append(m("div","detail","materializing surface")),r.append(h),bt(t,e).then(y=>{h.replaceChildren(y?.root?P(y.root,e):X("Embedded surface unavailable"))}).catch(y=>{h.replaceChildren(X(`Embedded surface failed: ${y instanceof Error?y.message:String(y)}`))})}else r.append(m("div","detail",r.dataset.presentationKind||r.dataset.slotId||"embedded surface"));return r}if(n==="control.slider")return cn(i,s,e);if(n==="control.toggle"){const r=m("label","toggle-row cultui-toggle");return w(r,t),r.append(m("span","field-control",i.value?"on":"off")),r.append(m("span","toggle-copy",g(i.label,"Toggle"))),r}if(n==="input.number"||n==="input.select"||n==="control.range"||n==="control.input.text"||n==="control.select"){const r=m("label","field cultui-field");return w(r,t),rt(r,i),S(r,o,a),r.append(m("span","field-label",g(i.label,""))),r.append(m("span","field-control cultui-field-value",i.value===void 0?"":String(i.value))),r}if(n==="color.swatch"){const r=m("div","paint-swatch cultui-swatch");return w(r,t),r.style.background=g(i.value,g(i.color,"currentColor")),r.title=g(i.label,"Color"),r}const c=m("section","pane");w(c,t),c.append(m("h2","",n));for(const r of s)c.append(P(r,e));return c}function Xt(t){const e=x(t.props);return{label:p(e.label,e.title,e.displayName,t.text,t.kind,"item"),status:p(e.status,e.state,""),detail:p(e.detail,e.phase,e.repoName,""),badges:Array.isArray(e.badges)?e.badges.map(n=>String(n).trim()).filter(Boolean):p(e.badges,"").split(",").map(n=>n.trim()).filter(Boolean)}}function S(t,e,n={}){const i=p(e.display,"");i&&(t.style.display=i);const o=p(e.direction,"");o&&(t.style.flexDirection=o==="horizontal"?"row":o==="vertical"?"column":o);const a=p(e.flexWrap,"");a&&(t.style.flexWrap=a);const s=p(e.gridTemplateColumns,"");s&&(t.style.gridTemplateColumns=s);const l=p(e.gridTemplateRows,"");l&&(t.style.gridTemplateRows=l);const f=p(e.gridTemplateAreas,"");f&&(t.style.gridTemplateAreas=f);const c=p(e.gridArea,"");c&&(t.style.gridArea=c);const r=p(e.placeItems,"");r&&(t.style.placeItems=r),M(t,"gap",p(e.gap,"")),M(t,"padding",p(e.padding,"")),M(t,"margin",p(e.margin,"")),M(t,"top",p(e.top,"")),M(t,"right",p(e.right,"")),M(t,"bottom",p(e.bottom,"")),M(t,"left",p(e.left,"")),M(t,"width",p(e.width,"")),M(t,"minWidth",p(e.minWidth,"")),M(t,"maxWidth",p(e.maxWidth,"")),M(t,"height",p(e.height,"")),M(t,"minHeight",p(e.minHeight,"")),M(t,"maxHeight",p(e.maxHeight,""));const d=p(e.alignItems,"");d&&(t.style.alignItems=d);const u=p(e.justifyContent,"");u&&(t.style.justifyContent=u);const h=p(e.alignSelf,"");h&&(t.style.alignSelf=h);const y=p(e.overflow,"");y&&(t.style.overflow=y);const b=p(e.overflowX,"");b&&(t.style.overflowX=b);const v=p(e.overflowY,"");v&&(t.style.overflowY=v);const C=p(e.position,"");C&&(t.style.position=C);const A=p(e.cursor,"");A&&(t.style.cursor=A);const N=p(n.background,"");N&&(t.style.background=ct(N));const O=p(n.color,"");O&&(t.style.color=ct(O)),M(t,"borderWidth",p(n.borderWidth,""));const W=p(n.borderColor,"");W&&(t.style.borderColor=ct(W));const Y=p(n.borderStyle,"");Y&&(t.style.borderStyle=Y),M(t,"borderRadius",p(n.borderRadius,""));const j=p(n.boxShadow,"");j&&(t.style.boxShadow=j);const z=p(n.font,"");z&&(t.style.font=z),M(t,"fontSize",p(n.fontSize,""));const E=p(n.fontWeight,"");E&&(t.style.fontWeight=E);const H=p(n.textTransform,"");H&&(t.style.textTransform=H);const tt=p(n.textAlign,"");tt&&(t.style.textAlign=tt);const ut=p(n.whiteSpace,"");ut&&(t.style.whiteSpace=ut);const At=p(n.overflow,"");At&&(t.style.overflow=At);const _t=p(n.textOverflow,"");_t&&(t.style.textOverflow=_t),M(t,"lineHeight",p(n.lineHeight,""))}function M(t,e,n){n&&(t.style[e]=R(n))}function F(t,e){const n={};for(const[i,o]of Object.entries(t))i.startsWith(e)&&(n[i.slice(e.length)]=o);return n}function Ge(t){const e=(t.children||[]).filter(u=>u.kind==="world.entity3d"),n=e.map(u=>He(x(u.props).position,[0,0,0])),i=n.map(u=>u[0]),o=n.map(u=>u[2]),a=Math.min(...i,-1),s=Math.max(...i,1),l=Math.min(...o,-1),f=Math.max(...o,1),c=Math.max(1,s-a),r=Math.max(1,f-l),d=6;return e.map((u,h)=>{const y=x(u.props);return{entityId:p(y.entityId,u.id),faction:g(y.faction,"neutral"),kind:g(y.entityKind,"entity"),label:p(y.label,y.entityId,u.id,"Entity"),controlled:St(y.controllable),xPercent:d+(n[h][0]-a)/c*(100-d*2),yPercent:d+(1-(n[h][2]-l)/r)*(100-d*2),source:u}})}function Xe(t,e,n,i,o){const a=m("section","cultui-world-scene");w(a,t),S(a,n,i),a.tabIndex=0,a.setAttribute("aria-label",g(e.label,"Interactive world"));const s=Ge(t),l=s.find(r=>r.controlled),f=m("div","cultui-world-heading");f.append(m("strong","",g(e.label,"World"))),f.append(m("span","",`${s.length} entities`)),a.append(f);const c=m("div","cultui-world-plane");for(const r of s){const d=m("button",`cultui-world-entity faction-${Pt(r.faction)} kind-${Pt(r.kind)}`);d.type="button",d.style.left=`${r.xPercent}%`,d.style.top=`${r.yPercent}%`,d.dataset.entityId=r.entityId,d.dataset.controlled=r.controlled?"true":"false",d.title=r.label,d.setAttribute("aria-label",`${r.label}, ${r.kind}, ${r.faction}`),d.append(m("span","cultui-world-entity-glyph",je(r.kind))),d.append(m("span","cultui-world-entity-label",r.label));const u=x(r.source.props),h=p(u.targetCommand,e.targetCommand,u.focusCommand,e.focusCommand);h&&d.addEventListener("click",()=>mt(h,{actorEntityId:l?.entityId||p(e.playerEntityId),entityId:r.entityId,targetEntityId:r.entityId,targetEntityKey:r.entityId},r.source,o)),c.append(d)}return a.append(c),a.addEventListener("keydown",r=>{const d=Ye(r.key);if(d){r.preventDefault();const h=p(e.movementCommand,x(l?.source.props).moveCommand);h&&mt(h,{actorEntityId:l?.entityId||p(e.playerEntityId),actorEntityKey:l?.entityId||p(e.playerEntityId),directionX:d[0],directionY:d[1],scalar:1},t,o);return}const u=r.key===" "?p(e.actionCommand,x(l?.source.props).actionCommand):r.key.toLowerCase()==="f"?p(e.focusCommand,x(l?.source.props).focusCommand):"";u&&(r.preventDefault(),mt(u,{actionId:r.key===" "?"0":"focus",actorEntityId:l?.entityId||p(e.playerEntityId),actorEntityKey:l?.entityId||p(e.playerEntityId)},t,o))}),a}function mt(t,e,n,i){i.commandSink?.(Oe(t,e,i),n)}function Oe(t,e,n=U){return Q(t,{action:e},n)}function Ye(t){switch(t.toLowerCase()){case"w":case"arrowup":return[0,1];case"s":case"arrowdown":return[0,-1];case"a":case"arrowleft":return[-1,0];case"d":case"arrowright":return[1,0];default:return}}function je(t){return t.includes("station")?"S":t.includes("projectile")?".":t.includes("ship")?"^":"+"}function Pt(t){return t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function G(t,e){const n=Number(t);return Number.isFinite(n)?n:e}function He(t,e){if(Array.isArray(t)){const n=t.map(i=>Number(i));if(n.length>=3&&n.slice(0,3).every(Number.isFinite))return[n[0],n[1],n[2]]}if(typeof t=="string"){const n=t.split(/[,\s]+/).map(i=>Number(i)).filter(Number.isFinite);if(n.length>=3)return[n[0],n[1],n[2]]}return e}function qe(t,e,n,i){const o=St(e.active),a=m("section","cultui-inventory-drag");w(a,t),S(a,n,i),a.dataset.active=o?"true":"false";const s=m("div","cultui-inventory-section-label","Drag");if(S(s,F(n,"sectionLabel."),F(i,"sectionLabel.")),a.append(s),!o){const d=m("div","cultui-inventory-empty","None");return S(d,F(n,"empty."),F(i,"empty.")),a.append(d),a}const l=p(e.itemKey,e.item,"item"),f=m("div","cultui-inventory-drag-chip",l);S(f,F(n,"dragChip."),F(i,"dragChip.")),a.append(f);const c=[e.originOffsetX,e.originOffsetY].map(d=>Number(d)).map(d=>Number.isFinite(d)?d:0),r=m("div","cultui-inventory-meta",`origin ${c[0]}, ${c[1]}`);return S(r,F(n,"meta."),F(i,"meta.")),a.append(r),a}function Ve(t,e,n,i,o){const a=m("section","cultui-inventory-grid");w(a,t),S(a,n,i);const s=B(p(e.columns,e.gridColumns,e.widthCells,""),0),l=s>0?s:6,f=B(e.rows,0),c=f>0?f:Math.max(3,Math.ceil(Math.max((t.children||[]).length,1)/l));a.style.setProperty("--inventory-columns",String(l)),a.style.setProperty("--inventory-rows",String(c)),a.dataset.cellSpriteMode=g(e.cellSpriteMode,"");const r=p(e.title,e.label,"Inventory"),d=m("div","cultui-inventory-section-label",r);S(d,F(n,"sectionLabel."),F(i,"sectionLabel.")),a.append(d);const u=m("div","cultui-inventory-board");u.style.display="grid",u.style.gridTemplateColumns=`repeat(${l}, ${R(p(e.cellSize,"72"))})`,u.style.gridTemplateRows=`repeat(${c}, ${R(p(e.cellSize,"72"))})`,u.style.gap=R(p(e.cellGap,"4")),u.style.overflow=p(e.boardOverflow,"auto"),u.style.padding=R(p(e.boardPadding,"4")),S(u,F(n,"board."),F(i,"board.")),u.addEventListener("dragover",b=>{Ze(e)&&(b.preventDefault(),b.dataTransfer&&(b.dataTransfer.dropEffect="move"))}),u.addEventListener("drop",b=>{const v=b.dataTransfer?.getData("application/vnd.gamecult.eve.inventory-item+json")||"";if(!v)return;let C;try{C=JSON.parse(v)}catch{return}const A=u.getBoundingClientRect(),N=Math.max(1,G(e.cellSize,72)),O=Math.max(0,G(e.cellGap,4)),W=N+O,Y=Math.max(0,Math.min(l-1,Math.floor((b.clientX-A.left)/W))),j=Math.max(0,Math.min(c-1,Math.floor((b.clientY-A.top)/W))),z=Qe(C,e,Y,j,o);z&&(b.preventDefault(),o.commandSink?.(z,t))});const h=new Set;for(const b of t.children||[]){const v=x(b.props),C=B(v.x,0),A=B(v.y,0);h.add(`${C}:${A}`),u.append(P(b,o))}const y=Math.min(l*c,256);for(let b=0;b{!a.draggable||!y.dataTransfer||(y.dataTransfer.effectAllowed="move",y.dataTransfer.setData("application/vnd.gamecult.eve.inventory-item+json",JSON.stringify(e)))});let f=B(e.shapeWidth,1),c=B(e.shapeHeight,1);const r=p(e.rotation,"").toLowerCase();["clockwise","counterclockwise","right","left","rotate90","rotate270"].includes(r)&&([f,c]=[c,f]),a.style.gridColumn=`${s+1} / span ${f}`,a.style.gridRow=`${l+1} / span ${c}`;const d=m("span","cultui-inventory-item-icon");S(d,F(n,"icon."),F(i,"icon.")),d.textContent=gn(p(e.iconAssetUri,e.iconAssetKey,e.itemKey,e.label,"")),a.append(d);const u=p(e.label,e.itemKey,"");if(u){const y=m("span","cultui-inventory-item-label",u);S(y,F(n,"label."),F(i,"label.")),a.append(y)}const h=Number(e.quantity);if(Number.isFinite(h)&&h>1){const y=m("span","cultui-inventory-item-quantity",String(h));S(y,F(n,"quantity."),F(i,"quantity.")),a.append(y)}return a.title=[u,p(e.source,""),p(e.quality,"")?`quality ${e.quality}`:"",p(e.durability,"")?`durability ${e.durability}`:""].filter(Boolean).join(" | "),a}function Ze(t){return Object.entries(t).some(([e,n])=>(e==="dropCommand"||e.startsWith("dropCommand."))&&typeof n=="string"&&n.length>0)}function Qe(t,e,n,i,o=U){const a=p(t.sourceKind,t.source,""),s=p(e[`dropCommand.${a}`],e.dropCommand,"");if(!a||!s)return;const l=G(t.sourceIndex,-1),f=G(e.targetIndex,-1),c=p(e.targetKind,""),r={sourceKind:a,originEntityKey:p(t.sourceEntityKey,t.entityKey,""),originIndex:l,originCargoIndex:a==="cargo"?l:-1,itemKey:p(t.itemKey,""),quantity:Math.max(1,G(t.quantity,1)),sourceX:G(t.x,-2147483648),sourceY:G(t.y,-2147483648),destinationKind:c,destinationEntityKey:p(e.targetEntityKey,e.entityKey,""),destinationIndex:f,destinationCargoIndex:c==="cargo"?f:-1,destinationX:Math.trunc(n),destinationY:Math.trunc(i),hasDestinationPosition:!0};return Q(s,{action:r},o)}function tn(t,e,n){const i=m("section","cultui-binding-map");w(i,t);const o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.setAttribute("class","cultui-xbox-controller"),o.setAttribute("viewBox","0 0 780 420"),o.setAttribute("role","img"),o.setAttribute("aria-label",g(e.label,"Xbox controller remapping")),o.innerHTML=rn(),i.append(o);const a=m("div","cultui-binding-overlay");for(const s of t.children||[]){const l=x(s.props),f=g(l.target,s.id||""),c=m("button","cultui-binding-box");w(c,s),c.type="button",c.dataset.target=f,c.dataset.kind=g(l.bindingKind,"button"),c.style.left=R(l.x??"50%"),c.style.top=R(l.y??"50%"),c.append(m("span","cultui-binding-target",g(l.label,f))),c.append(m("span","cultui-binding-source",g(l.current,"unmapped"))),c.addEventListener("click",()=>{const d=Yt(s);if(Ot(s)||d?.documentId)jt(bt(s,n),n);else{const u=g(l.commandId,"");u&&n.commandSink?.(Q(u,l,n),s)}}),a.append(c);const r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("class","cultui-binding-line"),r.setAttribute("x1",g(l.anchorX,"390")),r.setAttribute("y1",g(l.anchorY,"210")),r.setAttribute("x2",String(Mt(l.x,780))),r.setAttribute("y2",String(Mt(l.y,420))),o.append(r)}return i.append(a),i}function Ot(t){for(const e of t.embeddedDocuments||[]){const n=x(e.surface);if(n.root)return n}}function Yt(t){const e=(t.embeddedDocuments||[])[0],n=x(t.props),i=p(n.documentId,e?.documentId,"");if(i)return{documentId:i,presentationKind:p(n.presentationKind,e?.presentationKind,""),schemaId:p(n.schemaId,e?.schemaId,""),slotId:p(n.slotId,e?.slotId,"")}}async function bt(t,e){const n=Ot(t);if(n)return n;const i=Yt(t);if(!i?.documentId||!e.documentResolver)return;const o=await e.documentResolver(i,t);if(o)return x(o.surface).root?o.surface:o}function jt(t,e){const n=m("div","cultui-modal-backdrop"),i=m("section","cultui-modal");i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true");const o=m("header","cultui-modal-header");o.append(m("h2","","Configure Binding"));const a=m("button","cultui-modal-close","Close");a.type="button",a.addEventListener("click",()=>n.remove()),o.append(a);const s=m("div","cultui-modal-body");i.append(o,s),n.append(i),n.addEventListener("click",l=>{l.target===n&&n.remove()}),document.body.append(n),s.append(m("div","detail","materializing document")),Promise.resolve(t).then(l=>{o.querySelector("h2").textContent=l?.title||"Configure Binding",s.replaceChildren(l?.root?P(l.root,e):X("Embedded document unavailable"))}).catch(l=>{s.replaceChildren(X(`Embedded document failed: ${l instanceof Error?l.message:String(l)}`))})}function en(t,e,n,i,o){const a=x(t.props),s=(t.children||[])[0],l=x(s?.props),f=p(l.anchor,a.anchor,"trigger"),c=p(l.placement,a.placement,"below-start"),r=Number(p(l.offsetX,a.offsetX,"0"))||0,d=Number(p(l.offsetY,a.offsetY,"4"))||0,u=m("div","cultui-modal-backdrop");u.style.background="transparent",u.style.placeItems="start";const h=m("section","cultui-modal");h.setAttribute("role","dialog"),h.setAttribute("aria-modal","true"),h.style.position="fixed",h.style.width="min(420px, calc(100vw - 24px))",h.style.maxHeight="min(620px, calc(100vh - 24px))";const y=m("header","cultui-modal-header");y.append(m("h2","",p(l.title,a.title,a.label,"Options")));const b=m("button","cultui-modal-close","Close");b.type="button",b.addEventListener("click",()=>u.remove()),y.append(b);const v=m("div","cultui-modal-body");if(s){const A=s.children||[];A.length>0?v.replaceChildren(...A.map(N=>P(N,e))):v.append(P(s,e))}else v.append(X("Popup has no content"));h.append(y,v),u.append(h),u.addEventListener("click",A=>{A.target===u&&u.remove()}),document.body.append(u);const C=nn(f,c,n,h,i,o,r,d);h.style.left=`${C.left}px`,h.style.top=`${C.top}px`}function nn(t,e,n,i,o,a,s,l){const f=n.getBoundingClientRect(),c=i.getBoundingClientRect(),r=c.width||420,d=c.height||320,u=t==="cursor"?{left:o,right:o,top:a,bottom:a}:f;if(e==="right-down"||e==="dropdown")return it(u,r,d,s,l,"right","down");if(e==="left-down")return it(u,r,d,s,l,"left","down");if(e==="right-up")return it(u,r,d,s,l,"right","up");if(e==="left-up")return it(u,r,d,s,l,"left","up");switch(e){case"above-start":return D(u.left+s,u.top-d-l,r,d);case"above-end":return D(u.right-r+s,u.top-d-l,r,d);case"below-end":return D(u.right-r+s,u.bottom+l,r,d);case"right-start":return D(u.right+s,u.top+l,r,d);case"left-start":return D(u.left-r-s,u.top+l,r,d);case"center":return D((window.innerWidth-r)/2+s,(window.innerHeight-d)/2+l,r,d);default:return D(u.left+s,u.bottom+l,r,d)}}function it(t,e,n,i,o,a,s){const f=window.innerWidth-t.right-i-12,c=t.left-i-12,r=window.innerHeight-t.top-o-12,d=t.bottom-o-12,u=a==="right"?f>=e||f>=c:!(c>=e||c>=f),h=s==="down"?r>=n||r>=d:!(d>=n||d>=r),y=u?t.right+i:t.left-e-i,b=h?t.top+o:t.bottom-n-o;return D(y,b,e,n)}function D(t,e,n,i){return{left:kt(t,12,window.innerWidth-n-12),top:kt(e,12,window.innerHeight-i-12)}}function kt(t,e,n){return n - - - - - - - - - - - - - - - - - YBXA - `}function on(t,e=document.body){const n=wt(t),i=document.documentElement.style;ln(n.assets.fontCss);for(const[c,r]of Object.entries(We))i.setProperty(c,r);const o={colorBackground:"--bg",colorBackgroundTop:"--bg-top",colorBackgroundMid:"--bg-mid",colorBackgroundBottom:"--bg-bottom",colorShellSurfaceTop:"--shell-top",colorShellSurfaceBottom:"--shell-bottom",colorPanel:"--panel",colorPanelAlt:"--panel-2",colorPanelBorder:"--line",colorPanelBorderDeep:"--line-deep",colorText:"--text",colorTextBright:"--text-bright",colorMuted:"--quiet",colorAccent:"--accent",colorAccentStrong:"--accent-strong",colorCornerAccent:"--corner-accent",colorLink:"--cyan",colorShadow:"--shadow",colorPixelGrid:"--pixel-grid"};for(const[c,r]of Object.entries(o)){const d=n.tokens[c];d!==void 0&&i.setProperty(r,String(d))}const a=n.tokens.fontBody,s=n.tokens.fontDisplay,l=n.tokens.fontTitle,f=n.tokens.fontMono;a&&i.setProperty("--font-body",ot(String(a))),s&&i.setProperty("--font-title",ot(String(s))),l&&i.setProperty("--font-title",ot(String(l))),f&&i.setProperty("--font-mono",ot(String(f))),n.tokens.borderWidthPx&&i.setProperty("--border-width",`${n.tokens.borderWidthPx}px`),n.tokens.borderBottomWidthPx&&i.setProperty("--border-bottom-width",`${n.tokens.borderBottomWidthPx}px`),n.tokens.cornerAccentPx&&i.setProperty("--corner-accent-size",`${n.tokens.cornerAccentPx}px`),e.dataset.pixelArt=n.tokens.pixelArt||n.tokens.imageRendering==="pixelated"?"true":"false",e.dataset.scanlines=n.tokens.scanlineOverlay?"true":"false"}function Q(t,e={},n=U){const i=x(e.action),o=n.provider?.providerId||Z?.providerId||"surface unknown",a=n.activeSurfaceId||Z?.surface?.id||n.provider?.surfaces?.[0]?.surfaceId||o,s=an(n,a),l=p(s.commandBoundary,e.commandBoundary,i.commandBoundary,i.target),f=p(s.receiptSchema,e.receiptSchema,i.receiptSchema),c={type:"surface-command",schema:"gamecult.eve.command_invocation.v1",providerId:o,surfaceId:a,command:t||g(i.type,"invoke"),payload:{...i,transport:e.transport??null},issuedAt:new Date().toISOString(),clientId:n.clientId||"eve.browser"};return l&&(c.commandBoundary=l),f&&(c.receiptSchema=f),c}function an(t,e){const n=[...t.provider?.surfaces||[],...t.provider?.localAdvertisement?.surfaces||[]];return n.find(i=>i.surfaceId===e&&i.worldInteraction)?.worldInteraction||n.find(i=>i.worldInteraction)?.worldInteraction||{}}function Lt(t,e){const n=x(t.action);return g(t.command,g(t.commandId,g(n.command,g(n.target,g(n.type,e?.commandId||"")))))}function X(t){const e=m("section","pane");return e.append(m("h2","","No Surface")),e.append(m("div","detail",t)),e}function Nt(t,e,n,i,o){t.dataset.commandId=n,t.tabIndex=t instanceof HTMLButtonElement?t.tabIndex:0;const a=()=>{const s=Q(n,i,o);o.commandSink?.(s,e)};t.addEventListener("click",a),t.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),a())})}function cn(t,e,n){const i=sn(t,e),o=x(i.find(u=>u.kind==="control.box")?.props),a=i.filter(u=>u.kind==="control.part"),s=Number(t.min??0),l=Number(t.max??1),f=m("div","cultui-slider");f.dataset.skin=g(t.skin,"default"),f.dataset.bind=g(t.bind,""),un(f,o);const c=m("div","cultui-slider-visual"),r=m("input","cultui-slider-input");r.type="range",r.min=String(s),r.max=String(l),r.step=String(t.step??.01),r.setAttribute("aria-label",g(t.bind,"slider"));for(const u of a){const h=x(u.props),y=m("span",`cultui-slider-part ${g(h.name,"part")}`);fn(y,h),c.append(y)}return a.some(u=>x(u.props).name==="track")||c.append(m("span","cultui-slider-part track")),a.some(u=>x(u.props).name==="fill")||c.append(m("span","cultui-slider-part fill")),a.some(u=>x(u.props).name==="thumb")||c.append(m("span","cultui-slider-part thumb")),f.append(c,r),(u=>{const h=Number(u??s),y=Math.max(s,Math.min(l,Number.isFinite(h)?h:s)),b=l===s?0:(y-s)/(l-s)*100;r.value=String(y),f.style.setProperty("--cultui-slider-value",`${b}%`),f.dataset.value=String(y)})(t.value??s),r.addEventListener("input",()=>{const u=Q(g(t.command,"control.slider.input"),{...t,action:{...x(t.action),value:Number(r.value)},value:Number(r.value)},n);n.commandSink?.(u,{kind:"control.slider",props:t})}),f}function sn(t,e){const n=typeof t.skin=="string"?t.skin:"",o=[...n?Kt.controlSkins[n]?.children||[]:[],...e];return o.length?o:[{kind:"control.box",props:{height:18,overflow:"visible"}},{kind:"control.part",props:{name:"track",anchor:"center",size:["100%",6],radius:2,fill:"color.panelInset"}},{kind:"control.part",props:{name:"fill",anchor:["left","center"],size:["value%",6],radius:2,fill:"color.accent"}},{kind:"control.part",props:{name:"thumb",anchor:["value","center"],size:[12,12],bleed:3,radius:999,fill:"color.accent"}}]}function wt(t){if(Array.isArray(t)){const e={},n={};for(const i of t)i?.name&&(i.name==="font.web.google"&&typeof i.value=="string"?n.fontCss=i.value:e[i.name]=i.value);return{tokens:e,assets:n,controlSkins:{}}}return{tokens:x(t?.tokens),assets:x(t?.assets),controlSkins:x(t?.controlSkins)}}function J(t){if(!t)return"";const e=U.assetUrlResolver;return e?e(t,Z):/^(https?:|data:|blob:)/i.test(t)?t:U.assetBaseUrl&&t.startsWith("/")?`${U.assetBaseUrl.replace(/\/+$/,"")}${t}`:t}function ln(t){const e=typeof t=="string"?t.trim():"";if(nt?.dataset.href===e||(nt?.remove(),nt=void 0,!e))return;const n=document.createElement("link");n.rel="preconnect",n.href="https://fonts.gstatic.com",n.crossOrigin="anonymous",document.head.append(n);const i=document.createElement("link");i.rel="stylesheet",i.href=e,i.dataset.href=e,document.head.append(i),nt=i}function dn(t,e,n){const i=[];return(t==="text.title"||e.role==="title")&&i.push("cultui-title","eve-text-title"),t==="text.subtitle"&&i.push("eve-text-subtitle"),t==="label"&&i.push("cultui-label"),e.role==="mono"&&i.push("detail","mono"),i.length===0&&i.push("detail","eve-text"),i.join(" ")}function un(t,e){e.height!==void 0&&(t.style.minHeight=R(e.height)),e.width!==void 0&&(t.style.width=R(e.width)),typeof e.overflow=="string"&&(t.style.overflow=e.overflow)}function fn(t,e){const n=Array.isArray(e.size)?e.size:[e.size,void 0];n[0]!==void 0&&n[0]!=="value%"&&(t.style.width=R(n[0])),n[1]!==void 0&&(t.style.height=R(n[1])),e.radius!==void 0&&(t.style.borderRadius=R(e.radius)),e.fill!==void 0&&(t.style.background=ct(String(e.fill))),e.bleed!==void 0&&t.style.setProperty("--part-bleed",R(e.bleed)),(Array.isArray(e.anchor)?e.anchor:[e.anchor]).includes("value")&&(t.dataset.anchorValue="true")}function rt(t,e){e.gap!==void 0&&(t.style.gap=R(e.gap)),e.padding!==void 0&&(t.style.padding=R(e.padding)),e.size!==void 0&&(t.style.flex=mn(e.size)),e.min!==void 0&&(t.style.minWidth=R(e.min)),e.max!==void 0&&(t.style.maxWidth=R(e.max)),e.align!==void 0&&(t.style.alignItems=e.align==="end"?"flex-end":String(e.align)),(e.clip==="true"||e.clip===!0)&&(t.style.overflow="hidden"),e.scroll==="y"&&(t.style.overflowY="auto"),e.scroll==="x"&&(t.style.overflowX="auto")}function mn(t){return typeof t=="string"&&t.endsWith("fr")?`${Number(t.slice(0,-2))||1} 1 0`:t==="auto"||t==="content"?"0 0 auto":`0 0 ${R(t)}`}function R(t){return Array.isArray(t)?t.map(R).join(" "):typeof t=="number"?`${t}px`:typeof t=="string"&&/^-?\d+(\.\d+)?$/.test(t)?`${t}px`:String(t??"")}function ct(t){return{"color.accent":"var(--accent)","color.panelInset":"rgba(0, 0, 0, 0.34)","color.panel":"var(--panel)","color.text":"var(--text)"}[t]||t}function ot(t){return t.includes("Zen Kaku Gothic New")||t.includes("M PLUS 1")?t:t.includes("Montserrat")?`${t}, "Zen Kaku Gothic New", "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:t.includes("Ubuntu")?`${t}, "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:`${t}, "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`}function w(t,e){e.id&&(t.id=e.id),e.id&&(t.dataset.eveNodeId=e.id),e.kind&&(t.dataset.eveKind=e.kind)}function x(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function pn(t){return Array.isArray(t)?t:[]}function hn(t){return pn(t).map((e,n)=>Xt({kind:"list.item",props:x(e)}))}function g(t,e){return t==null?e:String(t)}function p(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e;if(typeof e=="number"&&Number.isFinite(e))return String(e)}return""}function St(t){return typeof t=="boolean"?t:typeof t=="number"?t!==0:typeof t=="string"?["1","true","yes","on"].includes(t.trim().toLowerCase()):!1}function B(t,e){const n=Number(t);return Number.isFinite(n)?Math.max(0,Math.floor(n)):e}function gn(t){const e=t.toLowerCase();return e.includes("sensor")?"S":e.includes("thermal")?"T":e.includes("fuel")?"F":e.includes("cargo")?"C":e.includes("weapon")?"W":t.trim().slice(0,1).toUpperCase()||"?"}function yn(t){const e=t.trim().split(/\s+/).filter(Boolean);return e.length&&e.slice(0,2).map(n=>n[0]?.toUpperCase()||"").join("")||"?"}function Bt(t){const e=Number(t);return Number.isFinite(e)?Math.max(0,Math.min(100,e)):0}function m(t,e="",n=""){const i=document.createElement(t);return e&&(i.className=e),n&&(i.textContent=n),i}const bn=document.querySelector("#surface"),dt=document.querySelector("#status"),Dt=document.querySelector("#receipt");let It=0,vn="player";async function Ht(){const t=await fetch("/api/surface");if(t.status===401){dt.textContent="This laboratory requires an unused invite link.";return}const e=await t.json();It=Number(e.version??0),ze(e,bn,{body:document.body,clientId:"ghostlight.browser",statusElement:dt})}async function qt(t){dt.textContent="The world is considering the command…";const e=await fetch("/api/command",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),n=await e.json();if(Dt.hidden=!1,Dt.textContent=JSON.stringify(n,null,2),!e.ok){dt.textContent=n.error??"The command was refused.";return}await Ht()}document.querySelector("#composer").addEventListener("submit",t=>{t.preventDefault();const e=document.querySelector("#attempt").value.trim();e&&qt({type:"assess",expected_revision:It,intent:{actor_id:vn,description:e,intended_effect:e}})});document.querySelector("#wait").addEventListener("click",()=>{qt({type:"wait",expected_revision:It,minutes:60})});Ht(); diff --git a/web/dist/assets/index-Dqaht4pv.js b/web/dist/assets/index-Dqaht4pv.js new file mode 100644 index 0000000..80e010f --- /dev/null +++ b/web/dist/assets/index-Dqaht4pv.js @@ -0,0 +1,153 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))i(o);new MutationObserver(o=>{for(const a of o)if(a.type==="childList")for(const s of a.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&i(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const a={};return o.integrity&&(a.integrity=o.integrity),o.referrerPolicy&&(a.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?a.credentials="include":o.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(o){if(o.ep)return;o.ep=!0;const a=n(o);fetch(o.href,a)}})();const G=new WeakMap,he=20;function nt(e,t,n,i,o,a,s,l){const f=at(e.canvas);if(!f)return!1;const c=f.gl;if(!ct(f,a,s))return G.set(e.canvas,null),!1;const r=it(t,n,i,o,l);c.bindFramebuffer(c.FRAMEBUFFER,f.framebuffer),c.viewport(0,0,a,s),c.disable(c.DEPTH_TEST),c.disable(c.CULL_FACE),c.enable(c.BLEND),c.blendFunc(c.ONE,c.ONE),c.clearColor(0,0,0,1),c.clear(c.COLOR_BUFFER_BIT),r.gravity.length>0&&(c.useProgram(f.splatProgram),c.uniform4f(c.getUniformLocation(f.splatProgram,"u_viewport"),o.minX,o.minY,o.maxX,o.maxY),c.uniform1f(c.getUniformLocation(f.splatProgram,"u_time"),_(t.simulationTimeSeconds,0)),c.bindBuffer(c.ARRAY_BUFFER,f.splatBuffer),c.bufferData(c.ARRAY_BUFFER,r.gravity,c.DYNAMIC_DRAW),Fe(c,f.splatProgram),c.drawArrays(c.TRIANGLES,0,r.gravity.length/he)),c.bindFramebuffer(c.FRAMEBUFFER,f.tintFramebuffer),c.clearColor(0,0,0,0),c.clear(c.COLOR_BUFFER_BIT),r.tint.length>0&&(c.useProgram(f.splatProgram),c.uniform4f(c.getUniformLocation(f.splatProgram,"u_viewport"),o.minX,o.minY,o.maxX,o.maxY),c.uniform1f(c.getUniformLocation(f.splatProgram,"u_time"),_(t.simulationTimeSeconds,0)),c.bindBuffer(c.ARRAY_BUFFER,f.splatBuffer),c.bufferData(c.ARRAY_BUFFER,r.tint,c.DYNAMIC_DRAW),Fe(c,f.splatProgram),c.drawArrays(c.TRIANGLES,0,r.tint.length/he)),c.disable(c.BLEND),c.bindFramebuffer(c.FRAMEBUFFER,null),c.viewport(0,0,a,s),c.useProgram(f.shadeProgram),c.activeTexture(c.TEXTURE0),c.bindTexture(c.TEXTURE_2D,f.fieldTexture),c.uniform1i(c.getUniformLocation(f.shadeProgram,"u_field"),0),c.activeTexture(c.TEXTURE1),c.bindTexture(c.TEXTURE_2D,f.tintTexture),c.uniform1i(c.getUniformLocation(f.shadeProgram,"u_tint"),1),c.uniform2f(c.getUniformLocation(f.shadeProgram,"u_resolution"),a,s),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_time"),_(n.simulationTimeSeconds,_(t.simulationTimeSeconds,0))),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineInterval"),_(t.lineInterval,_(t.scalarFieldLineInterval,_(t.depthRange,228.79605)/20))),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineOffset"),_(t.lineOffset,_(t.startDepth,2.310401))),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineWidth"),_(t.lineWidth,.3)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_lineFade"),_(t.lineFade,5)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_angleWidth"),_(t.angleWidth,.05)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_angleFade"),_(t.angleFade,1.15)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_dangerSteepness"),_(t.dangerSteepness,1.5)),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_scale"),_(t.isolineScale,2.6924083)),J(c,f.shadeProgram,"u_baseColor",V(t.scalarFieldBaseColor,[.002,.006,.012])),J(c,f.shadeProgram,"u_fieldGlowColor",V(t.scalarFieldGlowColor,[.018,.05,.075])),J(c,f.shadeProgram,"u_lineLowColor",V(t.scalarFieldLowLineColor,[0,.34,.52])),J(c,f.shadeProgram,"u_lineHighColor",V(t.scalarFieldHighLineColor,[1.45,.3,.05])),J(c,f.shadeProgram,"u_angleLowColor",V(t.scalarFieldLowAngleColor,[.06,.16,.24])),J(c,f.shadeProgram,"u_angleHighColor",V(t.scalarFieldHighAngleColor,[1.1,.24,.04])),c.uniform1f(c.getUniformLocation(f.shadeProgram,"u_tintScale"),_(t.vectorFieldTintScale,.45)),c.bindBuffer(c.ARRAY_BUFFER,f.quadBuffer);const d=c.getAttribLocation(f.shadeProgram,"a_position");return c.enableVertexAttribArray(d),c.vertexAttribPointer(d,2,c.FLOAT,!1,0,0),c.drawArrays(c.TRIANGLES,0,6),e.drawImage(f.canvas,0,0,a,s),!0}function it(e,t,n,i,o){const a=[],s=[];return rt(a,e,t,n),ot(s,e,o),{gravity:new Float32Array(a),tint:new Float32Array(s)}}function rt(e,t,n,i,o){const a=_(n.terrainRadius,_(t.terrainRadius,1200)),s=_(n.terrainDepth,_(t.terrainDepth,-8));s!==0&&se(e,0,0,Math.max(1,a*2),Math.max(1,a*2),-s,0,0,1,Math.max(1e-4,_(n.terrainDepthExponent,_(t.terrainDepthExponent,1.2))),0,1,0,0);for(const l of i)se(e,l.x,l.y,Math.max(1,l.radius),Math.max(1,l.radius),-l.depth,0,0,1,Math.max(1e-4,l.exponent),0,1,0,0),l.waveRadius>0&&l.waveDepth!==0&&se(e,l.x,l.y,l.waveRadius,l.waveRadius,-l.waveDepth,0,0,1,8,4,_(n.terrainWaveFrequency,_(t.terrainWaveFrequency,.6)),l.waveSpeed,0)}function ot(e,t,n){const i=st(n?.splats),o=Array.isArray(n?.layers)?n.layers:[],a=new Set,s=dt(t.vectorFieldLayer,t.tintFieldLayer,"fog.tint");o.forEach((E,H)=>{const ne=lt(E?.layerKey,"");_(E?.channel,-1)===4&&ne===s&&a.add(H)});const l=Math.max(0,ut(i.count,0));if(l<=0||a.size===0)return;const f=P(i.centerX),c=P(i.centerY),r=P(i.halfExtentX),d=P(i.halfExtentY),u=P(i.rotationCos),h=P(i.rotationSin),y=P(i.channel),b=P(i.falloff),v=P(i.valueR),C=P(i.valueG),A=P(i.valueB),N=P(i.valueA),j=P(i.sourceKind),W=P(i.frequencyX),Y=P(i.animationSpeed),q=P(i.sourceFlags),z=P(i.layerIndex);for(let E=0;ENumber(i));if(n.length>=3&&n.slice(0,3).every(Number.isFinite))return[n[0],n[1],n[2]]}if(typeof e=="string"){const n=e.split(/[,\s]+/).map(i=>Number(i)).filter(Number.isFinite);if(n.length>=3)return[n[0],n[1],n[2]]}return t}function J(e,t,n,i){e.uniform3f(e.getUniformLocation(t,n),i[0],i[1],i[2])}function P(e){return Array.isArray(e)?e.map(t=>_(t,0)):[]}function st(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function lt(e,t){return e==null?t:String(e)}function dt(...e){for(const t of e){if(typeof t=="string"&&t.trim())return t;if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function ut(e,t){const n=Number(e);return Number.isFinite(n)?Math.max(0,Math.floor(n)):t}const ft=`#version 300 es +in vec2 a_corner; +in vec2 a_center; +in vec2 a_half; +in vec2 a_rot; +in vec4 a_meta; +in vec4 a_source; +in vec4 a_value; +uniform vec4 u_viewport; +out vec2 v_local; +out vec4 v_meta; +out vec4 v_source; +out vec4 v_value; +void main() { + vec2 scaled = a_corner * a_half; + vec2 world = a_center + vec2( + scaled.x * a_rot.x - scaled.y * a_rot.y, + scaled.x * a_rot.y + scaled.y * a_rot.x + ); + vec2 clip = vec2( + ((world.x - u_viewport.x) / max(0.0001, u_viewport.z - u_viewport.x)) * 2.0 - 1.0, + ((world.y - u_viewport.y) / max(0.0001, u_viewport.w - u_viewport.y)) * 2.0 - 1.0 + ); + gl_Position = vec4(clip, 0.0, 1.0); + v_local = a_corner; + v_meta = a_meta; + v_source = a_source; + v_value = a_value; +}`,mt=`#version 300 es +precision highp float; +in vec2 v_local; +in vec4 v_meta; +in vec4 v_source; +in vec4 v_value; +uniform float u_time; +out vec4 outColor; +float hash21(vec2 p) { + p = fract(p * vec2(123.34, 456.21)); + p += dot(p, p + 45.32); + return fract(p.x * p.y); +} +float valueNoise(vec2 p) { + vec2 i = floor(p); + vec2 f = fract(p); + float a = hash21(i); + float b = hash21(i + vec2(1.0, 0.0)); + float c = hash21(i + vec2(0.0, 1.0)); + float d = hash21(i + vec2(1.0, 1.0)); + vec2 u = f * f * (3.0 - 2.0 * f); + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y) * 2.0 - 1.0; +} +float powerPulse(float x, float power) { + x = clamp(abs(x), 0.0, 1.0); + return pow((x + 1.0) * (1.0 - x), max(0.0001, power)); +} +void main() { + float d = length(v_local); + if (d > 1.0) discard; + float alpha = powerPulse(d, v_meta.x); + if (alpha <= 0.0001) discard; + float source = 1.0; + if (v_source.x > 0.5 && v_source.x < 2.5) { + float timeOffset = v_source.x > 1.5 ? u_time * v_source.z : 0.0; + source = valueNoise(v_local * v_source.y + timeOffset); + if (v_source.w != 0.0) source = abs(source); + } else if (v_source.x > 3.5) { + source = cos(pow(d * 2.0, 1.25) * v_source.y + u_time * v_source.z); + } + outColor = v_value * alpha * source; +}`,pt=`#version 300 es +in vec2 a_position; +out vec2 v_uv; +void main() { + v_uv = a_position * 0.5 + 0.5; + gl_Position = vec4(a_position, 0.0, 1.0); +}`,ht=`#version 300 es +precision highp float; +uniform sampler2D u_field; +uniform sampler2D u_tint; +uniform vec2 u_resolution; +uniform float u_time; +uniform float u_lineInterval; +uniform float u_lineOffset; +uniform float u_lineWidth; +uniform float u_lineFade; +uniform float u_angleWidth; +uniform float u_angleFade; +uniform float u_dangerSteepness; +uniform float u_scale; +uniform vec3 u_baseColor; +uniform vec3 u_fieldGlowColor; +uniform vec3 u_lineLowColor; +uniform vec3 u_lineHighColor; +uniform vec3 u_angleLowColor; +uniform vec3 u_angleHighColor; +uniform float u_tintScale; +in vec2 v_uv; +out vec4 outColor; +vec2 calcGrad(vec2 uv, float me) { + vec2 texel = 1.0 / max(vec2(1.0), u_resolution); + float n = -texture(u_field, vec2(uv.x, uv.y + texel.y)).r; + float e = -texture(u_field, vec2(uv.x + texel.x, uv.y)).r; + return vec2(e - me, n - me); +} +void main() { + float height = -texture(u_field, v_uv).r; + vec4 tint = texture(u_tint, v_uv); + vec2 plan = calcGrad(v_uv, height); + float slope = max(length(plan), 0.00001); + vec3 color = u_baseColor; + float fieldGlow = smoothstep(0.0, u_lineInterval * 7.0, abs(height)); + color += u_fieldGlowColor * fieldGlow; + color += tint.rgb * clamp(tint.a, 0.0, 1.0) * u_tintScale; + + float dangerBlend = smoothstep(0.0, u_dangerSteepness, pow(slope / max(0.0001, u_scale), 2.0)); + vec3 baseLine = mix(u_lineLowColor, u_lineHighColor, dangerBlend); + vec3 angleLine = mix(u_angleLowColor, u_angleHighColor, dangerBlend) * clamp(slope / max(0.0001, u_scale), 0.0, 1.0); + + vec3 lines = vec3(0.0); + float interval = max(0.0001, abs(u_lineInterval)); + float nearestLine = abs(fract((height + u_lineOffset) / interval) - 0.5) * interval; + float lineDistance = nearestLine / slope; + float line = 1.0 - smoothstep(u_lineWidth, u_lineWidth * u_lineFade, lineDistance); + lines += line * baseLine; + + float angle = atan(plan.y, plan.x) / 3.1415926536 + 1.0; + float nearestAngle = abs(fract(angle * 6.0) - 0.5) / 6.0; + float angleMask = smoothstep(interval * 0.25, interval * 1.5, abs(height)); + float angleLineAmount = 1.0 - smoothstep(u_angleWidth, u_angleWidth * u_angleFade, nearestAngle); + lines += angleLineAmount * angleMask * angleLine; + + color += clamp(lines, 0.0, 1.7); + outColor = vec4(color, 1.0); +}`,Ge=new Set(["gamecult.fields.splats.v1","gamecult.fields.gravity.v1","gamecult.fields.objects.v1"]),gt={pluginId:"fields.surface",capabilities:["field.surface2d","gravity.surface","field.scalar","field.vector","field.objects"],componentKinds:["field.surface2d","gravity.surface"],schemas:[...Ge],normalizeDocument:ge,renderComponent:yt};function yt(e,t,n,i,o,a){const s=document.createElement("canvas");s.className="cultui-gravity-surface",e.id&&(s.id=e.id),s.setAttribute("role","img"),s.setAttribute("aria-label",zt(t.label,"gravity surface")),s.style.display="block",s.style.width="100%",s.style.height="100%",s.style.pointerEvents="none",a.applyGeneratedLayout(s,n,i);let l=!1;const f={},c=()=>xt(s,t,f,a.resolveAssetUrl),r=()=>{!s.isConnected||l||(l=!0,requestAnimationFrame(()=>{l=!1,s.isConnected&&c()}))};s.addEventListener("cultui:asset-loaded",r);let d=0,u;const h=()=>{d&&window.clearInterval(d),u?.disconnect(),s.removeEventListener("cultui:asset-loaded",r)},y=()=>{if(!s.isConnected){h();return}bt(e,t,o,a.providerId,f).then(v=>{v&&s.isConnected&&r()}).catch(v=>{f.lastError=v instanceof Error?v.message:String(v)})};typeof ResizeObserver<"u"&&(u=new ResizeObserver(r),u.observe(s)),r();const b=Math.max(33,Math.min(1e3,Kt(t.stateRefreshMs,100)));return d=window.setInterval(y,b),queueMicrotask(y),window.setTimeout(r,300),window.setTimeout(r,1e3),s}async function bt(e,t,n,i,o){if(o.loading)return!1;const a=[me(e,t,"renderSplats","renderSplatsDocumentId","renderSplatsSchemaId"),me(e,t,"gravity","gravityDocumentId","gravitySchemaId"),me(e,t,"objects","objectsDocumentId","objectsSchemaId")].filter(s=>!!s?.documentId);if(a.length===0)return!1;o.loading=!0;try{let s=!1;for(const l of a){const f=await n.documentResolver?.(l,e);let c=ue(ge(f?.schemaId||l.schemaId,f?.document));if(Object.keys(c).length===0&&(c=ue(ge(l.schemaId,await vt(l,i||n.provider?.providerId)))),Object.keys(c).length===0)continue;const r=l.slotId==="renderSplats"?"renderSplats":l.slotId==="gravity"?"gravity":"objects",d=be(o[r]?.frameId,-1),u=be(c.frameId,d);o[r]=c,s||=u!==d}return o.lastLoadedAt=Date.now(),s}finally{o.loading=!1}}async function vt(e,t){if(typeof fetch!="function"||typeof window>"u"||!t)return;const n=new URLSearchParams({documentId:e.documentId});e.schemaId&&n.set("schemaId",e.schemaId),e.slotId&&n.set("slotId",e.slotId);const i=await fetch(`/eir/document/${encodeURIComponent(t)}?${n.toString()}`,{cache:"no-store",headers:{Accept:"application/json"}});if(i.ok)return ue(await i.json()).document}function me(e,t,n,i,o){const a=(e.embeddedDocuments||[]).find(l=>String(l?.slotId||"")===n),s=T(t[i],a?.documentId);if(s)return{documentId:s,schemaId:T(t[o],a?.schemaId),presentationKind:T(a?.presentationKind)||"data",slotId:n}}function ge(e,t){const n=Array.isArray(t)?t:void 0,i=n?n[0]:t?.schema,o=String(e||i||"");return!n||!Ge.has(o)?t:o==="gamecult.fields.splats.v1"?Pt(n):o==="gamecult.fields.gravity.v1"?Mt(n):Lt(n)}function xt(e,t,n,i){const o=e.getBoundingClientRect(),a=Math.max(1,Math.floor(o.width||e.clientWidth||1)),s=Math.max(1,Math.floor(o.height||e.clientHeight||1)),l=Math.max(1,Math.min(2,window.devicePixelRatio||1)),f=Math.max(1,Math.floor(a*l)),c=Math.max(1,Math.floor(s*l));(e.width!==f||e.height!==c)&&(e.width=f,e.height=c);const r=e.getContext("2d");if(!r)return;r.setTransform(l,0,0,l,0,0),r.clearRect(0,0,a,s);const d=kt(Ft(t),a,s),u=je(n?.gravity),h=Tt(n?.gravity)||Et(T(t.bodies,"")),y=Rt(n?.objects)||Ct(T(t.objects,""));nt(r,t,u,h,d,a,s,n?.renderSplats)||wt(r,t,a,s,"field.surface2d requires WebGL2 float render targets"),St(r,h,t,d,a,s,i),At(r,y,t,d,a,s,i)}function wt(e,t,n,i,o){e.save(),e.fillStyle=T(t.failureBackground,"rgba(0, 0, 0, 0.72)"),e.fillRect(0,0,n,i),e.font=T(t.failureFont,"700 13px Cascadia Mono, Consolas, monospace"),e.fillStyle=T(t.failureColor,"rgba(255, 184, 79, 0.95)"),e.fillText(o,16,28),e.restore()}function St(e,t,n,i,o,a,s){for(const l of t){const f=Xe(i,l.x,l.y,o,a),c=Math.max(18,Math.min(190,l.radius/Math.max(1,i.maxX-i.minX)*o*.32)),r=s(l.icon),d=l.kind.toLowerCase().includes("sun")?Math.max(I(n.sunIconMinPx,34),c*I(n.sunIconScale,.72)):Math.max(I(n.bodyIconMinPx,24),c*I(n.bodyIconScale,.48)),u=l.iconSize>0?l.iconSize:d;r&&It(e,r,f.x,f.y,u,.92),l.key&&Oe(e,n,l.key.replace(/^local\./,""),f.x+c*.44,f.y-c*.48,T(n.bodyLabelColor,"rgba(226, 244, 255, 0.82)"))}}const de=new Map;function It(e,t,n,i,o,a){let s=de.get(t);s||(s=new Image,s.decoding="async",s.onload=()=>requestAnimationFrame(()=>{e.canvas.dispatchEvent(new CustomEvent("cultui:asset-loaded"))}),s.src=t,de.set(t,s)),!(!s.complete||s.naturalWidth===0)&&(e.save(),e.globalAlpha=a,e.drawImage(s,n-o/2,i-o/2,o,o),e.restore())}function At(e,t,n,i,o,a,s){for(const l of t){const f=Xe(i,l.x,l.y,o,a);if(f.x<-40||f.x>o+40||f.y<-40||f.y>a+40)continue;const c=l.kind.toLowerCase().includes("station")?I(n.stationIconSizePx,34):l.controlled?I(n.shipIconSizePx,22):I(n.remoteShipIconSizePx,18),r=_t(n,l.faction,l.controlled,l.visibility),d=s(l.icon);e.save(),e.globalAlpha=Math.max(.25,Math.min(1,l.visibility)),e.translate(f.x,f.y);const u=Math.atan2(l.directionY,l.directionX)+Math.PI/2;if(l.kind.toLowerCase().includes("ship")&&e.rotate(u),d){const h=de.get(d);if(h)h.complete&&h.naturalWidth>0&&e.drawImage(h,-c/2,-c/2,c,c);else{const y=new Image;y.decoding="async",y.onload=()=>e.canvas.dispatchEvent(new CustomEvent("cultui:asset-loaded")),y.src=d,de.set(d,y)}}e.restore(),Oe(e,n,l.label,f.x+c*.55,f.y-c*.45,r)}}function Oe(e,t,n,i,o,a){n&&(e.save(),e.font=T(t.objectLabelFont,"700 12px Ubuntu, system-ui, sans-serif"),e.textBaseline="middle",e.lineWidth=I(t.objectLabelStrokeWidth,3),e.strokeStyle=T(t.objectLabelStroke,"rgba(0, 0, 0, 0.72)"),e.fillStyle=a,e.strokeText(n,i,o),e.fillText(n,i,o),e.restore())}function _t(e,t,n,i){const o=Math.max(.25,Math.min(1,i));if(n)return ie(T(e.objectControlledColor,"rgba(122, 240, 255, {alpha})"),o);const a=t.toLowerCase();return a.includes("raider")?ie(T(e.objectRaiderColor,"rgba(255, 143, 74, {alpha})"),o):a.includes("neutral")?ie(T(e.objectNeutralColor,"rgba(232, 232, 224, {alpha})"),o):ie(T(e.objectDefaultColor,"rgba(214, 244, 255, {alpha})"),o)}function ie(e,t){return e.replaceAll("{alpha}",String(t))}function Et(e){return e.split(";").map(t=>t.trim()).filter(Boolean).map(t=>{const n=t.split("|");return{key:n[0]??"",kind:n[1]??"",x:Number(n[2])||0,y:Number(n[3])||0,radius:Math.max(1,Number(n[4])||1),depth:Number(n[5])||0,exponent:Number(n[6])||1,waveRadius:Number(n[7])||0,waveDepth:Number(n[8])||0,waveSpeed:Number(n[9])||0,icon:n[10]??"",iconSize:Number(n[12])||0,tint:n[11]??""}})}function Ct(e){return e.split(";").map(t=>t.trim()).filter(Boolean).map(t=>{const n=t.split("|");return{key:n[0]??"",kind:n[1]??"",label:n[2]??"",x:Number(n[3])||0,y:Number(n[4])||0,directionX:Number(n[5])||0,directionY:Number(n[6])||1,faction:n[7]??"",controlled:n[8]==="1"||n[8]==="true",visibility:Number(n[9])||1,icon:n[10]??""}})}function Tt(e){const t=Array.isArray(e?.gravityInfluences)?e.gravityInfluences:[],n=Array.isArray(e?.bodies)?e.bodies:[];if(t.length===0&&n.length===0)return;const i=new Map;for(const o of n){const a=T(o.bodyKey,o.name,"");a&&i.set(a,o)}return(t.length>0?t:n).map(o=>{const a=T(o.bodyKey,o.name,"body"),s=i.get(a),l=T(o.kind,"Body");return{key:a,kind:l,x:I(o.x,0),y:I(o.y,0),radius:Math.max(1,I(o.radius,80)),depth:I(o.gravityDepth,0),exponent:I(o.gravityDepthExponent,1),waveRadius:I(o.waveRadius,0),waveDepth:I(o.waveDepth,0),waveSpeed:I(o.waveSpeed,0),icon:ye(o.iconAsset)||ye(s?.iconAsset),iconSize:I(s?.iconSize,I(o.iconSize,0)),tint:""}})}function Rt(e){const t=Array.isArray(e?.objects)?e.objects:[];if(t.length!==0)return t.map(n=>{const i=T(n.kind,"object");return{key:T(n.entityKey,String(n.entityIndex??""),"object"),kind:i,label:T(n.displayName,n.entityKey,"object"),x:I(n.x,0),y:I(n.y,0),directionX:I(n.directionX,1),directionY:I(n.directionY,0),faction:T(n.factionKey,""),controlled:Gt(n.controlled),visibility:I(n.visibility,1),icon:ye(n.iconAsset)}})}function ye(e){const t=je(e);return T(t.uri,"")}function Ft(e){const t=Math.max(1,I(e.viewRadius,Math.max(1200,I(e.terrainRadius,1200))));return{minX:I(e.minX,-t),minY:I(e.minY,-t),maxX:I(e.maxX,t),maxY:I(e.maxY,t)}}function kt(e,t,n){const i=Math.max(1e-4,e.maxX-e.minX),o=Math.max(1e-4,e.maxY-e.minY),a=Math.max(1e-4,t/Math.max(1,n)),s=i/o,l=(e.minX+e.maxX)*.5,f=(e.minY+e.maxY)*.5;if(a>s){const r=o*a;return{minX:l-r*.5,maxX:l+r*.5,minY:e.minY,maxY:e.maxY}}const c=i/a;return{minX:e.minX,maxX:e.maxX,minY:f-c*.5,maxY:f+c*.5}}function Xe(e,t,n,i,o){return{x:(t-e.minX)/Math.max(1,e.maxX-e.minX)*i,y:(n-e.minY)/Math.max(1,e.maxY-e.minY)*o}}function Pt(e){const t=L(e[9]);return{schema:e[0],frameId:e[1],publishedAtUtc:e[2],simulationTimeSeconds:e[3],runId:e[4],zoneIndex:e[5],zoneName:e[6],viewport:we(e[7]),layers:L(e[8]).map(Nt),splats:{count:t[0]??0,centerX:t[1]||[],centerY:t[2]||[],halfExtentX:t[3]||[],halfExtentY:t[4]||[],rotationCos:t[5]||[],rotationSin:t[6]||[],channel:t[7]||[],falloff:t[8]||[],valueR:t[9]||[],valueG:t[10]||[],valueB:t[11]||[],valueA:t[12]||[],sourceKey:t[13]||[],layerIndex:t[14]||[],sourceKind:t[15]||[],frequencyX:t[16]||[],frequencyY:t[17]||[],phaseX:t[18]||[],phaseY:t[19]||[],animationSpeed:t[20]||[],sourceFlags:t[21]||[]}}}function Mt(e){return{schema:e[0],frameId:e[1],publishedAtUtc:e[2],simulationTimeSeconds:e[3],runId:e[4],zoneIndex:e[5],zoneName:e[6],viewport:we(e[7]),gravityInfluences:L(e[8]).map(Bt),bodies:L(e[9]).map(Dt),terrainRadius:e[10],terrainDepth:e[11],terrainDepthExponent:e[12],terrainWaveFrequency:e[13]}}function Lt(e){return{schema:e[0],frameId:e[1],publishedAtUtc:e[2],simulationTimeSeconds:e[3],runId:e[4],zoneIndex:e[5],zoneName:e[6],currentEntityKey:e[7],viewport:we(e[8]),controlledEntityIndices:L(e[9]),objects:L(e[10]).map($t)}}function we(e){const t=L(e);return t.length?{minX:t[0],minY:t[1],maxX:t[2],maxY:t[3]}:e}function Nt(e){const t=L(e);return t.length?{layerKey:t[0],displayName:t[1],channel:t[2],blendMode:t[3],graphicsFormat:t[4],clearBeforeDraw:t[5],clearR:t[6],clearG:t[7],clearB:t[8],clearA:t[9]}:e}function Bt(e){const t=L(e);return t.length?{bodyKey:t[0],orbitKey:t[1],kind:t[2],x:t[3],y:t[4],radius:t[5],gravityDepth:t[6],gravityDepthExponent:t[7],waveRadius:t[8],waveDepth:t[9],waveSpeed:t[10]}:e}function Dt(e){const t=L(e);return t.length?{bodyKey:t[0],orbitKey:t[1],name:t[2],kind:t[3],x:t[4],y:t[5],radius:t[6],isAsteroidBelt:t[7],body:t[8],iconAsset:Se(t[9])}:e}function $t(e){const t=L(e);return t.length?{entityIndex:t[0],entityKey:t[1],displayName:t[2],kind:t[3],factionKey:t[4],x:t[5],y:t[6],z:t[7],directionX:t[8],directionY:t[9],velocityX:t[10],velocityY:t[11],controlled:t[12],targetEntityIndex:t[13],isActive:t[14],visibility:t[15],status:Ut(t[16]),inventory:L(t[17]).map(Wt),iconAsset:Se(t[18])}:e}function Ut(e){const t=L(e);return t.length?{hull:t[0],shield:t[1],heat:t[2]}:e||{}}function Wt(e){const t=L(e);return t.length?{source:t[0],itemKey:t[1],quantity:t[2],quality:t[3],durability:t[4],enabled:t[5],sourceIndex:t[6],x:t[7],y:t[8],iconAsset:Se(t[9])}:e}function Se(e){const t=L(e);return t.length?{assetKey:t[0],kind:t[1],uri:t[2],transport:t[3],contentHash:t[4],mimeType:t[5],metadata:t[6]||{}}:e||{}}function L(e){return Array.isArray(e)?e:[]}function ue(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function T(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function zt(e,t){return typeof e=="string"&&e?e:t}function Kt(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?Math.floor(n):t}function be(e,t){const n=Number(e);return Number.isFinite(n)?n:t}const je=ue,I=be;function Gt(e){return typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"&&["1","true","yes","on"].includes(e.trim().toLowerCase())}const Ot=[gt],Xt={"--bg":"#020909","--bg-top":"#020909","--bg-mid":"#020909","--bg-bottom":"#020909","--shell-top":"#010707","--shell-bottom":"#010707","--panel":"#071918","--panel-2":"#0a2423","--line":"rgba(103, 240, 228, 0.28)","--line-deep":"rgba(103, 240, 228, 0.18)","--text":"#e7f1f1","--text-bright":"#e7f1f1","--quiet":"#8ba5a3","--accent":"#ffb84f","--accent-strong":"#ffb84f","--corner-accent":"#ffb84f","--cyan":"#8efcff","--shadow":"rgba(0, 0, 0, 0.35)","--pixel-grid":"rgba(142, 252, 255, 0.04)","--border-width":"1px","--border-bottom-width":"1px","--corner-accent-size":"0","--font-body":'"M PLUS 1", "Ubuntu Sans", Ubuntu, "Noto Sans JP", system-ui, sans-serif',"--font-title":'"Montserrat", "Zen Kaku Gothic New", "M PLUS 1", "Ubuntu Sans", system-ui, sans-serif',"--font-mono":'"Ubuntu Sans Mono", "M PLUS 1 Code", "Cascadia Mono", Consolas, monospace'};let re,Ye=Ie(void 0),ee,U={};const Me=new WeakMap;function jt(e,t,n={}){if(Me.get(t)?.dispose(),ee=e,U=n,Ye=Ie(e.surface?.styles),globalThis.__eveCurrentMesh=e.mesh,un(e.surface?.styles,n.body??document.body),n.body&&(n.body.dataset.provider=e.providerId||n.provider?.providerId||""),n.statusElement&&(n.statusElement.textContent=`${e.title||e.surface?.title||"surface"}${n.source?` (${n.source})`:""}`),e.surface?.root){if(t.replaceChildren(k(e.surface.root,n)),n.stateBindingResolver){const i=new qt(e,t,n);Me.set(t,i),i.start()}}else t.replaceChildren(X("No surface root"));return t}function Yt(e,t,n){const i=t.targetProp.split(".").filter(Boolean);if(i.length===0)throw new Error("Eve state binding targetProp must not be empty.");e.props||={};let o=e.props;for(const a of i.slice(0,-1)){const s=o[a];(!s||typeof s!="object"||Array.isArray(s))&&(o[a]={}),o=o[a]}o[i[i.length-1]]=n}class qt{surface;host;options;disposed=!1;unsubscribers=[];constructor(t,n,i){this.surface=t,this.host=n,this.options=i}async start(){const t=this.options.stateBindingResolver,n=this.surface.surface?.root;if(!(!t||!n))for(const i of qe(n))for(const o of i.stateBindings||[]){if(this.disposed)return;const a=await t(o,i);if(!a||this.disposed)continue;const s=l=>{this.disposed||(Yt(i,o,l),this.renderCanonicalProjection())};if(s(await a.latest()),this.disposed)return;this.unsubscribers.push(a.watch(s))}}dispose(){this.disposed=!0;for(const t of this.unsubscribers.splice(0))t()}renderCanonicalProjection(){const t=this.surface.surface?.root;t&&this.host.replaceChildren(k(t,this.options))}}function*qe(e){yield e;for(const t of e.children||[])yield*qe(t)}function k(e,t=U){const n=e.kind||"panel",i=x(e.props),o=x(e.layout),a=x(e.style),s=e.children||[],l=e.embeddedDocuments||[];if(n==="surface"||n==="cockpit"||n==="dashboard"){const r=m("section","cultui-surface-root eve-surface");w(r,e),typeof o.direction=="string"?r.dataset.direction=o.direction:typeof i.layout=="object"&&i.layout&&typeof i.layout.direction=="string"&&(r.dataset.direction=String(i.layout.direction)),n!=="surface"&&(r.dataset.surfaceKind=n),S(r,o,a);for(const d of s)r.append(k(d,t));return r}if(n==="column"||n==="row"||n==="form"||n==="rail"){const r=m("div",`cultui-partition eve-${n}`);w(r,e),r.dataset.direction=n==="row"||n==="rail"?"horizontal":"vertical",n==="rail"&&(r.dataset.overflow="x"),ae(r,{...o,...i}),S(r,o,a);for(const d of s)r.append(k(d,t));return r}if(n==="grid"){const r=m("section","cultui-grid"),d=B(i.columns,0);d>0?r.style.gridTemplateColumns=`repeat(${d}, minmax(0, 1fr))`:typeof i.columns=="string"&&(r.style.gridTemplateColumns=i.columns);const u=B(i.rows,0);u>0&&(r.style.gridTemplateRows=`repeat(${u}, minmax(0, auto))`),S(r,o,a);for(const h of s)r.append(k(h,t));return r}if(n==="partition"){const r=m("section",`cultui-partition split-${g(i.split,"none")}`);w(r,e),ae(r,i),S(r,o,a),r.style.minWidth="0",g(i.split,"none")==="x"&&!p(i.flexWrap,o.flexWrap,"")&&(r.style.flexWrap="wrap"),typeof i.role=="string"&&(r.dataset.role=i.role);for(const d of s)r.append(k(d,t));return r}if(n==="input.binding-map")return cn(e,i,t);if(n==="inventory.drag_session")return tn(e,i,o,a);if(n==="inventory.grid")return nn(e,i,o,a,t);if(n==="inventory.item")return rn(e,i,o,a);const f=(t.pluginAdapters||Ot).find(r=>r.componentKinds.includes(n));if(f?.renderComponent)return f.renderComponent(e,i,o,a,t,{applyGeneratedLayout:S,providerId:ee?.providerId||t.provider?.providerId,resolveAssetUrl:Z});if(n==="world.scene3d"||n==="world.scene2d")return Vt(e,i,o,a,t);if(n==="image.background"){const r=m("div","cultui-background"),d=Z(p(i.src,i.assetUri,i.assetRef,""));return d&&(r.style.backgroundImage=`url("${d}")`),r.setAttribute("aria-label",g(i.label,"background")),r}if(n==="image.sprite"){const r=m("figure",`cultui-sprite ${g(i.slot,"center")}`);w(r,e);const d=Z(p(i.src,i.assetUri,i.assetRef,""));if(d){const u=m("img");u.src=d,u.alt=g(i.alt,g(i.actor,g(i.label,""))),r.append(u)}return r}if(n==="avatar"){const r=m("figure","cultui-avatar-card");w(r,e);const d=Z(p(i.src,i.assetUri,i.assetRef,""));if(d){const b=m("img");b.src=d,b.alt=g(i.alt,g(i.text,g(i.label,""))),r.append(b)}else r.append(m("div","cultui-avatar-fallback",In(p(i.text,i.label,i.actor,"?"))));const u=p(i.text,i.label,i.actor,"");u&&r.append(m("figcaption","cultui-avatar-name",u));const h=p(i.status,"");h&&r.append(m("div","cultui-avatar-status",h));const y=p(i.detail,"");return y&&r.append(m("div","cultui-avatar-detail",y)),r}if(n==="pane"||n==="panel"){const r=m("section","pane cultui-pane");w(r,e);const d=g(i.span,"");d&&(r.dataset.span=d);const u=g(i.density,"");u&&(r.dataset.density=u);const h=g(i.title,e.text||"");h&&r.append(m("h2","",h));for(const y of s)r.append(k(y,t));return r}if(n==="list"||n.endsWith(".roster")){const r=m("section","cultui-list");w(r,e),r.dataset.componentKind=n;const d=g(i.title,"");d&&r.append(m("h3","cultui-list-title",d));for(const[u,h]of wn(i.items).entries())r.append(k({id:`${e.id||"list"}-item-${u}`,kind:"list.item",props:{...h}},t));for(const u of s)r.append(k(u,t));return r}if(n==="list.item"||n.endsWith(".item")){const r=He(e),d=m("article","cultui-list-item");w(d,e),d.dataset.componentKind=n;const u=m("div","cultui-list-item-heading");if(u.append(m("strong","cultui-list-item-label",r.label)),r.status&&u.append(m("span","cultui-list-item-status",r.status)),d.append(u),r.detail&&d.append(m("div","cultui-list-item-detail",r.detail)),r.badges.length){const h=m("div","cultui-list-item-badges");for(const y of r.badges)h.append(m("span","cultui-list-item-badge",y));d.append(h)}for(const h of s)d.append(k(h,t));return d}if(n==="bar"){const r=m("div","cultui-meter");w(r,e);const d=g(i.label,""),u=g(i.value,"");if(d||u){const b=m("div","cultui-meter-head");b.append(m("span","",d)),b.append(m("strong","",u)),r.append(b)}const h=m("div","cultui-meter-track"),y=m("span","cultui-meter-fill");return y.style.width=`${Ue(i.percent)}%`,h.append(y),r.append(h),r}if(n==="card"){const r=De(i,e),d=r?m("button","card cultui-card cultui-card-button"):m("article","card cultui-card");w(d,e),S(d,o,a),d instanceof HTMLButtonElement&&(d.type="button");const u=g(i.title,e.text||"");u&&d.append(m("div","card-title",u));for(const h of s)d.append(k(h,t));return r&&$e(d,e,r,i,t),d}if(n==="control.button"){const r=m("button","cultui-button eve-control-button",g(i.label,"Action"));return w(r,e),r.type="button",S(r,o,a),$e(r,e,De(i,e),i,t),r}if(n==="control.popup"){const r=m("button","cultui-button eve-control-popup",g(i.label,"Open"));return w(r,e),r.type="button",S(r,o,a),r.addEventListener("click",d=>{sn(e,t,r,d.clientX,d.clientY)}),r}if(n==="text.dialogue"||n==="text"||n==="text.title"||n==="text.subtitle"||n==="label"){const r=m("div",gn(n,i),g(i.value,g(i.text,e.text||"")));return w(r,e),ae(r,i),S(r,o,a),r}if(n==="metric"){const r=m("dl","metric cultui-reactive-metric eve-metric");return w(r,e),S(r,o,a),r.append(m("dt","",g(i.label,"Metric"))),r.append(m("dd","metric-value",g(i.value,""))),r}if(n==="progress"){const r=m("div","cultui-meter eve-progress");w(r,e),S(r,o,a);const d=g(i.label,""),u=g(i.value,""),h=Number(i.min??0),y=Number(i.max??1),b=Number(i.value??0),v=Number.isFinite(b)&&Number.isFinite(h)&&Number.isFinite(y)&&y!==h?(b-h)/(y-h)*100:Ue(i.percent);if(d||u){const N=m("div","cultui-meter-head");N.append(m("span","",d)),N.append(m("strong","",u)),r.append(N)}const C=m("div","cultui-meter-track"),A=m("span","cultui-meter-fill");return A.style.width=`${Math.max(0,Math.min(100,v))}%`,C.append(A),r.append(C),r}if(n==="modal"){const r=m("section","cultui-modal-surface");w(r,e),S(r,o,a);const d=g(i.title,"");d&&r.append(m("h2","cultui-modal-surface-title",d));for(const u of s)r.append(k(u,t));return r}if(n==="options"){const r=m("section","cultui-options");w(r,e),S(r,o,a);const d=g(i.label,"");d&&r.append(m("h3","cultui-list-title",d));for(const u of s)r.append(k(u,t));return s.length===0&&r.append(X("waiting for options")),r}if(n==="image.preview"){const r=m("figure","cultui-image-preview");w(r,e);const d=m("div","cultui-image-frame"),u=Z(p(i.src,i.assetUri,i.assetRef,""));if(u){const h=m("img");h.src=u,h.alt=g(i.label,""),h.style.imageRendering=g(i.imageRendering,"auto"),i.zoom!==void 0&&(h.style.transform=`scale(${i.zoom})`,h.style.transformOrigin=g(i.crop,"50% 50%")),d.append(h)}else d.append(m("span","",g(i.label,"image")));return r.append(d),i.label&&r.append(m("figcaption","",String(i.label))),r}if(n==="canvas.preview"||n==="canvas.editor"){const r=m("div",`cultui-canvas-placeholder ${n==="canvas.editor"?"editor":"preview"}`);return w(r,e),r.append(m("div","viz-label",g(i.label,"Canvas"))),r.append(m("div","cultui-canvas-grid",i.state==="empty"?"waiting for pixels":g(i.state,""))),r}if(n==="surface.slot"){const r=m("section","cultui-embedded-slot");w(r,e),S(r,o,a),r.dataset.slotId=g(i.slotId,g(l[0]?.slotId,"")),r.dataset.documentId=g(i.documentId,g(l[0]?.documentId,"")),r.dataset.schemaId=g(i.schemaId,g(l[0]?.schemaId,"")),r.dataset.presentationKind=g(i.presentationKind,g(l[0]?.presentationKind,""));const d=l.map(h=>x(h.surface)).find(h=>x(h.root).kind||h.root),u=i.modal===!0||r.dataset.presentationKind.includes("modal");if((d||r.dataset.documentId)&&u){const h=m("button","cultui-button cultui-modal-trigger",g(i.label,r.dataset.slotId||"Configure"));h.type="button",h.addEventListener("click",()=>Ze(ve(e,t),t)),r.append(h)}else if(d||r.dataset.documentId){const h=m("div","cultui-embedded-slot-body");h.append(m("div","detail","materializing surface")),r.append(h),ve(e,t).then(y=>{h.replaceChildren(y?.root?k(y.root,t):X("Embedded surface unavailable"))}).catch(y=>{h.replaceChildren(X(`Embedded surface failed: ${y instanceof Error?y.message:String(y)}`))})}else r.append(m("div","detail",r.dataset.presentationKind||r.dataset.slotId||"embedded surface"));return r}if(n==="control.slider")return mn(i,s,t);if(n==="control.toggle"){const r=m("label","toggle-row cultui-toggle");return w(r,e),r.append(m("span","field-control",i.value?"on":"off")),r.append(m("span","toggle-copy",g(i.label,"Toggle"))),r}if(n==="input.number"||n==="input.select"||n==="control.range"||n==="control.input.text"||n==="control.select"){const r=m("label","field cultui-field");return w(r,e),ae(r,i),S(r,o,a),r.append(m("span","field-label",g(i.label,""))),r.append(m("span","field-control cultui-field-value",i.value===void 0?"":String(i.value))),r}if(n==="color.swatch"){const r=m("div","paint-swatch cultui-swatch");return w(r,e),r.style.background=g(i.value,g(i.color,"currentColor")),r.title=g(i.label,"Color"),r}const c=m("section","pane");w(c,e),c.append(m("h2","",n));for(const r of s)c.append(k(r,t));return c}function He(e){const t=x(e.props);return{label:p(t.label,t.title,t.displayName,e.text,e.kind,"item"),status:p(t.status,t.state,""),detail:p(t.detail,t.phase,t.repoName,""),badges:Array.isArray(t.badges)?t.badges.map(n=>String(n).trim()).filter(Boolean):p(t.badges,"").split(",").map(n=>n.trim()).filter(Boolean)}}function S(e,t,n={}){const i=p(t.display,"");i&&(e.style.display=i);const o=p(t.direction,"");o&&(e.style.flexDirection=o==="horizontal"?"row":o==="vertical"?"column":o);const a=p(t.flexWrap,"");a&&(e.style.flexWrap=a);const s=p(t.gridTemplateColumns,"");s&&(e.style.gridTemplateColumns=s);const l=p(t.gridTemplateRows,"");l&&(e.style.gridTemplateRows=l);const f=p(t.gridTemplateAreas,"");f&&(e.style.gridTemplateAreas=f);const c=p(t.gridArea,"");c&&(e.style.gridArea=c);const r=p(t.placeItems,"");r&&(e.style.placeItems=r),M(e,"gap",p(t.gap,"")),M(e,"padding",p(t.padding,"")),M(e,"margin",p(t.margin,"")),M(e,"top",p(t.top,"")),M(e,"right",p(t.right,"")),M(e,"bottom",p(t.bottom,"")),M(e,"left",p(t.left,"")),M(e,"width",p(t.width,"")),M(e,"minWidth",p(t.minWidth,"")),M(e,"maxWidth",p(t.maxWidth,"")),M(e,"height",p(t.height,"")),M(e,"minHeight",p(t.minHeight,"")),M(e,"maxHeight",p(t.maxHeight,""));const d=p(t.alignItems,"");d&&(e.style.alignItems=d);const u=p(t.justifyContent,"");u&&(e.style.justifyContent=u);const h=p(t.alignSelf,"");h&&(e.style.alignSelf=h);const y=p(t.overflow,"");y&&(e.style.overflow=y);const b=p(t.overflowX,"");b&&(e.style.overflowX=b);const v=p(t.overflowY,"");v&&(e.style.overflowY=v);const C=p(t.position,"");C&&(e.style.position=C);const A=p(t.cursor,"");A&&(e.style.cursor=A);const N=p(n.background,"");N&&(e.style.background=le(N));const j=p(n.color,"");j&&(e.style.color=le(j)),M(e,"borderWidth",p(n.borderWidth,""));const W=p(n.borderColor,"");W&&(e.style.borderColor=le(W));const Y=p(n.borderStyle,"");Y&&(e.style.borderStyle=Y),M(e,"borderRadius",p(n.borderRadius,""));const q=p(n.boxShadow,"");q&&(e.style.boxShadow=q);const z=p(n.font,"");z&&(e.style.font=z),M(e,"fontSize",p(n.fontSize,""));const E=p(n.fontWeight,"");E&&(e.style.fontWeight=E);const H=p(n.textTransform,"");H&&(e.style.textTransform=H);const ne=p(n.textAlign,"");ne&&(e.style.textAlign=ne);const fe=p(n.whiteSpace,"");fe&&(e.style.whiteSpace=fe);const Ce=p(n.overflow,"");Ce&&(e.style.overflow=Ce);const Te=p(n.textOverflow,"");Te&&(e.style.textOverflow=Te),M(e,"lineHeight",p(n.lineHeight,""))}function M(e,t,n){n&&(e.style[t]=R(n))}function F(e,t){const n={};for(const[i,o]of Object.entries(e))i.startsWith(t)&&(n[i.slice(t.length)]=o);return n}function Ht(e){const t=(e.children||[]).filter(u=>u.kind==="world.entity3d"),n=t.map(u=>en(x(u.props).position,[0,0,0])),i=n.map(u=>u[0]),o=n.map(u=>u[2]),a=Math.min(...i,-1),s=Math.max(...i,1),l=Math.min(...o,-1),f=Math.max(...o,1),c=Math.max(1,s-a),r=Math.max(1,f-l),d=6;return t.map((u,h)=>{const y=x(u.props);return{entityId:p(y.entityId,u.id),faction:g(y.faction,"neutral"),kind:g(y.entityKind,"entity"),label:p(y.label,y.entityId,u.id,"Entity"),controlled:Ae(y.controllable),xPercent:d+(n[h][0]-a)/c*(100-d*2),yPercent:d+(1-(n[h][2]-l)/r)*(100-d*2),source:u}})}function Vt(e,t,n,i,o){const a=m("section","cultui-world-scene");w(a,e),S(a,n,i),a.tabIndex=0,a.setAttribute("aria-label",g(t.label,"Interactive world"));const s=Ht(e),l=s.find(r=>r.controlled),f=m("div","cultui-world-heading");f.append(m("strong","",g(t.label,"World"))),f.append(m("span","",`${s.length} entities`)),a.append(f);const c=m("div","cultui-world-plane");for(const r of s){const d=m("button",`cultui-world-entity faction-${Le(r.faction)} kind-${Le(r.kind)}`);d.type="button",d.style.left=`${r.xPercent}%`,d.style.top=`${r.yPercent}%`,d.dataset.entityId=r.entityId,d.dataset.controlled=r.controlled?"true":"false",d.title=r.label,d.setAttribute("aria-label",`${r.label}, ${r.kind}, ${r.faction}`),d.append(m("span","cultui-world-entity-glyph",Qt(r.kind))),d.append(m("span","cultui-world-entity-label",r.label));const u=x(r.source.props),h=p(u.targetCommand,t.targetCommand,u.focusCommand,t.focusCommand);h&&d.addEventListener("click",()=>pe(h,{actorEntityId:l?.entityId||p(t.playerEntityId),entityId:r.entityId,targetEntityId:r.entityId,targetEntityKey:r.entityId},r.source,o)),c.append(d)}return a.append(c),a.addEventListener("keydown",r=>{const d=Zt(r.key);if(d){r.preventDefault();const h=p(t.movementCommand,x(l?.source.props).moveCommand);h&&pe(h,{actorEntityId:l?.entityId||p(t.playerEntityId),actorEntityKey:l?.entityId||p(t.playerEntityId),directionX:d[0],directionY:d[1],scalar:1},e,o);return}const u=r.key===" "?p(t.actionCommand,x(l?.source.props).actionCommand):r.key.toLowerCase()==="f"?p(t.focusCommand,x(l?.source.props).focusCommand):"";u&&(r.preventDefault(),pe(u,{actionId:r.key===" "?"0":"focus",actorEntityId:l?.entityId||p(t.playerEntityId),actorEntityKey:l?.entityId||p(t.playerEntityId)},e,o))}),a}function pe(e,t,n,i){i.commandSink?.(Jt(e,t,i),n)}function Jt(e,t,n=U){return te(e,{action:t},n)}function Zt(e){switch(e.toLowerCase()){case"w":case"arrowup":return[0,1];case"s":case"arrowdown":return[0,-1];case"a":case"arrowleft":return[-1,0];case"d":case"arrowright":return[1,0];default:return}}function Qt(e){return e.includes("station")?"S":e.includes("projectile")?".":e.includes("ship")?"^":"+"}function Le(e){return e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function O(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function en(e,t){if(Array.isArray(e)){const n=e.map(i=>Number(i));if(n.length>=3&&n.slice(0,3).every(Number.isFinite))return[n[0],n[1],n[2]]}if(typeof e=="string"){const n=e.split(/[,\s]+/).map(i=>Number(i)).filter(Number.isFinite);if(n.length>=3)return[n[0],n[1],n[2]]}return t}function tn(e,t,n,i){const o=Ae(t.active),a=m("section","cultui-inventory-drag");w(a,e),S(a,n,i),a.dataset.active=o?"true":"false";const s=m("div","cultui-inventory-section-label","Drag");if(S(s,F(n,"sectionLabel."),F(i,"sectionLabel.")),a.append(s),!o){const d=m("div","cultui-inventory-empty","None");return S(d,F(n,"empty."),F(i,"empty.")),a.append(d),a}const l=p(t.itemKey,t.item,"item"),f=m("div","cultui-inventory-drag-chip",l);S(f,F(n,"dragChip."),F(i,"dragChip.")),a.append(f);const c=[t.originOffsetX,t.originOffsetY].map(d=>Number(d)).map(d=>Number.isFinite(d)?d:0),r=m("div","cultui-inventory-meta",`origin ${c[0]}, ${c[1]}`);return S(r,F(n,"meta."),F(i,"meta.")),a.append(r),a}function nn(e,t,n,i,o){const a=m("section","cultui-inventory-grid");w(a,e),S(a,n,i);const s=B(p(t.columns,t.gridColumns,t.widthCells,""),0),l=s>0?s:6,f=B(t.rows,0),c=f>0?f:Math.max(3,Math.ceil(Math.max((e.children||[]).length,1)/l));a.style.setProperty("--inventory-columns",String(l)),a.style.setProperty("--inventory-rows",String(c)),a.dataset.cellSpriteMode=g(t.cellSpriteMode,"");const r=p(t.title,t.label,"Inventory"),d=m("div","cultui-inventory-section-label",r);S(d,F(n,"sectionLabel."),F(i,"sectionLabel.")),a.append(d);const u=m("div","cultui-inventory-board");u.style.display="grid",u.style.gridTemplateColumns=`repeat(${l}, ${R(p(t.cellSize,"72"))})`,u.style.gridTemplateRows=`repeat(${c}, ${R(p(t.cellSize,"72"))})`,u.style.gap=R(p(t.cellGap,"4")),u.style.overflow=p(t.boardOverflow,"auto"),u.style.padding=R(p(t.boardPadding,"4")),S(u,F(n,"board."),F(i,"board.")),u.addEventListener("dragover",b=>{on(t)&&(b.preventDefault(),b.dataTransfer&&(b.dataTransfer.dropEffect="move"))}),u.addEventListener("drop",b=>{const v=b.dataTransfer?.getData("application/vnd.gamecult.eve.inventory-item+json")||"";if(!v)return;let C;try{C=JSON.parse(v)}catch{return}const A=u.getBoundingClientRect(),N=Math.max(1,O(t.cellSize,72)),j=Math.max(0,O(t.cellGap,4)),W=N+j,Y=Math.max(0,Math.min(l-1,Math.floor((b.clientX-A.left)/W))),q=Math.max(0,Math.min(c-1,Math.floor((b.clientY-A.top)/W))),z=an(C,t,Y,q,o);z&&(b.preventDefault(),o.commandSink?.(z,e))});const h=new Set;for(const b of e.children||[]){const v=x(b.props),C=B(v.x,0),A=B(v.y,0);h.add(`${C}:${A}`),u.append(k(b,o))}const y=Math.min(l*c,256);for(let b=0;b{!a.draggable||!y.dataTransfer||(y.dataTransfer.effectAllowed="move",y.dataTransfer.setData("application/vnd.gamecult.eve.inventory-item+json",JSON.stringify(t)))});let f=B(t.shapeWidth,1),c=B(t.shapeHeight,1);const r=p(t.rotation,"").toLowerCase();["clockwise","counterclockwise","right","left","rotate90","rotate270"].includes(r)&&([f,c]=[c,f]),a.style.gridColumn=`${s+1} / span ${f}`,a.style.gridRow=`${l+1} / span ${c}`;const d=m("span","cultui-inventory-item-icon");S(d,F(n,"icon."),F(i,"icon.")),d.textContent=Sn(p(t.iconAssetUri,t.iconAssetKey,t.itemKey,t.label,"")),a.append(d);const u=p(t.label,t.itemKey,"");if(u){const y=m("span","cultui-inventory-item-label",u);S(y,F(n,"label."),F(i,"label.")),a.append(y)}const h=Number(t.quantity);if(Number.isFinite(h)&&h>1){const y=m("span","cultui-inventory-item-quantity",String(h));S(y,F(n,"quantity."),F(i,"quantity.")),a.append(y)}return a.title=[u,p(t.source,""),p(t.quality,"")?`quality ${t.quality}`:"",p(t.durability,"")?`durability ${t.durability}`:""].filter(Boolean).join(" | "),a}function on(e){return Object.entries(e).some(([t,n])=>(t==="dropCommand"||t.startsWith("dropCommand."))&&typeof n=="string"&&n.length>0)}function an(e,t,n,i,o=U){const a=p(e.sourceKind,e.source,""),s=p(t[`dropCommand.${a}`],t.dropCommand,"");if(!a||!s)return;const l=O(e.sourceIndex,-1),f=O(t.targetIndex,-1),c=p(t.targetKind,""),r={sourceKind:a,originEntityKey:p(e.sourceEntityKey,e.entityKey,""),originIndex:l,originCargoIndex:a==="cargo"?l:-1,itemKey:p(e.itemKey,""),quantity:Math.max(1,O(e.quantity,1)),sourceX:O(e.x,-2147483648),sourceY:O(e.y,-2147483648),destinationKind:c,destinationEntityKey:p(t.targetEntityKey,t.entityKey,""),destinationIndex:f,destinationCargoIndex:c==="cargo"?f:-1,destinationX:Math.trunc(n),destinationY:Math.trunc(i),hasDestinationPosition:!0};return te(s,{action:r},o)}function cn(e,t,n){const i=m("section","cultui-binding-map");w(i,e);const o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.setAttribute("class","cultui-xbox-controller"),o.setAttribute("viewBox","0 0 780 420"),o.setAttribute("role","img"),o.setAttribute("aria-label",g(t.label,"Xbox controller remapping")),o.innerHTML=dn(),i.append(o);const a=m("div","cultui-binding-overlay");for(const s of e.children||[]){const l=x(s.props),f=g(l.target,s.id||""),c=m("button","cultui-binding-box");w(c,s),c.type="button",c.dataset.target=f,c.dataset.kind=g(l.bindingKind,"button"),c.style.left=R(l.x??"50%"),c.style.top=R(l.y??"50%"),c.append(m("span","cultui-binding-target",g(l.label,f))),c.append(m("span","cultui-binding-source",g(l.current,"unmapped"))),c.addEventListener("click",()=>{const d=Je(s);if(Ve(s)||d?.documentId)Ze(ve(s,n),n);else{const u=g(l.commandId,"");u&&n.commandSink?.(te(u,l,n),s)}}),a.append(c);const r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("class","cultui-binding-line"),r.setAttribute("x1",g(l.anchorX,"390")),r.setAttribute("y1",g(l.anchorY,"210")),r.setAttribute("x2",String(Be(l.x,780))),r.setAttribute("y2",String(Be(l.y,420))),o.append(r)}return i.append(a),i}function Ve(e){for(const t of e.embeddedDocuments||[]){const n=x(t.surface);if(n.root)return n}}function Je(e){const t=(e.embeddedDocuments||[])[0],n=x(e.props),i=p(n.documentId,t?.documentId,"");if(i)return{documentId:i,presentationKind:p(n.presentationKind,t?.presentationKind,""),schemaId:p(n.schemaId,t?.schemaId,""),slotId:p(n.slotId,t?.slotId,"")}}async function ve(e,t){const n=Ve(e);if(n)return n;const i=Je(e);if(!i?.documentId||!t.documentResolver)return;const o=await t.documentResolver(i,e);if(o)return x(o.surface).root?o.surface:o}function Ze(e,t){const n=m("div","cultui-modal-backdrop"),i=m("section","cultui-modal");i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true");const o=m("header","cultui-modal-header");o.append(m("h2","","Configure Binding"));const a=m("button","cultui-modal-close","Close");a.type="button",a.addEventListener("click",()=>n.remove()),o.append(a);const s=m("div","cultui-modal-body");i.append(o,s),n.append(i),n.addEventListener("click",l=>{l.target===n&&n.remove()}),document.body.append(n),s.append(m("div","detail","materializing document")),Promise.resolve(e).then(l=>{o.querySelector("h2").textContent=l?.title||"Configure Binding",s.replaceChildren(l?.root?k(l.root,t):X("Embedded document unavailable"))}).catch(l=>{s.replaceChildren(X(`Embedded document failed: ${l instanceof Error?l.message:String(l)}`))})}function sn(e,t,n,i,o){const a=x(e.props),s=(e.children||[])[0],l=x(s?.props),f=p(l.anchor,a.anchor,"trigger"),c=p(l.placement,a.placement,"below-start"),r=Number(p(l.offsetX,a.offsetX,"0"))||0,d=Number(p(l.offsetY,a.offsetY,"4"))||0,u=m("div","cultui-modal-backdrop");u.style.background="transparent",u.style.placeItems="start";const h=m("section","cultui-modal");h.setAttribute("role","dialog"),h.setAttribute("aria-modal","true"),h.style.position="fixed",h.style.width="min(420px, calc(100vw - 24px))",h.style.maxHeight="min(620px, calc(100vh - 24px))";const y=m("header","cultui-modal-header");y.append(m("h2","",p(l.title,a.title,a.label,"Options")));const b=m("button","cultui-modal-close","Close");b.type="button",b.addEventListener("click",()=>u.remove()),y.append(b);const v=m("div","cultui-modal-body");if(s){const A=s.children||[];A.length>0?v.replaceChildren(...A.map(N=>k(N,t))):v.append(k(s,t))}else v.append(X("Popup has no content"));h.append(y,v),u.append(h),u.addEventListener("click",A=>{A.target===u&&u.remove()}),document.body.append(u);const C=ln(f,c,n,h,i,o,r,d);h.style.left=`${C.left}px`,h.style.top=`${C.top}px`}function ln(e,t,n,i,o,a,s,l){const f=n.getBoundingClientRect(),c=i.getBoundingClientRect(),r=c.width||420,d=c.height||320,u=e==="cursor"?{left:o,right:o,top:a,bottom:a}:f;if(t==="right-down"||t==="dropdown")return oe(u,r,d,s,l,"right","down");if(t==="left-down")return oe(u,r,d,s,l,"left","down");if(t==="right-up")return oe(u,r,d,s,l,"right","up");if(t==="left-up")return oe(u,r,d,s,l,"left","up");switch(t){case"above-start":return $(u.left+s,u.top-d-l,r,d);case"above-end":return $(u.right-r+s,u.top-d-l,r,d);case"below-end":return $(u.right-r+s,u.bottom+l,r,d);case"right-start":return $(u.right+s,u.top+l,r,d);case"left-start":return $(u.left-r-s,u.top+l,r,d);case"center":return $((window.innerWidth-r)/2+s,(window.innerHeight-d)/2+l,r,d);default:return $(u.left+s,u.bottom+l,r,d)}}function oe(e,t,n,i,o,a,s){const f=window.innerWidth-e.right-i-12,c=e.left-i-12,r=window.innerHeight-e.top-o-12,d=e.bottom-o-12,u=a==="right"?f>=t||f>=c:!(c>=t||c>=f),h=s==="down"?r>=n||r>=d:!(d>=n||d>=r),y=u?e.right+i:e.left-t-i,b=h?e.top+o:e.bottom-n-o;return $(y,b,t,n)}function $(e,t,n,i){return{left:Ne(e,12,window.innerWidth-n-12),top:Ne(t,12,window.innerHeight-i-12)}}function Ne(e,t,n){return n + + + + + + + + + + + + + + + + + YBXA + `}function un(e,t=document.body){const n=Ie(e),i=document.documentElement.style;hn(n.assets.fontCss);for(const[c,r]of Object.entries(Xt))i.setProperty(c,r);const o={colorBackground:"--bg",colorBackgroundTop:"--bg-top",colorBackgroundMid:"--bg-mid",colorBackgroundBottom:"--bg-bottom",colorShellSurfaceTop:"--shell-top",colorShellSurfaceBottom:"--shell-bottom",colorPanel:"--panel",colorPanelAlt:"--panel-2",colorPanelBorder:"--line",colorPanelBorderDeep:"--line-deep",colorText:"--text",colorTextBright:"--text-bright",colorMuted:"--quiet",colorAccent:"--accent",colorAccentStrong:"--accent-strong",colorCornerAccent:"--corner-accent",colorLink:"--cyan",colorShadow:"--shadow",colorPixelGrid:"--pixel-grid"};for(const[c,r]of Object.entries(o)){const d=n.tokens[c];d!==void 0&&i.setProperty(r,String(d))}const a=n.tokens.fontBody,s=n.tokens.fontDisplay,l=n.tokens.fontTitle,f=n.tokens.fontMono;a&&i.setProperty("--font-body",ce(String(a))),s&&i.setProperty("--font-title",ce(String(s))),l&&i.setProperty("--font-title",ce(String(l))),f&&i.setProperty("--font-mono",ce(String(f))),n.tokens.borderWidthPx&&i.setProperty("--border-width",`${n.tokens.borderWidthPx}px`),n.tokens.borderBottomWidthPx&&i.setProperty("--border-bottom-width",`${n.tokens.borderBottomWidthPx}px`),n.tokens.cornerAccentPx&&i.setProperty("--corner-accent-size",`${n.tokens.cornerAccentPx}px`),t.dataset.pixelArt=n.tokens.pixelArt||n.tokens.imageRendering==="pixelated"?"true":"false",t.dataset.scanlines=n.tokens.scanlineOverlay?"true":"false"}function te(e,t={},n=U){const i=x(t.action),o=n.provider?.providerId||ee?.providerId||"surface unknown",a=n.activeSurfaceId||ee?.surface?.id||n.provider?.surfaces?.[0]?.surfaceId||o,s=fn(n,a),l=p(s.commandBoundary,t.commandBoundary,i.commandBoundary,i.target),f=p(s.receiptSchema,t.receiptSchema,i.receiptSchema),c={type:"surface-command",schema:"gamecult.eve.command_invocation.v1",providerId:o,surfaceId:a,command:e||g(i.type,"invoke"),payload:{...i,transport:t.transport??null},issuedAt:new Date().toISOString(),clientId:n.clientId||"eve.browser"};return l&&(c.commandBoundary=l),f&&(c.receiptSchema=f),c}function fn(e,t){const n=[...e.provider?.surfaces||[],...e.provider?.localAdvertisement?.surfaces||[]];return n.find(i=>i.surfaceId===t&&i.worldInteraction)?.worldInteraction||n.find(i=>i.worldInteraction)?.worldInteraction||{}}function De(e,t){const n=x(e.action);return g(e.command,g(e.commandId,g(n.command,g(n.target,g(n.type,t?.commandId||"")))))}function X(e){const t=m("section","pane");return t.append(m("h2","","No Surface")),t.append(m("div","detail",e)),t}function $e(e,t,n,i,o){e.dataset.commandId=n,e.tabIndex=e instanceof HTMLButtonElement?e.tabIndex:0;const a=()=>{const s=te(n,i,o);o.commandSink?.(s,t)};e.addEventListener("click",a),e.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),a())})}function mn(e,t,n){const i=pn(e,t),o=x(i.find(u=>u.kind==="control.box")?.props),a=i.filter(u=>u.kind==="control.part"),s=Number(e.min??0),l=Number(e.max??1),f=m("div","cultui-slider");f.dataset.skin=g(e.skin,"default"),f.dataset.bind=g(e.bind,""),yn(f,o);const c=m("div","cultui-slider-visual"),r=m("input","cultui-slider-input");r.type="range",r.min=String(s),r.max=String(l),r.step=String(e.step??.01),r.setAttribute("aria-label",g(e.bind,"slider"));for(const u of a){const h=x(u.props),y=m("span",`cultui-slider-part ${g(h.name,"part")}`);bn(y,h),c.append(y)}return a.some(u=>x(u.props).name==="track")||c.append(m("span","cultui-slider-part track")),a.some(u=>x(u.props).name==="fill")||c.append(m("span","cultui-slider-part fill")),a.some(u=>x(u.props).name==="thumb")||c.append(m("span","cultui-slider-part thumb")),f.append(c,r),(u=>{const h=Number(u??s),y=Math.max(s,Math.min(l,Number.isFinite(h)?h:s)),b=l===s?0:(y-s)/(l-s)*100;r.value=String(y),f.style.setProperty("--cultui-slider-value",`${b}%`),f.dataset.value=String(y)})(e.value??s),r.addEventListener("input",()=>{const u=te(g(e.command,"control.slider.input"),{...e,action:{...x(e.action),value:Number(r.value)},value:Number(r.value)},n);n.commandSink?.(u,{kind:"control.slider",props:e})}),f}function pn(e,t){const n=typeof e.skin=="string"?e.skin:"",o=[...n?Ye.controlSkins[n]?.children||[]:[],...t];return o.length?o:[{kind:"control.box",props:{height:18,overflow:"visible"}},{kind:"control.part",props:{name:"track",anchor:"center",size:["100%",6],radius:2,fill:"color.panelInset"}},{kind:"control.part",props:{name:"fill",anchor:["left","center"],size:["value%",6],radius:2,fill:"color.accent"}},{kind:"control.part",props:{name:"thumb",anchor:["value","center"],size:[12,12],bleed:3,radius:999,fill:"color.accent"}}]}function Ie(e){if(Array.isArray(e)){const t={},n={};for(const i of e)i?.name&&(i.name==="font.web.google"&&typeof i.value=="string"?n.fontCss=i.value:t[i.name]=i.value);return{tokens:t,assets:n,controlSkins:{}}}return{tokens:x(e?.tokens),assets:x(e?.assets),controlSkins:x(e?.controlSkins)}}function Z(e){if(!e)return"";const t=U.assetUrlResolver;return t?t(e,ee):/^(https?:|data:|blob:)/i.test(e)?e:U.assetBaseUrl&&e.startsWith("/")?`${U.assetBaseUrl.replace(/\/+$/,"")}${e}`:e}function hn(e){const t=typeof e=="string"?e.trim():"";if(re?.dataset.href===t||(re?.remove(),re=void 0,!t))return;const n=document.createElement("link");n.rel="preconnect",n.href="https://fonts.gstatic.com",n.crossOrigin="anonymous",document.head.append(n);const i=document.createElement("link");i.rel="stylesheet",i.href=t,i.dataset.href=t,document.head.append(i),re=i}function gn(e,t,n){const i=[];return(e==="text.title"||t.role==="title")&&i.push("cultui-title","eve-text-title"),e==="text.subtitle"&&i.push("eve-text-subtitle"),e==="label"&&i.push("cultui-label"),t.role==="mono"&&i.push("detail","mono"),i.length===0&&i.push("detail","eve-text"),i.join(" ")}function yn(e,t){t.height!==void 0&&(e.style.minHeight=R(t.height)),t.width!==void 0&&(e.style.width=R(t.width)),typeof t.overflow=="string"&&(e.style.overflow=t.overflow)}function bn(e,t){const n=Array.isArray(t.size)?t.size:[t.size,void 0];n[0]!==void 0&&n[0]!=="value%"&&(e.style.width=R(n[0])),n[1]!==void 0&&(e.style.height=R(n[1])),t.radius!==void 0&&(e.style.borderRadius=R(t.radius)),t.fill!==void 0&&(e.style.background=le(String(t.fill))),t.bleed!==void 0&&e.style.setProperty("--part-bleed",R(t.bleed)),(Array.isArray(t.anchor)?t.anchor:[t.anchor]).includes("value")&&(e.dataset.anchorValue="true")}function ae(e,t){t.gap!==void 0&&(e.style.gap=R(t.gap)),t.padding!==void 0&&(e.style.padding=R(t.padding)),t.size!==void 0&&(e.style.flex=vn(t.size)),t.min!==void 0&&(e.style.minWidth=R(t.min)),t.max!==void 0&&(e.style.maxWidth=R(t.max)),t.align!==void 0&&(e.style.alignItems=t.align==="end"?"flex-end":String(t.align)),(t.clip==="true"||t.clip===!0)&&(e.style.overflow="hidden"),t.scroll==="y"&&(e.style.overflowY="auto"),t.scroll==="x"&&(e.style.overflowX="auto")}function vn(e){return typeof e=="string"&&e.endsWith("fr")?`${Number(e.slice(0,-2))||1} 1 0`:e==="auto"||e==="content"?"0 0 auto":`0 0 ${R(e)}`}function R(e){return Array.isArray(e)?e.map(R).join(" "):typeof e=="number"?`${e}px`:typeof e=="string"&&/^-?\d+(\.\d+)?$/.test(e)?`${e}px`:String(e??"")}function le(e){return{"color.accent":"var(--accent)","color.panelInset":"rgba(0, 0, 0, 0.34)","color.panel":"var(--panel)","color.text":"var(--text)"}[e]||e}function ce(e){return e.includes("Zen Kaku Gothic New")||e.includes("M PLUS 1")?e:e.includes("Montserrat")?`${e}, "Zen Kaku Gothic New", "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:e.includes("Ubuntu")?`${e}, "M PLUS 1", "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`:`${e}, "Noto Sans JP", "Hiragino Sans", "Yu Gothic", sans-serif`}function w(e,t){t.id&&(e.id=t.id),t.id&&(e.dataset.eveNodeId=t.id),t.kind&&(e.dataset.eveKind=t.kind)}function x(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function xn(e){return Array.isArray(e)?e:[]}function wn(e){return xn(e).map((t,n)=>He({kind:"list.item",props:x(t)}))}function g(e,t){return e==null?t:String(e)}function p(...e){for(const t of e){if(typeof t=="string"&&t.trim())return t;if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function Ae(e){return typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"?["1","true","yes","on"].includes(e.trim().toLowerCase()):!1}function B(e,t){const n=Number(e);return Number.isFinite(n)?Math.max(0,Math.floor(n)):t}function Sn(e){const t=e.toLowerCase();return t.includes("sensor")?"S":t.includes("thermal")?"T":t.includes("fuel")?"F":t.includes("cargo")?"C":t.includes("weapon")?"W":e.trim().slice(0,1).toUpperCase()||"?"}function In(e){const t=e.trim().split(/\s+/).filter(Boolean);return t.length&&t.slice(0,2).map(n=>n[0]?.toUpperCase()||"").join("")||"?"}function Ue(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(100,t)):0}function m(e,t="",n=""){const i=document.createElement(e);return t&&(i.className=t),n&&(i.textContent=n),i}const We=document.querySelector("#surface"),D=document.querySelector("#status"),ze=document.querySelector("#receipt"),An=document.querySelector("#compiler"),Qe=document.querySelector("#composer"),xe=document.querySelector("#compiler-results");let _e=0;async function Ee(){const e=await fetch("/api/surface");if(e.status===401){D.textContent="This laboratory requires an unused invite link.";return}const t=await e.json(),n=t.surface_id==="ghostlight.compiler";if(An.hidden=!n,Qe.hidden=n,We.hidden=n,n){D.textContent="No campaign exists. Retrieve the Vault and approve a world seed.";return}_e=Number(t.version??0),jt(t,We,{body:document.body,clientId:"ghostlight.browser",statusElement:D})}async function Q(e,t){D.textContent="Retrieving evidence and compiling…";const n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),i=n.headers.get("content-type")?.includes("json")?await n.json():await n.text();if(!n.ok)throw D.textContent=typeof i=="string"?i:"Compilation failed",new Error(D.textContent);return i}function Ke(e,t,n){xe.innerHTML=`
${e.map((i,o)=>`

${i.title??i.name}

${i.player_hook??i.premise}

${i.era?`${i.era} · ${i.place} · ${i.pressure}`:""}

`).join("")}
`,xe.querySelectorAll("button").forEach(i=>i.addEventListener("click",()=>n(e[Number(i.dataset.index)])))}document.querySelector("#suggest-form").addEventListener("submit",async e=>{e.preventDefault();const t=await Q("/api/compiler/openings",{setting:document.querySelector("#setting").value,constraints:[]});Ke(t.openings,"Choose opening",async n=>{const i=await Q("/api/compiler/roles",n);Ke(i.roles,"Choose role",async o=>et(await Q("/api/compiler/selected",{campaign_name:n.title,opening:n,role:o})))})});document.querySelector("#custom-form").addEventListener("submit",async e=>{e.preventDefault(),await et(await Q("/api/compiler/custom",Object.fromEntries(new FormData(e.currentTarget))))});async function et(e){const t=e.preview;xe.innerHTML=`

${t.title}

${t.campaign.transcript?.[0]?.text??""}

${Object.keys(t.campaign.locations).length} locations · ${Object.keys(t.campaign.actors).length} actors · ${Object.keys(t.campaign.institutions).length} institutions

${t.gaps.length?`Material gaps: ${t.gaps.join("; ")}`:"No declared material gaps."}

Branch assumptions: ${t.branch_assumptions.join("; ")||"none"}

`,document.querySelector("#approve-world").addEventListener("click",async()=>{await Q(`/api/compiler/approve/${e.preview_id}`,{}),await Ee()}),D.textContent="Preview compiled. Nothing has entered world state yet."}async function tt(e){D.textContent="The world is considering the command…";const t=await fetch("/api/command",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),n=await t.json();if(ze.hidden=!1,ze.textContent=JSON.stringify(n,null,2),!t.ok){D.textContent=n.error??"The command was refused.";return}await Ee()}Qe.addEventListener("submit",e=>{e.preventDefault();const t=document.querySelector("#attempt").value.trim();t&&tt({type:"assess",expected_revision:_e,intent:{actor_id:"player",description:t,intended_effect:t}})});document.querySelector("#wait").addEventListener("click",()=>{tt({type:"wait",expected_revision:_e,minutes:60})});Ee(); diff --git a/web/dist/assets/index-CyG_836Q.css b/web/dist/assets/index-Dt7lvyL0.css similarity index 94% rename from web/dist/assets/index-CyG_836Q.css rename to web/dist/assets/index-Dt7lvyL0.css index a0f8ce0..c24bc68 100644 --- a/web/dist/assets/index-CyG_836Q.css +++ b/web/dist/assets/index-Dt7lvyL0.css @@ -1 +1 @@ -@import"https://fonts.googleapis.com/css2?family=M+PLUS+1:wght@100;300;400;500;700&family=Montserrat:wght@100;300;400;500;700&family=Ubuntu+Sans:wght@300;400;500;700&family=Zen+Kaku+Gothic+New:wght@300;400;500;700&display=swap";@import"https://fonts.googleapis.com/css2?family=Crimson+Pro:opsz,wght@8..144,400;8..144,600&family=IBM+Plex+Mono:wght@400;600&display=swap";:root{color-scheme:dark;--bg: #020909;--bg-top: var(--bg);--bg-mid: var(--bg);--bg-bottom: var(--bg);--shell-top: #010707;--shell-bottom: #010707;--panel: #071918;--panel-2: #0a2423;--line: rgba(103, 240, 228, .28);--line-deep: rgba(103, 240, 228, .18);--line-hot: rgba(142, 252, 255, .72);--text: #e7f1f1;--text-bright: var(--text);--quiet: #8ba5a3;--accent: #ffb84f;--accent-strong: var(--accent);--corner-accent: var(--accent);--cyan: #8efcff;--shadow: rgba(0, 0, 0, .35);--pixel-grid: rgba(142, 252, 255, .04);--border-width: 1px;--border-bottom-width: var(--border-width);--corner-accent-size: 0;--font-body: "M PLUS 1", "Ubuntu Sans", Ubuntu, "Noto Sans JP", system-ui, sans-serif;--font-title: "Montserrat", "Zen Kaku Gothic New", "M PLUS 1", "Ubuntu Sans", system-ui, sans-serif;--font-mono: "Ubuntu Sans Mono", "M PLUS 1 Code", "Cascadia Mono", Consolas, monospace}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:linear-gradient(180deg,var(--bg-top),var(--bg-mid),var(--bg-bottom));color:var(--text);font-family:var(--font-body)}.topbar{height:84px;display:flex;justify-content:space-between;align-items:center;padding:10px 16px;border-bottom:1px solid var(--line);background:linear-gradient(180deg,var(--shell-top),var(--shell-bottom))}h1{margin:0;font-size:20px;letter-spacing:0}p{margin:4px 0 0;color:var(--quiet);font-size:13px}.hud{min-width:168px;padding:8px;border:1px solid var(--line-hot);border-radius:6px;background:#071918e0;color:var(--accent);font-family:Cascadia Mono,Consolas,monospace;font-size:11px;display:grid;gap:2px}.provider-bar{display:flex;align-items:center;gap:8px;padding:10px 16px;border-bottom:1px solid var(--line-deep);background:color-mix(in srgb,var(--panel) 70%,transparent)}.provider-bar label{color:var(--quiet);font:700 11px var(--font-mono);text-transform:uppercase}.provider-bar select{border:1px solid var(--line);border-radius:6px;background:var(--panel);color:var(--text);padding:8px 12px;font:700 13px var(--font-mono);min-width:min(28rem,52vw)}.provider-meta{color:var(--quiet);font:600 11px var(--font-mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.surface{padding:10px 16px 16px}.cockpit{display:grid;grid-template-columns:.78fr 1.08fr 1.34fr;gap:10px;min-height:calc(100vh - 138px)}.ctb{grid-column:1 / -1;min-height:88px;overflow-x:auto;display:flex;gap:8px;padding-bottom:8px}.pane{min-height:0;border:1px solid var(--line);border-radius:6px;background:#071918eb;padding:12px;box-shadow:0 12px 26px var(--shadow)}.pane h2{margin:0 0 10px;color:var(--quiet);font-size:12px;font-weight:500;text-transform:uppercase}.card{border:1px solid var(--line);border-radius:6px;background:#0a2423f5;padding:10px;box-shadow:0 8px 20px var(--shadow)}.cultui-card[data-command-id]{cursor:pointer;border-bottom-width:var(--border-bottom-width)}.cultui-card-button{display:block;width:100%;color:inherit;font:inherit;text-align:left}.ctb .card{flex:0 0 96px;min-height:76px;padding:6px}.avatar{width:34px;height:34px;border-radius:50%;border:1px solid var(--line-hot);object-fit:cover;background:#123}.card-title{white-space:pre-line;margin-top:4px;font:700 11px var(--font-mono)}.health{color:var(--accent);font:700 10px var(--font-mono)}.detail{white-space:pre-wrap;font:600 12px var(--font-mono);line-height:1.45}.list{display:grid;gap:8px}.metrics{display:grid;gap:9px;margin:12px 0}.metric label{display:flex;justify-content:space-between;color:var(--quiet);font:700 10px var(--font-mono)}.bar{height:7px;border-radius:7px;background:#010707;border:1px solid rgba(255,255,255,.12);overflow:hidden}.bar span{display:block;height:100%;background:linear-gradient(90deg,#bca8ff,#8efcff)}.graph{position:relative;min-height:calc(100vh - 166px);border:1px solid var(--line);border-radius:6px;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px),#030f11f0;background-size:44px 44px}.node{position:absolute;transform:translate(-50%,-50%);border:1px solid var(--line);border-radius:7px;background:#0a2423f2;padding:10px;overflow:hidden}.node.selected{border-color:var(--line-hot);box-shadow:0 0 0 1px #8efcff61}.node .detail{margin-top:6px;color:var(--quiet);font-size:10px}@media(max-width:900px){.cockpit{grid-template-columns:1fr}}.cultui-vn-stage{position:relative;min-height:calc(100vh - 138px);overflow:hidden;border:1px solid var(--line);border-radius:6px;background:var(--bg)}.cultui-grid{min-height:calc(100vh - 138px);display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:10px;align-content:start}.cultui-surface-root{min-height:calc(100vh - 150px);display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px;align-content:start}.cultui-surface-root[data-direction=vertical]{grid-template-columns:minmax(0,1fr)}.cultui-surface-root[data-direction=horizontal]{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}.cultui-embedded-slot .cultui-surface-root{min-height:0;grid-template-columns:minmax(0,1fr)}@media(max-width:900px){.cultui-pane[data-span=wide]{grid-column:1 / -1}}.cultui-pane{border-width:var(--border-width);border-bottom-width:var(--border-bottom-width);min-width:0}.cultui-pane[data-span=wide]{grid-column:span 2}.cultui-pane .cultui-pane{box-shadow:none;background:#030f1161}.cultui-pane[data-density=compact]{padding:8px}.cultui-pane[data-density=compact] h2{margin-bottom:6px}.cultui-partition{min-width:0;min-height:0;display:flex;gap:10px}.cultui-partition[data-direction=horizontal]{flex-direction:row}.cultui-partition[data-direction=vertical]{flex-direction:column}.cultui-partition[data-overflow=x]{overflow-x:auto;padding-bottom:4px}.cultui-partition.split-x{flex-direction:row}.cultui-partition.split-y,.cultui-partition.split-none{flex-direction:column}.cultui-partition.split-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.cultui-partition[data-role="inspector.row"]{min-height:34px;border:1px solid rgba(255,255,255,.06);border-radius:4px;background:linear-gradient(180deg,#201f2bf5,#13141df5);box-shadow:inset 0 1px #ffffff0d,0 2px 8px #0006}.cultui-partition[data-role="inspector.label"]{justify-content:center}.cultui-label{color:var(--accent);font:700 13px var(--font-mono);line-height:1.15;text-transform:uppercase}.cultui-slider{--cultui-slider-value: 0%;--part-bleed: 0px;position:relative;display:grid;align-items:center;width:100%;min-height:18px;overflow:visible}.cultui-slider-visual{position:absolute;inset:0;overflow:visible;pointer-events:none}.cultui-slider-input{position:absolute;inset:0;opacity:0;cursor:pointer}.cultui-slider-part{position:absolute;top:50%;display:block;transform:translateY(-50%)}.cultui-slider-part.track{right:0;left:0;height:6px;border-radius:2px;background:#00000057}.cultui-slider-part.fill{left:0;width:var(--cultui-slider-value);height:6px;border-radius:2px;background:var(--accent)}.cultui-slider-part.thumb{left:var(--cultui-slider-value);width:12px;height:12px;border-radius:999px;background:var(--accent);transform:translate(-50%,-50%);box-shadow:0 0 7px color-mix(in srgb,var(--accent) 45%,transparent)}.cultui-slider-part[data-anchor-value=true]{left:var(--cultui-slider-value);transform:translate(-50%,-50%)}@media(max-width:520px){.cultui-partition[data-role="inspector.row"]{flex-direction:column;align-items:stretch}.cultui-partition[data-role="inspector.label"]{flex:0 0 auto!important}}body[data-provider=repixelizer] .surface{position:relative}body[data-provider=repixelizer] .surface:after{content:"";pointer-events:none;position:fixed;inset:0;background:repeating-linear-gradient(0deg,rgba(255,255,255,.035) 0 1px,transparent 1px 4px);opacity:.28;mix-blend-mode:screen}body[data-pixel-art=true] img,body[data-pixel-art=true] .cultui-background{image-rendering:pixelated}.cultui-title{color:var(--accent);font:100 18px var(--font-title);line-height:1.35}.mono{color:var(--accent);font-family:var(--font-mono)}.cultui-reactive-metric{margin-top:8px}.cultui-reactive-list{display:grid;gap:8px}.cultui-list{display:grid;gap:8px;min-width:0}.cultui-list-title{margin:0;color:var(--quiet);font:700 10px var(--font-mono);letter-spacing:0;text-transform:uppercase}.cultui-list-item{display:grid;gap:5px;min-width:0;padding:8px;border:1px solid var(--line);border-radius:6px;background:var(--panel)}.cultui-list-item-heading,.cultui-list-item-badges{display:flex;gap:6px;align-items:center;flex-wrap:wrap;min-width:0}.cultui-list-item-label{min-width:0;overflow-wrap:anywhere}.cultui-list-item-status,.cultui-list-item-badge{padding:2px 5px;border:1px solid var(--line-hot);border-radius:4px;color:var(--quiet);font:600 10px var(--font-mono)}.cultui-list-item-detail{color:var(--quiet);font-size:12px;overflow-wrap:anywhere}.cultui-avatar-card{flex:0 0 104px;display:grid;gap:4px;align-content:start;min-height:92px;margin:0;padding:8px;border:1px solid var(--line);border-radius:6px;background:#0a2423f0;box-shadow:0 8px 20px var(--shadow)}.cultui-avatar-card img,.cultui-avatar-fallback{width:34px;height:34px;border:1px solid var(--line-hot);border-radius:50%;object-fit:cover;background:#010707db}.cultui-avatar-fallback{display:grid;place-items:center;color:var(--accent);font:700 12px var(--font-mono)}.cultui-avatar-name{color:var(--text-bright);font:700 11px var(--font-mono);line-height:1.15}.cultui-avatar-status,.cultui-avatar-detail{color:var(--quiet);font:700 10px var(--font-mono);line-height:1.2}.cultui-avatar-status{color:var(--accent)}.cultui-meter{display:grid;gap:4px}.cultui-meter-head{display:flex;justify-content:space-between;gap:8px;color:var(--quiet);font:700 10px var(--font-mono)}.cultui-meter-track{height:7px;overflow:hidden;border:1px solid rgba(255,255,255,.12);border-radius:7px;background:#010707e0}.cultui-meter-fill{display:block;height:100%;background:linear-gradient(90deg,#ffb84f,#8efcff)}.cultui-stream-item{border-left:2px solid var(--line-hot);padding-left:8px}.cultui-background{position:absolute;inset:0;background-size:cover;background-position:center;image-rendering:pixelated;opacity:.72}.cultui-graph{position:absolute;top:18px;left:18px;width:min(48rem,46vw);height:min(29rem,52vh);z-index:4}.cultui-placed{position:absolute;transform-origin:center}.cultui-placed[data-placement-mode=keystone],.cultui-placed[data-placement-mode=skew],.cultui-placed[data-placement-mode=sprite-chromakey]{box-shadow:0 12px 26px #00000047}.cultui-placed[data-chroma-key]{outline:1px dashed rgba(0,255,120,.45)}.cultui-node{position:absolute;transform:translate(-50%,-50%);border:2px solid var(--cyan);border-radius:999px;background:#07111ac2;color:var(--text);min-width:68px;min-height:44px;padding:8px 10px;font:700 12px Cascadia Mono,Consolas,monospace}.cultui-node.selected{border-color:var(--accent);box-shadow:0 0 0 2px #ffb84f47}.cultui-graph svg{position:absolute;inset:0;overflow:visible}.cultui-graph line{stroke:#8efcff5c;stroke-width:.006;stroke-linecap:round}.cultui-layer-embedded-surfaces{position:absolute;inset:0;z-index:5;pointer-events:none}.cultui-layer-embedded-surfaces>*{pointer-events:auto}.cultui-tex{min-width:12rem;min-height:3.2rem;border:1px solid rgba(142,252,255,.34);border-radius:6px;background:#07111ac7;color:var(--text);padding:10px 12px}.cultui-tex-label{color:var(--accent);font:700 10px Cascadia Mono,Consolas,monospace;text-transform:uppercase}.cultui-tex-source{margin-top:4px;font:700 15px "Cambria Math","STIX Two Math",Georgia,serif;white-space:pre-wrap}.cultui-layer-cards{position:absolute;top:18px;right:18px;left:calc(min(48rem,46vw) + 36px);z-index:3;display:grid;gap:10px}.cultui-dialogue{position:absolute;right:0;bottom:0;left:0;z-index:5;min-height:128px;border-right:0;border-bottom:0;border-left:0;border-radius:0;background:#05080deb}.cultui-rail-actions{position:absolute;right:18px;bottom:18px;z-index:6;display:grid;gap:8px;width:min(28rem,42vw)}.cultui-button{border:1px solid var(--line);border-radius:6px;background:#0a2423f0;color:var(--text);padding:9px 10px;text-align:left;font:700 12px Cascadia Mono,Consolas,monospace}.cultui-button:hover,.cultui-button:focus-visible{border-color:var(--line-hot);color:var(--accent)}.cultui-image-preview{display:grid;gap:8px;margin:0}.cultui-image-frame,.cultui-canvas-grid{display:grid;place-items:center;min-height:160px;border:2px solid var(--panel-border);background:repeating-linear-gradient(45deg,#f7efd80f 0 8px,#0000002e 8px 16px),linear-gradient(180deg,#07172c,#0a2039);overflow:hidden}.cultui-image-frame{aspect-ratio:1 / 1}.cultui-image-frame img{width:100%;height:100%;object-fit:cover}.cultui-image-preview figcaption,.cultui-canvas-grid{color:var(--muted);font-size:.75rem;line-height:1.25}.cultui-canvas-placeholder{display:grid;gap:8px}.cultui-canvas-placeholder.editor .cultui-canvas-grid{min-height:280px;background:linear-gradient(45deg,rgba(255,255,255,.08) 25%,transparent 25% 75%,rgba(255,255,255,.08) 75%),linear-gradient(45deg,rgba(255,255,255,.08) 25%,transparent 25% 75%,rgba(255,255,255,.08) 75%),#142033;background-position:0 0,8px 8px;background-size:16px 16px}.cultui-status-stage{display:grid;gap:8px;padding:12px;border:2px solid var(--panel-border);background:#061627eb}.cultui-field{display:grid;gap:4px}.cultui-field-value{display:block;border:2px solid var(--panel-border);background:#01040b94;padding:6px 8px}.cultui-world-scene{position:relative;z-index:2;width:100%;min-height:min(72vh,760px);overflow:hidden;outline:none;background:#02080c80}.cultui-world-scene:focus-visible{box-shadow:inset 0 0 0 2px var(--accent)}.cultui-world-heading{position:absolute;z-index:3;top:12px;left:12px;display:flex;gap:12px;align-items:baseline;color:var(--text);font-family:var(--font-mono);font-size:.75rem;pointer-events:none}.cultui-world-heading span{color:var(--quiet)}.cultui-world-plane{position:absolute;inset:0;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px);background-size:48px 48px}.cultui-world-entity{position:absolute;display:grid;justify-items:center;width:34px;height:34px;padding:0;border:1px solid rgba(224,238,240,.65);border-radius:50%;color:#f1f5f4;background:#182226eb;transform:translate(-50%,-50%);cursor:pointer}.cultui-world-entity.faction-player{border-color:#54d9c7;color:#9ff8e8}.cultui-world-entity.faction-raider,.cultui-world-entity.faction-hostile{border-color:#ff695f;color:#ffaaa3}.cultui-world-entity[data-controlled=true]{box-shadow:0 0 0 3px #ffbe4866}.cultui-world-entity-glyph{align-self:center;font:700 16px/1 var(--font-mono)}.cultui-world-entity-label{position:absolute;top:38px;width:max-content;max-width:132px;overflow:hidden;color:var(--text);font:600 11px/1.2 var(--font-body);text-overflow:ellipsis;white-space:nowrap;pointer-events:none}.cultui-swatch{width:36px;min-height:36px;border:2px solid var(--accent);box-shadow:inset 0 0 0 2px #00000073}.cultui-binding-map{position:relative;min-height:510px;border:1px solid var(--line);border-radius:6px;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px),#030f11eb;background-size:28px 28px;overflow:hidden}.cultui-xbox-controller{position:absolute;inset:18px;width:calc(100% - 36px);height:calc(100% - 36px)}.cultui-xbox-controller .shell,.cultui-xbox-controller .stick,.cultui-xbox-controller .dpad,.cultui-xbox-controller .face,.cultui-xbox-controller .menu,.cultui-xbox-controller .guide,.cultui-xbox-controller .bumper,.cultui-xbox-controller .trigger{fill:#0a2423f0;stroke:var(--line);stroke-width:3}.cultui-xbox-controller .stick-dot,.cultui-xbox-controller .guide{fill:#8efcff1f}.cultui-xbox-controller .face{fill:#ffb84f29}.cultui-xbox-controller text{fill:var(--text);font:700 16px var(--font-mono);text-anchor:middle}.cultui-binding-line{stroke:var(--accent);stroke-width:2;stroke-dasharray:5 6;opacity:.78}.cultui-binding-overlay{position:absolute;inset:0}.cultui-binding-box{position:absolute;width:clamp(112px,12vw,138px);min-height:50px;transform:translate(-50%,-50%);display:grid;gap:4px;border:1px solid var(--line-hot);border-radius:6px;background:#071918f5;color:var(--text);padding:8px;text-align:left;box-shadow:0 10px 20px var(--shadow)}.cultui-binding-box:hover,.cultui-binding-box:focus-visible{border-color:var(--accent);color:var(--accent)}.cultui-binding-target{font:700 11px var(--font-mono);text-transform:uppercase}.cultui-binding-source{color:var(--quiet);font:600 11px var(--font-mono);overflow-wrap:anywhere}.cultui-modal-backdrop{position:fixed;inset:0;z-index:1000;display:grid;place-items:center;background:#00000094;padding:20px}.cultui-modal{width:min(680px,96vw);max-height:min(780px,92vh);display:grid;grid-template-rows:auto minmax(0,1fr);border:1px solid var(--line-hot);border-radius:6px;background:var(--panel);box-shadow:0 18px 42px #00000085;overflow:hidden}.cultui-modal-header{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 14px;border-bottom:1px solid var(--line);background:var(--shell-top)}.cultui-modal-header h2{margin:0;color:var(--accent);font:700 13px var(--font-mono);text-transform:uppercase}.cultui-modal-close{border:1px solid var(--line);border-radius:6px;background:var(--panel-2);color:var(--text);padding:7px 10px;font:700 11px var(--font-mono)}.cultui-modal-body{min-height:0;overflow:auto;padding:14px}@media(max-width:900px){.cultui-graph{right:12px;left:12px;width:auto;height:min(18rem,34vh)}.cultui-layer-cards{top:calc(30px + min(18rem,34vh));right:12px;left:12px}.cultui-rail-actions{left:12px;width:auto}}:root{color-scheme:dark;font-family:Crimson Pro,serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(920px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre{font-family:IBM Plex Mono,monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:15rem}form{margin-top:1.5rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin-bottom:.65rem}textarea{box-sizing:border-box;width:100%;min-height:7rem;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.9rem;font:1.25rem/1.4 Crimson Pro,serif}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button{background:transparent;color:#d49b58}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}} +@import"https://fonts.googleapis.com/css2?family=M+PLUS+1:wght@100;300;400;500;700&family=Montserrat:wght@100;300;400;500;700&family=Ubuntu+Sans:wght@300;400;500;700&family=Zen+Kaku+Gothic+New:wght@300;400;500;700&display=swap";@import"https://fonts.googleapis.com/css2?family=Crimson+Pro:opsz,wght@8..144,400;8..144,600&family=IBM+Plex+Mono:wght@400;600&display=swap";:root{color-scheme:dark;--bg: #020909;--bg-top: var(--bg);--bg-mid: var(--bg);--bg-bottom: var(--bg);--shell-top: #010707;--shell-bottom: #010707;--panel: #071918;--panel-2: #0a2423;--line: rgba(103, 240, 228, .28);--line-deep: rgba(103, 240, 228, .18);--line-hot: rgba(142, 252, 255, .72);--text: #e7f1f1;--text-bright: var(--text);--quiet: #8ba5a3;--accent: #ffb84f;--accent-strong: var(--accent);--corner-accent: var(--accent);--cyan: #8efcff;--shadow: rgba(0, 0, 0, .35);--pixel-grid: rgba(142, 252, 255, .04);--border-width: 1px;--border-bottom-width: var(--border-width);--corner-accent-size: 0;--font-body: "M PLUS 1", "Ubuntu Sans", Ubuntu, "Noto Sans JP", system-ui, sans-serif;--font-title: "Montserrat", "Zen Kaku Gothic New", "M PLUS 1", "Ubuntu Sans", system-ui, sans-serif;--font-mono: "Ubuntu Sans Mono", "M PLUS 1 Code", "Cascadia Mono", Consolas, monospace}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:linear-gradient(180deg,var(--bg-top),var(--bg-mid),var(--bg-bottom));color:var(--text);font-family:var(--font-body)}.topbar{height:84px;display:flex;justify-content:space-between;align-items:center;padding:10px 16px;border-bottom:1px solid var(--line);background:linear-gradient(180deg,var(--shell-top),var(--shell-bottom))}h1{margin:0;font-size:20px;letter-spacing:0}p{margin:4px 0 0;color:var(--quiet);font-size:13px}.hud{min-width:168px;padding:8px;border:1px solid var(--line-hot);border-radius:6px;background:#071918e0;color:var(--accent);font-family:Cascadia Mono,Consolas,monospace;font-size:11px;display:grid;gap:2px}.provider-bar{display:flex;align-items:center;gap:8px;padding:10px 16px;border-bottom:1px solid var(--line-deep);background:color-mix(in srgb,var(--panel) 70%,transparent)}.provider-bar label{color:var(--quiet);font:700 11px var(--font-mono);text-transform:uppercase}.provider-bar select{border:1px solid var(--line);border-radius:6px;background:var(--panel);color:var(--text);padding:8px 12px;font:700 13px var(--font-mono);min-width:min(28rem,52vw)}.provider-meta{color:var(--quiet);font:600 11px var(--font-mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.surface{padding:10px 16px 16px}.cockpit{display:grid;grid-template-columns:.78fr 1.08fr 1.34fr;gap:10px;min-height:calc(100vh - 138px)}.ctb{grid-column:1 / -1;min-height:88px;overflow-x:auto;display:flex;gap:8px;padding-bottom:8px}.pane{min-height:0;border:1px solid var(--line);border-radius:6px;background:#071918eb;padding:12px;box-shadow:0 12px 26px var(--shadow)}.pane h2{margin:0 0 10px;color:var(--quiet);font-size:12px;font-weight:500;text-transform:uppercase}.card{border:1px solid var(--line);border-radius:6px;background:#0a2423f5;padding:10px;box-shadow:0 8px 20px var(--shadow)}.cultui-card[data-command-id]{cursor:pointer;border-bottom-width:var(--border-bottom-width)}.cultui-card-button{display:block;width:100%;color:inherit;font:inherit;text-align:left}.ctb .card{flex:0 0 96px;min-height:76px;padding:6px}.avatar{width:34px;height:34px;border-radius:50%;border:1px solid var(--line-hot);object-fit:cover;background:#123}.card-title{white-space:pre-line;margin-top:4px;font:700 11px var(--font-mono)}.health{color:var(--accent);font:700 10px var(--font-mono)}.detail{white-space:pre-wrap;font:600 12px var(--font-mono);line-height:1.45}.list{display:grid;gap:8px}.metrics{display:grid;gap:9px;margin:12px 0}.metric label{display:flex;justify-content:space-between;color:var(--quiet);font:700 10px var(--font-mono)}.bar{height:7px;border-radius:7px;background:#010707;border:1px solid rgba(255,255,255,.12);overflow:hidden}.bar span{display:block;height:100%;background:linear-gradient(90deg,#bca8ff,#8efcff)}.graph{position:relative;min-height:calc(100vh - 166px);border:1px solid var(--line);border-radius:6px;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px),#030f11f0;background-size:44px 44px}.node{position:absolute;transform:translate(-50%,-50%);border:1px solid var(--line);border-radius:7px;background:#0a2423f2;padding:10px;overflow:hidden}.node.selected{border-color:var(--line-hot);box-shadow:0 0 0 1px #8efcff61}.node .detail{margin-top:6px;color:var(--quiet);font-size:10px}@media(max-width:900px){.cockpit{grid-template-columns:1fr}}.cultui-vn-stage{position:relative;min-height:calc(100vh - 138px);overflow:hidden;border:1px solid var(--line);border-radius:6px;background:var(--bg)}.cultui-grid{min-height:calc(100vh - 138px);display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:10px;align-content:start}.cultui-surface-root{min-height:calc(100vh - 150px);display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px;align-content:start}.cultui-surface-root[data-direction=vertical]{grid-template-columns:minmax(0,1fr)}.cultui-surface-root[data-direction=horizontal]{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}.cultui-embedded-slot .cultui-surface-root{min-height:0;grid-template-columns:minmax(0,1fr)}@media(max-width:900px){.cultui-pane[data-span=wide]{grid-column:1 / -1}}.cultui-pane{border-width:var(--border-width);border-bottom-width:var(--border-bottom-width);min-width:0}.cultui-pane[data-span=wide]{grid-column:span 2}.cultui-pane .cultui-pane{box-shadow:none;background:#030f1161}.cultui-pane[data-density=compact]{padding:8px}.cultui-pane[data-density=compact] h2{margin-bottom:6px}.cultui-partition{min-width:0;min-height:0;display:flex;gap:10px}.cultui-partition[data-direction=horizontal]{flex-direction:row}.cultui-partition[data-direction=vertical]{flex-direction:column}.cultui-partition[data-overflow=x]{overflow-x:auto;padding-bottom:4px}.cultui-partition.split-x{flex-direction:row}.cultui-partition.split-y,.cultui-partition.split-none{flex-direction:column}.cultui-partition.split-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.cultui-partition[data-role="inspector.row"]{min-height:34px;border:1px solid rgba(255,255,255,.06);border-radius:4px;background:linear-gradient(180deg,#201f2bf5,#13141df5);box-shadow:inset 0 1px #ffffff0d,0 2px 8px #0006}.cultui-partition[data-role="inspector.label"]{justify-content:center}.cultui-label{color:var(--accent);font:700 13px var(--font-mono);line-height:1.15;text-transform:uppercase}.cultui-slider{--cultui-slider-value: 0%;--part-bleed: 0px;position:relative;display:grid;align-items:center;width:100%;min-height:18px;overflow:visible}.cultui-slider-visual{position:absolute;inset:0;overflow:visible;pointer-events:none}.cultui-slider-input{position:absolute;inset:0;opacity:0;cursor:pointer}.cultui-slider-part{position:absolute;top:50%;display:block;transform:translateY(-50%)}.cultui-slider-part.track{right:0;left:0;height:6px;border-radius:2px;background:#00000057}.cultui-slider-part.fill{left:0;width:var(--cultui-slider-value);height:6px;border-radius:2px;background:var(--accent)}.cultui-slider-part.thumb{left:var(--cultui-slider-value);width:12px;height:12px;border-radius:999px;background:var(--accent);transform:translate(-50%,-50%);box-shadow:0 0 7px color-mix(in srgb,var(--accent) 45%,transparent)}.cultui-slider-part[data-anchor-value=true]{left:var(--cultui-slider-value);transform:translate(-50%,-50%)}@media(max-width:520px){.cultui-partition[data-role="inspector.row"]{flex-direction:column;align-items:stretch}.cultui-partition[data-role="inspector.label"]{flex:0 0 auto!important}}body[data-provider=repixelizer] .surface{position:relative}body[data-provider=repixelizer] .surface:after{content:"";pointer-events:none;position:fixed;inset:0;background:repeating-linear-gradient(0deg,rgba(255,255,255,.035) 0 1px,transparent 1px 4px);opacity:.28;mix-blend-mode:screen}body[data-pixel-art=true] img,body[data-pixel-art=true] .cultui-background{image-rendering:pixelated}.cultui-title{color:var(--accent);font:100 18px var(--font-title);line-height:1.35}.mono{color:var(--accent);font-family:var(--font-mono)}.cultui-reactive-metric{margin-top:8px}.cultui-reactive-list{display:grid;gap:8px}.cultui-list{display:grid;gap:8px;min-width:0}.cultui-list-title{margin:0;color:var(--quiet);font:700 10px var(--font-mono);letter-spacing:0;text-transform:uppercase}.cultui-list-item{display:grid;gap:5px;min-width:0;padding:8px;border:1px solid var(--line);border-radius:6px;background:var(--panel)}.cultui-list-item-heading,.cultui-list-item-badges{display:flex;gap:6px;align-items:center;flex-wrap:wrap;min-width:0}.cultui-list-item-label{min-width:0;overflow-wrap:anywhere}.cultui-list-item-status,.cultui-list-item-badge{padding:2px 5px;border:1px solid var(--line-hot);border-radius:4px;color:var(--quiet);font:600 10px var(--font-mono)}.cultui-list-item-detail{color:var(--quiet);font-size:12px;overflow-wrap:anywhere}.cultui-avatar-card{flex:0 0 104px;display:grid;gap:4px;align-content:start;min-height:92px;margin:0;padding:8px;border:1px solid var(--line);border-radius:6px;background:#0a2423f0;box-shadow:0 8px 20px var(--shadow)}.cultui-avatar-card img,.cultui-avatar-fallback{width:34px;height:34px;border:1px solid var(--line-hot);border-radius:50%;object-fit:cover;background:#010707db}.cultui-avatar-fallback{display:grid;place-items:center;color:var(--accent);font:700 12px var(--font-mono)}.cultui-avatar-name{color:var(--text-bright);font:700 11px var(--font-mono);line-height:1.15}.cultui-avatar-status,.cultui-avatar-detail{color:var(--quiet);font:700 10px var(--font-mono);line-height:1.2}.cultui-avatar-status{color:var(--accent)}.cultui-meter{display:grid;gap:4px}.cultui-meter-head{display:flex;justify-content:space-between;gap:8px;color:var(--quiet);font:700 10px var(--font-mono)}.cultui-meter-track{height:7px;overflow:hidden;border:1px solid rgba(255,255,255,.12);border-radius:7px;background:#010707e0}.cultui-meter-fill{display:block;height:100%;background:linear-gradient(90deg,#ffb84f,#8efcff)}.cultui-stream-item{border-left:2px solid var(--line-hot);padding-left:8px}.cultui-background{position:absolute;inset:0;background-size:cover;background-position:center;image-rendering:pixelated;opacity:.72}.cultui-graph{position:absolute;top:18px;left:18px;width:min(48rem,46vw);height:min(29rem,52vh);z-index:4}.cultui-placed{position:absolute;transform-origin:center}.cultui-placed[data-placement-mode=keystone],.cultui-placed[data-placement-mode=skew],.cultui-placed[data-placement-mode=sprite-chromakey]{box-shadow:0 12px 26px #00000047}.cultui-placed[data-chroma-key]{outline:1px dashed rgba(0,255,120,.45)}.cultui-node{position:absolute;transform:translate(-50%,-50%);border:2px solid var(--cyan);border-radius:999px;background:#07111ac2;color:var(--text);min-width:68px;min-height:44px;padding:8px 10px;font:700 12px Cascadia Mono,Consolas,monospace}.cultui-node.selected{border-color:var(--accent);box-shadow:0 0 0 2px #ffb84f47}.cultui-graph svg{position:absolute;inset:0;overflow:visible}.cultui-graph line{stroke:#8efcff5c;stroke-width:.006;stroke-linecap:round}.cultui-layer-embedded-surfaces{position:absolute;inset:0;z-index:5;pointer-events:none}.cultui-layer-embedded-surfaces>*{pointer-events:auto}.cultui-tex{min-width:12rem;min-height:3.2rem;border:1px solid rgba(142,252,255,.34);border-radius:6px;background:#07111ac7;color:var(--text);padding:10px 12px}.cultui-tex-label{color:var(--accent);font:700 10px Cascadia Mono,Consolas,monospace;text-transform:uppercase}.cultui-tex-source{margin-top:4px;font:700 15px "Cambria Math","STIX Two Math",Georgia,serif;white-space:pre-wrap}.cultui-layer-cards{position:absolute;top:18px;right:18px;left:calc(min(48rem,46vw) + 36px);z-index:3;display:grid;gap:10px}.cultui-dialogue{position:absolute;right:0;bottom:0;left:0;z-index:5;min-height:128px;border-right:0;border-bottom:0;border-left:0;border-radius:0;background:#05080deb}.cultui-rail-actions{position:absolute;right:18px;bottom:18px;z-index:6;display:grid;gap:8px;width:min(28rem,42vw)}.cultui-button{border:1px solid var(--line);border-radius:6px;background:#0a2423f0;color:var(--text);padding:9px 10px;text-align:left;font:700 12px Cascadia Mono,Consolas,monospace}.cultui-button:hover,.cultui-button:focus-visible{border-color:var(--line-hot);color:var(--accent)}.cultui-image-preview{display:grid;gap:8px;margin:0}.cultui-image-frame,.cultui-canvas-grid{display:grid;place-items:center;min-height:160px;border:2px solid var(--panel-border);background:repeating-linear-gradient(45deg,#f7efd80f 0 8px,#0000002e 8px 16px),linear-gradient(180deg,#07172c,#0a2039);overflow:hidden}.cultui-image-frame{aspect-ratio:1 / 1}.cultui-image-frame img{width:100%;height:100%;object-fit:cover}.cultui-image-preview figcaption,.cultui-canvas-grid{color:var(--muted);font-size:.75rem;line-height:1.25}.cultui-canvas-placeholder{display:grid;gap:8px}.cultui-canvas-placeholder.editor .cultui-canvas-grid{min-height:280px;background:linear-gradient(45deg,rgba(255,255,255,.08) 25%,transparent 25% 75%,rgba(255,255,255,.08) 75%),linear-gradient(45deg,rgba(255,255,255,.08) 25%,transparent 25% 75%,rgba(255,255,255,.08) 75%),#142033;background-position:0 0,8px 8px;background-size:16px 16px}.cultui-status-stage{display:grid;gap:8px;padding:12px;border:2px solid var(--panel-border);background:#061627eb}.cultui-field{display:grid;gap:4px}.cultui-field-value{display:block;border:2px solid var(--panel-border);background:#01040b94;padding:6px 8px}.cultui-world-scene{position:relative;z-index:2;width:100%;min-height:min(72vh,760px);overflow:hidden;outline:none;background:#02080c80}.cultui-world-scene:focus-visible{box-shadow:inset 0 0 0 2px var(--accent)}.cultui-world-heading{position:absolute;z-index:3;top:12px;left:12px;display:flex;gap:12px;align-items:baseline;color:var(--text);font-family:var(--font-mono);font-size:.75rem;pointer-events:none}.cultui-world-heading span{color:var(--quiet)}.cultui-world-plane{position:absolute;inset:0;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px);background-size:48px 48px}.cultui-world-entity{position:absolute;display:grid;justify-items:center;width:34px;height:34px;padding:0;border:1px solid rgba(224,238,240,.65);border-radius:50%;color:#f1f5f4;background:#182226eb;transform:translate(-50%,-50%);cursor:pointer}.cultui-world-entity.faction-player{border-color:#54d9c7;color:#9ff8e8}.cultui-world-entity.faction-raider,.cultui-world-entity.faction-hostile{border-color:#ff695f;color:#ffaaa3}.cultui-world-entity[data-controlled=true]{box-shadow:0 0 0 3px #ffbe4866}.cultui-world-entity-glyph{align-self:center;font:700 16px/1 var(--font-mono)}.cultui-world-entity-label{position:absolute;top:38px;width:max-content;max-width:132px;overflow:hidden;color:var(--text);font:600 11px/1.2 var(--font-body);text-overflow:ellipsis;white-space:nowrap;pointer-events:none}.cultui-swatch{width:36px;min-height:36px;border:2px solid var(--accent);box-shadow:inset 0 0 0 2px #00000073}.cultui-binding-map{position:relative;min-height:510px;border:1px solid var(--line);border-radius:6px;background:linear-gradient(var(--pixel-grid) 1px,transparent 1px),linear-gradient(90deg,var(--pixel-grid) 1px,transparent 1px),#030f11eb;background-size:28px 28px;overflow:hidden}.cultui-xbox-controller{position:absolute;inset:18px;width:calc(100% - 36px);height:calc(100% - 36px)}.cultui-xbox-controller .shell,.cultui-xbox-controller .stick,.cultui-xbox-controller .dpad,.cultui-xbox-controller .face,.cultui-xbox-controller .menu,.cultui-xbox-controller .guide,.cultui-xbox-controller .bumper,.cultui-xbox-controller .trigger{fill:#0a2423f0;stroke:var(--line);stroke-width:3}.cultui-xbox-controller .stick-dot,.cultui-xbox-controller .guide{fill:#8efcff1f}.cultui-xbox-controller .face{fill:#ffb84f29}.cultui-xbox-controller text{fill:var(--text);font:700 16px var(--font-mono);text-anchor:middle}.cultui-binding-line{stroke:var(--accent);stroke-width:2;stroke-dasharray:5 6;opacity:.78}.cultui-binding-overlay{position:absolute;inset:0}.cultui-binding-box{position:absolute;width:clamp(112px,12vw,138px);min-height:50px;transform:translate(-50%,-50%);display:grid;gap:4px;border:1px solid var(--line-hot);border-radius:6px;background:#071918f5;color:var(--text);padding:8px;text-align:left;box-shadow:0 10px 20px var(--shadow)}.cultui-binding-box:hover,.cultui-binding-box:focus-visible{border-color:var(--accent);color:var(--accent)}.cultui-binding-target{font:700 11px var(--font-mono);text-transform:uppercase}.cultui-binding-source{color:var(--quiet);font:600 11px var(--font-mono);overflow-wrap:anywhere}.cultui-modal-backdrop{position:fixed;inset:0;z-index:1000;display:grid;place-items:center;background:#00000094;padding:20px}.cultui-modal{width:min(680px,96vw);max-height:min(780px,92vh);display:grid;grid-template-rows:auto minmax(0,1fr);border:1px solid var(--line-hot);border-radius:6px;background:var(--panel);box-shadow:0 18px 42px #00000085;overflow:hidden}.cultui-modal-header{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 14px;border-bottom:1px solid var(--line);background:var(--shell-top)}.cultui-modal-header h2{margin:0;color:var(--accent);font:700 13px var(--font-mono);text-transform:uppercase}.cultui-modal-close{border:1px solid var(--line);border-radius:6px;background:var(--panel-2);color:var(--text);padding:7px 10px;font:700 11px var(--font-mono)}.cultui-modal-body{min-height:0;overflow:auto;padding:14px}@media(max-width:900px){.cultui-graph{right:12px;left:12px;width:auto;height:min(18rem,34vh)}.cultui-layer-cards{top:calc(30px + min(18rem,34vh));right:12px;left:12px}.cultui-rail-actions{left:12px;width:auto}}:root{color-scheme:dark;font-family:Crimson Pro,serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(920px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre{font-family:IBM Plex Mono,monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:15rem}form,.card{margin-top:1.5rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin-bottom:.65rem}textarea,input{box-sizing:border-box;width:100%;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.9rem;margin:.35rem 0;font:1.05rem/1.4 Crimson Pro,serif}textarea{min-height:7rem}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button{background:transparent;color:#d49b58}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}.compiler-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem}.cards{display:grid;gap:.7rem}.card h3{margin:.1rem 0}.card p{color:#b9c0b7}.warning{color:#e4a86a!important}@media(max-width:700px){.compiler-grid{grid-template-columns:1fr}}@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}} diff --git a/web/dist/index.html b/web/dist/index.html index 6e1e8d2..741548c 100644 --- a/web/dist/index.html +++ b/web/dist/index.html @@ -1,5 +1,11 @@ -GhostlightDungeon - +GhostlightDungeon + -

STARFIRE / PRIVATE VERSE

GhostlightDungeon

Reading the world…

+

STARFIRE / PRIVATE VERSE

GhostlightDungeon

Reading the world…

+
+
+
diff --git a/web/index.html b/web/index.html index 0c1a4d1..1a5ca63 100644 --- a/web/index.html +++ b/web/index.html @@ -1,3 +1,9 @@ GhostlightDungeon -

STARFIRE / PRIVATE VERSE

GhostlightDungeon

Reading the world…

+

STARFIRE / PRIVATE VERSE

GhostlightDungeon

Reading the world…

+
+
+
diff --git a/web/src/main.ts b/web/src/main.ts index 90d037e..5365df0 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -5,32 +5,54 @@ import "./style.css"; const host = document.querySelector("#surface")!; const status = document.querySelector("#status")!; const receipt = document.querySelector("#receipt")!; +const compiler = document.querySelector("#compiler")!; +const composer = document.querySelector("#composer")!; +const compilerResults = document.querySelector("#compiler-results")!; let revision = 0; -let actorId = "player"; async function refresh() { const response = await fetch("/api/surface"); if (response.status === 401) { status.textContent = "This laboratory requires an unused invite link."; return; } const surface = await response.json(); + const needsCompilation = surface.surface_id === "ghostlight.compiler"; + compiler.hidden = !needsCompilation; composer.hidden = needsCompilation; host.hidden = needsCompilation; + if (needsCompilation) { status.textContent = "No campaign exists. Retrieve the Vault and approve a world seed."; return; } revision = Number(surface.version ?? 0); renderEveSurface(surface, host, { body: document.body, clientId: "ghostlight.browser", statusElement: status }); } -async function send(command: unknown) { - status.textContent = "The world is considering the command…"; - const response = await fetch("/api/command", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(command) }); - const body = await response.json(); - receipt.hidden = false; - receipt.textContent = JSON.stringify(body, null, 2); - if (!response.ok) { status.textContent = body.error ?? "The command was refused."; return; } - await refresh(); +async function compilerPost(path: string, body: unknown) { + status.textContent = "Retrieving evidence and compiling…"; + const response = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const value = response.headers.get("content-type")?.includes("json") ? await response.json() : await response.text(); + if (!response.ok) { status.textContent = typeof value === "string" ? value : "Compilation failed"; throw new Error(status.textContent); } + return value; } -document.querySelector("#composer")!.addEventListener("submit", event => { +function showCards(items: any[], action: string, choose: (item: any) => void) { + compilerResults.innerHTML = `
${items.map((item, index) => `

${item.title ?? item.name}

${item.player_hook ?? item.premise}

${item.era ? `${item.era} · ${item.place} · ${item.pressure}` : ""}

`).join("")}
`; + compilerResults.querySelectorAll("button").forEach(button => button.addEventListener("click", () => choose(items[Number(button.dataset.index)]))); +} + +document.querySelector("#suggest-form")!.addEventListener("submit", async event => { event.preventDefault(); - const text = document.querySelector("#attempt")!.value.trim(); - if (!text) return; - void send({ type: "assess", expected_revision: revision, intent: { actor_id: actorId, description: text, intended_effect: text } }); + const result = await compilerPost("/api/compiler/openings", { setting: document.querySelector("#setting")!.value, constraints: [] }); + showCards(result.openings, "Choose opening", async opening => { + const roles = await compilerPost("/api/compiler/roles", opening); + showCards(roles.roles, "Choose role", async role => showPreview(await compilerPost("/api/compiler/selected", { campaign_name: opening.title, opening, role }))); + }); }); + +document.querySelector("#custom-form")!.addEventListener("submit", async event => { event.preventDefault(); await showPreview(await compilerPost("/api/compiler/custom", Object.fromEntries(new FormData(event.currentTarget as HTMLFormElement)))); }); + +async function showPreview(result: any) { + const preview = result.preview; + compilerResults.innerHTML = `

${preview.title}

${preview.campaign.transcript?.[0]?.text ?? ""}

${Object.keys(preview.campaign.locations).length} locations · ${Object.keys(preview.campaign.actors).length} actors · ${Object.keys(preview.campaign.institutions).length} institutions

${preview.gaps.length ? `Material gaps: ${preview.gaps.join("; ")}` : "No declared material gaps."}

Branch assumptions: ${preview.branch_assumptions.join("; ") || "none"}

`; + document.querySelector("#approve-world")!.addEventListener("click", async () => { await compilerPost(`/api/compiler/approve/${result.preview_id}`, {}); await refresh(); }); + status.textContent = "Preview compiled. Nothing has entered world state yet."; +} + +async function send(command: unknown) { status.textContent = "The world is considering the command…"; const response = await fetch("/api/command", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(command) }); const body = await response.json(); receipt.hidden = false; receipt.textContent = JSON.stringify(body, null, 2); if (!response.ok) { status.textContent = body.error ?? "The command was refused."; return; } await refresh(); } +composer.addEventListener("submit", event => { event.preventDefault(); const text = document.querySelector("#attempt")!.value.trim(); if (text) void send({ type: "assess", expected_revision: revision, intent: { actor_id: "player", description: text, intended_effect: text } }); }); document.querySelector("#wait")!.addEventListener("click", () => void send({ type: "wait", expected_revision: revision, minutes: 60 })); void refresh(); diff --git a/web/src/style.css b/web/src/style.css index 505e5d2..9b82016 100644 --- a/web/src/style.css +++ b/web/src/style.css @@ -1,2 +1,2 @@ @import url('https://fonts.googleapis.com/css2?family=Crimson+Pro:opsz,wght@8..144,400;8..144,600&family=IBM+Plex+Mono:wght@400;600&display=swap'); -:root{color-scheme:dark;font-family:"Crimson Pro",serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(920px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre{font-family:"IBM Plex Mono",monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:15rem}form{margin-top:1.5rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin-bottom:.65rem}textarea{box-sizing:border-box;width:100%;min-height:7rem;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.9rem;font:1.25rem/1.4 "Crimson Pro",serif}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button{background:transparent;color:#d49b58}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}} +:root{color-scheme:dark;font-family:"Crimson Pro",serif;background:#0c1110;color:#e8e1cf}body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)}header,main{width:min(920px,calc(100% - 2rem));margin:auto}header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d}h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0}.eyebrow,#status,label,button,pre{font-family:"IBM Plex Mono",monospace}.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem}#status{color:#9aa69f;font-size:.78rem}main{padding:1.5rem 0 5rem}#surface{min-height:15rem}form,.card{margin-top:1.5rem;padding:1rem;border:1px solid #66543d;background:#17201ddd}label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin-bottom:.65rem}textarea,input{box-sizing:border-box;width:100%;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.9rem;margin:.35rem 0;font:1.05rem/1.4 "Crimson Pro",serif}textarea{min-height:7rem}button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer}button+button{background:transparent;color:#d49b58}pre{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font-size:.72rem}.compiler-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem}.cards{display:grid;gap:.7rem}.card h3{margin:.1rem 0}.card p{color:#b9c0b7}.warning{color:#e4a86a!important}@media(max-width:700px){.compiler-grid{grid-template-columns:1fr}}@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}}