aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / cortex-rs / src / main.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | fn default_db_path() -> PathBuf { |
| 17 | let home = std::env::var("HOME") |
| 18 | .or_else(|_| std::env::var("USERPROFILE")) |
| 19 | .unwrap_or_else(|_| ".".to_string()); |
| 20 | PathBuf::from(home).join(".config/cortex/cortex.db") |
| 21 | } |
| 22 | |
| 23 | use aien_localhttp::Client; |
| 24 | use axum::{ |
| 25 | middleware, |
| 26 | routing::{get, post}, |
| 27 | Router, |
| 28 | }; |
| 29 | use clap::Parser; |
| 30 | use std::fs; |
| 31 | use std::net::SocketAddr; |
| 32 | use std::path::PathBuf; |
| 33 | use std::sync::Arc; |
| 34 | use tokio::sync::Semaphore; |
| 35 | use tower_http::cors::{Any, CorsLayer}; |
| 36 | use tower_http::trace::TraceLayer; |
| 37 | use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; |
| 38 | |
| 39 | use cortex_rs::auth::auth_middleware; |
| 40 | use cortex_rs::bench; |
| 41 | use cortex_rs::db::Database; |
| 42 | use cortex_rs::handlers::*; |
| 43 | use cortex_rs::models::CortexEntity; |
| 44 | |
| 45 | #[derive(Parser, Debug)] |
| 46 | #[command(name = "cortex-rs", about = "Sovereign Native Memory Engine in Rust")] |
| 47 | struct Args { |
| 48 | #[arg(long, default_value = "127.0.0.1")] |
| 49 | host: String, |
| 50 | |
| 51 | #[arg(long, default_value = "18080")] |
| 52 | port: u16, |
| 53 | |
| 54 | #[arg(long, default_value_os_t = default_db_path())] |
| 55 | db_path: PathBuf, |
| 56 | |
| 57 | #[arg(long, default_value = "http://127.0.0.1:18081")] |
| 58 | encoder_url: String, |
| 59 | |
| 60 | #[arg(long)] |
| 61 | import: Option<PathBuf>, |
| 62 | |
| 63 | #[arg(long)] |
| 64 | bench: bool, |
| 65 | |
| 66 | #[arg(long, default_value = "1000")] |
| 67 | bench_records: usize, |
| 68 | } |
| 69 | |
| 70 | #[tokio::main] |
| 71 | async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 72 | let args = Args::parse(); |
| 73 | |
| 74 | if args.bench { |
| 75 | return bench::run_benchmark(args.bench_records); |
| 76 | } |
| 77 | |
| 78 | // The encoder client speaks plain http only (aien-localhttp). Refuse an |
| 79 | // unusable --encoder-url at startup instead of degrading every write and |
| 80 | // recall to lexical-only with a warning per request. |
| 81 | cortex_rs::embeddings::validate_encoder_url(&args.encoder_url)?; |
| 82 | |
| 83 | tracing_subscriber::registry() |
| 84 | .with( |
| 85 | tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), |
| 86 | ) |
| 87 | .with(tracing_subscriber::fmt::layer()) |
| 88 | .init(); |
| 89 | |
| 90 | tracing::info!( |
| 91 | "Initializing Cortex-RS SQLite database at {:?}...", |
| 92 | args.db_path |
| 93 | ); |
| 94 | if let Some(parent) = args.db_path.parent() { |
| 95 | let _ = fs::create_dir_all(parent); |
| 96 | } |
| 97 | |
| 98 | let database = Arc::new(Database::open(&args.db_path)?); |
| 99 | |
| 100 | if let Some(import_file) = &args.import { |
| 101 | tracing::info!("Importing existing entities from {:?}...", import_file); |
| 102 | if import_file.exists() { |
| 103 | let data = fs::read_to_string(import_file)?; |
| 104 | let raw_list: Vec<serde_json::Value> = serde_json::from_str(&data)?; |
| 105 | let mut count = 0; |
| 106 | for val in raw_list { |
| 107 | let entity_val = if let Some(e) = val.get("entity") { |
| 108 | e.clone() |
| 109 | } else { |
| 110 | val |
| 111 | }; |
| 112 | if let Ok(entity) = serde_json::from_value::<CortexEntity>(entity_val) { |
| 113 | let _ = database.import_entity_raw(&entity, None); |
| 114 | count += 1; |
| 115 | } |
| 116 | } |
| 117 | tracing::info!("Successfully imported {} entities into SQLite!", count); |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | let state = Arc::new(AppState { |
| 122 | db: database, |
| 123 | http_client: Client::new(), |
| 124 | encoder_url: args.encoder_url, |
| 125 | worker_limit: Arc::new(Semaphore::new(2)), |
| 126 | }); |
| 127 | |
| 128 | let protected_routes = Router::new() |
| 129 | .route("/api/cortex/write", post(write_handler)) |
| 130 | .route( |
| 131 | "/api/cortex/search", |
| 132 | get(search_get_handler).post(search_post_handler), |
| 133 | ) |
| 134 | .route("/api/cortex/recall", post(recall_handler)) |
| 135 | .route("/api/cortex/get", get(get_handler)) |
| 136 | .route("/api/cortex/traverse", post(traverse_handler)) |
| 137 | .route("/api/cortex/v2/sessions", post(create_session_handler)) |
| 138 | .route("/api/cortex/v2/sessions/:id", get(get_session_handler)) |
| 139 | .route( |
| 140 | "/api/cortex/v2/sessions/:id/close", |
| 141 | post(close_session_handler), |
| 142 | ) |
| 143 | .route( |
| 144 | "/api/cortex/v2/sessions/:id/events", |
| 145 | get(get_session_events_handler).post(batch_append_events_handler), |
| 146 | ) |
| 147 | .route( |
| 148 | "/api/cortex/v2/sessions/:id/watermark", |
| 149 | get(get_watermark_handler).post(set_watermark_handler), |
| 150 | ) |
| 151 | .route("/api/cortex/v2/candidates", get(get_candidates_handler)) |
| 152 | .route( |
| 153 | "/api/cortex/v2/candidates/:id", |
| 154 | get(get_candidate_by_id_handler), |
| 155 | ) |
| 156 | .route( |
| 157 | "/api/cortex/v2/candidates/:id/promote", |
| 158 | post(promote_candidate_handler), |
| 159 | ) |
| 160 | .route( |
| 161 | "/api/cortex/v2/sessions/:id/process", |
| 162 | post(process_session_handler), |
| 163 | ) |
| 164 | .route("/api/cortex/v2/context", post(compile_context_handler)) |
| 165 | .layer(middleware::from_fn(auth_middleware)); |
| 166 | |
| 167 | // Loopback origins only by default. A deployment that serves the cockpit on |
| 168 | // another address lists it in CORTEX_EXTRA_ORIGINS (comma-separated). |
| 169 | let mut origins: Vec<axum::http::HeaderValue> = vec![ |
| 170 | "http://127.0.0.1:18095".parse().unwrap(), |
| 171 | "http://localhost:18095".parse().unwrap(), |
| 172 | ]; |
| 173 | if let Ok(extra) = std::env::var("CORTEX_EXTRA_ORIGINS") { |
| 174 | for o in extra.split(',').map(str::trim).filter(|o| !o.is_empty()) { |
| 175 | match o.parse() { |
| 176 | Ok(v) => origins.push(v), |
| 177 | Err(_) => tracing::warn!("ignoring invalid CORTEX_EXTRA_ORIGINS entry {o:?}"), |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | let app = Router::new() |
| 183 | .route("/health", get(health_handler)) |
| 184 | .route("/status", get(health_handler)) |
| 185 | .merge(protected_routes) |
| 186 | .layer( |
| 187 | CorsLayer::new() |
| 188 | .allow_origin(origins) |
| 189 | .allow_methods(Any) |
| 190 | .allow_headers(Any), |
| 191 | ) |
| 192 | .layer(TraceLayer::new_for_http()) |
| 193 | .with_state(state); |
| 194 | |
| 195 | // INVARIANT: Bind strictly to loopback 127.0.0.1 to guarantee zero LAN exposure unless configured |
| 196 | if args.host != "127.0.0.1" && args.host != "localhost" { |
| 197 | tracing::warn!( |
| 198 | "Non-loopback binding detected ({}); enforcing local authentication.", |
| 199 | args.host |
| 200 | ); |
| 201 | } |
| 202 | |
| 203 | let addr: SocketAddr = format!("{}:{}", args.host, args.port) |
| 204 | .parse() |
| 205 | .unwrap_or_else(|_| SocketAddr::from(([127, 0, 0, 1], args.port))); |
| 206 | tracing::info!("Cortex-RS server listening on http://{}", addr); |
| 207 | |
| 208 | let listener = tokio::net::TcpListener::bind(addr).await?; |
| 209 | axum::serve(listener, app).await?; |
| 210 | |
| 211 | Ok(()) |
| 212 | } |