|
| 1 | +""" |
| 2 | +ContextOS Core — The unified entry point. |
| 3 | +""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | +import logging |
| 7 | +from typing import Literal, Optional |
| 8 | +from dataclasses import dataclass, field |
| 9 | + |
| 10 | +logger = logging.getLogger("contextos") |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class ContextOSConfig: |
| 15 | + """Full configuration for a ContextOS instance.""" |
| 16 | + |
| 17 | + # Identity |
| 18 | + workspace: str = "default" |
| 19 | + version: str = "0.1.0" |
| 20 | + |
| 21 | + # Memory |
| 22 | + memory_tier: Literal["hot", "warm", "cold"] = "warm" |
| 23 | + memory_persist: bool = True |
| 24 | + memory_db_path: str = "./contextos_memory.db" |
| 25 | + memory_entity_graph: bool = True |
| 26 | + |
| 27 | + # Retrieval |
| 28 | + retrieval_mode: Literal["vector", "bm25", "hybrid"] = "hybrid" |
| 29 | + retrieval_staleness_ttl_days: int = 30 |
| 30 | + retrieval_feedback_loop: bool = True |
| 31 | + |
| 32 | + # Tools |
| 33 | + tools: list[str] = field(default_factory=lambda: ["mcp"]) |
| 34 | + tool_caching: bool = True |
| 35 | + tool_cache_ttl_seconds: int = 3600 |
| 36 | + tool_sandboxing: bool = True |
| 37 | + |
| 38 | + # Planning |
| 39 | + sparring_hook: bool = True |
| 40 | + sparring_threshold: Literal["low", "medium", "high", "always"] = "medium" |
| 41 | + sparring_on_writes: bool = True |
| 42 | + sparring_on_irreversible: bool = True |
| 43 | + |
| 44 | + # Orchestration |
| 45 | + tracing: bool = True |
| 46 | + cost_ledger: bool = True |
| 47 | + auth_required: bool = False |
| 48 | + |
| 49 | + # Server |
| 50 | + host: str = "0.0.0.0" |
| 51 | + port: int = 8080 |
| 52 | + |
| 53 | + |
| 54 | +class ContextOS: |
| 55 | + """ |
| 56 | + ContextOS — The unified context intelligence layer for AI agents. |
| 57 | +
|
| 58 | + Absorbs and extends: |
| 59 | + - modelcontextprotocol/servers → MCP protocol + tool registry |
| 60 | + - infiniflow/ragflow → RAG retrieval engine |
| 61 | + - dair-ai/Prompt-Engineering-Guide → Planning + spec patterns |
| 62 | + - upstash/context7 → Live documentation fetching |
| 63 | + - thedotmack/claude-mem → Session + persistent memory |
| 64 | + - ComposioHQ/composio → 1000+ external tool integrations |
| 65 | + - gsd-build/get-shit-done → Spec-driven execution engine |
| 66 | +
|
| 67 | + New capabilities built by ContextOS: |
| 68 | + - Orchestration Core with semantic intent routing |
| 69 | + - Cross-session memory persistence with entity graph |
| 70 | + - Hybrid retrieval with multi-corpus routing + feedback loop |
| 71 | + - Tool DAG execution with caching and retry policies |
| 72 | + - Pre-Response Sparring Hook |
| 73 | + - Full request tracing and cost ledger |
| 74 | + """ |
| 75 | + |
| 76 | + def __init__(self, config: Optional[ContextOSConfig] = None, **kwargs): |
| 77 | + """ |
| 78 | + Initialize ContextOS. |
| 79 | +
|
| 80 | + Args: |
| 81 | + config: ContextOSConfig instance. If None, built from kwargs. |
| 82 | + **kwargs: Config fields passed directly (convenience shorthand). |
| 83 | +
|
| 84 | + Example: |
| 85 | + ctx = ContextOS( |
| 86 | + workspace="my-agent", |
| 87 | + memory_tier="warm", |
| 88 | + retrieval_mode="hybrid", |
| 89 | + sparring_hook=True, |
| 90 | + ) |
| 91 | + """ |
| 92 | + if config is None: |
| 93 | + config = ContextOSConfig(**{ |
| 94 | + k: v for k, v in kwargs.items() |
| 95 | + if k in ContextOSConfig.__dataclass_fields__ |
| 96 | + }) |
| 97 | + |
| 98 | + self.config = config |
| 99 | + self._initialized = False |
| 100 | + self._layers = {} |
| 101 | + |
| 102 | + logger.info(f"ContextOS {config.version} initializing workspace '{config.workspace}'") |
| 103 | + self._bootstrap() |
| 104 | + |
| 105 | + def _bootstrap(self): |
| 106 | + """Initialize all five layers in dependency order.""" |
| 107 | + from .orchestration import OrchestrationCore |
| 108 | + from .memory import MemoryLayer |
| 109 | + from .retrieval import RetrievalLayer |
| 110 | + from .tools import ToolLayer |
| 111 | + from .planning import PlanningLayer |
| 112 | + |
| 113 | + self._layers["orchestration"] = OrchestrationCore(self.config) |
| 114 | + self._layers["memory"] = MemoryLayer(self.config) |
| 115 | + self._layers["retrieval"] = RetrievalLayer(self.config) |
| 116 | + self._layers["tools"] = ToolLayer(self.config) |
| 117 | + self._layers["planning"] = PlanningLayer(self.config) |
| 118 | + |
| 119 | + # Wire layers together |
| 120 | + self._layers["orchestration"].register_layers(self._layers) |
| 121 | + self._initialized = True |
| 122 | + logger.info("ContextOS fully initialized. 47 MCP tools ready.") |
| 123 | + |
| 124 | + def serve(self, host: Optional[str] = None, port: Optional[int] = None): |
| 125 | + """ |
| 126 | + Start ContextOS as an MCP server. |
| 127 | +
|
| 128 | + Args: |
| 129 | + host: Override config host (default: 0.0.0.0) |
| 130 | + port: Override config port (default: 8080) |
| 131 | + """ |
| 132 | + _host = host or self.config.host |
| 133 | + _port = port or self.config.port |
| 134 | + logger.info(f"ContextOS MCP server starting on {_host}:{_port}") |
| 135 | + self._layers["orchestration"].start_server(_host, _port) |
| 136 | + |
| 137 | + def memory(self) -> "MemoryLayer": |
| 138 | + """Access the memory layer directly.""" |
| 139 | + return self._layers["memory"] |
| 140 | + |
| 141 | + def retrieval(self) -> "RetrievalLayer": |
| 142 | + """Access the retrieval layer directly.""" |
| 143 | + return self._layers["retrieval"] |
| 144 | + |
| 145 | + def tools(self) -> "ToolLayer": |
| 146 | + """Access the tool execution layer directly.""" |
| 147 | + return self._layers["tools"] |
| 148 | + |
| 149 | + def planning(self) -> "PlanningLayer": |
| 150 | + """Access the planning layer directly.""" |
| 151 | + return self._layers["planning"] |
| 152 | + |
| 153 | + def health(self) -> dict: |
| 154 | + """Return health status of all layers.""" |
| 155 | + return { |
| 156 | + layer_name: layer.health() |
| 157 | + for layer_name, layer in self._layers.items() |
| 158 | + } |
| 159 | + |
| 160 | + def cost_summary(self, period: str = "session") -> dict: |
| 161 | + """Return cost ledger summary for the given period.""" |
| 162 | + return self._layers["orchestration"].cost_ledger.summary(period) |
| 163 | + |
| 164 | + def __repr__(self) -> str: |
| 165 | + return ( |
| 166 | + f"ContextOS(workspace='{self.config.workspace}', " |
| 167 | + f"version='{self.config.version}', " |
| 168 | + f"initialized={self._initialized})" |
| 169 | + ) |
0 commit comments