Add OpenRouter model routing

This commit is contained in:
Meta Vens 2026-08-22 07:30:52 +02:00
commit 4c04c13c14
5 changed files with 410 additions and 57 deletions

View file

@ -27,7 +27,10 @@ use ghostlight_dungeon::{
CampaignMeshSnapshot, MeshPublisher, MeshRuntimeIdentity, PROVIDER_ID as EVE_PROVIDER_ID,
SURFACE_ID as EVE_SURFACE_ID, SessionZeroMeshSnapshot,
},
model::{DeepSeekPort, ModelPort, ModelStageRequest, run_validated_stage},
model::{
DeepSeekPort, MODEL_CAPABLE, MODEL_FAST, ModelPort, ModelRuntimeStatus, ModelStageRequest,
OpenRouterPort, run_validated_stage,
},
narrator::Narrator,
persistence::CampaignStore,
persona::PersonaProjectionEngine,
@ -68,7 +71,7 @@ struct AppState {
entitlements: Arc<dyn EntitlementPort>,
auth: Arc<Mutex<AppSessionOwner>>,
heimdall: Arc<HeimdallClient>,
deepseek_status: String,
model_status: ModelRuntimeStatus,
compiler: Option<Arc<WorldCompiler>>,
assessor: Option<Arc<ActionAssessor>>,
model: Option<Arc<dyn ModelPort>>,
@ -255,51 +258,81 @@ async fn main() -> anyhow::Result<()> {
for (account_hash, campaign_id) in &legacy_auth_state.session_campaigns {
app_sessions.migrate_preference(account_hash, *campaign_id)?;
}
let secret_path = std::env::var_os("GHOSTLIGHT_DEEPSEEK_CREDENTIAL")
let provider_name = std::env::var("GHOSTLIGHT_MODEL_PROVIDER")
.unwrap_or_else(|_| "deepseek".into())
.to_ascii_lowercase();
let (default_fast_model, default_capable_model, default_secret_name) =
match provider_name.as_str() {
"deepseek" => ("deepseek-v4-flash", "deepseek-v4-pro", "deepseek.dpapi"),
"openrouter" => ("stealth/ox-alpha", "stealth/ox-alpha", "openrouter.key"),
unsupported => anyhow::bail!("unsupported model provider {unsupported}"),
};
let fast_model =
std::env::var("GHOSTLIGHT_MODEL_FAST").unwrap_or_else(|_| default_fast_model.into());
let capable_model =
std::env::var("GHOSTLIGHT_MODEL_CAPABLE").unwrap_or_else(|_| default_capable_model.into());
let secret_path = std::env::var_os("GHOSTLIGHT_MODEL_CREDENTIAL")
.map(PathBuf::from)
.unwrap_or_else(|| runtime_root.join("secrets/deepseek.dpapi"));
let (deepseek_status, compiler, assessor, shared_model) = if secret_path.is_file() {
let provider: Arc<dyn ModelPort> =
Arc::new(DeepSeekPort::from_runtime_secret(&secret_path)?);
.unwrap_or_else(|| runtime_root.join("secrets").join(default_secret_name));
let configured_status = |readiness: String| ModelRuntimeStatus {
provider: provider_name.clone(),
fast_model: fast_model.clone(),
capable_model: capable_model.clone(),
readiness,
};
let (model_status, compiler, assessor, shared_model) = if secret_path.is_file() {
let provider: Arc<dyn ModelPort> = match provider_name.as_str() {
"deepseek" => Arc::new(DeepSeekPort::from_runtime_secret_with_models(
&secret_path,
fast_model.clone(),
capable_model.clone(),
)?),
"openrouter" => Arc::new(OpenRouterPort::from_runtime_secret(
&secret_path,
fast_model.clone(),
capable_model.clone(),
)?),
_ => unreachable!("provider name was validated above"),
};
let probe = run_validated_stage(
provider.as_ref(),
&ModelStageRequest {
stage: "startup_probe".into(),
model: "deepseek-v4-flash".into(),
model: MODEL_FAST.into(),
snapshot_binding: "service-startup".into(),
lived_stream: "Reply with the single word ready.".into(),
output_schema: None,
source_receipt_ids: vec![],
temperature: Some(0.0),
max_output_tokens: Some(16),
max_output_tokens: Some(128),
},
)
.await;
let deepseek_status = match probe {
let readiness = match probe {
Ok(probe) => format!("ready:{}", probe.receipt.output_hash),
Err(error) => {
tracing::warn!(%error, "DeepSeek startup probe failed; runtime remains available");
tracing::warn!(provider = %provider_name, %error, "model startup probe failed; runtime remains available");
"degraded:startup-probe-failed".into()
}
};
let vault_endpoint = std::env::var("GHOSTLIGHT_VAULT_MCP_URL")
.unwrap_or_else(|_| "http://127.0.0.1:17875/mcp".into());
(
deepseek_status,
configured_status(readiness),
Some(Arc::new(WorldCompiler::new(
Arc::new(VoidBotMcpVault::new(vault_endpoint)),
provider.clone(),
"deepseek-v4-flash",
"deepseek-v4-pro",
MODEL_FAST,
MODEL_CAPABLE,
))),
Some(Arc::new(ActionAssessor::new(
provider.clone(),
"deepseek-v4-pro",
MODEL_CAPABLE,
))),
Some(provider),
)
} else {
("missing-secret".into(), None, None, None)
(configured_status("missing-secret".into()), None, None, None)
};
let mesh_target = std::env::var("GHOSTLIGHT_ODIN_RUDP")
.ok()
@ -341,9 +374,9 @@ async fn main() -> anyhow::Result<()> {
let session_zero_director = shared_model.as_ref().map(|model| {
Arc::new(SessionZeroDirector::new(
model.clone(),
"deepseek-v4-flash",
"deepseek-v4-pro",
"deepseek-v4-flash",
MODEL_FAST,
MODEL_CAPABLE,
MODEL_FAST,
))
});
let state = AppState {
@ -353,7 +386,7 @@ async fn main() -> anyhow::Result<()> {
entitlements: Arc::new(FixtureEntitlementPort),
auth: Arc::new(Mutex::new(app_sessions)),
heimdall: Arc::new(HeimdallClient::from_env()?),
deepseek_status,
model_status,
compiler,
assessor,
model: shared_model,
@ -3278,7 +3311,7 @@ async fn compile_destination(
let Some(compiler) = &state.compiler else {
return (
StatusCode::SERVICE_UNAVAILABLE,
"DeepSeek credential is unavailable",
"Model provider credential is unavailable",
)
.into_response();
};
@ -3379,7 +3412,7 @@ async fn compile_fission(
let Some(compiler) = &state.compiler else {
return (
StatusCode::SERVICE_UNAVAILABLE,
"DeepSeek credential is unavailable",
"Model provider credential is unavailable",
)
.into_response();
};
@ -3534,7 +3567,7 @@ async fn publish_latest_narration(
.ok_or_else(|| anyhow::anyhow!("narration requires the model provider"))?;
let narrator = Narrator {
model: model.clone(),
model_name: "deepseek-v4-pro".into(),
model_name: MODEL_CAPABLE.into(),
};
let (projection, receipt) = narrator.project(&runtime.store, &campaign).await?;
runtime.store.insert(
@ -3832,7 +3865,7 @@ async fn command(
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(ErrorBody {
error: "DeepSeek assessor is unavailable".into(),
error: "Model assessor is unavailable".into(),
}),
)
.into_response();
@ -3977,7 +4010,7 @@ async fn command(
if !campaign.gestalts.is_empty() {
let planner = GestaltPresencePlanner {
model: model.clone(),
model_name: "deepseek-v4-flash".into(),
model_name: MODEL_FAST.into(),
};
match planner.plan(campaign, &summary).await {
Ok((plan, receipt)) => {
@ -4026,9 +4059,9 @@ async fn command(
reaction_campaign.id,
reaction_campaign.revision,
)),
projector_model: "deepseek-v4-flash".into(),
persona_model: "deepseek-v4-pro".into(),
interpreter_model: "deepseek-v4-flash".into(),
projector_model: MODEL_FAST.into(),
persona_model: MODEL_CAPABLE.into(),
interpreter_model: MODEL_FAST.into(),
};
match appraise_present(engine, &reaction_campaign, &summary).await {
Ok(wave) if !wave.reactions.is_empty() => {
@ -4138,7 +4171,7 @@ async fn command(
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(ErrorBody {
error: "DeepSeek assessor is unavailable".into(),
error: "Model assessor is unavailable".into(),
}),
)
.into_response();
@ -4586,10 +4619,10 @@ async fn refresh_mesh(state: &AppState) -> anyhow::Result<serde_json::Value> {
}
}
let publisher = state.mesh.clone();
let deepseek = state.deepseek_status.clone();
let model_status = state.model_status.clone();
let pressure = state.live_turns.load(Ordering::SeqCst);
tokio::task::spawn_blocking(move || {
publisher.publish_snapshot(&snapshots, &session_zero_snapshots, &deepseek, pressure)
publisher.publish_snapshot(&snapshots, &session_zero_snapshots, &model_status, pressure)
})
.await?
}
@ -5314,7 +5347,12 @@ mod tests {
entitlements: Arc::new(FixtureEntitlementPort),
auth: Arc::new(Mutex::new(auth)),
heimdall: Arc::new(HeimdallClient::fixture()),
deepseek_status: "fixture".into(),
model_status: ModelRuntimeStatus {
provider: "fixture".into(),
fast_model: "fixture".into(),
capable_model: "fixture".into(),
readiness: "ready".into(),
},
compiler: None,
assessor: None,
model: None,

View file

@ -11,7 +11,7 @@ use crate::{
StrategicTickPlan, StrategicTickReceipt, VaultEvidenceReceipt, VaultManifest,
WorldActionProposal, WorldClock, WorldCommitReceipt, WorldCompilePreview, WorldFact,
},
model::ModelStageReceipt,
model::{ModelRuntimeStatus, ModelStageReceipt},
session_zero::{
ActiveContractBoundaryPolicy, ApprovedCampaignBrief, CampaignContract, CampaignDmPersona,
CampaignGovernance, CampaignMembership, CellBudgetProposal, CharacterDraft,
@ -248,7 +248,7 @@ impl MeshPublisher {
&self,
campaigns: &[CampaignMeshSnapshot],
session_zeros: &[SessionZeroMeshSnapshot],
deepseek_status: &str,
model_status: &ModelRuntimeStatus,
live_turn_pressure: usize,
) -> Result<Value> {
let updated_at = Utc::now().to_rfc3339();
@ -257,7 +257,7 @@ impl MeshPublisher {
"status":"ok",
"campaigns":campaigns.len(),
"sessionZeros":session_zeros.len(),
"deepseek":deepseek_status,
"modelProvider":model_status,
"scheduler":{"live_turn_pressure":live_turn_pressure},
"updatedAtUtc":updated_at,
"runtime":self.identity.runtime_id.as_str(),
@ -638,11 +638,14 @@ mod tests {
fn health_is_read_from_the_same_typed_mesh_record_that_is_published() {
let temp = tempdir().unwrap();
let publisher = MeshPublisher::open(temp.path().join("mesh.cc"), None).unwrap();
let model_status = fixture_model_status();
let written = publisher
.publish_snapshot(&[], &[], "fixture-ready", 2)
.publish_snapshot(&[], &[], &model_status, 2)
.unwrap();
assert_eq!(publisher.health().unwrap(), written);
assert_eq!(written["scheduler"]["live_turn_pressure"], 2);
assert_eq!(written["modelProvider"]["provider"], "fixture");
assert!(written.get("deepseek").is_none());
let catalog = publisher
.node
.lock()
@ -676,8 +679,9 @@ mod tests {
MeshPublisher::open(temp.path().join("mesh.cc"), Some(unavailable)).unwrap();
let started = std::time::Instant::now();
let model_status = fixture_model_status();
let written = publisher
.publish_snapshot(&[], &[], "fixture-ready", 0)
.publish_snapshot(&[], &[], &model_status, 0)
.expect("local projection remains writable while rendezvous is unavailable");
assert!(
@ -695,6 +699,15 @@ mod tests {
);
}
fn fixture_model_status() -> ModelRuntimeStatus {
ModelRuntimeStatus {
provider: "fixture".into(),
fast_model: "fixture-fast".into(),
capable_model: "fixture-capable".into(),
readiness: "ready".into(),
}
}
#[test]
fn public_provider_advertises_one_subject_scoped_surface_and_heimdall_plugin() {
let temp = tempdir().unwrap();

View file

@ -6,6 +6,18 @@ use sha2::{Digest, Sha256};
use std::time::Instant;
use zeroize::Zeroizing;
pub const MODEL_FAST: &str = "ghostlight.fast.v1";
pub const MODEL_CAPABLE: &str = "ghostlight.capable.v1";
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ModelRuntimeStatus {
pub provider: String,
pub fast_model: String,
pub capable_model: String,
pub readiness: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ModelStageRequest {
pub stage: String,
@ -85,6 +97,7 @@ pub struct ModelStageOutput {
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ModelProviderOutput {
pub content: String,
pub resolved_model: Option<String>,
pub provider_request_id: Option<String>,
pub system_fingerprint: Option<String>,
pub finish_reason: Option<String>,
@ -138,6 +151,7 @@ pub async fn run_validated_stage_with_timeout(
})??;
let ModelProviderOutput {
content: output,
resolved_model,
provider_request_id,
system_fingerprint,
finish_reason,
@ -224,7 +238,10 @@ pub async fn run_validated_stage_with_timeout(
.last_mut()
.expect("attempt was just recorded")
.local_validation_result = "valid".into();
let request_bytes = serde_json::to_vec(&attempt_request)?;
let receipt_model = resolved_model.unwrap_or_else(|| attempt_request.model.clone());
let mut receipted_request = attempt_request.clone();
receipted_request.model.clone_from(&receipt_model);
let request_bytes = serde_json::to_vec(&receipted_request)?;
let provider = port.provider().to_owned();
let request_hash = format!("sha256:{:x}", Sha256::digest(&request_bytes));
let output_hash = format!("sha256:{:x}", Sha256::digest(output.as_bytes()));
@ -234,7 +251,7 @@ pub async fn run_validated_stage_with_timeout(
format!(
"{}|{}|{}|{}|{}|{}",
provider,
request.model,
receipt_model,
request.stage,
request.snapshot_binding,
request_hash,
@ -250,7 +267,7 @@ pub async fn run_validated_stage_with_timeout(
schema: "ghostlight.persona_stage_receipt.v1".into(),
receipt_hash,
provider,
model: request.model.clone(),
model: receipt_model,
stage: request.stage.clone(),
snapshot_binding: request.snapshot_binding.clone(),
request_hash,
@ -285,6 +302,7 @@ mod tests {
struct CorrectionAware {
calls: AtomicUsize,
}
struct PhysicallyRoutedModel;
#[async_trait]
impl ModelPort for NeverReturns {
@ -329,6 +347,25 @@ mod tests {
}
}
#[async_trait]
impl ModelPort for PhysicallyRoutedModel {
async fn run(&self, _: &ModelStageRequest) -> Result<String> {
unreachable!("run_observed owns this fixture")
}
async fn run_observed(&self, _: &ModelStageRequest) -> Result<ModelProviderOutput> {
Ok(ModelProviderOutput {
content: "ready".into(),
resolved_model: Some("stealth/ox-alpha".into()),
..Default::default()
})
}
fn provider(&self) -> &'static str {
"openrouter"
}
}
#[tokio::test]
async fn schema_invalid_json_gets_one_same_snapshot_retry() {
let port = InvalidThenValid {
@ -404,10 +441,39 @@ mod tests {
assert!(error.to_string().contains("timed out"));
}
#[tokio::test]
async fn receipt_hashes_the_physical_provider_model_not_the_logical_class() {
let request = ModelStageRequest {
stage: "startup_probe".into(),
model: MODEL_FAST.into(),
snapshot_binding: "service-startup".into(),
lived_stream: "ready?".into(),
output_schema: None,
source_receipt_ids: vec![],
temperature: Some(0.0),
max_output_tokens: Some(16),
};
let output = run_validated_stage(&PhysicallyRoutedModel, &request)
.await
.unwrap();
assert_eq!(output.receipt.provider, "openrouter");
assert_eq!(output.receipt.model, "stealth/ox-alpha");
let mut physical_request = request;
physical_request.model = "stealth/ox-alpha".into();
assert_eq!(
output.receipt.request_hash,
format!(
"sha256:{:x}",
Sha256::digest(serde_json::to_vec(&physical_request).unwrap())
)
);
}
#[test]
fn deepseek_response_preserves_usage_metadata_without_reasoning_content() {
let output = decode_deepseek_response(&serde_json::json!({
"id":"request-7",
"model":"deepseek-v4-flash",
"system_fingerprint":"fp-live",
"choices":[{
"finish_reason":"stop",
@ -427,6 +493,7 @@ mod tests {
}))
.unwrap();
assert_eq!(output.content, "ready");
assert_eq!(output.resolved_model.as_deref(), Some("deepseek-v4-flash"));
assert_eq!(output.provider_request_id.as_deref(), Some("request-7"));
assert_eq!(output.finish_reason.as_deref(), Some("stop"));
assert_eq!(output.token_usage.as_ref().unwrap().total_tokens, 150);
@ -469,6 +536,62 @@ mod tests {
assert!(narrative.get("temperature").is_none());
assert!(narrative.get("response_format").is_none());
}
#[test]
fn openrouter_requests_use_the_selected_physical_model_and_hide_reasoning() {
let request = ModelStageRequest {
stage: "interpreter".into(),
model: MODEL_FAST.into(),
snapshot_binding: "campaign:one:revision:4".into(),
lived_stream: "fixture".into(),
output_schema: Some(serde_json::json!({"type":"object"})),
source_receipt_ids: vec![],
temperature: None,
max_output_tokens: Some(321),
};
let body = openrouter_request_body(&request, "stealth/ox-alpha");
assert_eq!(body["model"], "stealth/ox-alpha");
assert_eq!(body["reasoning"]["effort"], "low");
assert_eq!(body["reasoning"]["exclude"], true);
assert_eq!(body["response_format"]["type"], "json_object");
assert_eq!(body["temperature"].as_f64(), Some(0.0));
assert!(body.get("thinking").is_none());
let mut capable = request;
capable.model = MODEL_CAPABLE.into();
assert_eq!(
openrouter_request_body(&capable, "stealth/ox-alpha")["reasoning"]["effort"],
"high"
);
}
#[test]
fn openrouter_response_preserves_cache_usage_without_reasoning_content() {
let output = decode_openai_chat_response(
&serde_json::json!({
"id":"generation-9",
"model":"stealth/ox-alpha",
"choices":[{
"finish_reason":"stop",
"message":{"content":"ready", "reasoning":"private"}
}],
"usage":{
"prompt_tokens":120,
"completion_tokens":30,
"total_tokens":150,
"prompt_tokens_details":{"cached_tokens":80},
"completion_tokens_details":{"reasoning_tokens":0}
}
}),
"OpenRouter",
)
.unwrap();
assert_eq!(output.resolved_model.as_deref(), Some("stealth/ox-alpha"));
let usage = output.token_usage.as_ref().unwrap();
assert_eq!(usage.prompt_cache_hit_tokens, 80);
assert_eq!(usage.prompt_cache_miss_tokens, 40);
assert!(!format!("{output:?}").contains("private"));
}
}
#[derive(Clone)]
@ -491,9 +614,19 @@ pub struct DeepSeekPort {
client: reqwest::Client,
api_key: Zeroizing<String>,
endpoint: String,
fast_model: String,
capable_model: String,
}
impl DeepSeekPort {
pub fn new(api_key: String) -> Self {
Self::with_models(api_key, "deepseek-v4-flash", "deepseek-v4-pro")
}
pub fn with_models(
api_key: String,
fast_model: impl Into<String>,
capable_model: impl Into<String>,
) -> Self {
Self {
client: reqwest::Client::builder()
.connect_timeout(std::time::Duration::from_secs(10))
@ -501,10 +634,11 @@ impl DeepSeekPort {
.expect("static DeepSeek client configuration is valid"),
api_key: Zeroizing::new(api_key),
endpoint: "https://api.deepseek.com/chat/completions".into(),
fast_model: fast_model.into(),
capable_model: capable_model.into(),
}
}
#[cfg(windows)]
#[cfg(windows)]
pub fn from_machine_dpapi(path: impl AsRef<std::path::Path>) -> Result<Self> {
Ok(Self::new(crate::windows_secret::unprotect_machine_utf8(
@ -522,22 +656,42 @@ impl DeepSeekPort {
}
pub fn from_runtime_secret(path: impl AsRef<std::path::Path>) -> Result<Self> {
Self::from_runtime_secret_with_models(path, "deepseek-v4-flash", "deepseek-v4-pro")
}
pub fn from_runtime_secret_with_models(
path: impl AsRef<std::path::Path>,
fast_model: impl Into<String>,
capable_model: impl Into<String>,
) -> Result<Self> {
#[cfg(windows)]
if path
.as_ref()
.extension()
.is_some_and(|value| value == "dpapi")
{
return Self::from_machine_dpapi(path);
return Ok(Self::with_models(
crate::windows_secret::unprotect_machine_utf8(path)?,
fast_model,
capable_model,
));
}
Self::from_utf8_secret_file(path)
let bytes = Zeroizing::new(std::fs::read(path.as_ref())?);
let secret = std::str::from_utf8(bytes.as_slice())?.trim().to_owned();
if secret.is_empty() {
anyhow::bail!("DeepSeek credential file is empty");
}
Ok(Self::with_models(secret, fast_model, capable_model))
}
async fn run_with_observation(
&self,
request: &ModelStageRequest,
) -> Result<ModelProviderOutput> {
let body = deepseek_request_body(request);
let resolved_model = resolve_model(request, &self.fast_model, &self.capable_model);
let mut routed_request = request.clone();
routed_request.model.clone_from(&resolved_model);
let body = deepseek_request_body(&routed_request);
let value: serde_json::Value = self
.client
.post(&self.endpoint)
@ -548,7 +702,9 @@ impl DeepSeekPort {
.error_for_status()?
.json()
.await?;
decode_deepseek_response(&value)
let mut output = decode_deepseek_response(&value)?;
output.resolved_model = Some(resolved_model);
Ok(output)
}
}
@ -584,11 +740,146 @@ impl ModelPort for DeepSeekPort {
}
fn decode_deepseek_response(value: &serde_json::Value) -> Result<ModelProviderOutput> {
decode_openai_chat_response(value, "DeepSeek")
}
pub struct OpenRouterPort {
client: reqwest::Client,
api_key: Zeroizing<String>,
endpoint: String,
fast_model: String,
capable_model: String,
}
impl OpenRouterPort {
pub fn new(
api_key: String,
fast_model: impl Into<String>,
capable_model: impl Into<String>,
) -> Self {
Self {
client: reqwest::Client::builder()
.connect_timeout(std::time::Duration::from_secs(10))
.build()
.expect("static OpenRouter client configuration is valid"),
api_key: Zeroizing::new(api_key),
endpoint: "https://openrouter.ai/api/v1/chat/completions".into(),
fast_model: fast_model.into(),
capable_model: capable_model.into(),
}
}
pub fn from_utf8_secret_file(
path: impl AsRef<std::path::Path>,
fast_model: impl Into<String>,
capable_model: impl Into<String>,
) -> Result<Self> {
let bytes = Zeroizing::new(std::fs::read(path.as_ref())?);
let secret = std::str::from_utf8(bytes.as_slice())?.trim().to_owned();
if secret.is_empty() {
anyhow::bail!("OpenRouter credential file is empty");
}
Ok(Self::new(secret, fast_model, capable_model))
}
pub fn from_runtime_secret(
path: impl AsRef<std::path::Path>,
fast_model: impl Into<String>,
capable_model: impl Into<String>,
) -> Result<Self> {
#[cfg(windows)]
if path
.as_ref()
.extension()
.is_some_and(|value| value == "dpapi")
{
return Ok(Self::new(
crate::windows_secret::unprotect_machine_utf8(path)?,
fast_model,
capable_model,
));
}
Self::from_utf8_secret_file(path, fast_model, capable_model)
}
async fn run_with_observation(
&self,
request: &ModelStageRequest,
) -> Result<ModelProviderOutput> {
let resolved_model = resolve_model(request, &self.fast_model, &self.capable_model);
let body = openrouter_request_body(request, &resolved_model);
let value: serde_json::Value = self
.client
.post(&self.endpoint)
.bearer_auth(self.api_key.as_str())
.header("HTTP-Referer", "https://ghostlight.gamecult.org")
.header("X-Title", "Ghostlight Dungeon")
.json(&body)
.send()
.await?
.error_for_status()?
.json()
.await?;
let mut output = decode_openai_chat_response(&value, "OpenRouter")?;
output.resolved_model = Some(resolved_model);
Ok(output)
}
}
fn openrouter_request_body(request: &ModelStageRequest, resolved_model: &str) -> serde_json::Value {
let mut body = serde_json::json!({
"model": resolved_model,
"messages": [{"role": "user", "content": request.lived_stream}],
"stream": false,
"reasoning": {
"effort": if request.model == MODEL_CAPABLE { "high" } else { "low" },
"exclude": true
}
});
if request.output_schema.is_some() {
body["response_format"] = serde_json::json!({"type":"json_object"});
body["temperature"] = serde_json::json!(request.temperature.unwrap_or(0.0));
} else if let Some(temperature) = request.temperature {
body["temperature"] = serde_json::json!(temperature);
}
if let Some(max_tokens) = request.max_output_tokens {
body["max_tokens"] = serde_json::json!(max_tokens);
}
body
}
#[async_trait]
impl ModelPort for OpenRouterPort {
async fn run(&self, request: &ModelStageRequest) -> Result<String> {
Ok(self.run_with_observation(request).await?.content)
}
async fn run_observed(&self, request: &ModelStageRequest) -> Result<ModelProviderOutput> {
self.run_with_observation(request).await
}
fn provider(&self) -> &'static str {
"openrouter"
}
}
fn resolve_model(request: &ModelStageRequest, fast_model: &str, capable_model: &str) -> String {
match request.model.as_str() {
MODEL_FAST => fast_model.to_owned(),
MODEL_CAPABLE => capable_model.to_owned(),
explicit => explicit.to_owned(),
}
}
fn decode_openai_chat_response(
value: &serde_json::Value,
provider_name: &str,
) -> Result<ModelProviderOutput> {
let content = 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"))?;
.ok_or_else(|| anyhow!("{provider_name} response contained no assistant content"))?;
let token_usage = value
.get("usage")
.filter(|usage| !usage.is_null())
@ -598,16 +889,27 @@ fn decode_deepseek_response(value: &serde_json::Value) -> Result<ModelProviderOu
total_tokens: usage["total_tokens"].as_u64().unwrap_or_default(),
prompt_cache_hit_tokens: usage["prompt_cache_hit_tokens"]
.as_u64()
.or_else(|| usage["prompt_tokens_details"]["cached_tokens"].as_u64())
.unwrap_or_default(),
prompt_cache_miss_tokens: usage["prompt_cache_miss_tokens"]
.as_u64()
.unwrap_or_default(),
prompt_cache_miss_tokens: usage["prompt_cache_miss_tokens"].as_u64().unwrap_or_else(
|| {
usage["prompt_tokens"]
.as_u64()
.unwrap_or_default()
.saturating_sub(
usage["prompt_tokens_details"]["cached_tokens"]
.as_u64()
.unwrap_or_default(),
)
},
),
reasoning_tokens: usage["completion_tokens_details"]["reasoning_tokens"]
.as_u64()
.unwrap_or_default(),
});
Ok(ModelProviderOutput {
content,
resolved_model: value["model"].as_str().map(str::to_owned),
provider_request_id: value["id"].as_str().map(str::to_owned),
system_fingerprint: value["system_fingerprint"].as_str().map(str::to_owned),
finish_reason: value["choices"][0]["finish_reason"]

View file

@ -3,7 +3,7 @@ use crate::{
Campaign, CellActionProposal, StrategicActivityKind, StrategicActivityOutcome,
StrategicCellEffect, StrategicOutcomeBand, StrategicOutcomeEffect, StrategicTickPlan,
},
model::{ModelPort, ModelStageOutput, ModelStageRequest, run_validated_stage},
model::{MODEL_FAST, ModelPort, ModelStageOutput, ModelStageRequest, run_validated_stage},
resolution::{cell_action_digest, effective_member_knowledge, subject_state_references},
};
use anyhow::{Result, anyhow};
@ -155,7 +155,7 @@ pub async fn resolve_activity_outcomes(
);
let mut request = ModelStageRequest {
stage: "strategic_outcome_resolver".into(),
model: "deepseek-v4-flash".into(),
model: MODEL_FAST.into(),
snapshot_binding: binding,
lived_stream: format!(
"{static_contract}\n\nOUTCOME_CONTEXT:\n{}",
@ -274,7 +274,7 @@ async fn verify_outcomes(
);
let request = ModelStageRequest {
stage: "strategic_outcome_verifier".into(),
model: "deepseek-v4-flash".into(),
model: MODEL_FAST.into(),
snapshot_binding: format!(
"{}:verifier:{outcome_hash}",
activity_outcome_binding(

View file

@ -3,7 +3,7 @@ use crate::{
AgencyAxis, AgencySubjectKind, Campaign, ResolutionDemand, ResolutionWaveCommit,
SimulationCell,
},
model::{ModelPort, ModelStageOutput, ModelStageRequest, run_validated_stage},
model::{MODEL_FAST, ModelPort, ModelStageOutput, ModelStageRequest, run_validated_stage},
outcome::{activity_outcome_binding, resolve_activity_outcomes},
persona::{
CellConstituentSlice, CellMemberSlice, CellPerceivedEventSlice, CellProjectionEngine,
@ -80,9 +80,9 @@ pub async fn propose_resolution_wave_with_policy(
let engine = CellProjectionEngine {
model,
permit,
projector_model: "deepseek-v4-flash".into(),
persona_model: "deepseek-v4-flash".into(),
interpreter_model: "deepseek-v4-flash".into(),
projector_model: MODEL_FAST.into(),
persona_model: MODEL_FAST.into(),
interpreter_model: MODEL_FAST.into(),
campaign_contract: campaign_contract.cloned(),
aggregate_boundaries: aggregate_boundaries.to_vec(),
};
@ -263,7 +263,7 @@ async fn project_resolution_demand(
);
let mut request = ModelStageRequest {
stage: "resolution_demand".into(),
model: "deepseek-v4-flash".into(),
model: MODEL_FAST.into(),
snapshot_binding: format!(
"campaign:{}:revision:{}:resolution:{}",
campaign.id, campaign.revision, campaign.resolution_policy.resolution_epoch