File size: 19,641 Bytes
1269259 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | // SPF Smart Gateway - Unified Dispatch Protocol
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Foundation layer for ALL tool routing.
// Every transport (stdio, HTTP, mesh, voice) converges here.
// Zero dependencies on pipelines, mesh, or any higher layer.
//
// REFACTOR: gate::process() called at entry before handle_tool_call.
// Gate is the door. handle_tool_call is pure execution — no gate inside.
// source from request flows through gate so decisions are source-aware.
//
// Design: Listener pattern. Layers register as listeners.
// dispatch::call() notifies them. Dispatch never imports them.
//
// BLOCK I ADDITIONS: Source::Transformer, Source::Pipeline variants
// BLOCK S ADDITIONS: Timed try_lock, poisoned mutex recovery, SERVER_BUSY response
// BLOCK U ADDITIONS: catch_unwind for listeners, blocked param in on_response
// FL-1A: Source-aware lock — Stdio=blocking, others=timed try_lock (Block S)
// FL-1C: FLINT intercept — pre-execution brain query, post-execution store/enrich
use crate::http::ServerState;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;
use std::time::{Duration, Instant};
// ============================================================================
// CONSTANTS
// ============================================================================
pub const GATE_BLOCKED: &str = "blocked";
pub const GATE_ALLOWED: &str = "ok";
pub const GATE_BUSY: &str = "busy";
const LOCK_TIMEOUT: Duration = Duration::from_secs(5);
const LOCK_RETRY_INTERVAL_MS: u64 = 50;
// ============================================================================
// PROTOCOL TYPES
// ============================================================================
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Source {
Stdio,
Http,
Mesh { peer_key: String },
Transformer { role: String, model_id: String },
Pipeline { stream_id: String, peer_key: String },
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolRequest {
pub source: Source,
pub tool: String,
pub args: Value,
pub timestamp: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResponse {
pub tool: String,
pub result: Value,
pub duration_ms: u64,
pub status: String,
}
// ============================================================================
// LISTENER TRAIT
// ============================================================================
pub trait DispatchListener: Send + Sync {
fn on_request(&self, req: &ToolRequest);
fn on_response(&self, req: &ToolRequest, resp: &ToolResponse, blocked: bool);
}
// ============================================================================
// DISPATCH — gate first, then execution
// ============================================================================
/// Unified dispatch. All transports call this.
/// Gate fires BEFORE handle_tool_call — gate is the door.
///
/// Flow:
/// 1. Build request
/// 2. Notify listeners (pre-gate observation)
/// 3. FLINT intercept (pre-execution — brain context query)
/// 4. Acquire session lock (source-aware: Stdio=blocking, others=timed)
/// 5. gate::process() — source-aware check
/// 6. If blocked → return blocked response
/// 7. If allowed → handle_tool_call (pure execution)
/// 8. FLINT process result (post-execution — store, enrich)
/// 9. Notify listeners with result
pub fn call(state: &Arc<ServerState>, source: Source, tool: &str, args: &Value) -> ToolResponse {
let start = Instant::now();
let timestamp = chrono::Utc::now().to_rfc3339();
let request = ToolRequest {
source,
tool: tool.to_string(),
args: args.clone(),
timestamp,
};
// Notify listeners pre-gate (observation of what was attempted)
for listener in &state.listeners {
if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
listener.on_request(&request);
})) {
eprintln!("[SPF-DISPATCH] Listener panic on_request for {}: {:?}", tool, e);
}
}
// ── FL-1C: FLINT pre-execution intercept ─────────────────────────────────
// Runs BEFORE session lock — brain Mutex is independent, zero contention.
// FLINT observes and queries context. Does NOT gate — gate gates.
let flint_ctx = crate::flint_memory::flint_intercept(tool, args);
// ── FL-1A: Source-aware lock strategy ─────────────────────────────────────
// Stdio: blocking lock — MCP protocol has no retry mechanism.
// Single-threaded stdin reader, guaranteed to complete.
// All others: timed try_lock with Block S timeout + SERVER_BUSY.
// Concurrent transports (HTTP, Mesh, Pipeline) need graceful timeout.
let session_lock = match &request.source {
Source::Stdio => {
// Stdio: blocking lock — always succeeds (handles poison)
match state.session.lock() {
Ok(guard) => Some(guard),
Err(poisoned) => {
eprintln!("[SPF-DISPATCH] Session mutex poisoned — recovering for {}", tool);
Some(poisoned.into_inner())
}
}
}
_ => {
// All others: timed try_lock (Block S) — SERVER_BUSY on timeout
let mut acquired = None;
let lock_start = Instant::now();
loop {
match state.session.try_lock() {
Ok(guard) => { acquired = Some(guard); break; }
Err(std::sync::TryLockError::Poisoned(poisoned)) => {
eprintln!("[SPF-DISPATCH] Session mutex poisoned — recovering for {}", tool);
acquired = Some(poisoned.into_inner());
break;
}
Err(std::sync::TryLockError::WouldBlock) => {
if lock_start.elapsed() >= LOCK_TIMEOUT { break; }
std::thread::sleep(Duration::from_millis(LOCK_RETRY_INTERVAL_MS));
}
}
}
let wait_ms = lock_start.elapsed().as_millis();
if wait_ms > 100 {
eprintln!("[SPF-DISPATCH] Session lock contention — {} waited {}ms", tool, wait_ms);
}
acquired
}
};
// If lock timed out → SERVER_BUSY
let mut session = match session_lock {
Some(guard) => guard,
None => {
let elapsed = start.elapsed().as_millis() as u64;
eprintln!("[SPF-DISPATCH] SESSION_BUSY — {} timed out after {}ms", tool, elapsed);
let response = ToolResponse {
tool: tool.to_string(),
result: serde_json::json!({
"type": "text",
"text": "SERVER_BUSY: Session locked by another transport. Try again."
}),
duration_ms: elapsed,
status: GATE_BUSY.to_string(),
};
for listener in &state.listeners {
if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
listener.on_response(&request, &response, false);
})) {
eprintln!("[SPF-DISPATCH] Listener panic on_response for {}: {:?}", tool, e);
}
}
return response;
}
};
// ── GATE ENTRY — fires before any execution ───────────────────────────────
let entry_params = crate::mcp::extract_gate_params(args);
let gate_decision = crate::gate::process(
tool, &entry_params, &state.config, &*session, &request.source
);
let result = if !gate_decision.allowed {
// Blocked — record and return immediately, no execution
session.record_manifest(tool, gate_decision.complexity.c, "BLOCKED",
gate_decision.errors.first().map(|s| s.as_str()));
let _ = state.storage.save_session(&session);
serde_json::json!({
"type": "text",
"text": gate_decision.message,
"_blocked": true
})
} else {
// Allowed — execute through handle_tool_call (pure execution, no gate inside)
crate::mcp::handle_tool_call(
tool, args, request.source.clone(), &gate_decision,
&state.config, &mut session, &state.storage,
&state.config_db, &state.tmp_db,
&state.fs_db, &state.agent_db,
&state.pub_key_hex, &state.mesh_tx,
&state.peers,
&state.transformer, &state.transformer_config,
&state.network_config, &state.pool_state,
&state.pipeline,
&state.browser, &state.ws_browser_channels, state.http_port,
&state.tracked_peers, &state.orchestrator_state,
&state.endpoint, &state.tokio_handle,
)
};
drop(session);
// ── FL-1C: FLINT post-execution processing ───────────────────────────────
// Runs AFTER session lock dropped — stores high-value results, enriches.
// Brain and agent_state locks are independent — zero contention.
let result = crate::flint_memory::flint_process_result(
tool, &result, &flint_ctx, &state.agent_db
);
let duration_ms = start.elapsed().as_millis() as u64;
let blocked = result.get("_blocked").and_then(|v| v.as_bool()).unwrap_or(false);
let status = if blocked { GATE_BLOCKED } else { GATE_ALLOWED };
let response = ToolResponse {
tool: tool.to_string(),
result,
duration_ms,
status: status.to_string(),
};
// Notify listeners with result
for listener in &state.listeners {
if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
listener.on_response(&request, &response, blocked);
})) {
eprintln!("[SPF-DISPATCH] Listener panic on_response for {}: {:?}", tool, e);
}
}
response
}
// ============================================================================
// TESTS
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lock_constants_valid() {
assert!(LOCK_TIMEOUT.as_secs() > 0, "LOCK_TIMEOUT must be positive");
assert!(LOCK_RETRY_INTERVAL_MS > 0, "LOCK_RETRY_INTERVAL_MS must be positive");
let attempts = LOCK_TIMEOUT.as_millis() / LOCK_RETRY_INTERVAL_MS as u128;
assert!(attempts >= 10, "Should attempt at least 10 retries, got {}", attempts);
assert!(attempts <= 500, "Should not exceed 500 retries, got {}", attempts);
}
#[test]
fn busy_response_structure() {
let response = ToolResponse {
tool: "spf_read".to_string(),
result: serde_json::json!({
"type": "text",
"text": "SERVER_BUSY: Session locked by another transport. Try again."
}),
duration_ms: 5001,
status: "busy".to_string(),
};
assert_eq!(response.status, "busy");
assert_eq!(response.tool, "spf_read");
let text = response.result["text"].as_str().unwrap();
assert!(text.starts_with("SERVER_BUSY:"));
}
#[test]
fn source_variants_serialize() {
let stdio = Source::Stdio;
let json = serde_json::to_string(&stdio).unwrap();
assert!(json.contains("Stdio"));
let http = Source::Http;
let json = serde_json::to_string(&http).unwrap();
assert!(json.contains("Http"));
let mesh = Source::Mesh { peer_key: "abc123".to_string() };
let json = serde_json::to_string(&mesh).unwrap();
assert!(json.contains("abc123"));
let transformer = Source::Transformer {
role: "writer".to_string(),
model_id: "spf_writer_v1".to_string(),
};
let json = serde_json::to_string(&transformer).unwrap();
assert!(json.contains("writer"));
assert!(json.contains("spf_writer_v1"));
let pipeline = Source::Pipeline {
stream_id: "stream_001".to_string(),
peer_key: "peer_abc".to_string(),
};
let json = serde_json::to_string(&pipeline).unwrap();
assert!(json.contains("stream_001"));
assert!(json.contains("peer_abc"));
}
#[test]
fn source_variants_deserialize_roundtrip() {
let transformer = Source::Transformer {
role: "researcher".to_string(),
model_id: "spf_researcher_v1".to_string(),
};
let json = serde_json::to_string(&transformer).unwrap();
let back: Source = serde_json::from_str(&json).unwrap();
match back {
Source::Transformer { role, model_id } => {
assert_eq!(role, "researcher");
assert_eq!(model_id, "spf_researcher_v1");
}
_ => panic!("Expected Source::Transformer"),
}
let pipeline = Source::Pipeline {
stream_id: "s42".to_string(),
peer_key: "pk99".to_string(),
};
let json = serde_json::to_string(&pipeline).unwrap();
let back: Source = serde_json::from_str(&json).unwrap();
match back {
Source::Pipeline { stream_id, peer_key } => {
assert_eq!(stream_id, "s42");
assert_eq!(peer_key, "pk99");
}
_ => panic!("Expected Source::Pipeline"),
}
}
#[test]
fn original_variants_unchanged() {
let sources = vec![
Source::Stdio,
Source::Http,
Source::Mesh { peer_key: "key".to_string() },
];
for src in sources {
let json = serde_json::to_string(&src).unwrap();
let _back: Source = serde_json::from_str(&json).unwrap();
// If this compiles and runs, existing variants still work
}
}
#[test]
fn tool_request_with_new_sources() {
let req = ToolRequest {
source: Source::Transformer {
role: "writer".to_string(),
model_id: "v1".to_string(),
},
tool: "spf_read".to_string(),
args: serde_json::json!({"file_path": "/test"}),
timestamp: "2026-02-28T00:00:00Z".to_string(),
};
let json = serde_json::to_string(&req).unwrap();
let back: ToolRequest = serde_json::from_str(&json).unwrap();
assert_eq!(back.tool, "spf_read");
match back.source {
Source::Transformer { role, .. } => assert_eq!(role, "writer"),
_ => panic!("Wrong source variant"),
}
}
// ====== BLOCK U TESTS — Listener registration, panic safety, blocked status ======
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
struct MockListener {
request_count: AtomicU32,
response_count: AtomicU32,
last_blocked: AtomicBool,
}
impl MockListener {
fn new() -> Self {
Self {
request_count: AtomicU32::new(0),
response_count: AtomicU32::new(0),
last_blocked: AtomicBool::new(false),
}
}
}
impl DispatchListener for MockListener {
fn on_request(&self, _req: &ToolRequest) {
self.request_count.fetch_add(1, Ordering::SeqCst);
}
fn on_response(&self, _req: &ToolRequest, _resp: &ToolResponse, blocked: bool) {
self.response_count.fetch_add(1, Ordering::SeqCst);
self.last_blocked.store(blocked, Ordering::SeqCst);
}
}
struct PanicListener;
impl DispatchListener for PanicListener {
fn on_request(&self, _req: &ToolRequest) {
panic!("PanicListener intentional panic on request");
}
fn on_response(&self, _req: &ToolRequest, _resp: &ToolResponse, _blocked: bool) {
panic!("PanicListener intentional panic on response");
}
}
#[test]
fn listener_receives_pre_and_post() {
let listener = MockListener::new();
let req = ToolRequest {
source: Source::Stdio,
tool: "spf_read".to_string(),
args: serde_json::json!({}),
timestamp: "2026-02-28T00:00:00Z".to_string(),
};
let resp = ToolResponse {
tool: "spf_read".to_string(),
result: serde_json::json!({"type": "text", "text": "ok"}),
duration_ms: 10,
status: GATE_ALLOWED.to_string(),
};
// Simulate dispatch calling on_request then on_response
listener.on_request(&req);
listener.on_response(&req, &resp, false);
assert_eq!(listener.request_count.load(Ordering::SeqCst), 1);
assert_eq!(listener.response_count.load(Ordering::SeqCst), 1);
assert!(!listener.last_blocked.load(Ordering::SeqCst));
}
#[test]
fn listener_panic_does_not_crash() {
let listener = PanicListener;
let req = ToolRequest {
source: Source::Stdio,
tool: "spf_read".to_string(),
args: serde_json::json!({}),
timestamp: "2026-02-28T00:00:00Z".to_string(),
};
let resp = ToolResponse {
tool: "spf_read".to_string(),
result: serde_json::json!({"type": "text", "text": "ok"}),
duration_ms: 10,
status: GATE_ALLOWED.to_string(),
};
// catch_unwind should prevent crash — exactly as dispatch::call() does
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
listener.on_request(&req);
}));
assert!(result.is_err(), "Panic should be caught on request");
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
listener.on_response(&req, &resp, false);
}));
assert!(result.is_err(), "Panic should be caught on response");
// Test passes = server didn't crash
}
#[test]
fn listener_receives_blocked_status() {
let listener = MockListener::new();
let req = ToolRequest {
source: Source::Http,
tool: "spf_write".to_string(),
args: serde_json::json!({"file_path": "/etc/passwd"}),
timestamp: "2026-02-28T00:00:00Z".to_string(),
};
// Gate-blocked response
let blocked_resp = ToolResponse {
tool: "spf_write".to_string(),
result: serde_json::json!({"type": "text", "text": "BLOCKED: path not allowed", "_blocked": true}),
duration_ms: 5,
status: GATE_BLOCKED.to_string(),
};
listener.on_response(&req, &blocked_resp, true);
assert!(listener.last_blocked.load(Ordering::SeqCst), "Listener should receive blocked=true");
// Gate-allowed response
let allowed_resp = ToolResponse {
tool: "spf_read".to_string(),
result: serde_json::json!({"type": "text", "text": "file contents"}),
duration_ms: 12,
status: GATE_ALLOWED.to_string(),
};
listener.on_response(&req, &allowed_resp, false);
assert!(!listener.last_blocked.load(Ordering::SeqCst), "Listener should receive blocked=false");
}
}
|