Build GhostlightDungeon kernel and private Eve harness
This commit is contained in:
parent
e4204debd9
commit
6f51f3a4a3
24 changed files with 5159 additions and 0 deletions
3
.gitmodules
vendored
3
.gitmodules
vendored
|
|
@ -1,3 +1,6 @@
|
|||
[submodule "vendor/cultcache-py"]
|
||||
path = vendor/cultcache-py
|
||||
url = https://github.com/GameCult/cultcache-py.git
|
||||
[submodule "vendor/eve"]
|
||||
path = vendor/eve
|
||||
url = https://github.com/GameCult/Eve.git
|
||||
|
|
|
|||
2180
Cargo.lock
generated
Normal file
2180
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
29
Cargo.toml
Normal file
29
Cargo.toml
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
[workspace]
|
||||
members = ["crates/ghostlight-dungeon"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
version = "0.1.0"
|
||||
|
||||
[workspace.dependencies]
|
||||
anyhow = "1"
|
||||
async-trait = "0.1"
|
||||
axum = { version = "0.8", features = ["macros"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
cultcache-rs = { git = "https://github.com/GameCult/cultcache-rs.git", rev = "0ba87453115e3d44e8fcb7419866cd7dd70fb096" }
|
||||
rand = "0.9"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }
|
||||
rmp-serde = "1.3"
|
||||
schemars = { version = "1", features = ["chrono04", "uuid1"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tower-http = { version = "0.6", features = ["fs", "trace"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
uuid = { version = "1", features = ["v4", "serde"] }
|
||||
|
||||
29
crates/ghostlight-dungeon/Cargo.toml
Normal file
29
crates/ghostlight-dungeon/Cargo.toml
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
[package]
|
||||
name = "ghostlight-dungeon"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
async-trait.workspace = true
|
||||
axum.workspace = true
|
||||
chrono.workspace = true
|
||||
cultcache-rs.workspace = true
|
||||
rand.workspace = true
|
||||
reqwest.workspace = true
|
||||
rmp-serde.workspace = true
|
||||
schemars.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio.workspace = true
|
||||
tower-http.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
76
crates/ghostlight-dungeon/src/d20.rs
Normal file
76
crates/ghostlight-dungeon/src/d20.rs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
use crate::domain::{OutcomeBand, RollReceipt};
|
||||
|
||||
pub fn capped_modifier(values: impl IntoIterator<Item = i8>) -> i8 {
|
||||
values
|
||||
.into_iter()
|
||||
.map(i16::from)
|
||||
.sum::<i16>()
|
||||
.clamp(-10, 10) as i8
|
||||
}
|
||||
|
||||
pub fn outcome(d20: u8, modifier: i8, dc: u8) -> OutcomeBand {
|
||||
let total = i16::from(d20) + i16::from(modifier);
|
||||
let base = if total >= i16::from(dc) + 10 {
|
||||
OutcomeBand::StrongSuccess
|
||||
} else if total >= i16::from(dc) {
|
||||
OutcomeBand::Success
|
||||
} else if total >= i16::from(dc) - 5 {
|
||||
OutcomeBand::Mixed
|
||||
} else {
|
||||
OutcomeBand::Failure
|
||||
};
|
||||
shift(
|
||||
base,
|
||||
if d20 == 20 {
|
||||
1
|
||||
} else if d20 == 1 {
|
||||
-1
|
||||
} else {
|
||||
0
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn shift(band: OutcomeBand, delta: i8) -> OutcomeBand {
|
||||
use OutcomeBand::*;
|
||||
match (band, delta) {
|
||||
(Failure, 1) => Mixed,
|
||||
(Mixed, 1) => Success,
|
||||
(Success, 1) => StrongSuccess,
|
||||
(StrongSuccess, -1) => Success,
|
||||
(Success, -1) => Mixed,
|
||||
(Mixed, -1) => Failure,
|
||||
(value, _) => value,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn receipt(digest: String, d20: u8, modifier: i8, dc: u8) -> RollReceipt {
|
||||
RollReceipt {
|
||||
schema: "ghostlight.roll_receipt.v1".into(),
|
||||
assessment_digest: digest,
|
||||
d20,
|
||||
modifier_total: modifier,
|
||||
total: i16::from(d20) + i16::from(modifier),
|
||||
dc,
|
||||
outcome: outcome(d20, modifier, dc),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn caps_context_not_attributes() {
|
||||
assert_eq!(capped_modifier([8, 7, -2]), 10);
|
||||
}
|
||||
#[test]
|
||||
fn margin_bands_hold() {
|
||||
assert_eq!(outcome(10, 0, 15), OutcomeBand::Mixed);
|
||||
assert_eq!(outcome(15, 0, 15), OutcomeBand::Success);
|
||||
assert_eq!(outcome(20, 5, 15), OutcomeBand::StrongSuccess);
|
||||
}
|
||||
#[test]
|
||||
fn natural_one_only_shifts_one_band() {
|
||||
assert_eq!(outcome(1, 10, 5), OutcomeBand::Mixed);
|
||||
}
|
||||
}
|
||||
236
crates/ghostlight-dungeon/src/domain.rs
Normal file
236
crates/ghostlight-dungeon/src/domain.rs
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
use chrono::{DateTime, Utc};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct Campaign {
|
||||
pub schema: String,
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub revision: u64,
|
||||
pub branch_origin: BranchOrigin,
|
||||
pub world_time: DateTime<Utc>,
|
||||
pub tick_hours: u32,
|
||||
pub player_actor_id: String,
|
||||
pub locations: BTreeMap<String, Location>,
|
||||
pub actors: BTreeMap<String, ActorState>,
|
||||
pub institutions: BTreeMap<String, InstitutionState>,
|
||||
pub clocks: BTreeMap<String, WorldClock>,
|
||||
pub facts: BTreeMap<String, WorldFact>,
|
||||
pub transcript: Vec<NarrativeTurn>,
|
||||
pub last_player_activity: DateTime<Utc>,
|
||||
pub pending_ticks: u8,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct BranchOrigin {
|
||||
pub canon_cutoff: String,
|
||||
pub evidence_receipt_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct Location {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub container_id: Option<String>,
|
||||
pub routes: BTreeMap<String, Route>,
|
||||
pub persistent_features: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct Route {
|
||||
pub destination_id: String,
|
||||
pub distance: String,
|
||||
pub travel_minutes: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct ActorState {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub location_id: String,
|
||||
pub capabilities: BTreeSet<String>,
|
||||
pub knowledge: BTreeSet<String>,
|
||||
pub equipment: BTreeSet<String>,
|
||||
pub conditions: BTreeSet<String>,
|
||||
pub obligations: BTreeSet<String>,
|
||||
pub relationships: BTreeMap<String, String>,
|
||||
pub goals: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct InstitutionState {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub resources: Vec<String>,
|
||||
pub goals: Vec<String>,
|
||||
pub posture: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct WorldClock {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub progress: u8,
|
||||
pub threshold: u8,
|
||||
pub consequence: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct WorldFact {
|
||||
pub id: String,
|
||||
pub statement: String,
|
||||
pub scope: FactScope,
|
||||
pub evidence_receipt_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum FactScope {
|
||||
CanonBaseline,
|
||||
BranchLocal,
|
||||
ProvisionalLocal,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct NarrativeTurn {
|
||||
pub revision: u64,
|
||||
pub at: DateTime<Utc>,
|
||||
pub speaker: String,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct ActionIntent {
|
||||
pub actor_id: String,
|
||||
pub description: String,
|
||||
pub intended_effect: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum WorldCommand {
|
||||
CreateCampaign {
|
||||
campaign: Campaign,
|
||||
},
|
||||
Speak {
|
||||
expected_revision: u64,
|
||||
actor_id: String,
|
||||
text: String,
|
||||
intended_effect: Option<String>,
|
||||
},
|
||||
Assess {
|
||||
expected_revision: u64,
|
||||
intent: ActionIntent,
|
||||
},
|
||||
Attempt {
|
||||
assessment_digest: String,
|
||||
},
|
||||
Wait {
|
||||
expected_revision: u64,
|
||||
minutes: u32,
|
||||
},
|
||||
AdvanceStrategicTick {
|
||||
expected_revision: u64,
|
||||
source: TickSource,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TickSource {
|
||||
Scheduler,
|
||||
ReturnCatchUp,
|
||||
PlayerWait,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct ContextModifier {
|
||||
pub label: String,
|
||||
pub value: i8,
|
||||
pub references: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct ActionAssessment {
|
||||
pub schema: String,
|
||||
pub campaign_id: Uuid,
|
||||
pub revision: u64,
|
||||
pub intent: ActionIntent,
|
||||
pub admissible: bool,
|
||||
pub missing_permission: Option<String>,
|
||||
pub dc: u8,
|
||||
pub modifiers: Vec<ContextModifier>,
|
||||
pub modifier_total: i8,
|
||||
pub effect_ceiling: String,
|
||||
pub success_stake: String,
|
||||
pub mixed_stake: String,
|
||||
pub failure_stake: String,
|
||||
pub bargains: Vec<String>,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
pub digest: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OutcomeBand {
|
||||
Failure,
|
||||
Mixed,
|
||||
Success,
|
||||
StrongSuccess,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct RollReceipt {
|
||||
pub schema: String,
|
||||
pub assessment_digest: String,
|
||||
pub d20: u8,
|
||||
pub modifier_total: i8,
|
||||
pub total: i16,
|
||||
pub dc: u8,
|
||||
pub outcome: OutcomeBand,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct WorldCommitReceipt {
|
||||
pub schema: String,
|
||||
pub campaign_id: Uuid,
|
||||
pub previous_revision: u64,
|
||||
pub revision: u64,
|
||||
pub command_kind: String,
|
||||
pub committed_at: DateTime<Utc>,
|
||||
pub roll: Option<RollReceipt>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct VaultEvidenceReceipt {
|
||||
pub schema: String,
|
||||
pub id: String,
|
||||
pub provider: String,
|
||||
pub query_hash: String,
|
||||
pub witnesses: Vec<SourceWitness>,
|
||||
pub retrieved_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct SourceWitness {
|
||||
pub source_id: String,
|
||||
pub exact_locator: String,
|
||||
pub content_hash: String,
|
||||
pub excerpt: String,
|
||||
pub authority_lane: String,
|
||||
pub temporal_scope: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
|
||||
pub struct WorldCompilePreview {
|
||||
pub schema: String,
|
||||
pub title: String,
|
||||
pub campaign: Campaign,
|
||||
pub evidence_receipts: Vec<VaultEvidenceReceipt>,
|
||||
pub gaps: Vec<String>,
|
||||
pub branch_assumptions: Vec<String>,
|
||||
pub requires_approval: bool,
|
||||
}
|
||||
423
crates/ghostlight-dungeon/src/kernel.rs
Normal file
423
crates/ghostlight-dungeon/src/kernel.rs
Normal file
|
|
@ -0,0 +1,423 @@
|
|||
use crate::d20::{capped_modifier, receipt};
|
||||
use crate::domain::*;
|
||||
use crate::persistence::CampaignStore;
|
||||
use chrono::{Duration, Utc};
|
||||
use rand::Rng;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeMap;
|
||||
use thiserror::Error;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum KernelError {
|
||||
#[error("campaign not found")]
|
||||
NotFound,
|
||||
#[error("stale revision: expected {expected}, actual {actual}")]
|
||||
Stale { expected: u64, actual: u64 },
|
||||
#[error("action is impossible: {0}")]
|
||||
Impossible(String),
|
||||
#[error("assessment is stale or unknown")]
|
||||
StaleAssessment,
|
||||
#[error("invalid command: {0}")]
|
||||
Invalid(String),
|
||||
#[error("persistence failure: {0}")]
|
||||
Persistence(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum CommandResult {
|
||||
Created {
|
||||
campaign: Campaign,
|
||||
},
|
||||
Assessed {
|
||||
assessment: ActionAssessment,
|
||||
},
|
||||
Committed {
|
||||
campaign: Campaign,
|
||||
receipt: WorldCommitReceipt,
|
||||
},
|
||||
}
|
||||
|
||||
struct Request {
|
||||
command: WorldCommand,
|
||||
reply: oneshot::Sender<Result<CommandResult, KernelError>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WorldKernel {
|
||||
tx: mpsc::Sender<Request>,
|
||||
}
|
||||
|
||||
impl WorldKernel {
|
||||
pub fn start(store: CampaignStore) -> Self {
|
||||
let (tx, mut rx) = mpsc::channel::<Request>(64);
|
||||
tokio::spawn(async move {
|
||||
let mut assessments = BTreeMap::new();
|
||||
while let Some(request) = rx.recv().await {
|
||||
let result = execute(&store, &mut assessments, request.command);
|
||||
let _ = request.reply.send(result);
|
||||
}
|
||||
});
|
||||
Self { tx }
|
||||
}
|
||||
pub async fn command(&self, command: WorldCommand) -> Result<CommandResult, KernelError> {
|
||||
let (reply, receive) = oneshot::channel();
|
||||
self.tx
|
||||
.send(Request { command, reply })
|
||||
.await
|
||||
.map_err(|_| KernelError::Invalid("kernel stopped".into()))?;
|
||||
receive
|
||||
.await
|
||||
.map_err(|_| KernelError::Invalid("kernel stopped".into()))?
|
||||
}
|
||||
}
|
||||
|
||||
fn execute(
|
||||
store: &CampaignStore,
|
||||
assessments: &mut BTreeMap<String, ActionAssessment>,
|
||||
command: WorldCommand,
|
||||
) -> Result<CommandResult, KernelError> {
|
||||
if let WorldCommand::CreateCampaign { campaign } = command {
|
||||
store
|
||||
.insert(
|
||||
"campaign.v1",
|
||||
"ghostlight.campaign.v1",
|
||||
&campaign.id.to_string(),
|
||||
&campaign,
|
||||
)
|
||||
.map_err(persist)?;
|
||||
return Ok(CommandResult::Created { campaign });
|
||||
}
|
||||
let campaign_id = single_campaign_id(store)?;
|
||||
let (row, mut campaign): (_, Campaign) = store
|
||||
.load("campaign.v1", &campaign_id)
|
||||
.map_err(persist)?
|
||||
.ok_or(KernelError::NotFound)?;
|
||||
match command {
|
||||
WorldCommand::Assess {
|
||||
expected_revision,
|
||||
intent,
|
||||
} => {
|
||||
require_revision(&campaign, expected_revision)?;
|
||||
let assessment = assess(&campaign, intent);
|
||||
assessments.insert(assessment.digest.clone(), assessment.clone());
|
||||
Ok(CommandResult::Assessed { assessment })
|
||||
}
|
||||
WorldCommand::Attempt { assessment_digest } => {
|
||||
let assessment = assessments
|
||||
.remove(&assessment_digest)
|
||||
.ok_or(KernelError::StaleAssessment)?;
|
||||
if assessment.revision != campaign.revision || assessment.expires_at < Utc::now() {
|
||||
return Err(KernelError::StaleAssessment);
|
||||
}
|
||||
if !assessment.admissible {
|
||||
return Err(KernelError::Impossible(
|
||||
assessment
|
||||
.missing_permission
|
||||
.unwrap_or_else(|| "not admissible".into()),
|
||||
));
|
||||
}
|
||||
let roll = receipt(
|
||||
assessment.digest.clone(),
|
||||
rand::rng().random_range(1..=20),
|
||||
assessment.modifier_total,
|
||||
assessment.dc,
|
||||
);
|
||||
let text = match roll.outcome {
|
||||
OutcomeBand::StrongSuccess => &assessment.success_stake,
|
||||
OutcomeBand::Success => &assessment.success_stake,
|
||||
OutcomeBand::Mixed => &assessment.mixed_stake,
|
||||
OutcomeBand::Failure => &assessment.failure_stake,
|
||||
};
|
||||
campaign.transcript.push(NarrativeTurn {
|
||||
revision: campaign.revision + 1,
|
||||
at: Utc::now(),
|
||||
speaker: "world".into(),
|
||||
text: text.clone(),
|
||||
});
|
||||
commit(store, row, campaign, "attempt", Some(roll))
|
||||
}
|
||||
WorldCommand::Speak {
|
||||
expected_revision,
|
||||
actor_id,
|
||||
text,
|
||||
intended_effect,
|
||||
} => {
|
||||
require_revision(&campaign, expected_revision)?;
|
||||
if !campaign.actors.contains_key(&actor_id) {
|
||||
return Err(KernelError::Invalid("unknown actor".into()));
|
||||
}
|
||||
campaign.transcript.push(NarrativeTurn {
|
||||
revision: campaign.revision + 1,
|
||||
at: Utc::now(),
|
||||
speaker: actor_id,
|
||||
text,
|
||||
});
|
||||
if let Some(effect) = intended_effect {
|
||||
campaign.transcript.push(NarrativeTurn {
|
||||
revision: campaign.revision + 1,
|
||||
at: Utc::now(),
|
||||
speaker: "system".into(),
|
||||
text: format!("Intended effect requires assessment: {effect}"),
|
||||
});
|
||||
}
|
||||
campaign.last_player_activity = Utc::now();
|
||||
commit(store, row, campaign, "speak", None)
|
||||
}
|
||||
WorldCommand::Wait {
|
||||
expected_revision,
|
||||
minutes,
|
||||
} => {
|
||||
require_revision(&campaign, expected_revision)?;
|
||||
campaign.world_time += Duration::minutes(i64::from(minutes));
|
||||
campaign.last_player_activity = Utc::now();
|
||||
commit(store, row, campaign, "wait", None)
|
||||
}
|
||||
WorldCommand::AdvanceStrategicTick {
|
||||
expected_revision,
|
||||
source: _,
|
||||
} => {
|
||||
require_revision(&campaign, expected_revision)?;
|
||||
campaign.world_time += Duration::hours(i64::from(campaign.tick_hours));
|
||||
for clock in campaign.clocks.values_mut() {
|
||||
clock.progress = clock.progress.saturating_add(1).min(clock.threshold);
|
||||
}
|
||||
campaign.pending_ticks = campaign.pending_ticks.saturating_sub(1);
|
||||
commit(store, row, campaign, "strategic_tick", None)
|
||||
}
|
||||
WorldCommand::CreateCampaign { .. } => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn single_campaign_id(store: &CampaignStore) -> Result<String, KernelError> {
|
||||
let keys = store.keys("campaign.v1").map_err(persist)?;
|
||||
match keys.as_slice() {
|
||||
[id] => Ok(id.clone()),
|
||||
[] => Err(KernelError::NotFound),
|
||||
_ => Err(KernelError::Invalid(
|
||||
"a campaign store must contain exactly one campaign".into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn require_revision(c: &Campaign, expected: u64) -> Result<(), KernelError> {
|
||||
if c.revision == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(KernelError::Stale {
|
||||
expected,
|
||||
actual: c.revision,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn assess(c: &Campaign, intent: ActionIntent) -> ActionAssessment {
|
||||
let actor = c.actors.get(&intent.actor_id);
|
||||
let admissible = actor.is_some() && !intent.description.trim().is_empty();
|
||||
let missing = if actor.is_none() {
|
||||
Some("actor does not exist in this branch".into())
|
||||
} else if intent.description.trim().is_empty() {
|
||||
Some("no attempt was described".into())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let modifiers = vec![];
|
||||
let modifier_total = capped_modifier(modifiers.iter().map(|m: &ContextModifier| m.value));
|
||||
let mut a = ActionAssessment {
|
||||
schema: "ghostlight.player_action_assessment.v1".into(),
|
||||
campaign_id: c.id,
|
||||
revision: c.revision,
|
||||
intent,
|
||||
admissible,
|
||||
missing_permission: missing,
|
||||
dc: 15,
|
||||
modifiers,
|
||||
modifier_total,
|
||||
effect_ceiling:
|
||||
"A bounded local consequence; no unsupported world fact or custody transfer.".into(),
|
||||
success_stake: "The intended local effect succeeds and the world reacts.".into(),
|
||||
mixed_stake: "The effect lands with the previewed cost or complication.".into(),
|
||||
failure_stake: "Opposition holds and gains a concrete advantage.".into(),
|
||||
bargains: if admissible {
|
||||
vec![]
|
||||
} else {
|
||||
vec![
|
||||
"Narrow the effect, obtain access, recruit help, or accept a concrete sacrifice."
|
||||
.into(),
|
||||
]
|
||||
},
|
||||
expires_at: Utc::now() + Duration::minutes(10),
|
||||
digest: String::new(),
|
||||
};
|
||||
let bytes = rmp_serde::to_vec_named(&a).expect("assessment serializes");
|
||||
a.digest = format!("sha256:{:x}", Sha256::digest(bytes));
|
||||
a
|
||||
}
|
||||
|
||||
fn commit(
|
||||
store: &CampaignStore,
|
||||
row: cultcache_rs::CultCacheEnvelope,
|
||||
mut campaign: Campaign,
|
||||
kind: &str,
|
||||
roll: Option<RollReceipt>,
|
||||
) -> Result<CommandResult, KernelError> {
|
||||
let previous_revision = campaign.revision;
|
||||
campaign.revision += 1;
|
||||
let receipt = WorldCommitReceipt {
|
||||
schema: "ghostlight.world_commit_receipt.v1".into(),
|
||||
campaign_id: campaign.id,
|
||||
previous_revision,
|
||||
revision: campaign.revision,
|
||||
command_kind: kind.into(),
|
||||
committed_at: Utc::now(),
|
||||
roll,
|
||||
};
|
||||
store
|
||||
.append_with_replace(
|
||||
&row,
|
||||
"ghostlight.campaign.v1",
|
||||
&campaign,
|
||||
"world_commit_receipt.v1",
|
||||
"ghostlight.world_commit_receipt.v1",
|
||||
&format!("{}-{}", campaign.id, campaign.revision),
|
||||
&receipt,
|
||||
)
|
||||
.map_err(persist)?;
|
||||
Ok(CommandResult::Committed { campaign, receipt })
|
||||
}
|
||||
|
||||
fn persist(e: anyhow::Error) -> KernelError {
|
||||
KernelError::Persistence(e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
fn campaign() -> Campaign {
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let actor = ActorState {
|
||||
id: "player".into(),
|
||||
name: "Player".into(),
|
||||
location_id: "room".into(),
|
||||
capabilities: BTreeSet::new(),
|
||||
knowledge: BTreeSet::new(),
|
||||
equipment: BTreeSet::new(),
|
||||
conditions: BTreeSet::new(),
|
||||
obligations: BTreeSet::new(),
|
||||
relationships: BTreeMap::new(),
|
||||
goals: vec![],
|
||||
};
|
||||
Campaign {
|
||||
schema: "ghostlight.campaign.v1".into(),
|
||||
id,
|
||||
name: "Test".into(),
|
||||
revision: 0,
|
||||
branch_origin: BranchOrigin {
|
||||
canon_cutoff: "test".into(),
|
||||
evidence_receipt_ids: vec![],
|
||||
},
|
||||
world_time: Utc::now(),
|
||||
tick_hours: 6,
|
||||
player_actor_id: "player".into(),
|
||||
locations: BTreeMap::from([(
|
||||
"room".into(),
|
||||
Location {
|
||||
id: "room".into(),
|
||||
name: "Room".into(),
|
||||
container_id: None,
|
||||
routes: BTreeMap::new(),
|
||||
persistent_features: vec!["stable".into()],
|
||||
},
|
||||
)]),
|
||||
actors: BTreeMap::from([("player".into(), actor)]),
|
||||
institutions: BTreeMap::new(),
|
||||
clocks: BTreeMap::new(),
|
||||
facts: BTreeMap::new(),
|
||||
transcript: vec![],
|
||||
last_player_activity: Utc::now(),
|
||||
pending_ticks: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_command_cannot_mutate_campaign() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap();
|
||||
let kernel = WorldKernel::start(store.clone());
|
||||
let seed = campaign();
|
||||
kernel
|
||||
.command(WorldCommand::CreateCampaign {
|
||||
campaign: seed.clone(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
kernel
|
||||
.command(WorldCommand::Wait {
|
||||
expected_revision: 0,
|
||||
minutes: 30,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let stale = kernel
|
||||
.command(WorldCommand::Wait {
|
||||
expected_revision: 0,
|
||||
minutes: 30,
|
||||
})
|
||||
.await;
|
||||
assert!(matches!(stale, Err(KernelError::Stale { actual: 1, .. })));
|
||||
let (_, stored): (_, Campaign) = store
|
||||
.load("campaign.v1", &seed.id.to_string())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(stored.revision, 1);
|
||||
assert_eq!(stored.world_time, seed.world_time + Duration::minutes(30));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn assessment_is_private_and_attempt_commits_roll_atomically() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap();
|
||||
let kernel = WorldKernel::start(store.clone());
|
||||
let seed = campaign();
|
||||
kernel
|
||||
.command(WorldCommand::CreateCampaign {
|
||||
campaign: seed.clone(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let result = kernel
|
||||
.command(WorldCommand::Assess {
|
||||
expected_revision: 0,
|
||||
intent: ActionIntent {
|
||||
actor_id: "player".into(),
|
||||
description: "Open the ordinary door".into(),
|
||||
intended_effect: "Pass through".into(),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let CommandResult::Assessed { assessment } = result else {
|
||||
panic!("expected assessment")
|
||||
};
|
||||
let (_, before): (_, Campaign) = store
|
||||
.load("campaign.v1", &seed.id.to_string())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(before.revision, 0);
|
||||
let result = kernel
|
||||
.command(WorldCommand::Attempt {
|
||||
assessment_digest: assessment.digest,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let CommandResult::Committed { campaign, receipt } = result else {
|
||||
panic!("expected commit")
|
||||
};
|
||||
assert_eq!(campaign.revision, 1);
|
||||
assert!(receipt.roll.is_some());
|
||||
assert_eq!(store.keys("world_commit_receipt.v1").unwrap().len(), 1);
|
||||
}
|
||||
}
|
||||
10
crates/ghostlight-dungeon/src/lib.rs
Normal file
10
crates/ghostlight-dungeon/src/lib.rs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
pub mod d20;
|
||||
pub mod domain;
|
||||
pub mod kernel;
|
||||
pub mod model;
|
||||
pub mod persistence;
|
||||
pub mod persona;
|
||||
pub mod surface;
|
||||
pub mod vault;
|
||||
|
||||
pub use kernel::{KernelError, WorldKernel};
|
||||
209
crates/ghostlight-dungeon/src/main.rs
Normal file
209
crates/ghostlight-dungeon/src/main.rs
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, HeaderValue, StatusCode, header},
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use ghostlight_dungeon::{
|
||||
WorldKernel,
|
||||
domain::{Campaign, WorldCommand},
|
||||
persistence::CampaignStore,
|
||||
surface::player_surface,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
net::SocketAddr,
|
||||
path::PathBuf,
|
||||
sync::Arc,
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
use tower_http::services::ServeDir;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
kernel: WorldKernel,
|
||||
store: CampaignStore,
|
||||
invites: Arc<Mutex<BTreeSet<String>>>,
|
||||
sessions: Arc<Mutex<BTreeSet<String>>>,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env())
|
||||
.init();
|
||||
let runtime_root = std::env::var_os("GHOSTLIGHT_DUNGEON_ROOT")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(r"F:\GameCult\GhostlightDungeon"));
|
||||
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_tokens = std::env::var("GHOSTLIGHT_INVITES")
|
||||
.unwrap_or_else(|_| "tester-one,tester-two".into())
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let state = AppState {
|
||||
kernel,
|
||||
store,
|
||||
invites: Arc::new(Mutex::new(invite_tokens)),
|
||||
sessions: Arc::new(Mutex::new(BTreeSet::new())),
|
||||
};
|
||||
let web_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../web/dist");
|
||||
let app = Router::new()
|
||||
.route("/health", get(health))
|
||||
.route("/invite/{token}", get(invite))
|
||||
.route("/api/surface", get(surface))
|
||||
.route("/api/command", post(command))
|
||||
.fallback_service(ServeDir::new(web_root).append_index_html_on_directories(true))
|
||||
.with_state(state);
|
||||
let address: SocketAddr = "0.0.0.0:8831".parse()?;
|
||||
let listener = tokio::net::TcpListener::bind(address).await?;
|
||||
tracing::info!(%address, "GhostlightDungeon listening");
|
||||
axum::serve(listener, app).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn health(State(state): State<AppState>) -> Json<serde_json::Value> {
|
||||
Json(
|
||||
serde_json::json!({"schema":"ghostlight.service_health.v1","status":"ok","storeIdentity":state.store.identity()}),
|
||||
)
|
||||
}
|
||||
|
||||
async fn invite(Path(token): Path<String>, State(state): State<AppState>) -> Response {
|
||||
if !state.invites.lock().await.remove(&token) {
|
||||
return (StatusCode::UNAUTHORIZED, "invalid or consumed invite").into_response();
|
||||
}
|
||||
let session = uuid::Uuid::new_v4().to_string();
|
||||
state.sessions.lock().await.insert(session.clone());
|
||||
let mut response = Redirect::to("/").into_response();
|
||||
response.headers_mut().insert(
|
||||
header::SET_COOKIE,
|
||||
HeaderValue::from_str(&format!(
|
||||
"ghostlight_session={session}; HttpOnly; SameSite=Strict; Path=/"
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
async fn surface(headers: HeaderMap, State(state): State<AppState>) -> Response {
|
||||
if !authorized(&headers, &state).await {
|
||||
return StatusCode::UNAUTHORIZED.into_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(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn command(
|
||||
headers: HeaderMap,
|
||||
State(state): State<AppState>,
|
||||
Json(command): Json<WorldCommand>,
|
||||
) -> Response {
|
||||
if !authorized(&headers, &state).await {
|
||||
return StatusCode::UNAUTHORIZED.into_response();
|
||||
}
|
||||
match state.kernel.command(command).await {
|
||||
Ok(result) => Json(result).into_response(),
|
||||
Err(error) => (
|
||||
StatusCode::CONFLICT,
|
||||
Json(ErrorBody {
|
||||
error: error.to_string(),
|
||||
}),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn authorized(headers: &HeaderMap, state: &AppState) -> bool {
|
||||
let session = headers
|
||||
.get(header::COOKIE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|cookies| {
|
||||
cookies
|
||||
.split(';')
|
||||
.map(str::trim)
|
||||
.find_map(|cookie| cookie.strip_prefix("ghostlight_session="))
|
||||
});
|
||||
match session {
|
||||
Some(id) => state.sessions.lock().await.contains(id),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn load_campaign(store: &CampaignStore) -> anyhow::Result<Campaign> {
|
||||
let id = store
|
||||
.keys("campaign.v1")?
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("campaign missing"))?;
|
||||
store
|
||||
.load("campaign.v1", &id)?
|
||||
.map(|(_, c)| c)
|
||||
.ok_or_else(|| anyhow::anyhow!("campaign missing"))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ErrorBody {
|
||||
error: String,
|
||||
}
|
||||
|
||||
fn seed_campaign() -> Campaign {
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let location = ghostlight_dungeon::domain::Location {
|
||||
id: "starfire-lab".into(),
|
||||
name: "Starfire Narrative Laboratory".into(),
|
||||
container_id: None,
|
||||
routes: BTreeMap::new(),
|
||||
persistent_features: vec![
|
||||
"A stable room waiting for an approved world compilation.".into(),
|
||||
],
|
||||
};
|
||||
let actor = ghostlight_dungeon::domain::ActorState {
|
||||
id: "player".into(),
|
||||
name: "Tester".into(),
|
||||
location_id: location.id.clone(),
|
||||
capabilities: BTreeSet::new(),
|
||||
knowledge: BTreeSet::new(),
|
||||
equipment: BTreeSet::new(),
|
||||
conditions: BTreeSet::new(),
|
||||
obligations: BTreeSet::new(),
|
||||
relationships: BTreeMap::new(),
|
||||
goals: vec!["Compile a world worth entering.".into()],
|
||||
};
|
||||
Campaign {
|
||||
schema: "ghostlight.campaign.v1".into(),
|
||||
id,
|
||||
name: "GhostlightDungeon MVP".into(),
|
||||
revision: 0,
|
||||
branch_origin: ghostlight_dungeon::domain::BranchOrigin {
|
||||
canon_cutoff: "fixture-development".into(),
|
||||
evidence_receipt_ids: vec![],
|
||||
},
|
||||
world_time: chrono::Utc::now(),
|
||||
tick_hours: 6,
|
||||
player_actor_id: actor.id.clone(),
|
||||
locations: BTreeMap::from([(location.id.clone(), location)]),
|
||||
actors: BTreeMap::from([(actor.id.clone(), actor)]),
|
||||
institutions: BTreeMap::new(),
|
||||
clocks: BTreeMap::new(),
|
||||
facts: BTreeMap::new(),
|
||||
transcript: vec![],
|
||||
last_player_activity: chrono::Utc::now(),
|
||||
pending_ticks: 0,
|
||||
}
|
||||
}
|
||||
143
crates/ghostlight-dungeon/src/model.rs
Normal file
143
crates/ghostlight-dungeon/src/model.rs
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
use anyhow::{Result, anyhow};
|
||||
use async_trait::async_trait;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::time::Instant;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct ModelStageRequest {
|
||||
pub stage: String,
|
||||
pub model: String,
|
||||
pub snapshot_binding: String,
|
||||
pub lived_stream: String,
|
||||
pub output_schema: Option<serde_json::Value>,
|
||||
pub source_receipt_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct ModelStageReceipt {
|
||||
pub schema: String,
|
||||
pub provider: String,
|
||||
pub model: String,
|
||||
pub stage: String,
|
||||
pub snapshot_binding: String,
|
||||
pub request_hash: String,
|
||||
pub output_hash: String,
|
||||
pub source_receipt_ids: Vec<String>,
|
||||
pub latency_ms: u64,
|
||||
pub validation_result: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ModelStageOutput {
|
||||
pub narrative: String,
|
||||
pub structured: Option<serde_json::Value>,
|
||||
pub receipt: ModelStageReceipt,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ModelPort: Send + Sync {
|
||||
async fn run(&self, request: &ModelStageRequest) -> Result<String>;
|
||||
fn provider(&self) -> &'static str;
|
||||
}
|
||||
|
||||
pub async fn run_validated_stage(
|
||||
port: &dyn ModelPort,
|
||||
request: &ModelStageRequest,
|
||||
) -> Result<ModelStageOutput> {
|
||||
let request_bytes = serde_json::to_vec(request)?;
|
||||
for attempt in 0..2 {
|
||||
let started = Instant::now();
|
||||
let output = port.run(request).await?;
|
||||
if output.trim().is_empty() {
|
||||
if attempt == 0 {
|
||||
continue;
|
||||
}
|
||||
return Err(anyhow!("model returned empty output twice"));
|
||||
}
|
||||
let structured = match &request.output_schema {
|
||||
Some(_) => match serde_json::from_str(&output) {
|
||||
Ok(value) => Some(value),
|
||||
Err(_) if attempt == 0 => continue,
|
||||
Err(error) => return Err(anyhow!("model returned malformed JSON twice: {error}")),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
return Ok(ModelStageOutput {
|
||||
narrative: output.clone(),
|
||||
structured,
|
||||
receipt: ModelStageReceipt {
|
||||
schema: "ghostlight.persona_stage_receipt.v1".into(),
|
||||
provider: port.provider().into(),
|
||||
model: request.model.clone(),
|
||||
stage: request.stage.clone(),
|
||||
snapshot_binding: request.snapshot_binding.clone(),
|
||||
request_hash: format!("sha256:{:x}", Sha256::digest(&request_bytes)),
|
||||
output_hash: format!("sha256:{:x}", Sha256::digest(output.as_bytes())),
|
||||
source_receipt_ids: request.source_receipt_ids.clone(),
|
||||
latency_ms: started.elapsed().as_millis() as u64,
|
||||
validation_result: "valid".into(),
|
||||
},
|
||||
});
|
||||
}
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FixtureModel;
|
||||
#[async_trait]
|
||||
impl ModelPort for FixtureModel {
|
||||
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
|
||||
Ok(if request.output_schema.is_some() {
|
||||
r#"{"private_deltas":[],"speech":null,"reaction_priority":0,"world_actions":[]}"#.into()
|
||||
} else {
|
||||
format!("{}", request.lived_stream)
|
||||
})
|
||||
}
|
||||
fn provider(&self) -> &'static str {
|
||||
"fixture"
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DeepSeekPort {
|
||||
client: reqwest::Client,
|
||||
api_key: String,
|
||||
endpoint: String,
|
||||
}
|
||||
impl DeepSeekPort {
|
||||
pub fn new(api_key: String) -> Self {
|
||||
Self {
|
||||
client: reqwest::Client::new(),
|
||||
api_key,
|
||||
endpoint: "https://api.deepseek.com/chat/completions".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl ModelPort for DeepSeekPort {
|
||||
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
|
||||
let mut body = serde_json::json!({"model":request.model,"messages":[{"role":"user","content":request.lived_stream}],"stream":false,"thinking":{"type":"disabled"}});
|
||||
if request.output_schema.is_some() {
|
||||
body["response_format"] = serde_json::json!({"type":"json_object"});
|
||||
}
|
||||
let value: serde_json::Value = self
|
||||
.client
|
||||
.post(&self.endpoint)
|
||||
.bearer_auth(&self.api_key)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.json()
|
||||
.await?;
|
||||
value
|
||||
.pointer("/choices/0/message/content")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| anyhow!("DeepSeek response contained no assistant content"))
|
||||
}
|
||||
fn provider(&self) -> &'static str {
|
||||
"deepseek"
|
||||
}
|
||||
}
|
||||
111
crates/ghostlight-dungeon/src/persistence.rs
Normal file
111
crates/ghostlight-dungeon/src/persistence.rs
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
use anyhow::{Context, Result, anyhow};
|
||||
use chrono::Utc;
|
||||
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||
use serde::{Serialize, de::DeserializeOwned};
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CampaignStore {
|
||||
inner: OwnedRedbMessagePackBackingStore,
|
||||
}
|
||||
|
||||
impl CampaignStore {
|
||||
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
|
||||
Ok(Self {
|
||||
inner: OwnedRedbMessagePackBackingStore::new(path.as_ref())?,
|
||||
})
|
||||
}
|
||||
pub fn identity(&self) -> &str {
|
||||
self.inner.file_identity()
|
||||
}
|
||||
|
||||
pub fn keys(&self, kind: &str) -> Result<Vec<String>> {
|
||||
Ok(self
|
||||
.inner
|
||||
.pull_all()?
|
||||
.into_iter()
|
||||
.filter(|r| r.r#type == kind)
|
||||
.map(|r| r.key)
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn load<T: DeserializeOwned>(
|
||||
&self,
|
||||
kind: &str,
|
||||
key: &str,
|
||||
) -> Result<Option<(CultCacheEnvelope, T)>> {
|
||||
let row = self
|
||||
.inner
|
||||
.pull_all()?
|
||||
.into_iter()
|
||||
.find(|r| r.r#type == kind && r.key == key);
|
||||
row.map(|r| {
|
||||
let value = rmp_serde::from_slice(&r.payload).context("decode CultCache row")?;
|
||||
Ok((r, value))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn insert<T: Serialize>(
|
||||
&self,
|
||||
kind: &str,
|
||||
schema: &str,
|
||||
key: &str,
|
||||
value: &T,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
let row = envelope(kind, schema, key, value)?;
|
||||
if !self.inner.insert_entry_if_absent(row.clone())? {
|
||||
return Err(anyhow!("row already exists: {kind}/{key}"));
|
||||
}
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
pub fn replace<T: Serialize>(
|
||||
&self,
|
||||
expected: &CultCacheEnvelope,
|
||||
schema: &str,
|
||||
value: &T,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
let next = envelope(&expected.r#type, schema, &expected.key, value)?;
|
||||
if !self.inner.compare_and_swap_entry(expected, next.clone())? {
|
||||
return Err(anyhow!("stale CultCache snapshot"));
|
||||
}
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
pub fn append_with_replace<T: Serialize, R: Serialize>(
|
||||
&self,
|
||||
expected: &CultCacheEnvelope,
|
||||
next_schema: &str,
|
||||
next: &T,
|
||||
receipt_kind: &str,
|
||||
receipt_schema: &str,
|
||||
receipt_key: &str,
|
||||
receipt: &R,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
let next_row = envelope(&expected.r#type, next_schema, &expected.key, next)?;
|
||||
let receipt_row = envelope(receipt_kind, receipt_schema, receipt_key, receipt)?;
|
||||
if !self.inner.compare_and_swap_batch(
|
||||
std::slice::from_ref(expected),
|
||||
vec![next_row.clone(), receipt_row],
|
||||
)? {
|
||||
return Err(anyhow!("stale CultCache snapshot"));
|
||||
}
|
||||
Ok(next_row)
|
||||
}
|
||||
}
|
||||
|
||||
fn envelope<T: Serialize>(
|
||||
kind: &str,
|
||||
schema: &str,
|
||||
key: &str,
|
||||
value: &T,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
Ok(CultCacheEnvelope {
|
||||
key: key.into(),
|
||||
r#type: kind.into(),
|
||||
payload: rmp_serde::to_vec_named(value)?,
|
||||
stored_at: Utc::now().to_rfc3339(),
|
||||
schema_id: Some(schema.into()),
|
||||
})
|
||||
}
|
||||
189
crates/ghostlight-dungeon/src/persona.rs
Normal file
189
crates/ghostlight-dungeon/src/persona.rs
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
use crate::model::{ModelPort, ModelStageRequest, run_validated_stage};
|
||||
use anyhow::{Result, anyhow};
|
||||
use async_trait::async_trait;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct PermittedActorSlice {
|
||||
pub actor_id: String,
|
||||
pub snapshot_binding: String,
|
||||
pub identity_experience: Vec<String>,
|
||||
pub memories: Vec<String>,
|
||||
pub perceived_events: Vec<String>,
|
||||
pub relationships: Vec<String>,
|
||||
pub goals: Vec<String>,
|
||||
pub knowledge: Vec<String>,
|
||||
pub capabilities: Vec<String>,
|
||||
pub pressures: Vec<String>,
|
||||
pub affordances: Vec<String>,
|
||||
pub source_receipt_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct LivedNarrativeStream {
|
||||
pub text: String,
|
||||
pub snapshot_binding: String,
|
||||
pub projector_receipt: crate::model::ModelStageReceipt,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct PersonaProposalBundle {
|
||||
pub private_deltas: Vec<serde_json::Value>,
|
||||
pub speech: Option<String>,
|
||||
pub reaction_priority: i16,
|
||||
pub world_actions: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PersonaTerminalBundle {
|
||||
pub lived_stream: LivedNarrativeStream,
|
||||
pub persona_output: String,
|
||||
pub proposals: PersonaProposalBundle,
|
||||
pub stage_receipts: Vec<crate::model::ModelStageReceipt>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ExecutionPermit: Send + Sync {
|
||||
async fn require(&self, actor_id: &str, snapshot_binding: &str, stage: &str) -> Result<()>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AllowAllPermit;
|
||||
#[async_trait]
|
||||
impl ExecutionPermit for AllowAllPermit {
|
||||
async fn require(&self, _: &str, _: &str, _: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PersonaProjectionEngine {
|
||||
pub model: Arc<dyn ModelPort>,
|
||||
pub permit: Arc<dyn ExecutionPermit>,
|
||||
pub projector_model: String,
|
||||
pub persona_model: String,
|
||||
pub interpreter_model: String,
|
||||
}
|
||||
|
||||
impl PersonaProjectionEngine {
|
||||
pub async fn execute(&self, slice: PermittedActorSlice) -> Result<PersonaTerminalBundle> {
|
||||
self.permit
|
||||
.require(&slice.actor_id, &slice.snapshot_binding, "projector")
|
||||
.await?;
|
||||
let projector_prompt = format!(
|
||||
"Project this permitted typed experience into one private lived narrative stream. Emit narrative only; no JSON, action syntax, schemas, or raw field labels.\n\n{}",
|
||||
serde_json::to_string(&slice)?
|
||||
);
|
||||
let projected = run_validated_stage(
|
||||
self.model.as_ref(),
|
||||
&ModelStageRequest {
|
||||
stage: "projector".into(),
|
||||
model: self.projector_model.clone(),
|
||||
snapshot_binding: slice.snapshot_binding.clone(),
|
||||
lived_stream: projector_prompt,
|
||||
output_schema: None,
|
||||
source_receipt_ids: slice.source_receipt_ids.clone(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
require_narrative_membrane(&projected.narrative)?;
|
||||
let lived = LivedNarrativeStream {
|
||||
text: projected.narrative.clone(),
|
||||
snapshot_binding: slice.snapshot_binding.clone(),
|
||||
projector_receipt: projected.receipt.clone(),
|
||||
};
|
||||
|
||||
self.permit
|
||||
.require(&slice.actor_id, &slice.snapshot_binding, "persona")
|
||||
.await?;
|
||||
// This is the membrane: the Persona's domain context is exactly one lived stream.
|
||||
let persona = run_validated_stage(
|
||||
self.model.as_ref(),
|
||||
&ModelStageRequest {
|
||||
stage: "persona".into(),
|
||||
model: self.persona_model.clone(),
|
||||
snapshot_binding: slice.snapshot_binding.clone(),
|
||||
lived_stream: lived.text.clone(),
|
||||
output_schema: None,
|
||||
source_receipt_ids: vec![],
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
self.permit
|
||||
.require(&slice.actor_id, &slice.snapshot_binding, "interpreter")
|
||||
.await?;
|
||||
let schema = serde_json::json!({"type":"object","required":["private_deltas","speech","reaction_priority","world_actions"]});
|
||||
let interpreted = run_validated_stage(
|
||||
self.model.as_ref(),
|
||||
&ModelStageRequest {
|
||||
stage: "interpreter".into(),
|
||||
model: self.interpreter_model.clone(),
|
||||
snapshot_binding: slice.snapshot_binding.clone(),
|
||||
lived_stream: format!(
|
||||
"LIVED STREAM:\n{}\n\nPERSONA OUTPUT:\n{}",
|
||||
lived.text, persona.narrative
|
||||
),
|
||||
output_schema: Some(schema),
|
||||
source_receipt_ids: slice.source_receipt_ids,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
self.permit
|
||||
.require(&slice.actor_id, &slice.snapshot_binding, "terminal")
|
||||
.await?;
|
||||
let proposals: PersonaProposalBundle = serde_json::from_value(
|
||||
interpreted
|
||||
.structured
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow!("interpreter produced no typed proposal"))?,
|
||||
)?;
|
||||
Ok(PersonaTerminalBundle {
|
||||
lived_stream: lived,
|
||||
persona_output: persona.narrative,
|
||||
proposals,
|
||||
stage_receipts: vec![projected.receipt, persona.receipt, interpreted.receipt],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn require_narrative_membrane(text: &str) -> Result<()> {
|
||||
let trimmed = text.trim();
|
||||
if trimmed.is_empty() || trimmed.starts_with('{') || trimmed.contains("```json") {
|
||||
return Err(anyhow!("projector violated lived-narrative membrane"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::FixtureModel;
|
||||
#[tokio::test]
|
||||
async fn persona_receives_only_projected_stream() {
|
||||
let engine = PersonaProjectionEngine {
|
||||
model: Arc::new(FixtureModel),
|
||||
permit: Arc::new(AllowAllPermit),
|
||||
projector_model: "flash".into(),
|
||||
persona_model: "pro".into(),
|
||||
interpreter_model: "flash".into(),
|
||||
};
|
||||
let slice = PermittedActorSlice {
|
||||
actor_id: "npc".into(),
|
||||
snapshot_binding: "campaign:1".into(),
|
||||
identity_experience: vec!["A tired navigator".into()],
|
||||
memories: vec![],
|
||||
perceived_events: vec![],
|
||||
relationships: vec![],
|
||||
goals: vec![],
|
||||
knowledge: vec![],
|
||||
capabilities: vec![],
|
||||
pressures: vec![],
|
||||
affordances: vec![],
|
||||
source_receipt_ids: vec![],
|
||||
};
|
||||
let result = engine.execute(slice).await.unwrap();
|
||||
assert_eq!(result.stage_receipts.len(), 3);
|
||||
assert_eq!(result.proposals.reaction_priority, 0);
|
||||
}
|
||||
}
|
||||
16
crates/ghostlight-dungeon/src/surface.rs
Normal file
16
crates/ghostlight-dungeon/src/surface.rs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
use crate::domain::Campaign;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn player_surface(campaign: &Campaign) -> Value {
|
||||
let turns = campaign.transcript.iter().map(|t| json!({"id":format!("turn-{}-{}",t.revision,t.speaker),"kind":"text","props":{"value":format!("{}: {}",t.speaker,t.text)},"children":[]})).collect::<Vec<_>>();
|
||||
json!({
|
||||
"type":"surface-state", "schema":"gamecult.eve.surface.v1", "providerId":"gamecult.ghostlight.dungeon",
|
||||
"providerKind":"narrative.simulation", "title":campaign.name, "version":campaign.revision,
|
||||
"surface":{"id":format!("ghostlight.campaign.{}",campaign.id),"root":{"id":"dungeon.root","kind":"surface","props":{},"children":[
|
||||
{"id":"dungeon.status","kind":"card","props":{"title":format!("{} · revision {} · {}",campaign.name,campaign.revision,campaign.world_time)},"children":[]},
|
||||
{"id":"dungeon.transcript","kind":"card","props":{"title":"Story"},"children":turns},
|
||||
{"id":"dungeon.composer","kind":"text-input","props":{"label":"What do you attempt?","commandId":"attempt.assess"},"children":[]}
|
||||
]},"styles":{"tokens":{"colorBackground":"#0c1110","colorPanel":"#17201d","colorText":"#e8e1cf","colorMuted":"#9aa69f","colorAccent":"#d49b58"}}},
|
||||
"commands":[{"id":"attempt.assess","schema":"gamecult.eve.command.v1","receiptSchema":"ghostlight.player_action_assessment.v1"}]
|
||||
})
|
||||
}
|
||||
102
crates/ghostlight-dungeon/src/vault.rs
Normal file
102
crates/ghostlight-dungeon/src/vault.rs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
use crate::domain::{SourceWitness, VaultEvidenceReceipt};
|
||||
use anyhow::{Result, anyhow};
|
||||
use async_trait::async_trait;
|
||||
use chrono::Utc;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct VaultQuery {
|
||||
pub query: String,
|
||||
pub authority_lanes: Vec<String>,
|
||||
pub temporal_scope: String,
|
||||
pub limit: u8,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait VaultProvider: Send + Sync {
|
||||
async fn search(&self, query: &VaultQuery) -> Result<VaultEvidenceReceipt>;
|
||||
async fn exact_document(&self, source_id: &str) -> Result<SourceWitness>;
|
||||
fn provider_id(&self) -> &'static str;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FixtureVault {
|
||||
pub witnesses: Vec<SourceWitness>,
|
||||
}
|
||||
#[async_trait]
|
||||
impl VaultProvider for FixtureVault {
|
||||
async fn search(&self, query: &VaultQuery) -> Result<VaultEvidenceReceipt> {
|
||||
Ok(receipt(
|
||||
self.provider_id(),
|
||||
query,
|
||||
self.witnesses
|
||||
.iter()
|
||||
.take(query.limit as usize)
|
||||
.cloned()
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
async fn exact_document(&self, source_id: &str) -> Result<SourceWitness> {
|
||||
self.witnesses
|
||||
.iter()
|
||||
.find(|w| w.source_id == source_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow!("fixture source not found"))
|
||||
}
|
||||
fn provider_id(&self) -> &'static str {
|
||||
"fixture"
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct VoidBotMcpVault {
|
||||
client: Client,
|
||||
endpoint: String,
|
||||
}
|
||||
impl VoidBotMcpVault {
|
||||
pub fn starfire_loopback() -> Self {
|
||||
Self {
|
||||
client: Client::new(),
|
||||
endpoint: "http://127.0.0.1:17875/mcp".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl VaultProvider for VoidBotMcpVault {
|
||||
async fn search(&self, query: &VaultQuery) -> Result<VaultEvidenceReceipt> {
|
||||
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"))?;
|
||||
Ok(receipt(self.provider_id(), query, witnesses))
|
||||
}
|
||||
async fn exact_document(&self, _source_id: &str) -> Result<SourceWitness> {
|
||||
Err(anyhow!(
|
||||
"exact-document VoidBot adapter awaits restored trusted crossing contract verification"
|
||||
))
|
||||
}
|
||||
fn provider_id(&self) -> &'static str {
|
||||
"voidbot.aetheria"
|
||||
}
|
||||
}
|
||||
|
||||
fn receipt(
|
||||
provider: &str,
|
||||
query: &VaultQuery,
|
||||
witnesses: Vec<SourceWitness>,
|
||||
) -> VaultEvidenceReceipt {
|
||||
let query_bytes = rmp_serde::to_vec_named(query).expect("query serializes");
|
||||
let query_hash = format!("sha256:{:x}", Sha256::digest(query_bytes));
|
||||
VaultEvidenceReceipt {
|
||||
schema: "ghostlight.vault_evidence_receipt.v1".into(),
|
||||
id: format!("vault:{query_hash}"),
|
||||
provider: provider.into(),
|
||||
query_hash,
|
||||
witnesses,
|
||||
retrieved_at: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,9 @@
|
|||
"version": "0.0.0",
|
||||
"description": "Persistent research repo for socially situated generative agent architecture.",
|
||||
"scripts": {
|
||||
"dungeon:build": "cargo build --workspace && npm --prefix web run build",
|
||||
"dungeon:test": "cargo test --workspace && npm --prefix web run build",
|
||||
"dungeon:run": "cargo run -p ghostlight-dungeon",
|
||||
"state:status": "\"C:\\Users\\Meta\\.cache\\codex-runtimes\\codex-primary-runtime\\dependencies\\python\\python.exe\" .\\tools\\ghostlight_state.py status",
|
||||
"state:prepare-compaction": "\"C:\\Users\\Meta\\.cache\\codex-runtimes\\codex-primary-runtime\\dependencies\\python\\python.exe\" .\\tools\\ghostlight_prepare_compaction.py",
|
||||
"agent-state:validate": "\"C:\\Users\\Meta\\.cache\\codex-runtimes\\codex-primary-runtime\\dependencies\\python\\python.exe\" .\\tools\\validate_agent_state.py",
|
||||
|
|
|
|||
1
vendor/eve
vendored
Submodule
1
vendor/eve
vendored
Submodule
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 076d2124ed476cdaeff540c9d24c2d4fb57d04cf
|
||||
153
web/dist/assets/index-CmB__dez.js
vendored
Normal file
153
web/dist/assets/index-CmB__dez.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
web/dist/assets/index-CyG_836Q.css
vendored
Normal file
1
web/dist/assets/index-CyG_836Q.css
vendored
Normal file
File diff suppressed because one or more lines are too long
5
web/dist/index.html
vendored
Normal file
5
web/dist/index.html
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
<!doctype html>
|
||||
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-CmB__dez.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-CyG_836Q.css">
|
||||
</head>
|
||||
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status">Reading the world…</p></header><main><section id="surface"></section><form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre></main></body></html>
|
||||
3
web/index.html
Normal file
3
web/index.html
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<!doctype html>
|
||||
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title></head>
|
||||
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status">Reading the world…</p></header><main><section id="surface"></section><form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre></main><script type="module" src="/src/main.ts"></script></body></html>
|
||||
1191
web/package-lock.json
generated
Normal file
1191
web/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
8
web/package.json
Normal file
8
web/package.json
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"name": "@gamecult/ghostlight-dungeon-web",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": { "build": "vite build", "dev": "vite --host 127.0.0.1 --port 8832" },
|
||||
"dependencies": { "@gamecult/eve-browser-lowering": "file:../vendor/eve/packages/eve-browser-lowering" },
|
||||
"devDependencies": { "typescript": "^5.6.3", "vite": "^7.1.2" }
|
||||
}
|
||||
36
web/src/main.ts
Normal file
36
web/src/main.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { renderEveSurface } from "@gamecult/eve-browser-lowering";
|
||||
import "@gamecult/eve-browser-lowering/styles.css";
|
||||
import "./style.css";
|
||||
|
||||
const host = document.querySelector<HTMLElement>("#surface")!;
|
||||
const status = document.querySelector<HTMLElement>("#status")!;
|
||||
const receipt = document.querySelector<HTMLElement>("#receipt")!;
|
||||
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();
|
||||
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();
|
||||
}
|
||||
|
||||
document.querySelector<HTMLFormElement>("#composer")!.addEventListener("submit", event => {
|
||||
event.preventDefault();
|
||||
const text = document.querySelector<HTMLTextAreaElement>("#attempt")!.value.trim();
|
||||
if (!text) return;
|
||||
void send({ type: "assess", expected_revision: revision, intent: { actor_id: actorId, description: text, intended_effect: text } });
|
||||
});
|
||||
document.querySelector<HTMLButtonElement>("#wait")!.addEventListener("click", () => void send({ type: "wait", expected_revision: revision, minutes: 60 }));
|
||||
void refresh();
|
||||
2
web/src/style.css
Normal file
2
web/src/style.css
Normal file
|
|
@ -0,0 +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}}
|
||||
Loading…
Reference in a new issue