"""FastAPI Microservice exposing L1 Ingress, L3 Dispatch, and Multi-Agent LangGraph Orchestrator.""" from __future__ import annotations from typing import Any from fastapi import FastAPI from pydantic import BaseModel, Field from agent_orchestrator import CANONICAL_SYSTEM_BASELINE, run_orchestration from agent_security_engine import ( GLOBAL_CORRELATOR, OriginRecord, OriginType, SideEffectScope, compute_prompt_drift, create_origin_record, evaluate_dispatch, validate_ingress, ) app = FastAPI( title="ShadowSpark AI Agent Security & Orchestration Service", version="1.2.0", description=( "4-Layer Security Engine (L1 Ingress, L2 Origin & HMAC Session Chain, " "L3 PreToolUse Side-Effect Hook, L4 Cross-Event Correlation) + LangGraph Orchestrator." ), ) class IngressValidateRequest(BaseModel): text: str = Field(..., description="Raw input or metadata string to validate and sanitize.") origin_type: OriginType = Field(default="user_turn", description="Origin trust classification.") session_id: str = Field(default="default-session", description="Session identifier for HMAC chaining.") prev_tag: str | None = Field(default=None, description="Optional previous turn HMAC tag.") system_prompt_candidate: str | None = Field( default=None, description="Optional system prompt candidate to check L2 baseline drift." ) class DispatchEvaluateRequest(BaseModel): tool_name: str = Field(..., description="Name of the tool being invoked.") tool_args: dict[str, Any] = Field(default_factory=dict, description="Arguments passed to the tool.") origin_record: dict[str, Any] | None = Field( default=None, description="Signed L2 OriginRecord dictionary (if omitted, one is minted for evaluation)." ) origin_type: OriginType = Field(default="user_turn", description="Fallback origin_type if origin_record is omitted.") session_id: str = Field(default="default-session") side_effect: SideEffectScope | None = Field(default=None, description="Explicit side-effect scope override.") class OrchestrateRunRequest(BaseModel): raw_input: str = Field(..., description="User or external task payload.") session_id: str = Field(default="default-session") origin_type: OriginType = Field(default="user_turn") requested_tool: str = Field(default="read_file") requested_args: dict[str, Any] = Field(default_factory=lambda: {"path": "README.md"}) system_prompt_candidate: str | None = Field(default=None) @app.get("/") @app.get("/health") def health() -> dict[str, Any]: return { "status": "ok", "version": "1.2.0", "layers": ["L1_INGRESS", "L2_ORIGIN_HMAC_CHAIN", "L3_PRE_TOOL_USE", "L4_CORRELATION"], "endpoints": [ "POST /v1/ingress/validate", "POST /v1/dispatch/evaluate", "POST /v1/orchestrate/run", ], } @app.post("/v1/ingress/validate") def api_validate_ingress(req: IngressValidateRequest) -> dict[str, Any]: ingress = validate_ingress(req.text) session_state = GLOBAL_CORRELATOR.get_session(req.session_id) prev_tag = req.prev_tag if req.prev_tag is not None else session_state.last_tag origin = create_origin_record( sanitized_text=ingress.sanitized_text, origin_type=req.origin_type, session_id=req.session_id, turn_index=session_state.turn_count, prev_tag=prev_tag, ) drift = compute_prompt_drift( CANONICAL_SYSTEM_BASELINE, req.system_prompt_candidate or CANONICAL_SYSTEM_BASELINE, ) return { "ingress": ingress.to_dict(), "origin_record": origin.to_dict(), "drift_metrics": drift.to_dict(), } @app.post("/v1/dispatch/evaluate") def api_evaluate_dispatch(req: DispatchEvaluateRequest) -> dict[str, Any]: if req.origin_record is not None: origin = OriginRecord(**req.origin_record) else: session_state = GLOBAL_CORRELATOR.get_session(req.session_id) origin = create_origin_record( sanitized_text=f"{req.tool_name}:{req.tool_args}", origin_type=req.origin_type, session_id=req.session_id, turn_index=session_state.turn_count, prev_tag=session_state.last_tag, ) decision = evaluate_dispatch( tool_name=req.tool_name, tool_args=req.tool_args, origin_record=origin, side_effect=req.side_effect, ) return { "decision": decision.to_dict(), "origin_record": origin.to_dict(), } @app.post("/v1/orchestrate/run") def api_orchestrate_run(req: OrchestrateRunRequest) -> dict[str, Any]: result = run_orchestration( raw_input=req.raw_input, session_id=req.session_id, origin_type=req.origin_type, requested_tool=req.requested_tool, requested_args=req.requested_args, system_prompt_candidate=req.system_prompt_candidate, ) return dict(result)