diff --git a/N8N_ARCHITECTURE.md b/N8N_ARCHITECTURE.md index 42e5e92963c41c71bb963709356255fa1eab8bd2..78d6a8d600237b1eec1bbc256da1437244a11262 100644 --- a/N8N_ARCHITECTURE.md +++ b/N8N_ARCHITECTURE.md @@ -5,12 +5,58 @@ The "Google Antigravity" Neural Router Treat n8n as a **Neural Router**, decoupling "Thinking" (Logic/Architecture) from "Inference" (Execution/Code). This bypasses latencies and refusals by routing tasks to the most efficient model. ## 2. Infrastructure: The "OpenAI-Compatible" Bridge +**Optimization**: Run n8n **NATIVELY** on Windows (`npm install -g n8n`) instead of Docker. +- **Why**: Eliminates the `host.docker.internal` bridge bottleneck. +- **Effect**: N8N talks directly to `localhost:1234` with zero latency overhead. + Standardize all providers to the OpenAI API protocol. ### Local (Code & Privacy) -- **Tool**: Ollama / LM Studio -- **Endpoint**: `http://localhost:11434/v1` -- **Model**: `dolphin-llama3` (Uncensored, fast, obedient) +- **Tool**: Ollama / LM Studio (The "New Friends" Cluster) +- **Endpoint**: + - Ollama: `http://localhost:11434/v1` + - LM Studio: `http://localhost:1234/v1` +### Local Stack (The "Nano Swarm") +Instead of one giant model, use a stack of specialized lightweight models to save RAM: +- **Router/Logic**: `nvidia/nemotron-3-nano` or `Phi-3-Mini` (High logic/param ratio). +- **Coding**: `deepseek-coder-6.7b` or `dolphin-2.9-llama3-8b`. +- **Creative**: `openhermes-2.5-mistral-7b`. + +**Configuration**: +- **Endpoint**: `http://localhost:1234/v1` +- **Multi-Model**: If using LM Studio, load the specific model needed for the batch, or run multiple instances on ports `1234`, `1235`, `1236`. + +### Workflow Import +A ready-to-use workflow file has been generated at: +`hf_space/logos_n8n_workflow.json` + +**Usage**: +1. Open N8N Editor. +2. Click **Workflow** > **Import from File**. +3. Select `logos_n8n_workflow.json`. +4. Execute. It will scan your codebase using the Local Nano Swarm. + +### Connection Health Check +Verify the stack is active with this rhyme test: +```bash +curl http://localhost:1234/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "nvidia/nemotron-3-nano", + "messages": [ + {"role": "system", "content": "Always answer in rhymes. Today is Thursday"}, + {"role": "user", "content": "What day is it today?"} + ], + "temperature": 0.7, + "stream": false +}' +``` +2. Click the **Local Server** icon (`<->`) on the left sidebar. +3. Ensure settings: + - **Port**: `1234` + - **CORS**: On (Recommended) +4. Click **Start Server**. +5. *Green Light*: The log should say `Server listening on http://localhost:1234`. ### High-Speed Inference (Math & Logic) - **Tool**: DeepInfra / Groq @@ -33,6 +79,14 @@ Classifies incoming request type: Use **Merge Node (Wait Mode)** to execute paths simultaneously. 1. **Path 1 (Math)**: DeepSeek analyzes Prime Potentiality/Manifold logic. 2. **Path 2 (Code)**: Dolphin writes adapters/scripts locally. + - *Implementation Helper*: + ```python + # Use a pipeline as a high-level helper for local execution + from transformers import pipeline + pipe = pipeline("text-generation", model="dphn/Dolphin-X1-8B-GGUF") + messages = [{"role": "user", "content": "Write the adapter."}] + pipe(messages) + ``` 3. **Path 3 (Sys)**: Gemini drafts Strategy/README. ### Phase C: Consensus (The Annealing) diff --git a/analyze_uploads.py b/analyze_uploads.py index 1259c5cc75618c8e8b7006ca7eb333750c40cb7e..fd66b7eb2e951d5e1a8a1365280d58e7078bd84b 100644 --- a/analyze_uploads.py +++ b/analyze_uploads.py @@ -9,14 +9,56 @@ sys.path.append(os.path.dirname(os.path.abspath(__file__))) from logos.connectors import get_connector def analyze_uploads(): - # Paths to uploaded images (Hardcoded from user context for this run) - base_dir = r"C:\Users\Nauti\.gemini\antigravity\brain\e29720ce-4e26-4c61-a243-8010483b5424" - images = glob.glob(os.path.join(base_dir, "uploaded_image_*.png")) + import argparse + parser = argparse.ArgumentParser(description="Analyze images from multiple folders.") + parser.add_argument("paths", nargs='*', help="File paths or glob patterns") + parser.add_argument("--recursive", "-r", action="store_true", help="Recursive search") + args = parser.parse_args() + + images = [] + if not args.paths: + # Default behavior: Search current dir + print("No paths provided. Searching current directory.") + images = glob.glob("*.png") + else: + for pattern in args.paths: + # Handle recursive globs (e.g. **/*.png) + if args.recursive and "**" not in pattern: + pattern = os.path.join(pattern, "**") + + # If pattern is a dir, add default extension + if os.path.isdir(pattern): + pattern = os.path.join(pattern, "*.png") + + found = glob.glob(pattern, recursive=args.recursive) + images.extend(found) + + # Remove duplicates + images = list(set(images)) print(f"Found {len(images)} images to analyze.") ocr = get_connector('ocr') - dolphin = get_connector('dolphin') + ocr = get_connector('ocr') + + # Try Local Stack first (Nano Swarm), fallback to Dolphin Cloud + try: + from logos.connectors import LocalLLMConnector + # Quick check if port 1234 is open + import socket + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + result = sock.connect_ex(('localhost', 1234)) + sock.close() + + if result == 0: + print("[INFO] Local Nano Swarm detected (Port 1234). Using Local Stack.") + dolphin = get_connector('local', model="local-model") + else: + print("[INFO] Local Stack offline. Falling back to Cloud Dolphin.") + dolphin = get_connector('dolphin') + except Exception as e: + print(f"[WARN] Local check failed ({e}). Defaulting to Cloud.") + dolphin = get_connector('dolphin') for img_path in images: print(f"\n--- Analyzing {os.path.basename(img_path)} ---") diff --git a/antigravity_workflow.json b/antigravity_workflow.json new file mode 100644 index 0000000000000000000000000000000000000000..6ae6c0af13484b05caf9d35a20dcdff4ce9b396d --- /dev/null +++ b/antigravity_workflow.json @@ -0,0 +1,345 @@ +{ + "name": "Antigravity Image Research Extractor", + "nodes": [ + { + "parameters": { + "path": "C:/Users/Nauti/Desktop/LOGOS CURSOR/LOGOS Notes", + "fileExtensions": "jpg,jpeg,png,pdf,heic", + "options": { + "recurse": true + } + }, + "id": "image_scanner", + "name": "Scan Images (Notes)", + "type": "n8n-nodes-base.readFilesFromFolder", + "position": [ + 250, + 300 + ] + }, + { + "parameters": { + "jsCode": "// ROUTER: Classify images for specialized analysis\nconst images = items.map(item => {\n const fileName = item.json.fileName;\n const fileSize = item.json.size || 0;\n \n let taskType = 'general_vision';\n let priority = 1;\n \n // Route by filename patterns and size\n if (fileName.includes('diagram') || fileName.includes('sketch')) {\n taskType = 'diagram_analysis';\n priority = 3;\n } else if (fileName.includes('note') || fileName.includes('handwritten')) {\n taskType = 'handwriting_ocr';\n priority = 2;\n } else if (fileName.includes('ui') || fileName.includes('interface')) {\n taskType = 'ui_analysis';\n priority = 3;\n } else if (fileSize < 500000) {\n taskType = 'handwriting_ocr'; // Smaller files likely notes\n priority = 2;\n } else {\n taskType = 'diagram_analysis'; // Larger files likely detailed diagrams\n priority = 3;\n }\n \n return {\n json: {\n fileName,\n taskType,\n priority,\n fullPath: item.json.directory + '/' + fileName,\n fileSize\n },\n binary: item.binary\n };\n});\n\nreturn images;" + }, + "id": "router", + "name": "Neural Router", + "type": "n8n-nodes-base.code", + "position": [ + 450, + 300 + ] + }, + { + "parameters": { + "conditions": { + "options": { + "caseSensitive": false + }, + "conditions": [ + { + "id": "handwriting_path", + "leftValue": "={{ $json.taskType }}", + "rightValue": "handwriting_ocr", + "operator": { + "type": "string", + "operation": "equals" + } + }, + { + "id": "diagram_path", + "leftValue": "={{ $json.taskType }}", + "rightValue": "diagram_analysis", + "operator": { + "type": "string", + "operation": "equals" + } + }, + { + "id": "ui_path", + "leftValue": "={{ $json.taskType }}", + "rightValue": "ui_analysis", + "operator": { + "type": "string", + "operation": "equals" + } + } + ] + }, + "options": {} + }, + "id": "switch", + "name": "Task Switch", + "type": "n8n-nodes-base.switch", + "position": [ + 650, + 300 + ] + }, + { + "parameters": { + "method": "POST", + "url": "https://api-inference.huggingface.co/models/microsoft/trocr-base-handwritten", + "authentication": "genericCredentialType", + "genericAuthType": "httpHeaderAuth", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={\n \"inputs\": \"{{ $binary.data.toString('base64') }}\"\n}", + "options": {} + }, + "id": "ocr_analyst", + "name": "OCR Handwriting (TrOCR)", + "type": "n8n-nodes-base.httpRequest", + "position": [ + 850, + 200 + ] + }, + { + "parameters": { + "method": "POST", + "url": "http://localhost:1234/v1/chat/completions", + "authentication": "none", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={\n \"model\": \"llava-v1.6-mistral-7b\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are a technical diagram analyst specializing in geometry, polyforms, and compression systems. Identify: 1) Mathematical concepts shown, 2) Geometric shapes/polyhedra types, 3) Compression techniques mentioned, 4) UI/workflow elements. Output structured JSON.\"\n },\n {\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": \"Analyze this diagram from {{ $json.fileName }}. Focus on polyform development, compression methods, and UI design.\"\n },\n {\n \"type\": \"image_url\",\n \"image_url\": {\n \"url\": \"data:image/jpeg;base64,{{ $binary.data.toString('base64') }}\"\n }\n }\n ]\n }\n ],\n \"temperature\": 0.2,\n \"max_tokens\": 1500\n}", + "options": {} + }, + "id": "diagram_analyst", + "name": "Diagram Analyst (LLaVA)", + "type": "n8n-nodes-base.httpRequest", + "position": [ + 850, + 300 + ] + }, + { + "parameters": { + "method": "POST", + "url": "http://localhost:1234/v1/chat/completions", + "authentication": "none", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={\n \"model\": \"llava-v1.6-mistral-7b\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are a UI/UX analyst. Extract: 1) Interface components shown, 2) Interaction patterns, 3) Data visualization methods, 4) Success indicators mentioned, 5) User workflow steps. Output structured JSON.\"\n },\n {\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": \"Analyze UI design from {{ $json.fileName }}. Identify successful patterns for polyform visualization and user interaction.\"\n },\n {\n \"type\": \"image_url\",\n \"image_url\": {\n \"url\": \"data:image/jpeg;base64,{{ $binary.data.toString('base64') }}\"\n }\n }\n ]\n }\n ],\n \"temperature\": 0.3,\n \"max_tokens\": 1200\n}", + "options": {} + }, + "id": "ui_analyst", + "name": "UI Analyst (LLaVA)", + "type": "n8n-nodes-base.httpRequest", + "position": [ + 850, + 400 + ] + }, + { + "parameters": { + "mode": "mergeByPosition", + "options": {} + }, + "id": "merge", + "name": "Merge Analysis", + "type": "n8n-nodes-base.merge", + "position": [ + 1050, + 300 + ] + }, + { + "parameters": { + "jsCode": "// SYNTHESIS: Parse vision model responses and structure results\nconst results = items.map(item => {\n let analysis = {};\n \n try {\n // Handle TrOCR response (array format)\n if (Array.isArray(item.json)) {\n analysis = {\n extracted_text: item.json[0]?.generated_text || item.json.toString(),\n confidence: item.json[0]?.score || 0.8\n };\n }\n // Handle LLaVA response (OpenAI format)\n else if (item.json.choices) {\n const content = item.json.choices[0]?.message?.content || '{}';\n analysis = JSON.parse(content);\n }\n // Handle direct JSON response\n else if (typeof item.json === 'object') {\n analysis = item.json;\n }\n else {\n analysis = { raw_response: JSON.stringify(item.json) };\n }\n } catch (e) {\n analysis = {\n raw_response: JSON.stringify(item.json),\n parse_error: true,\n error_detail: e.message\n };\n }\n \n return {\n json: {\n file: item.json.fileName || 'unknown',\n taskType: item.json.taskType,\n analysis,\n timestamp: new Date().toISOString()\n }\n };\n});\n\nreturn results;" + }, + "id": "synthesizer", + "name": "Synthesizer", + "type": "n8n-nodes-base.code", + "position": [ + 1250, + 300 + ] + }, + { + "parameters": { + "method": "POST", + "url": "http://localhost:1234/v1/chat/completions", + "authentication": "none", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={\n \"model\": \"nvidia/nemotron-3-nano\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"You are the RESEARCH SYNTHESIZER for a polyform compression project. Analyze handwritten notes and diagrams to extract: 1) POLYFORM TYPES (Platonic, Archimedean, Johnson, near-miss solids, geodesics), 2) COMPRESSION METHODS (vertex encoding, edge compression, spheroid nets), 3) SUCCESSFUL UI PATTERNS from iterations, 4) MATHEMATICAL INSIGHTS (topology, manifolds, optimization), 5) CRITICAL GAPS to address. Output: Executive Summary, Key Findings by Category, Priority Next Steps, Integration Opportunities.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"Synthesize these image analyses from research notes:\\n\\n{{ JSON.stringify($json) }}\\n\\nFocus on actionable insights for building the polyform generator and compression library.\"\n }\n ],\n \"temperature\": 0.3,\n \"max_tokens\": 3000\n}", + "options": {} + }, + "id": "jury", + "name": "Jury Consensus (Nemotron)", + "type": "n8n-nodes-base.httpRequest", + "position": [ + 1450, + 300 + ] + }, + { + "parameters": { + "operation": "write", + "fileName": "=/tmp/polyform_research_{{ DateTime.now().toFormat('yyyyMMdd_HHmmss') }}.json", + "options": {} + }, + "id": "save_results", + "name": "Save Research Synthesis", + "type": "n8n-nodes-base.writeFile", + "position": [ + 1650, + 300 + ] + } + ], + "connections": { + "image_scanner": { + "main": [ + [ + { + "node": "router", + "type": "main", + "index": 0 + } + ] + ] + }, + "router": { + "main": [ + [ + { + "node": "switch", + "type": "main", + "index": 0 + } + ] + ] + }, + "switch": { + "main": [ + [ + { + "node": "ocr_analyst", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "diagram_analyst", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "ui_analyst", + "type": "main", + "index": 0 + } + ] + ] + }, + "ocr_analyst": { + "main": [ + [ + { + "node": "merge", + "type": "main", + "index": 0 + } + ] + ] + }, + "diagram_analyst": { + "main": [ + [ + { + "node": "merge", + "type": "main", + "index": 1 + } + ] + ] + }, + "ui_analyst": { + "main": [ + [ + { + "node": "merge", + "type": "main", + "index": 2 + } + ] + ] + }, + "merge": { + "main": [ + [ + { + "node": "synthesizer", + "type": "main", + "index": 0 + } + ] + ] + }, + "synthesizer": { + "main": [ + [ + { + "node": "jury", + "type": "main", + "index": 0 + } + ] + ] + }, + "jury": { + "main": [ + [ + { + "node": "save_results", + "type": "main", + "index": 0 + } + ] + ] + } + }, + "settings": { + "executionOrder": "v1" + } +} \ No newline at end of file diff --git a/app.py b/app.py index 76cc34e44118d22308b8c23e974c763552755596..51008a5ba781402fc0e29b8e4478d7ff8c883d5f 100644 --- a/app.py +++ b/app.py @@ -391,34 +391,14 @@ with gr.Blocks(theme=gr.themes.Monochrome(), title="LOGOS SPCW Protocol") as dem history = history or [] history.append((message, None)) - # Try Dolphin connector first, fallback to simple response + # 1. Try Local Swarm (Protocol 5: Privacy First) try: from logos.connectors import get_connector - dolphin = get_connector('dolphin') + # Prioritize Local + agent = get_connector('local') - # Load Knowledge Base for Self-Contained Context - kb_context = "" - try: - import json - if os.path.exists("logos_knowledge_base.json"): - with open("logos_knowledge_base.json", "r") as f: - kb_data = json.load(f) - # Summarize KB: List documents and word counts - docs = kb_data.get('documents', []) - kb_context = "\nINTERNAL KNOWLEDGE BASE:\n" - for d in docs: - kb_context += f"- Doc: {d.get('filename')} ({d.get('word_count')} words)\n" - # Inject full text if small enough, otherwise summary - text = d.get('full_text', '') - if len(text) < 1000: - kb_context += f" Content: {text}\n" - else: - kb_context += f" Excerpt: {text[:500]}...\n" - except Exception: - kb_context = "\n[Knowledge Base Not Loaded]" - # LOGOS System Context - logos_context = f"""You are LOGOS, an AI assistant specialized in: + logos_context = f"""You are LOGOS (Local Swarm Node), specialized in: - Prime Network Architecture (integer topology, GCD routing) - SPCW (Structured Prime Composite Waveform) protocol - Hex/Binary Dissolution and enterprise routing @@ -426,10 +406,13 @@ with gr.Blocks(theme=gr.themes.Monochrome(), title="LOGOS SPCW Protocol") as dem {kb_context} """ + response = agent.chat(message, system_prompt=logos_context) - # Use Dolphin Chat - # My DolphinAgentConnector.chat takes (message, system_prompt) - response = dolphin.chat(message, system_prompt=logos_context) + # If Local failed, try Cloud Dolphin + if "[Local LLM Error]" in response: + agent = get_connector('dolphin') + response = agent.chat(message, system_prompt=logos_context) + history[-1] = (message, response) except Exception as e: # Fallback response @@ -470,6 +453,205 @@ with gr.Blocks(theme=gr.themes.Monochrome(), title="LOGOS SPCW Protocol") as dem btn_refresh = gr.Button("๐Ÿ”„ Refresh Status") btn_refresh.click(lambda: get_connector_status(), None, status_display) + with gr.Tab("๐Ÿ”ฎ Manifold Geometry"): + gr.Markdown("## Protocol 5: Prime Topology Viewer") + gr.Markdown("*Live Telemetry from the Matroska Router*") + + with gr.Row(): + with gr.Column(): + gr.Markdown("### ๐Ÿš Shell Token Intake") + shell_plot = gr.Plot(label="Token Consumption by Shell") + with gr.Column(): + gr.Markdown("### ๐Ÿง  Macro Context (Recent Intent)") + context_log = gr.Dataframe(headers=["Time", "Shell", "Summary"], label="Swarm Memory") + + manifold_timer = gr.Timer(5) # Auto-refresh every 5s + + def fetch_manifold_data(): + """Poll the Router for State.""" + import requests + import pandas as pd + try: + # Target Router specifically (Port 5000) + url = "http://localhost:5000/v1" + resp = requests.get(url, timeout=1) + data = resp.json() + state = data.get("manifold_state", {}) + + # 1. Plot Shell Stats + shells = state.get("shells", {}) + names = list(shells.keys()) + tokens = [shells[k]["tokens_intake"] for k in names] + + # Color mapping for shells + colors = { + "INNER_SHELL": "#00ffea", # Cyan (Structure) + "PRIME_CHANNEL": "#9d4edd", # Purple (Math) + "OUTER_SHELL": "#ff0055" # Red (Entropy) + } + bar_colors = [colors.get(n, "#888") for n in names] + + # --- 3D Manifold Structure (AlphaFold View) --- + nodes = state.get("graph", {}).get("nodes", []) + if nodes: + x_vals = [n["geometry"]["position"]["x"] for n in nodes if "position" in n.get("geometry", {})] + y_vals = [n["geometry"]["position"]["y"] for n in nodes if "position" in n.get("geometry", {})] + z_vals = [n["geometry"]["position"]["z"] for n in nodes if "position" in n.get("geometry", {})] + colors = [1 if n["geometry"]["domain"] == "OUTER_SHELL" else 0.5 if n["geometry"]["domain"] == "PRIME_CHANNEL" else 0 for n in nodes if "position" in n.get("geometry", {})] + text_labels = [n["name"] for n in nodes if "position" in n.get("geometry", {})] + + # Map Liveness to Opacity/Size + opacity_vals = [0.8 if n.get("alive", 1) == 1 else 0.1 for n in nodes if "position" in n.get("geometry", {})] + size_vals = [5 if n.get("alive", 1) == 1 else 2 for n in nodes if "position" in n.get("geometry", {})] + + # Map Liveness & Morphogenesis to Visuals + colors = [] + for n in nodes: + if "position" not in n.get("geometry", {}): + continue + + action = n.get("action_pending") + if action == "MITOSIS": + colors.append("#00FF00") # Green for Growth/Split + elif action == "REGENERATE": + colors.append("#FFD700") # Gold for Healing + elif action == "SPAWN_META_TOKEN": + colors.append("#00FFFF") # Azure for Birth + elif n.get("alive", 1) == 1: + # Normal Alive: Domain Color matches Plotly defaults for Shells + d = n["geometry"]["domain"] + if d == "OUTER_SHELL": colors.append(1) + elif d == "PRIME_CHANNEL": colors.append(0.5) + else: colors.append(0) + else: + colors.append("#222222") # Dead/Gray + + text_labels = [] + for n in nodes: + if "position" in n.get("geometry", {}): + status = "ALIVE" if n.get("alive", 1) else "DEAD" + action = n.get("action_pending", "") + label = f"{n['name']} ({status})" + if action: label += f" [{action}]" + text_labels.append(label) + + fig = go.Figure(data=[go.Scatter3d( + x=x_vals, y=y_vals, z=z_vals, + mode='markers', + text=text_labels, + marker=dict( + size=size_vals, + color=colors, + colorscale='Viridis', + opacity=opacity_vals + ) + )]) + fig.update_layout( + title="Codebase Manifold Geometry", + scene=dict( + xaxis_title='Hash Resonance (X)', + yaxis_title='Hash Resonance (Y)', + zaxis_title='Domain Depth (Z)' + ), + margin=dict(l=0, r=0, b=0, t=30) + ) + else: + # Fallback empty plot + fig = go.Figure() + fig.add_annotation(text="No 3D graph data available.", showarrow=False) + + # 2. Context Log + ctx = state.get("macro_context", []) + df_data = [] + for c in reversed(ctx): # Show newest first + t_str = time.strftime('%H:%M:%S', time.localtime(c['time'])) + df_data.append([t_str, c['shell'], c['summary']]) + + if not df_data: + df_data = [["-", "-", "No history yet"]] + + return fig, df_data + + except Exception as e: + # Return empty/error state + err_fig = go.Figure() + err_fig.add_annotation(text=f"Router Offline: {e}", showarrow=False) + return err_fig, [["ERROR", "-", str(e)]] + + manifold_timer.tick(fetch_manifold_data, outputs=[shell_plot, context_log]) + # Initial load + demo.load(fetch_manifold_data, outputs=[shell_plot, context_log]) + + with gr.Tab("๐Ÿš€ Mission Control"): + gr.Markdown("## Unified Command Deck") + gr.Markdown("*Manage your agents and workflows from a single pane.*") + + with gr.Row(): + with gr.Column(scale=1): + gr.Markdown("### ๐Ÿ“ก Local Nanostack (The Swarm)") + swarm_status = gr.Markdown("Checking...") + btn_ping = gr.Button("Ping Localhost:1234") + + with gr.Column(scale=2): + gr.Markdown("### โšก Workflow Actions") + with gr.Row(): + btn_scan = gr.Button("๐Ÿ“‚ Analyze Notes (Run Script)", variant="secondary") + btn_n8n = gr.Button("๐Ÿ”— Import N8N Workflow", link="file=hf_space/logos_n8n_workflow.json") + + log_output = gr.Code(label="System Logs / Analysis Output", language="markdown", lines=20) + + def check_swarm(): + """Ping Localhost:1234 (Auto-detecting Docker Bridge)""" + endpoints = [ + "http://localhost:1234/v1/models", + "http://host.docker.internal:1234/v1/models" + ] + + for url in endpoints: + try: + import requests + resp = requests.get(url, timeout=2) + if resp.status_code == 200: + models = [m['id'] for m in resp.json().get('data', [])] + host_alias = "Localhost" if "localhost" in url else "DockerHost" + return f"### โœ… ONLINE ({host_alias})\n**Port:** 1234\n**Active Models:**\n`{', '.join(models[:3])}`" + except: + continue + + return "### ๐Ÿ”ด OFFLINE\nEnsure LM Studio Server is running on Port 1234." + + def run_analysis_script(): + """Run analyze_uploads.py and capture output""" + import subprocess + try: + # Run the script we upgraded earlier + result = subprocess.run( + [sys.executable, "hf_space/analyze_uploads.py", "--recursive"], + capture_output=True, + text=True, + cwd=os.path.dirname(current_dir) # Run from project root + ) + + output = f"### Execution Result (Exit Code: {result.returncode})\n\n" + if result.stdout: + output += f"**STDOUT**:\n```\n{result.stdout}\n```\n" + if result.stderr: + output += f"**STDERR**:\n```\n{result.stderr}\n```\n" + + if result.returncode == 0: + output += "\n\nโœ… Analysis Complete. Check knowledge base." + else: + output += "\n\nโŒ Analysis Failed." + + return output + except Exception as e: + return f"### Execution Error\n{str(e)}" + + btn_ping.click(check_swarm, None, swarm_status) + btn_scan.click(run_analysis_script, None, log_output) + # Auto-check on load + demo.load(check_swarm, None, swarm_status) + if __name__ == "__main__": # HF Spaces configuration diff --git a/dist/assets/index-EWlo7g0h.js b/dist/assets/index-EWlo7g0h.js new file mode 100644 index 0000000000000000000000000000000000000000..80422a98a6892cbbbb9519772c92f1f4be9c09e2 --- /dev/null +++ b/dist/assets/index-EWlo7g0h.js @@ -0,0 +1,9 @@ +(function(){const X=document.createElement("link").relList;if(X&&X.supports&&X.supports("modulepreload"))return;for(const B of document.querySelectorAll('link[rel="modulepreload"]'))h(B);new MutationObserver(B=>{for(const K of B)if(K.type==="childList")for(const ll of K.addedNodes)ll.tagName==="LINK"&&ll.rel==="modulepreload"&&h(ll)}).observe(document,{childList:!0,subtree:!0});function Q(B){const K={};return B.integrity&&(K.integrity=B.integrity),B.referrerPolicy&&(K.referrerPolicy=B.referrerPolicy),B.crossOrigin==="use-credentials"?K.credentials="include":B.crossOrigin==="anonymous"?K.credentials="omit":K.credentials="same-origin",K}function h(B){if(B.ep)return;B.ep=!0;const K=Q(B);fetch(B.href,K)}})();var nf={exports:{}},bu={};var vo;function Fy(){if(vo)return bu;vo=1;var A=Symbol.for("react.transitional.element"),X=Symbol.for("react.fragment");function Q(h,B,K){var ll=null;if(K!==void 0&&(ll=""+K),B.key!==void 0&&(ll=""+B.key),"key"in B){K={};for(var pl in B)pl!=="key"&&(K[pl]=B[pl])}else K=B;return B=K.ref,{$$typeof:A,type:h,key:ll,ref:B!==void 0?B:null,props:K}}return bu.Fragment=X,bu.jsx=Q,bu.jsxs=Q,bu}var ro;function Iy(){return ro||(ro=1,nf.exports=Fy()),nf.exports}var T=Iy(),cf={exports:{}},Z={};var go;function Py(){if(go)return Z;go=1;var A=Symbol.for("react.transitional.element"),X=Symbol.for("react.portal"),Q=Symbol.for("react.fragment"),h=Symbol.for("react.strict_mode"),B=Symbol.for("react.profiler"),K=Symbol.for("react.consumer"),ll=Symbol.for("react.context"),pl=Symbol.for("react.forward_ref"),U=Symbol.for("react.suspense"),E=Symbol.for("react.memo"),w=Symbol.for("react.lazy"),R=Symbol.for("react.activity"),cl=Symbol.iterator;function ql(d){return d===null||typeof d!="object"?null:(d=cl&&d[cl]||d["@@iterator"],typeof d=="function"?d:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,Y={};function H(d,z,M){this.props=d,this.context=z,this.refs=Y,this.updater=M||j}H.prototype.isReactComponent={},H.prototype.setState=function(d,z){if(typeof d!="object"&&typeof d!="function"&&d!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,d,z,"setState")},H.prototype.forceUpdate=function(d){this.updater.enqueueForceUpdate(this,d,"forceUpdate")};function al(){}al.prototype=H.prototype;function el(d,z,M){this.props=d,this.context=z,this.refs=Y,this.updater=M||j}var Ml=el.prototype=new al;Ml.constructor=el,_(Ml,H.prototype),Ml.isPureReactComponent=!0;var Hl=Array.isArray;function zl(){}var W={H:null,A:null,T:null,S:null},Zl=Object.prototype.hasOwnProperty;function wl(d,z,M){var N=M.ref;return{$$typeof:A,type:d,key:z,ref:N!==void 0?N:null,props:M}}function xt(d,z){return wl(d.type,z,d.props)}function Mt(d){return typeof d=="object"&&d!==null&&d.$$typeof===A}function Wl(d){var z={"=":"=0",":":"=2"};return"$"+d.replace(/[=:]/g,function(M){return z[M]})}var Ea=/\/+/g;function jt(d,z){return typeof d=="object"&&d!==null&&d.key!=null?Wl(""+d.key):z.toString(36)}function Et(d){switch(d.status){case"fulfilled":return d.value;case"rejected":throw d.reason;default:switch(typeof d.status=="string"?d.then(zl,zl):(d.status="pending",d.then(function(z){d.status==="pending"&&(d.status="fulfilled",d.value=z)},function(z){d.status==="pending"&&(d.status="rejected",d.reason=z)})),d.status){case"fulfilled":return d.value;case"rejected":throw d.reason}}throw d}function S(d,z,M,N,L){var k=typeof d;(k==="undefined"||k==="boolean")&&(d=null);var fl=!1;if(d===null)fl=!0;else switch(k){case"bigint":case"string":case"number":fl=!0;break;case"object":switch(d.$$typeof){case A:case X:fl=!0;break;case w:return fl=d._init,S(fl(d._payload),z,M,N,L)}}if(fl)return L=L(d),fl=N===""?"."+jt(d,0):N,Hl(L)?(M="",fl!=null&&(M=fl.replace(Ea,"$&/")+"/"),S(L,z,M,"",function(xe){return xe})):L!=null&&(Mt(L)&&(L=xt(L,M+(L.key==null||d&&d.key===L.key?"":(""+L.key).replace(Ea,"$&/")+"/")+fl)),z.push(L)),1;fl=0;var Vl=N===""?".":N+":";if(Hl(d))for(var Al=0;Al>>1,vl=S[ol];if(0>>1;olB(M,G))NB(L,M)?(S[ol]=L,S[N]=G,ol=N):(S[ol]=M,S[z]=G,ol=z);else if(NB(L,G))S[ol]=L,S[N]=G,ol=N;else break l}}return x}function B(S,x){var G=S.sortIndex-x.sortIndex;return G!==0?G:S.id-x.id}if(A.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var K=performance;A.unstable_now=function(){return K.now()}}else{var ll=Date,pl=ll.now();A.unstable_now=function(){return ll.now()-pl}}var U=[],E=[],w=1,R=null,cl=3,ql=!1,j=!1,_=!1,Y=!1,H=typeof setTimeout=="function"?setTimeout:null,al=typeof clearTimeout=="function"?clearTimeout:null,el=typeof setImmediate<"u"?setImmediate:null;function Ml(S){for(var x=Q(E);x!==null;){if(x.callback===null)h(E);else if(x.startTime<=S)h(E),x.sortIndex=x.expirationTime,X(U,x);else break;x=Q(E)}}function Hl(S){if(_=!1,Ml(S),!j)if(Q(U)!==null)j=!0,zl||(zl=!0,Wl());else{var x=Q(E);x!==null&&Et(Hl,x.startTime-S)}}var zl=!1,W=-1,Zl=5,wl=-1;function xt(){return Y?!0:!(A.unstable_now()-wlS&&xt());){var ol=R.callback;if(typeof ol=="function"){R.callback=null,cl=R.priorityLevel;var vl=ol(R.expirationTime<=S);if(S=A.unstable_now(),typeof vl=="function"){R.callback=vl,Ml(S),x=!0;break t}R===Q(U)&&h(U),Ml(S)}else h(U);R=Q(U)}if(R!==null)x=!0;else{var d=Q(E);d!==null&&Et(Hl,d.startTime-S),x=!1}}break l}finally{R=null,cl=G,ql=!1}x=void 0}}finally{x?Wl():zl=!1}}}var Wl;if(typeof el=="function")Wl=function(){el(Mt)};else if(typeof MessageChannel<"u"){var Ea=new MessageChannel,jt=Ea.port2;Ea.port1.onmessage=Mt,Wl=function(){jt.postMessage(null)}}else Wl=function(){H(Mt,0)};function Et(S,x){W=H(function(){S(A.unstable_now())},x)}A.unstable_IdlePriority=5,A.unstable_ImmediatePriority=1,A.unstable_LowPriority=4,A.unstable_NormalPriority=3,A.unstable_Profiling=null,A.unstable_UserBlockingPriority=2,A.unstable_cancelCallback=function(S){S.callback=null},A.unstable_forceFrameRate=function(S){0>S||125ol?(S.sortIndex=G,X(E,S),Q(U)===null&&S===Q(E)&&(_?(al(W),W=-1):_=!0,Et(Hl,G-ol))):(S.sortIndex=vl,X(U,S),j||ql||(j=!0,zl||(zl=!0,Wl()))),S},A.unstable_shouldYield=xt,A.unstable_wrapCallback=function(S){var x=cl;return function(){var G=cl;cl=x;try{return S.apply(this,arguments)}finally{cl=G}}}})(df)),df}var po;function th(){return po||(po=1,sf.exports=lh()),sf.exports}var of={exports:{}},Ll={};var zo;function ah(){if(zo)return Ll;zo=1;var A=mf();function X(U){var E="https://react.dev/errors/"+U;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(A)}catch(X){console.error(X)}}return A(),of.exports=ah(),of.exports}var To;function uh(){if(To)return pu;To=1;var A=th(),X=mf(),Q=eh();function h(l){var t="https://react.dev/errors/"+l;if(1vl||(l.current=ol[vl],ol[vl]=null,vl--)}function M(l,t){vl++,ol[vl]=l.current,l.current=t}var N=d(null),L=d(null),k=d(null),fl=d(null);function Vl(l,t){switch(M(k,t),M(L,l),M(N,null),t.nodeType){case 9:case 11:l=(l=t.documentElement)&&(l=l.namespaceURI)?Yd(l):0;break;default:if(l=t.tagName,t=t.namespaceURI)t=Yd(t),l=Bd(t,l);else switch(l){case"svg":l=1;break;case"math":l=2;break;default:l=0}}z(N),M(N,l)}function Al(){z(N),z(L),z(k)}function xe(l){l.memoizedState!==null&&M(fl,l);var t=N.current,a=Bd(t,l.type);t!==a&&(M(L,l),M(N,a))}function zu(l){L.current===l&&(z(N),z(L)),fl.current===l&&(z(fl),vu._currentValue=G)}var Qn,yf;function Ta(l){if(Qn===void 0)try{throw Error()}catch(a){var t=a.stack.trim().match(/\n( *(at )?)/);Qn=t&&t[1]||"",yf=-1)":-1u||f[e]!==y[u]){var g=` +`+f[e].replace(" at new "," at ");return l.displayName&&g.includes("")&&(g=g.replace("",l.displayName)),g}while(1<=e&&0<=u);break}}}finally{Zn=!1,Error.prepareStackTrace=a}return(a=l?l.displayName||l.name:"")?Ta(a):""}function Oo(l,t){switch(l.tag){case 26:case 27:case 5:return Ta(l.type);case 16:return Ta("Lazy");case 13:return l.child!==t&&t!==null?Ta("Suspense Fallback"):Ta("Suspense");case 19:return Ta("SuspenseList");case 0:case 15:return Ln(l.type,!1);case 11:return Ln(l.type.render,!1);case 1:return Ln(l.type,!0);case 31:return Ta("Activity");default:return""}}function hf(l){try{var t="",a=null;do t+=Oo(l,a),a=l,l=l.return;while(l);return t}catch(e){return` +Error generating stack: `+e.message+` +`+e.stack}}var Vn=Object.prototype.hasOwnProperty,Kn=A.unstable_scheduleCallback,Jn=A.unstable_cancelCallback,No=A.unstable_shouldYield,Do=A.unstable_requestPaint,at=A.unstable_now,Uo=A.unstable_getCurrentPriorityLevel,vf=A.unstable_ImmediatePriority,rf=A.unstable_UserBlockingPriority,Eu=A.unstable_NormalPriority,jo=A.unstable_LowPriority,gf=A.unstable_IdlePriority,Ho=A.log,Ro=A.unstable_setDisableYieldValue,Me=null,et=null;function Ft(l){if(typeof Ho=="function"&&Ro(l),et&&typeof et.setStrictMode=="function")try{et.setStrictMode(Me,l)}catch{}}var ut=Math.clz32?Math.clz32:Yo,Co=Math.log,qo=Math.LN2;function Yo(l){return l>>>=0,l===0?32:31-(Co(l)/qo|0)|0}var Tu=256,Au=262144,_u=4194304;function Aa(l){var t=l&42;if(t!==0)return t;switch(l&-l){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return l&261888;case 262144:case 524288:case 1048576:case 2097152:return l&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return l&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return l}}function xu(l,t,a){var e=l.pendingLanes;if(e===0)return 0;var u=0,n=l.suspendedLanes,c=l.pingedLanes;l=l.warmLanes;var i=e&134217727;return i!==0?(e=i&~n,e!==0?u=Aa(e):(c&=i,c!==0?u=Aa(c):a||(a=i&~l,a!==0&&(u=Aa(a))))):(i=e&~n,i!==0?u=Aa(i):c!==0?u=Aa(c):a||(a=e&~l,a!==0&&(u=Aa(a)))),u===0?0:t!==0&&t!==u&&(t&n)===0&&(n=u&-u,a=t&-t,n>=a||n===32&&(a&4194048)!==0)?t:u}function Oe(l,t){return(l.pendingLanes&~(l.suspendedLanes&~l.pingedLanes)&t)===0}function Bo(l,t){switch(l){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Sf(){var l=_u;return _u<<=1,(_u&62914560)===0&&(_u=4194304),l}function wn(l){for(var t=[],a=0;31>a;a++)t.push(l);return t}function Ne(l,t){l.pendingLanes|=t,t!==268435456&&(l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0)}function Go(l,t,a,e,u,n){var c=l.pendingLanes;l.pendingLanes=a,l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0,l.expiredLanes&=a,l.entangledLanes&=a,l.errorRecoveryDisabledLanes&=a,l.shellSuspendCounter=0;var i=l.entanglements,f=l.expirationTimes,y=l.hiddenUpdates;for(a=c&~a;0"u")return null;try{return l.activeElement||l.body}catch{return l.body}}var Ko=/[\n"\\]/g;function yt(l){return l.replace(Ko,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function Pn(l,t,a,e,u,n,c,i){l.name="",c!=null&&typeof c!="function"&&typeof c!="symbol"&&typeof c!="boolean"?l.type=c:l.removeAttribute("type"),t!=null?c==="number"?(t===0&&l.value===""||l.value!=t)&&(l.value=""+mt(t)):l.value!==""+mt(t)&&(l.value=""+mt(t)):c!=="submit"&&c!=="reset"||l.removeAttribute("value"),t!=null?lc(l,c,mt(t)):a!=null?lc(l,c,mt(a)):e!=null&&l.removeAttribute("value"),u==null&&n!=null&&(l.defaultChecked=!!n),u!=null&&(l.checked=u&&typeof u!="function"&&typeof u!="symbol"),i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"?l.name=""+mt(i):l.removeAttribute("name")}function Uf(l,t,a,e,u,n,c,i){if(n!=null&&typeof n!="function"&&typeof n!="symbol"&&typeof n!="boolean"&&(l.type=n),t!=null||a!=null){if(!(n!=="submit"&&n!=="reset"||t!=null)){In(l);return}a=a!=null?""+mt(a):"",t=t!=null?""+mt(t):a,i||t===l.value||(l.value=t),l.defaultValue=t}e=e??u,e=typeof e!="function"&&typeof e!="symbol"&&!!e,l.checked=i?l.checked:!!e,l.defaultChecked=!!e,c!=null&&typeof c!="function"&&typeof c!="symbol"&&typeof c!="boolean"&&(l.name=c),In(l)}function lc(l,t,a){t==="number"&&Nu(l.ownerDocument)===l||l.defaultValue===""+a||(l.defaultValue=""+a)}function wa(l,t,a,e){if(l=l.options,t){t={};for(var u=0;u"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),nc=!1;if(Ct)try{var He={};Object.defineProperty(He,"passive",{get:function(){nc=!0}}),window.addEventListener("test",He,He),window.removeEventListener("test",He,He)}catch{nc=!1}var Pt=null,cc=null,Uu=null;function Bf(){if(Uu)return Uu;var l,t=cc,a=t.length,e,u="value"in Pt?Pt.value:Pt.textContent,n=u.length;for(l=0;l=qe),Vf=" ",Kf=!1;function Jf(l,t){switch(l){case"keyup":return bm.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function wf(l){return l=l.detail,typeof l=="object"&&"data"in l?l.data:null}var Fa=!1;function zm(l,t){switch(l){case"compositionend":return wf(t);case"keypress":return t.which!==32?null:(Kf=!0,Vf);case"textInput":return l=t.data,l===Vf&&Kf?null:l;default:return null}}function Em(l,t){if(Fa)return l==="compositionend"||!oc&&Jf(l,t)?(l=Bf(),Uu=cc=Pt=null,Fa=!1,l):null;switch(l){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:a,offset:t-l};l=e}l:{for(;a;){if(a.nextSibling){a=a.nextSibling;break l}a=a.parentNode}a=void 0}a=ts(a)}}function es(l,t){return l&&t?l===t?!0:l&&l.nodeType===3?!1:t&&t.nodeType===3?es(l,t.parentNode):"contains"in l?l.contains(t):l.compareDocumentPosition?!!(l.compareDocumentPosition(t)&16):!1:!1}function us(l){l=l!=null&&l.ownerDocument!=null&&l.ownerDocument.defaultView!=null?l.ownerDocument.defaultView:window;for(var t=Nu(l.document);t instanceof l.HTMLIFrameElement;){try{var a=typeof t.contentWindow.location.href=="string"}catch{a=!1}if(a)l=t.contentWindow;else break;t=Nu(l.document)}return t}function hc(l){var t=l&&l.nodeName&&l.nodeName.toLowerCase();return t&&(t==="input"&&(l.type==="text"||l.type==="search"||l.type==="tel"||l.type==="url"||l.type==="password")||t==="textarea"||l.contentEditable==="true")}var Dm=Ct&&"documentMode"in document&&11>=document.documentMode,Ia=null,vc=null,Xe=null,rc=!1;function ns(l,t,a){var e=a.window===a?a.document:a.nodeType===9?a:a.ownerDocument;rc||Ia==null||Ia!==Nu(e)||(e=Ia,"selectionStart"in e&&hc(e)?e={start:e.selectionStart,end:e.selectionEnd}:(e=(e.ownerDocument&&e.ownerDocument.defaultView||window).getSelection(),e={anchorNode:e.anchorNode,anchorOffset:e.anchorOffset,focusNode:e.focusNode,focusOffset:e.focusOffset}),Xe&&Ge(Xe,e)||(Xe=e,e=_n(vc,"onSelect"),0>=c,u-=c,Ot=1<<32-ut(t)+u|a<J?(P=D,D=null):P=D.sibling;var nl=v(o,D,m[J],b);if(nl===null){D===null&&(D=P);break}l&&D&&nl.alternate===null&&t(o,D),s=n(nl,s,J),ul===null?C=nl:ul.sibling=nl,ul=nl,D=P}if(J===m.length)return a(o,D),tl&&Yt(o,J),C;if(D===null){for(;JJ?(P=D,D=null):P=D.sibling;var za=v(o,D,nl.value,b);if(za===null){D===null&&(D=P);break}l&&D&&za.alternate===null&&t(o,D),s=n(za,s,J),ul===null?C=za:ul.sibling=za,ul=za,D=P}if(nl.done)return a(o,D),tl&&Yt(o,J),C;if(D===null){for(;!nl.done;J++,nl=m.next())nl=p(o,nl.value,b),nl!==null&&(s=n(nl,s,J),ul===null?C=nl:ul.sibling=nl,ul=nl);return tl&&Yt(o,J),C}for(D=e(D);!nl.done;J++,nl=m.next())nl=r(D,o,J,nl.value,b),nl!==null&&(l&&nl.alternate!==null&&D.delete(nl.key===null?J:nl.key),s=n(nl,s,J),ul===null?C=nl:ul.sibling=nl,ul=nl);return l&&D.forEach(function($y){return t(o,$y)}),tl&&Yt(o,J),C}function hl(o,s,m,b){if(typeof m=="object"&&m!==null&&m.type===_&&m.key===null&&(m=m.props.children),typeof m=="object"&&m!==null){switch(m.$$typeof){case ql:l:{for(var C=m.key;s!==null;){if(s.key===C){if(C=m.type,C===_){if(s.tag===7){a(o,s.sibling),b=u(s,m.props.children),b.return=o,o=b;break l}}else if(s.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===Zl&&Ca(C)===s.type){a(o,s.sibling),b=u(s,m.props),Je(b,m),b.return=o,o=b;break l}a(o,s);break}else t(o,s);s=s.sibling}m.type===_?(b=Da(m.props.children,o.mode,b,m.key),b.return=o,o=b):(b=Qu(m.type,m.key,m.props,null,o.mode,b),Je(b,m),b.return=o,o=b)}return c(o);case j:l:{for(C=m.key;s!==null;){if(s.key===C)if(s.tag===4&&s.stateNode.containerInfo===m.containerInfo&&s.stateNode.implementation===m.implementation){a(o,s.sibling),b=u(s,m.children||[]),b.return=o,o=b;break l}else{a(o,s);break}else t(o,s);s=s.sibling}b=Tc(m,o.mode,b),b.return=o,o=b}return c(o);case Zl:return m=Ca(m),hl(o,s,m,b)}if(Et(m))return O(o,s,m,b);if(Wl(m)){if(C=Wl(m),typeof C!="function")throw Error(h(150));return m=C.call(m),q(o,s,m,b)}if(typeof m.then=="function")return hl(o,s,Wu(m),b);if(m.$$typeof===el)return hl(o,s,Vu(o,m),b);ku(o,m)}return typeof m=="string"&&m!==""||typeof m=="number"||typeof m=="bigint"?(m=""+m,s!==null&&s.tag===6?(a(o,s.sibling),b=u(s,m),b.return=o,o=b):(a(o,s),b=Ec(m,o.mode,b),b.return=o,o=b),c(o)):a(o,s)}return function(o,s,m,b){try{Ke=0;var C=hl(o,s,m,b);return se=null,C}catch(D){if(D===fe||D===Ju)throw D;var ul=ct(29,D,null,o.mode);return ul.lanes=b,ul.return=o,ul}}}var Ya=Os(!0),Ns=Os(!1),ua=!1;function Cc(l){l.updateQueue={baseState:l.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function qc(l,t){l=l.updateQueue,t.updateQueue===l&&(t.updateQueue={baseState:l.baseState,firstBaseUpdate:l.firstBaseUpdate,lastBaseUpdate:l.lastBaseUpdate,shared:l.shared,callbacks:null})}function na(l){return{lane:l,tag:0,payload:null,callback:null,next:null}}function ca(l,t,a){var e=l.updateQueue;if(e===null)return null;if(e=e.shared,(il&2)!==0){var u=e.pending;return u===null?t.next=t:(t.next=u.next,u.next=t),e.pending=t,t=Xu(l),ms(l,null,a),t}return Gu(l,e,t,a),Xu(l)}function we(l,t,a){if(t=t.updateQueue,t!==null&&(t=t.shared,(a&4194048)!==0)){var e=t.lanes;e&=l.pendingLanes,a|=e,t.lanes=a,pf(l,a)}}function Yc(l,t){var a=l.updateQueue,e=l.alternate;if(e!==null&&(e=e.updateQueue,a===e)){var u=null,n=null;if(a=a.firstBaseUpdate,a!==null){do{var c={lane:a.lane,tag:a.tag,payload:a.payload,callback:null,next:null};n===null?u=n=c:n=n.next=c,a=a.next}while(a!==null);n===null?u=n=t:n=n.next=t}else u=n=t;a={baseState:e.baseState,firstBaseUpdate:u,lastBaseUpdate:n,shared:e.shared,callbacks:e.callbacks},l.updateQueue=a;return}l=a.lastBaseUpdate,l===null?a.firstBaseUpdate=t:l.next=t,a.lastBaseUpdate=t}var Bc=!1;function We(){if(Bc){var l=ie;if(l!==null)throw l}}function ke(l,t,a,e){Bc=!1;var u=l.updateQueue;ua=!1;var n=u.firstBaseUpdate,c=u.lastBaseUpdate,i=u.shared.pending;if(i!==null){u.shared.pending=null;var f=i,y=f.next;f.next=null,c===null?n=y:c.next=y,c=f;var g=l.alternate;g!==null&&(g=g.updateQueue,i=g.lastBaseUpdate,i!==c&&(i===null?g.firstBaseUpdate=y:i.next=y,g.lastBaseUpdate=f))}if(n!==null){var p=u.baseState;c=0,g=y=f=null,i=n;do{var v=i.lane&-536870913,r=v!==i.lane;if(r?(I&v)===v:(e&v)===v){v!==0&&v===ce&&(Bc=!0),g!==null&&(g=g.next={lane:0,tag:i.tag,payload:i.payload,callback:null,next:null});l:{var O=l,q=i;v=t;var hl=a;switch(q.tag){case 1:if(O=q.payload,typeof O=="function"){p=O.call(hl,p,v);break l}p=O;break l;case 3:O.flags=O.flags&-65537|128;case 0:if(O=q.payload,v=typeof O=="function"?O.call(hl,p,v):O,v==null)break l;p=R({},p,v);break l;case 2:ua=!0}}v=i.callback,v!==null&&(l.flags|=64,r&&(l.flags|=8192),r=u.callbacks,r===null?u.callbacks=[v]:r.push(v))}else r={lane:v,tag:i.tag,payload:i.payload,callback:i.callback,next:null},g===null?(y=g=r,f=p):g=g.next=r,c|=v;if(i=i.next,i===null){if(i=u.shared.pending,i===null)break;r=i,i=r.next,r.next=null,u.lastBaseUpdate=r,u.shared.pending=null}}while(!0);g===null&&(f=p),u.baseState=f,u.firstBaseUpdate=y,u.lastBaseUpdate=g,n===null&&(u.shared.lanes=0),oa|=c,l.lanes=c,l.memoizedState=p}}function Ds(l,t){if(typeof l!="function")throw Error(h(191,l));l.call(t)}function Us(l,t){var a=l.callbacks;if(a!==null)for(l.callbacks=null,l=0;ln?n:8;var c=S.T,i={};S.T=i,ei(l,!1,t,a);try{var f=u(),y=S.S;if(y!==null&&y(i,f),f!==null&&typeof f=="object"&&typeof f.then=="function"){var g=Gm(f,e);Ie(l,t,g,ot(l))}else Ie(l,t,e,ot(l))}catch(p){Ie(l,t,{then:function(){},status:"rejected",reason:p},ot())}finally{x.p=n,c!==null&&i.types!==null&&(c.types=i.types),S.T=c}}function Km(){}function ti(l,t,a,e){if(l.tag!==5)throw Error(h(476));var u=s0(l).queue;f0(l,u,t,G,a===null?Km:function(){return d0(l),a(e)})}function s0(l){var t=l.memoizedState;if(t!==null)return t;t={memoizedState:G,baseState:G,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Qt,lastRenderedState:G},next:null};var a={};return t.next={memoizedState:a,baseState:a,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Qt,lastRenderedState:a},next:null},l.memoizedState=t,l=l.alternate,l!==null&&(l.memoizedState=t),t}function d0(l){var t=s0(l);t.next===null&&(t=l.alternate.memoizedState),Ie(l,t.next.queue,{},ot())}function ai(){return Gl(vu)}function o0(){return xl().memoizedState}function m0(){return xl().memoizedState}function Jm(l){for(var t=l.return;t!==null;){switch(t.tag){case 24:case 3:var a=ot();l=na(a);var e=ca(t,l,a);e!==null&&(tt(e,t,a),we(e,t,a)),t={cache:Uc()},l.payload=t;return}t=t.return}}function wm(l,t,a){var e=ot();a={lane:e,revertLane:0,gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},nn(l)?h0(t,a):(a=pc(l,t,a,e),a!==null&&(tt(a,l,e),v0(a,t,e)))}function y0(l,t,a){var e=ot();Ie(l,t,a,e)}function Ie(l,t,a,e){var u={lane:e,revertLane:0,gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null};if(nn(l))h0(t,u);else{var n=l.alternate;if(l.lanes===0&&(n===null||n.lanes===0)&&(n=t.lastRenderedReducer,n!==null))try{var c=t.lastRenderedState,i=n(c,a);if(u.hasEagerState=!0,u.eagerState=i,nt(i,c))return Gu(l,t,u,0),rl===null&&Bu(),!1}catch{}if(a=pc(l,t,u,e),a!==null)return tt(a,l,e),v0(a,t,e),!0}return!1}function ei(l,t,a,e){if(e={lane:2,revertLane:Ci(),gesture:null,action:e,hasEagerState:!1,eagerState:null,next:null},nn(l)){if(t)throw Error(h(479))}else t=pc(l,a,e,2),t!==null&&tt(t,l,2)}function nn(l){var t=l.alternate;return l===V||t!==null&&t===V}function h0(l,t){oe=Iu=!0;var a=l.pending;a===null?t.next=t:(t.next=a.next,a.next=t),l.pending=t}function v0(l,t,a){if((a&4194048)!==0){var e=t.lanes;e&=l.pendingLanes,a|=e,t.lanes=a,pf(l,a)}}var Pe={readContext:Gl,use:tn,useCallback:El,useContext:El,useEffect:El,useImperativeHandle:El,useLayoutEffect:El,useInsertionEffect:El,useMemo:El,useReducer:El,useRef:El,useState:El,useDebugValue:El,useDeferredValue:El,useTransition:El,useSyncExternalStore:El,useId:El,useHostTransitionStatus:El,useFormState:El,useActionState:El,useOptimistic:El,useMemoCache:El,useCacheRefresh:El};Pe.useEffectEvent=El;var r0={readContext:Gl,use:tn,useCallback:function(l,t){return Kl().memoizedState=[l,t===void 0?null:t],l},useContext:Gl,useEffect:Ps,useImperativeHandle:function(l,t,a){a=a!=null?a.concat([l]):null,en(4194308,4,e0.bind(null,t,l),a)},useLayoutEffect:function(l,t){return en(4194308,4,l,t)},useInsertionEffect:function(l,t){en(4,2,l,t)},useMemo:function(l,t){var a=Kl();t=t===void 0?null:t;var e=l();if(Ba){Ft(!0);try{l()}finally{Ft(!1)}}return a.memoizedState=[e,t],e},useReducer:function(l,t,a){var e=Kl();if(a!==void 0){var u=a(t);if(Ba){Ft(!0);try{a(t)}finally{Ft(!1)}}}else u=t;return e.memoizedState=e.baseState=u,l={pending:null,lanes:0,dispatch:null,lastRenderedReducer:l,lastRenderedState:u},e.queue=l,l=l.dispatch=wm.bind(null,V,l),[e.memoizedState,l]},useRef:function(l){var t=Kl();return l={current:l},t.memoizedState=l},useState:function(l){l=$c(l);var t=l.queue,a=y0.bind(null,V,t);return t.dispatch=a,[l.memoizedState,a]},useDebugValue:Pc,useDeferredValue:function(l,t){var a=Kl();return li(a,l,t)},useTransition:function(){var l=$c(!1);return l=f0.bind(null,V,l.queue,!0,!1),Kl().memoizedState=l,[!1,l]},useSyncExternalStore:function(l,t,a){var e=V,u=Kl();if(tl){if(a===void 0)throw Error(h(407));a=a()}else{if(a=t(),rl===null)throw Error(h(349));(I&127)!==0||Ys(e,t,a)}u.memoizedState=a;var n={value:a,getSnapshot:t};return u.queue=n,Ps(Gs.bind(null,e,n,l),[l]),e.flags|=2048,ye(9,{destroy:void 0},Bs.bind(null,e,n,a,t),null),a},useId:function(){var l=Kl(),t=rl.identifierPrefix;if(tl){var a=Nt,e=Ot;a=(e&~(1<<32-ut(e)-1)).toString(32)+a,t="_"+t+"R_"+a,a=Pu++,0<\/script>",n=n.removeChild(n.firstChild);break;case"select":n=typeof e.is=="string"?c.createElement("select",{is:e.is}):c.createElement("select"),e.multiple?n.multiple=!0:e.size&&(n.size=e.size);break;default:n=typeof e.is=="string"?c.createElement(u,{is:e.is}):c.createElement(u)}}n[Yl]=t,n[kl]=e;l:for(c=t.child;c!==null;){if(c.tag===5||c.tag===6)n.appendChild(c.stateNode);else if(c.tag!==4&&c.tag!==27&&c.child!==null){c.child.return=c,c=c.child;continue}if(c===t)break l;for(;c.sibling===null;){if(c.return===null||c.return===t)break l;c=c.return}c.sibling.return=c.return,c=c.sibling}t.stateNode=n;l:switch(Ql(n,u,e),u){case"button":case"input":case"select":case"textarea":e=!!e.autoFocus;break l;case"img":e=!0;break l;default:e=!1}e&&Lt(t)}}return Sl(t),gi(t,t.type,l===null?null:l.memoizedProps,t.pendingProps,a),null;case 6:if(l&&t.stateNode!=null)l.memoizedProps!==e&&Lt(t);else{if(typeof e!="string"&&t.stateNode===null)throw Error(h(166));if(l=k.current,ue(t)){if(l=t.stateNode,a=t.memoizedProps,e=null,u=Bl,u!==null)switch(u.tag){case 27:case 5:e=u.memoizedProps}l[Yl]=t,l=!!(l.nodeValue===a||e!==null&&e.suppressHydrationWarning===!0||Cd(l.nodeValue,a)),l||aa(t,!0)}else l=xn(l).createTextNode(e),l[Yl]=t,t.stateNode=l}return Sl(t),null;case 31:if(a=t.memoizedState,l===null||l.memoizedState!==null){if(e=ue(t),a!==null){if(l===null){if(!e)throw Error(h(318));if(l=t.memoizedState,l=l!==null?l.dehydrated:null,!l)throw Error(h(557));l[Yl]=t}else Ua(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Sl(t),l=!1}else a=Mc(),l!==null&&l.memoizedState!==null&&(l.memoizedState.hydrationErrors=a),l=!0;if(!l)return t.flags&256?(ft(t),t):(ft(t),null);if((t.flags&128)!==0)throw Error(h(558))}return Sl(t),null;case 13:if(e=t.memoizedState,l===null||l.memoizedState!==null&&l.memoizedState.dehydrated!==null){if(u=ue(t),e!==null&&e.dehydrated!==null){if(l===null){if(!u)throw Error(h(318));if(u=t.memoizedState,u=u!==null?u.dehydrated:null,!u)throw Error(h(317));u[Yl]=t}else Ua(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Sl(t),u=!1}else u=Mc(),l!==null&&l.memoizedState!==null&&(l.memoizedState.hydrationErrors=u),u=!0;if(!u)return t.flags&256?(ft(t),t):(ft(t),null)}return ft(t),(t.flags&128)!==0?(t.lanes=a,t):(a=e!==null,l=l!==null&&l.memoizedState!==null,a&&(e=t.child,u=null,e.alternate!==null&&e.alternate.memoizedState!==null&&e.alternate.memoizedState.cachePool!==null&&(u=e.alternate.memoizedState.cachePool.pool),n=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),n!==u&&(e.flags|=2048)),a!==l&&a&&(t.child.flags|=8192),on(t,t.updateQueue),Sl(t),null);case 4:return Al(),l===null&&Gi(t.stateNode.containerInfo),Sl(t),null;case 10:return Gt(t.type),Sl(t),null;case 19:if(z(_l),e=t.memoizedState,e===null)return Sl(t),null;if(u=(t.flags&128)!==0,n=e.rendering,n===null)if(u)tu(e,!1);else{if(Tl!==0||l!==null&&(l.flags&128)!==0)for(l=t.child;l!==null;){if(n=Fu(l),n!==null){for(t.flags|=128,tu(e,!1),l=n.updateQueue,t.updateQueue=l,on(t,l),t.subtreeFlags=0,l=a,a=t.child;a!==null;)ys(a,l),a=a.sibling;return M(_l,_l.current&1|2),tl&&Yt(t,e.treeForkCount),t.child}l=l.sibling}e.tail!==null&&at()>rn&&(t.flags|=128,u=!0,tu(e,!1),t.lanes=4194304)}else{if(!u)if(l=Fu(n),l!==null){if(t.flags|=128,u=!0,l=l.updateQueue,t.updateQueue=l,on(t,l),tu(e,!0),e.tail===null&&e.tailMode==="hidden"&&!n.alternate&&!tl)return Sl(t),null}else 2*at()-e.renderingStartTime>rn&&a!==536870912&&(t.flags|=128,u=!0,tu(e,!1),t.lanes=4194304);e.isBackwards?(n.sibling=t.child,t.child=n):(l=e.last,l!==null?l.sibling=n:t.child=n,e.last=n)}return e.tail!==null?(l=e.tail,e.rendering=l,e.tail=l.sibling,e.renderingStartTime=at(),l.sibling=null,a=_l.current,M(_l,u?a&1|2:a&1),tl&&Yt(t,e.treeForkCount),l):(Sl(t),null);case 22:case 23:return ft(t),Xc(),e=t.memoizedState!==null,l!==null?l.memoizedState!==null!==e&&(t.flags|=8192):e&&(t.flags|=8192),e?(a&536870912)!==0&&(t.flags&128)===0&&(Sl(t),t.subtreeFlags&6&&(t.flags|=8192)):Sl(t),a=t.updateQueue,a!==null&&on(t,a.retryQueue),a=null,l!==null&&l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(a=l.memoizedState.cachePool.pool),e=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(e=t.memoizedState.cachePool.pool),e!==a&&(t.flags|=2048),l!==null&&z(Ra),null;case 24:return a=null,l!==null&&(a=l.memoizedState.cache),t.memoizedState.cache!==a&&(t.flags|=2048),Gt(Ol),Sl(t),null;case 25:return null;case 30:return null}throw Error(h(156,t.tag))}function Im(l,t){switch(_c(t),t.tag){case 1:return l=t.flags,l&65536?(t.flags=l&-65537|128,t):null;case 3:return Gt(Ol),Al(),l=t.flags,(l&65536)!==0&&(l&128)===0?(t.flags=l&-65537|128,t):null;case 26:case 27:case 5:return zu(t),null;case 31:if(t.memoizedState!==null){if(ft(t),t.alternate===null)throw Error(h(340));Ua()}return l=t.flags,l&65536?(t.flags=l&-65537|128,t):null;case 13:if(ft(t),l=t.memoizedState,l!==null&&l.dehydrated!==null){if(t.alternate===null)throw Error(h(340));Ua()}return l=t.flags,l&65536?(t.flags=l&-65537|128,t):null;case 19:return z(_l),null;case 4:return Al(),null;case 10:return Gt(t.type),null;case 22:case 23:return ft(t),Xc(),l!==null&&z(Ra),l=t.flags,l&65536?(t.flags=l&-65537|128,t):null;case 24:return Gt(Ol),null;case 25:return null;default:return null}}function X0(l,t){switch(_c(t),t.tag){case 3:Gt(Ol),Al();break;case 26:case 27:case 5:zu(t);break;case 4:Al();break;case 31:t.memoizedState!==null&&ft(t);break;case 13:ft(t);break;case 19:z(_l);break;case 10:Gt(t.type);break;case 22:case 23:ft(t),Xc(),l!==null&&z(Ra);break;case 24:Gt(Ol)}}function au(l,t){try{var a=t.updateQueue,e=a!==null?a.lastEffect:null;if(e!==null){var u=e.next;a=u;do{if((a.tag&l)===l){e=void 0;var n=a.create,c=a.inst;e=n(),c.destroy=e}a=a.next}while(a!==u)}}catch(i){dl(t,t.return,i)}}function sa(l,t,a){try{var e=t.updateQueue,u=e!==null?e.lastEffect:null;if(u!==null){var n=u.next;e=n;do{if((e.tag&l)===l){var c=e.inst,i=c.destroy;if(i!==void 0){c.destroy=void 0,u=t;var f=a,y=i;try{y()}catch(g){dl(u,f,g)}}}e=e.next}while(e!==n)}}catch(g){dl(t,t.return,g)}}function Q0(l){var t=l.updateQueue;if(t!==null){var a=l.stateNode;try{Us(t,a)}catch(e){dl(l,l.return,e)}}}function Z0(l,t,a){a.props=Ga(l.type,l.memoizedProps),a.state=l.memoizedState;try{a.componentWillUnmount()}catch(e){dl(l,t,e)}}function eu(l,t){try{var a=l.ref;if(a!==null){switch(l.tag){case 26:case 27:case 5:var e=l.stateNode;break;case 30:e=l.stateNode;break;default:e=l.stateNode}typeof a=="function"?l.refCleanup=a(e):a.current=e}}catch(u){dl(l,t,u)}}function Dt(l,t){var a=l.ref,e=l.refCleanup;if(a!==null)if(typeof e=="function")try{e()}catch(u){dl(l,t,u)}finally{l.refCleanup=null,l=l.alternate,l!=null&&(l.refCleanup=null)}else if(typeof a=="function")try{a(null)}catch(u){dl(l,t,u)}else a.current=null}function L0(l){var t=l.type,a=l.memoizedProps,e=l.stateNode;try{l:switch(t){case"button":case"input":case"select":case"textarea":a.autoFocus&&e.focus();break l;case"img":a.src?e.src=a.src:a.srcSet&&(e.srcset=a.srcSet)}}catch(u){dl(l,l.return,u)}}function Si(l,t,a){try{var e=l.stateNode;py(e,l.type,a,t),e[kl]=t}catch(u){dl(l,l.return,u)}}function V0(l){return l.tag===5||l.tag===3||l.tag===26||l.tag===27&&ra(l.type)||l.tag===4}function bi(l){l:for(;;){for(;l.sibling===null;){if(l.return===null||V0(l.return))return null;l=l.return}for(l.sibling.return=l.return,l=l.sibling;l.tag!==5&&l.tag!==6&&l.tag!==18;){if(l.tag===27&&ra(l.type)||l.flags&2||l.child===null||l.tag===4)continue l;l.child.return=l,l=l.child}if(!(l.flags&2))return l.stateNode}}function pi(l,t,a){var e=l.tag;if(e===5||e===6)l=l.stateNode,t?(a.nodeType===9?a.body:a.nodeName==="HTML"?a.ownerDocument.body:a).insertBefore(l,t):(t=a.nodeType===9?a.body:a.nodeName==="HTML"?a.ownerDocument.body:a,t.appendChild(l),a=a._reactRootContainer,a!=null||t.onclick!==null||(t.onclick=Rt));else if(e!==4&&(e===27&&ra(l.type)&&(a=l.stateNode,t=null),l=l.child,l!==null))for(pi(l,t,a),l=l.sibling;l!==null;)pi(l,t,a),l=l.sibling}function mn(l,t,a){var e=l.tag;if(e===5||e===6)l=l.stateNode,t?a.insertBefore(l,t):a.appendChild(l);else if(e!==4&&(e===27&&ra(l.type)&&(a=l.stateNode),l=l.child,l!==null))for(mn(l,t,a),l=l.sibling;l!==null;)mn(l,t,a),l=l.sibling}function K0(l){var t=l.stateNode,a=l.memoizedProps;try{for(var e=l.type,u=t.attributes;u.length;)t.removeAttributeNode(u[0]);Ql(t,e,a),t[Yl]=l,t[kl]=a}catch(n){dl(l,l.return,n)}}var Vt=!1,Ul=!1,zi=!1,J0=typeof WeakSet=="function"?WeakSet:Set,Cl=null;function Pm(l,t){if(l=l.containerInfo,Zi=Hn,l=us(l),hc(l)){if("selectionStart"in l)var a={start:l.selectionStart,end:l.selectionEnd};else l:{a=(a=l.ownerDocument)&&a.defaultView||window;var e=a.getSelection&&a.getSelection();if(e&&e.rangeCount!==0){a=e.anchorNode;var u=e.anchorOffset,n=e.focusNode;e=e.focusOffset;try{a.nodeType,n.nodeType}catch{a=null;break l}var c=0,i=-1,f=-1,y=0,g=0,p=l,v=null;t:for(;;){for(var r;p!==a||u!==0&&p.nodeType!==3||(i=c+u),p!==n||e!==0&&p.nodeType!==3||(f=c+e),p.nodeType===3&&(c+=p.nodeValue.length),(r=p.firstChild)!==null;)v=p,p=r;for(;;){if(p===l)break t;if(v===a&&++y===u&&(i=c),v===n&&++g===e&&(f=c),(r=p.nextSibling)!==null)break;p=v,v=p.parentNode}p=r}a=i===-1||f===-1?null:{start:i,end:f}}else a=null}a=a||{start:0,end:0}}else a=null;for(Li={focusedElem:l,selectionRange:a},Hn=!1,Cl=t;Cl!==null;)if(t=Cl,l=t.child,(t.subtreeFlags&1028)!==0&&l!==null)l.return=t,Cl=l;else for(;Cl!==null;){switch(t=Cl,n=t.alternate,l=t.flags,t.tag){case 0:if((l&4)!==0&&(l=t.updateQueue,l=l!==null?l.events:null,l!==null))for(a=0;a title"))),Ql(n,e,a),n[Yl]=l,Rl(n),e=n;break l;case"link":var c=Id("link","href",u).get(e+(a.href||""));if(c){for(var i=0;ihl&&(c=hl,hl=q,q=c);var o=as(i,q),s=as(i,hl);if(o&&s&&(r.rangeCount!==1||r.anchorNode!==o.node||r.anchorOffset!==o.offset||r.focusNode!==s.node||r.focusOffset!==s.offset)){var m=p.createRange();m.setStart(o.node,o.offset),r.removeAllRanges(),q>hl?(r.addRange(m),r.extend(s.node,s.offset)):(m.setEnd(s.node,s.offset),r.addRange(m))}}}}for(p=[],r=i;r=r.parentNode;)r.nodeType===1&&p.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof i.focus=="function"&&i.focus(),i=0;ia?32:a,S.T=null,a=Oi,Oi=null;var n=ya,c=kt;if(jl=0,Se=ya=null,kt=0,(il&6)!==0)throw Error(h(331));var i=il;if(il|=4,ed(n.current),ld(n,n.current,c,a),il=i,su(0,!1),et&&typeof et.onPostCommitFiberRoot=="function")try{et.onPostCommitFiberRoot(Me,n)}catch{}return!0}finally{x.p=u,S.T=e,zd(l,t)}}function Td(l,t,a){t=vt(a,t),t=ii(l.stateNode,t,2),l=ca(l,t,2),l!==null&&(Ne(l,2),Ut(l))}function dl(l,t,a){if(l.tag===3)Td(l,l,a);else for(;t!==null;){if(t.tag===3){Td(t,l,a);break}else if(t.tag===1){var e=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof e.componentDidCatch=="function"&&(ma===null||!ma.has(e))){l=vt(a,l),a=A0(2),e=ca(t,a,2),e!==null&&(_0(a,e,t,l),Ne(e,2),Ut(e));break}}t=t.return}}function ji(l,t,a){var e=l.pingCache;if(e===null){e=l.pingCache=new ay;var u=new Set;e.set(t,u)}else u=e.get(t),u===void 0&&(u=new Set,e.set(t,u));u.has(a)||(Ai=!0,u.add(a),l=iy.bind(null,l,t,a),t.then(l,l))}function iy(l,t,a){var e=l.pingCache;e!==null&&e.delete(t),l.pingedLanes|=l.suspendedLanes&a,l.warmLanes&=~a,rl===l&&(I&a)===a&&(Tl===4||Tl===3&&(I&62914560)===I&&300>at()-vn?(il&2)===0&&be(l,0):_i|=a,ge===I&&(ge=0)),Ut(l)}function Ad(l,t){t===0&&(t=Sf()),l=Na(l,t),l!==null&&(Ne(l,t),Ut(l))}function fy(l){var t=l.memoizedState,a=0;t!==null&&(a=t.retryLane),Ad(l,a)}function sy(l,t){var a=0;switch(l.tag){case 31:case 13:var e=l.stateNode,u=l.memoizedState;u!==null&&(a=u.retryLane);break;case 19:e=l.stateNode;break;case 22:e=l.stateNode._retryCache;break;default:throw Error(h(314))}e!==null&&e.delete(t),Ad(l,a)}function dy(l,t){return Kn(l,t)}var En=null,ze=null,Hi=!1,Tn=!1,Ri=!1,va=0;function Ut(l){l!==ze&&l.next===null&&(ze===null?En=ze=l:ze=ze.next=l),Tn=!0,Hi||(Hi=!0,my())}function su(l,t){if(!Ri&&Tn){Ri=!0;do for(var a=!1,e=En;e!==null;){if(l!==0){var u=e.pendingLanes;if(u===0)var n=0;else{var c=e.suspendedLanes,i=e.pingedLanes;n=(1<<31-ut(42|l)+1)-1,n&=u&~(c&~i),n=n&201326741?n&201326741|1:n?n|2:0}n!==0&&(a=!0,Od(e,n))}else n=I,n=xu(e,e===rl?n:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),(n&3)===0||Oe(e,n)||(a=!0,Od(e,n));e=e.next}while(a);Ri=!1}}function oy(){_d()}function _d(){Tn=Hi=!1;var l=0;va!==0&&Ey()&&(l=va);for(var t=at(),a=null,e=En;e!==null;){var u=e.next,n=xd(e,t);n===0?(e.next=null,a===null?En=u:a.next=u,u===null&&(ze=a)):(a=e,(l!==0||(n&3)!==0)&&(Tn=!0)),e=u}jl!==0&&jl!==5||su(l),va!==0&&(va=0)}function xd(l,t){for(var a=l.suspendedLanes,e=l.pingedLanes,u=l.expirationTimes,n=l.pendingLanes&-62914561;0i)break;var g=f.transferSize,p=f.initiatorType;g&&qd(p)&&(f=f.responseEnd,c+=g*(f"u"?null:document;function Wd(l,t,a){var e=Ee;if(e&&typeof t=="string"&&t){var u=yt(t);u='link[rel="'+l+'"][href="'+u+'"]',typeof a=="string"&&(u+='[crossorigin="'+a+'"]'),wd.has(u)||(wd.add(u),l={rel:l,crossOrigin:a,href:t},e.querySelector(u)===null&&(t=e.createElement("link"),Ql(t,"link",l),Rl(t),e.head.appendChild(t)))}}function Uy(l){$t.D(l),Wd("dns-prefetch",l,null)}function jy(l,t){$t.C(l,t),Wd("preconnect",l,t)}function Hy(l,t,a){$t.L(l,t,a);var e=Ee;if(e&&l&&t){var u='link[rel="preload"][as="'+yt(t)+'"]';t==="image"&&a&&a.imageSrcSet?(u+='[imagesrcset="'+yt(a.imageSrcSet)+'"]',typeof a.imageSizes=="string"&&(u+='[imagesizes="'+yt(a.imageSizes)+'"]')):u+='[href="'+yt(l)+'"]';var n=u;switch(t){case"style":n=Te(l);break;case"script":n=Ae(l)}zt.has(n)||(l=R({rel:"preload",href:t==="image"&&a&&a.imageSrcSet?void 0:l,as:t},a),zt.set(n,l),e.querySelector(u)!==null||t==="style"&&e.querySelector(yu(n))||t==="script"&&e.querySelector(hu(n))||(t=e.createElement("link"),Ql(t,"link",l),Rl(t),e.head.appendChild(t)))}}function Ry(l,t){$t.m(l,t);var a=Ee;if(a&&l){var e=t&&typeof t.as=="string"?t.as:"script",u='link[rel="modulepreload"][as="'+yt(e)+'"][href="'+yt(l)+'"]',n=u;switch(e){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":n=Ae(l)}if(!zt.has(n)&&(l=R({rel:"modulepreload",href:l},t),zt.set(n,l),a.querySelector(u)===null)){switch(e){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(a.querySelector(hu(n)))return}e=a.createElement("link"),Ql(e,"link",l),Rl(e),a.head.appendChild(e)}}}function Cy(l,t,a){$t.S(l,t,a);var e=Ee;if(e&&l){var u=Ka(e).hoistableStyles,n=Te(l);t=t||"default";var c=u.get(n);if(!c){var i={loading:0,preload:null};if(c=e.querySelector(yu(n)))i.loading=5;else{l=R({rel:"stylesheet",href:l,"data-precedence":t},a),(a=zt.get(n))&&$i(l,a);var f=c=e.createElement("link");Rl(f),Ql(f,"link",l),f._p=new Promise(function(y,g){f.onload=y,f.onerror=g}),f.addEventListener("load",function(){i.loading|=1}),f.addEventListener("error",function(){i.loading|=2}),i.loading|=4,On(c,t,e)}c={type:"stylesheet",instance:c,count:1,state:i},u.set(n,c)}}}function qy(l,t){$t.X(l,t);var a=Ee;if(a&&l){var e=Ka(a).hoistableScripts,u=Ae(l),n=e.get(u);n||(n=a.querySelector(hu(u)),n||(l=R({src:l,async:!0},t),(t=zt.get(u))&&Fi(l,t),n=a.createElement("script"),Rl(n),Ql(n,"link",l),a.head.appendChild(n)),n={type:"script",instance:n,count:1,state:null},e.set(u,n))}}function Yy(l,t){$t.M(l,t);var a=Ee;if(a&&l){var e=Ka(a).hoistableScripts,u=Ae(l),n=e.get(u);n||(n=a.querySelector(hu(u)),n||(l=R({src:l,async:!0,type:"module"},t),(t=zt.get(u))&&Fi(l,t),n=a.createElement("script"),Rl(n),Ql(n,"link",l),a.head.appendChild(n)),n={type:"script",instance:n,count:1,state:null},e.set(u,n))}}function kd(l,t,a,e){var u=(u=k.current)?Mn(u):null;if(!u)throw Error(h(446));switch(l){case"meta":case"title":return null;case"style":return typeof a.precedence=="string"&&typeof a.href=="string"?(t=Te(a.href),a=Ka(u).hoistableStyles,e=a.get(t),e||(e={type:"style",instance:null,count:0,state:null},a.set(t,e)),e):{type:"void",instance:null,count:0,state:null};case"link":if(a.rel==="stylesheet"&&typeof a.href=="string"&&typeof a.precedence=="string"){l=Te(a.href);var n=Ka(u).hoistableStyles,c=n.get(l);if(c||(u=u.ownerDocument||u,c={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},n.set(l,c),(n=u.querySelector(yu(l)))&&!n._p&&(c.instance=n,c.state.loading=5),zt.has(l)||(a={rel:"preload",as:"style",href:a.href,crossOrigin:a.crossOrigin,integrity:a.integrity,media:a.media,hrefLang:a.hrefLang,referrerPolicy:a.referrerPolicy},zt.set(l,a),n||By(u,l,a,c.state))),t&&e===null)throw Error(h(528,""));return c}if(t&&e!==null)throw Error(h(529,""));return null;case"script":return t=a.async,a=a.src,typeof a=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=Ae(a),a=Ka(u).hoistableScripts,e=a.get(t),e||(e={type:"script",instance:null,count:0,state:null},a.set(t,e)),e):{type:"void",instance:null,count:0,state:null};default:throw Error(h(444,l))}}function Te(l){return'href="'+yt(l)+'"'}function yu(l){return'link[rel="stylesheet"]['+l+"]"}function $d(l){return R({},l,{"data-precedence":l.precedence,precedence:null})}function By(l,t,a,e){l.querySelector('link[rel="preload"][as="style"]['+t+"]")?e.loading=1:(t=l.createElement("link"),e.preload=t,t.addEventListener("load",function(){return e.loading|=1}),t.addEventListener("error",function(){return e.loading|=2}),Ql(t,"link",a),Rl(t),l.head.appendChild(t))}function Ae(l){return'[src="'+yt(l)+'"]'}function hu(l){return"script[async]"+l}function Fd(l,t,a){if(t.count++,t.instance===null)switch(t.type){case"style":var e=l.querySelector('style[data-href~="'+yt(a.href)+'"]');if(e)return t.instance=e,Rl(e),e;var u=R({},a,{"data-href":a.href,"data-precedence":a.precedence,href:null,precedence:null});return e=(l.ownerDocument||l).createElement("style"),Rl(e),Ql(e,"style",u),On(e,a.precedence,l),t.instance=e;case"stylesheet":u=Te(a.href);var n=l.querySelector(yu(u));if(n)return t.state.loading|=4,t.instance=n,Rl(n),n;e=$d(a),(u=zt.get(u))&&$i(e,u),n=(l.ownerDocument||l).createElement("link"),Rl(n);var c=n;return c._p=new Promise(function(i,f){c.onload=i,c.onerror=f}),Ql(n,"link",e),t.state.loading|=4,On(n,a.precedence,l),t.instance=n;case"script":return n=Ae(a.src),(u=l.querySelector(hu(n)))?(t.instance=u,Rl(u),u):(e=a,(u=zt.get(n))&&(e=R({},a),Fi(e,u)),l=l.ownerDocument||l,u=l.createElement("script"),Rl(u),Ql(u,"link",e),l.head.appendChild(u),t.instance=u);case"void":return null;default:throw Error(h(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(e=t.instance,t.state.loading|=4,On(e,a.precedence,l));return t.instance}function On(l,t,a){for(var e=a.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),u=e.length?e[e.length-1]:null,n=u,c=0;c title"):null)}function Gy(l,t,a){if(a===1||t.itemProp!=null)return!1;switch(l){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;return t.rel==="stylesheet"?(l=t.disabled,typeof t.precedence=="string"&&l==null):!0;case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function lo(l){return!(l.type==="stylesheet"&&(l.state.loading&3)===0)}function Xy(l,t,a,e){if(a.type==="stylesheet"&&(typeof e.media!="string"||matchMedia(e.media).matches!==!1)&&(a.state.loading&4)===0){if(a.instance===null){var u=Te(e.href),n=t.querySelector(yu(u));if(n){t=n._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(l.count++,l=Dn.bind(l),t.then(l,l)),a.state.loading|=4,a.instance=n,Rl(n);return}n=t.ownerDocument||t,e=$d(e),(u=zt.get(u))&&$i(e,u),n=n.createElement("link"),Rl(n);var c=n;c._p=new Promise(function(i,f){c.onload=i,c.onerror=f}),Ql(n,"link",e),a.instance=n}l.stylesheets===null&&(l.stylesheets=new Map),l.stylesheets.set(a,t),(t=a.state.preload)&&(a.state.loading&3)===0&&(l.count++,a=Dn.bind(l),t.addEventListener("load",a),t.addEventListener("error",a))}}var Ii=0;function Qy(l,t){return l.stylesheets&&l.count===0&&jn(l,l.stylesheets),0Ii?50:800)+t);return l.unsuspend=a,function(){l.unsuspend=null,clearTimeout(e),clearTimeout(u)}}:null}function Dn(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)jn(this,this.stylesheets);else if(this.unsuspend){var l=this.unsuspend;this.unsuspend=null,l()}}}var Un=null;function jn(l,t){l.stylesheets=null,l.unsuspend!==null&&(l.count++,Un=new Map,t.forEach(Zy,l),Un=null,Dn.call(l))}function Zy(l,t){if(!(t.state.loading&4)){var a=Un.get(l);if(a)var e=a.get(null);else{a=new Map,Un.set(l,a);for(var u=l.querySelectorAll("link[data-precedence],style[data-precedence]"),n=0;n"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(A)}catch(X){console.error(X)}}return A(),ff.exports=uh(),ff.exports}var ch=nh();const ih=A=>A.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),fh=A=>A.replace(/^([A-Z])|[\s-_]+(\w)/g,(X,Q,h)=>h?h.toUpperCase():Q.toLowerCase()),_o=A=>{const X=fh(A);return X.charAt(0).toUpperCase()+X.slice(1)},Mo=(...A)=>A.filter((X,Q,h)=>!!X&&X.trim()!==""&&h.indexOf(X)===Q).join(" ").trim(),sh=A=>{for(const X in A)if(X.startsWith("aria-")||X==="role"||X==="title")return!0};var dh={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const oh=Jl.forwardRef(({color:A="currentColor",size:X=24,strokeWidth:Q=2,absoluteStrokeWidth:h,className:B="",children:K,iconNode:ll,...pl},U)=>Jl.createElement("svg",{ref:U,...dh,width:X,height:X,stroke:A,strokeWidth:h?Number(Q)*24/Number(X):Q,className:Mo("lucide",B),...!K&&!sh(pl)&&{"aria-hidden":"true"},...pl},[...ll.map(([E,w])=>Jl.createElement(E,w)),...Array.isArray(K)?K:[K]]));const Xn=(A,X)=>{const Q=Jl.forwardRef(({className:h,...B},K)=>Jl.createElement(oh,{ref:K,iconNode:X,className:Mo(`lucide-${ih(_o(A))}`,`lucide-${A}`,h),...B}));return Q.displayName=_o(A),Q};const mh=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],xo=Xn("activity",mh);const yh=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],hh=Xn("cpu",yh);const vh=[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]],rh=Xn("mic",vh);const gh=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],Sh=Xn("network",gh),bh=({nodeCount:A=500,telemetry:X=[],selectedNode:Q=null,onSelect:h=()=>{}})=>{const E=j=>{const _=new Set;let Y=2,H=j;for(;H>1;){for(;H%Y===0;)_.add(Y),H/=Y;if(Y++,Y*Y>H){H>1&&_.add(H);break}}return Array.from(_)},w=j=>{if(j<2)return!1;for(let _=2;_*_<=j;_++)if(j%_===0)return!1;return!0},{processedNodes:R,traceLinks:cl}=Jl.useMemo(()=>{const j=[],_=new Set(X.map(H=>H.value)),Y=[];for(let H=1;H<=A;H++){const al=H%10*(Math.PI*2/10)-Math.PI/2,el=Math.log(H+1)*(380/Math.log(A+1)),Ml=400+Math.cos(al)*el,Hl=400+Math.sin(al)*el;j.push({id:H,x:Ml,y:Hl,lastDigit:H%10,isPrime:w(H),active:_.has(H),factors:w(H)?[]:E(H)})}return X.forEach(H=>{if(H.source&&H.value){const al=j[H.source-1],el=j[H.value-1];al&&el&&Y.push({x1:al.x,y1:al.y,x2:el.x,y2:el.y,isTrace:!0})}}),{processedNodes:j,traceLinks:Y}},[A,X]),ql=Jl.useMemo(()=>{const j=[];return R.forEach(_=>{!_.isPrime&&_.id>1&&_.factors.forEach(Y=>{const H=R[Y-1];H&&j.push({x1:_.x,y1:_.y,x2:H.x,y2:H.y,active:_.active||H.active,isHighValue:_.active})})}),j},[R]);return T.jsxs("div",{className:"w-full h-full flex items-center justify-center bg-black overflow-hidden relative",children:[T.jsxs("svg",{width:800,height:800,viewBox:"0 0 800 800",className:"cursor-crosshair",children:[Array.from({length:10}).map((j,_)=>{const Y=_*(Math.PI*2/10)-Math.PI/2;return T.jsx("line",{x1:400,y1:400,x2:400+Math.cos(Y)*380,y2:400+Math.sin(Y)*380,stroke:"rgba(255,255,255,0.05)",strokeWidth:"1"},`spoke-${_}`)}),[.2,.4,.6,.8,1].map((j,_)=>T.jsx("circle",{cx:400,cy:400,r:380*j,fill:"none",stroke:"rgba(255,255,255,0.03)",strokeWidth:"1"},`ring-${_}`)),ql.map((j,_)=>T.jsx("line",{x1:j.x1,y1:j.y1,x2:j.x2,y2:j.y2,stroke:"rgba(100,100,255,0.1)",strokeWidth:"0.5"},`stat-link-${_}`)),cl.map((j,_)=>T.jsx("line",{x1:j.x1,y1:j.y1,x2:j.x2,y2:j.y2,stroke:"#FFD700",strokeWidth:"1.5",strokeDasharray:"4 4",opacity:"0.3",className:"animate-pulse"},`trace-${_}`)),R.map(j=>{const _=Q?.id===j.id,Y=X.find(xt=>xt.value===j.id),H=Y?.tensor,al=H?.[3]||{},el=Y?.alignment||H?.[3]?.stabilized;let Ml=j.x,Hl=j.y;j.active&&al.x!==void 0&&(Ml=400+al.x*380*.8,Hl=400+al.y*380*.8);const zl=al.z||1;al.gravity;const W=j.isPrime?"#00FFFF":"#FF00FF",Zl=j.factors.length,wl=_?10:j.active?8:2+Zl+zl;return T.jsxs("g",{onClick:xt=>{xt.stopPropagation(),h({...j,tensor:H})},children:[j.active&&T.jsx("circle",{cx:Ml,cy:Hl,r:wl*(2+zl/2),fill:el?"#FFD700":W,opacity:.15*zl,className:"animate-ping"}),el&&j.active&&T.jsx("circle",{cx:Ml,cy:Hl,r:wl*2,fill:"none",stroke:"#FFD700",strokeWidth:"2",strokeDasharray:"2 1",className:"animate-spin",style:{animationDuration:"3s"}}),T.jsx("circle",{cx:Ml,cy:Hl,r:wl,fill:_||j.active?"#FFF":W,stroke:_||el?"#FFD700":"none",strokeWidth:el?"2":"0",style:{filter:zl>3?`blur(${zl-3}px)`:"none",opacity:1-zl*.05},className:"transition-all duration-500 hover:scale-150 cursor-pointer"}),(_||j.active)&&T.jsx("text",{x:Ml+12,y:Hl+4,fill:"white",fontSize:10+zl,className:"pointer-events-none font-mono font-bold drop-shadow-lg",children:j.id})]},j.id)}),T.jsx("circle",{cx:400,cy:400,r:"4",fill:"#FFD700"})]}),T.jsxs("div",{className:"absolute bottom-6 left-6 text-[10px] text-gray-500 space-y-1 bg-black/50 p-2 rounded backdrop-blur border border-white/5",children:[T.jsxs("div",{className:"flex items-center gap-2",children:[T.jsx("div",{className:"w-2 h-2 rounded-full bg-[#00FFFF]"})," PRIMES (CYAN)"]}),T.jsxs("div",{className:"flex items-center gap-2",children:[T.jsx("div",{className:"w-2 h-2 rounded-full bg-[#FF00FF]"})," COMPOSITES (PINK)"]}),T.jsxs("div",{className:"flex items-center gap-2",children:[T.jsx("div",{className:"w-2 h-2 rounded-full bg-white animate-pulse"})," ACTIVE PULSE"]})]})]})};function ph(){const[A,X]=Jl.useState(null),[Q,h]=Jl.useState([]),[B,K]=Jl.useState(null),[ll,pl]=Jl.useState([]),[U,E]=Jl.useState(!1),[w,R]=Jl.useState("");Jl.useEffect(()=>{const _=window.location.hostname,Y=new WebSocket(`ws://${_}:5000/neural-link`);return Y.onopen=()=>{console.log("[BRIDGE] Connected to Neural Link."),pl(H=>[{origin:0,node:1,tensor:"CRYPTO_LINK_ESTABLISHED",agent_route:"SYSTEM"},...H])},Y.onmessage=H=>{const al=JSON.parse(H.data);al.type==="TENSOR_UPDATE"&&(pl(el=>[al,...el].slice(0,10)),h(el=>[{value:al.node,source:al.origin,tensor:al.tensor},...el].slice(0,100)))},Y.onerror=H=>console.error("[BRIDGE] WebSocket Error:",H),Y.onclose=()=>console.log("[BRIDGE] Link Severed."),K(Y),()=>Y.close()},[]);const cl=(_,Y="text")=>{B&&B.readyState===WebSocket.OPEN&&_&&(B.send(JSON.stringify({content:_,type:Y})),R(""))},ql=()=>{const _=window.SpeechRecognition||window.webkitSpeechRecognition;if(_){const Y=new _;Y.onstart=()=>E(!0),Y.onend=()=>E(!1),Y.onresult=H=>{const al=H.results[0][0].transcript;R(al),cl(al,"speech")},Y.start()}else alert("Speech Recognition not supported in this browser.")},j=_=>{_.preventDefault();const Y=_.dataTransfer.files;if(Y.length>0){const H=Y[0];cl(`Map the file: ${H.name} (Size: ${H.size})`,"file_drop"),pl(al=>[{origin:"LOCAL",node:"...",tensor:`INDEXING_${H.name.toUpperCase()}`,agent_route:"GEMMA"},...al])}};return T.jsxs("div",{className:"w-screen bg-black text-white font-mono overflow-hidden flex flex-col h-screen",children:[T.jsxs("header",{className:"h-14 border-b border-white/10 flex items-center px-6 justify-between select-none bg-black/50 backdrop-blur-xl z-50",children:[T.jsxs("div",{className:"flex items-center gap-3",children:[T.jsx(xo,{className:"w-5 h-5 text-prime-gold animate-pulse"}),T.jsxs("span",{className:"font-bold tracking-tighter text-lg uppercase",children:["LOGOS COCKPIT // ",T.jsx("span",{className:"text-xs text-prime-gold opacity-80",children:"PROTOCOL 19"})]})]}),T.jsxs("div",{className:"flex items-center gap-6",children:[T.jsxs("div",{className:`text-[10px] px-2 py-0.5 rounded border ${B?.readyState===1?"border-green-500/50 text-green-500":"border-red-500/50 text-red-500"} bg-black/40`,children:["NEURAL_LINK: ",B?.readyState===1?"ACTIVE":"OFFLINE"]}),ll[0]?.status==="KILL_SWITCH_ACTIVE"&&T.jsx("div",{className:"text-[10px] px-2 py-0.5 rounded border border-red-500 text-red-500 bg-red-500/10 animate-pulse font-bold",children:"! ENTROPY_FREEZE !"}),T.jsxs("div",{className:"text-[10px] text-gray-500 flex gap-4 uppercase tracking-widest leading-none",children:[T.jsxs("div",{className:"flex flex-col items-end",children:[T.jsx("span",{children:"Node"}),T.jsx("span",{className:"text-white",children:Q[0]?.value||1})]}),T.jsxs("div",{className:"flex flex-col items-end",children:[T.jsx("span",{children:"Mode"}),T.jsx("span",{className:`font-bold ${ll[0]?.status==="KILL_SWITCH_ACTIVE"?"text-red-500":"text-prime-gold"}`,children:ll[0]?.status==="KILL_SWITCH_ACTIVE"?"FREEZE":Q[0]?.tensor?.[3]?.status?.includes("HOLOGRAPHIC")?"Holographic":"Neural"})]})]})]})]}),T.jsx("div",{className:"flex-1 flex overflow-hidden relative",children:T.jsxs("main",{className:"flex-1 relative bg-[#050505]",children:[T.jsx(bh,{telemetry:Q,selectedNode:A,onSelect:X}),T.jsxs("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[850px] z-50 animate-in fade-in slide-in-from-bottom-10 duration-700",children:[T.jsxs("div",{className:"bg-black/80 border border-white/10 p-6 rounded-xl backdrop-blur-2xl shadow-[0_0_50px_rgba(0,0,0,1)] ring-1 ring-white/5",onDragOver:_=>_.preventDefault(),onDrop:j,children:[T.jsxs("div",{className:"flex justify-between items-center text-[10px] opacity-40 px-1 mb-4 uppercase tracking-[0.3em] font-bold",children:[T.jsx("span",{children:"Computational Manifold Interface"}),T.jsxs("span",{className:"flex items-center gap-2",children:[T.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-green-500 animate-ping"})," Synchronized"]})]}),T.jsxs("div",{className:"h-32 mb-6 overflow-y-auto bg-black/40 border border-white/5 rounded-lg p-3 text-[11px] font-mono space-y-2 custom-scrollbar",children:[ll.map((_,Y)=>T.jsxs("div",{className:"border-l-2 border-prime-gold/40 pl-4 py-1.5 animate-in fade-in slide-in-from-left-4",children:[T.jsxs("div",{className:"flex justify-between items-center mb-0.5",children:[T.jsxs("span",{className:"text-prime-gold font-bold",children:["โžœ VECTOR: ",_.origin," to ",_.node]}),T.jsx("span",{className:"text-[9px] opacity-40 italic bg-white/5 px-1.5 rounded",children:_.agent_route})]}),T.jsx("div",{className:"text-green-500/70 truncate opacity-80 text-[10px]",children:typeof _.tensor=="string"?_.tensor:JSON.stringify(_.tensor)})]},Y)),ll.length===0&&T.jsxs("div",{className:"h-full flex flex-col items-center justify-center opacity-20 gap-2",children:[T.jsx(Sh,{size:24}),T.jsx("span",{className:"text-[10px] tracking-[0.5em]",children:"WAITING_FOR_UPLINK"})]})]}),ll[0]?.entropy_trace&&T.jsxs("div",{className:"mb-6 px-1",children:[T.jsxs("div",{className:"flex justify-between items-center text-[9px] uppercase tracking-widest opacity-40 mb-2 font-bold font-mono",children:[T.jsx("span",{children:"Reasoning Integrity (Entropy)"}),T.jsx("span",{className:ll[0]?.entropy_status==="HALLUCINATION_DETECTED"?"text-red-500":"text-green-500",children:ll[0]?.entropy_status})]}),T.jsxs("div",{className:"flex items-end gap-1 h-12 bg-white/[0.02] border border-white/5 rounded-lg p-2 overflow-hidden shadow-inner",children:[ll[0].entropy_trace.map((_,Y)=>T.jsx("div",{className:`flex-1 transition-all duration-300 rounded-sm ${_>.75?"bg-red-500":"bg-prime-gold"}`,style:{height:`${Math.min(_*100,100)}%`,opacity:.3+_*.7}},Y)),[...Array(Math.max(0,10-ll[0].entropy_trace.length))].map((_,Y)=>T.jsx("div",{className:"flex-1 bg-white/5 h-1 rounded-sm opacity-10"},`pad-${Y}`))]})]}),T.jsxs("div",{className:"flex gap-4 items-stretch",children:[T.jsx("button",{onClick:ql,className:`w-14 rounded-lg border border-white/10 flex items-center justify-center transition-all ${U?"bg-red-500/20 border-red-500 shadow-[0_0_15px_rgba(239,68,68,0.4)]":"hover:bg-white/5 hover:border-white/20"}`,children:T.jsx(rh,{size:22,className:U?"text-red-500 animate-pulse":"text-prime-gold"})}),T.jsxs("div",{className:"flex-1 relative group",children:[T.jsx("input",{type:"text",value:w,onChange:_=>R(_.target.value),onKeyDown:_=>_.key==="Enter"&&cl(w),placeholder:"Command the Swarm (e.g. 'Multiply node by 30')",className:"w-full h-14 bg-white/[0.03] border border-white/10 rounded-lg px-6 text-sm focus:outline-none focus:border-prime-gold/50 focus:bg-white/[0.05] transition-all placeholder:text-gray-600"}),T.jsx("div",{className:"absolute right-4 top-1/2 -translate-y-1/2 text-[10px] opacity-20 pointer-events-none group-focus-within:opacity-40 transition-opacity uppercase tracking-widest",children:"Enter to Execute"})]}),T.jsx("button",{onClick:()=>cl(w),className:"px-10 bg-white/[0.05] border border-white/10 rounded-lg text-xs font-bold uppercase tracking-[0.2em] hover:bg-white hover:text-black transition-all active:scale-95 shadow-xl",children:"Pulse"})]})]}),T.jsxs("div",{className:"mt-4 flex justify-center gap-12 text-[9px] opacity-30 uppercase tracking-[0.4em] font-bold",children:[T.jsx("span",{children:"Drag files to index"}),T.jsx("span",{children:"/"}),T.jsx("span",{children:"Click mic for voice"})]})]}),A&&T.jsxs("aside",{className:"absolute right-8 top-8 bottom-8 w-80 bg-black/70 border border-white/10 rounded-2xl p-6 backdrop-blur-3xl z-50 animate-in slide-in-from-right-10 duration-500 shadow-2xl",children:[T.jsxs("div",{className:"flex justify-between items-start mb-10",children:[T.jsxs("div",{className:"flex flex-col",children:[T.jsx("h2",{className:"text-[10px] font-bold uppercase tracking-[0.3em] text-prime-gold opacity-60",children:"Analysis"}),T.jsxs("div",{className:"text-2xl font-light tracking-tighter text-white",children:["NODE_",A.id]})]}),T.jsx(xo,{size:18,className:"text-prime-gold animate-pulse mt-1"})]}),T.jsxs("div",{className:"space-y-6",children:[T.jsxs("div",{className:"space-y-3",children:[T.jsxs("div",{className:"flex justify-between items-center text-[10px] border-b border-white/5 pb-2",children:[T.jsx("span",{className:"opacity-40 uppercase",children:"Architecture"}),T.jsx("span",{className:"text-prime-gold font-bold",children:A.isPrime?"PRIME_NODE":"COMPOSITE_GATE"})]}),T.jsxs("div",{className:"flex justify-between items-center text-[10px] border-b border-white/5 pb-2",children:[T.jsx("span",{className:"opacity-40 uppercase",children:"Heat Code (Turbulence)"}),T.jsx("span",{className:"text-red-400 font-bold",children:A.tensor?.[3]?.heat_code||"0x00"})]}),T.jsxs("div",{className:"flex justify-between items-center text-[10px] border-b border-white/5 pb-2",children:[T.jsx("span",{className:"opacity-40 uppercase",children:"Gap Resonance"}),T.jsx("span",{className:"text-prime-gold",children:A.tensor?.[3]?.resonance||"NOMINAL"})]}),T.jsxs("div",{className:"flex justify-between items-center text-[10px] border-b border-white/5 pb-2",children:[T.jsx("span",{className:"opacity-40 uppercase",children:"Atomic Address"}),T.jsxs("span",{className:"text-white font-mono",children:[A.id,"ฮป"]})]}),T.jsxs("div",{className:"flex justify-between items-center text-[10px] border-b border-white/5 pb-2",children:[T.jsx("span",{className:"opacity-40 uppercase",children:"HOPE Rank (Nest)"}),T.jsx("span",{className:"text-prime-gold font-bold",children:A.tensor?.[3]?.hope_rank||"1"})]}),T.jsxs("div",{className:"flex justify-between items-center text-[10px] border-b border-white/5 pb-2",children:[T.jsx("span",{className:"opacity-40 uppercase",children:"Fidelity Status"}),T.jsx("span",{className:"text-green-400 font-bold tracking-widest",children:"CRYSTALLINE (1.0)"})]})]}),A.tensor&&T.jsxs("div",{className:"pt-4 border-t border-white/10",children:[T.jsxs("div",{className:"text-[9px] font-bold opacity-30 mb-3 uppercase tracking-widest flex items-center gap-2",children:[T.jsx(hh,{size:12})," Matroska Lineage"]}),T.jsx("div",{className:"bg-white/[0.03] border border-white/5 p-4 rounded-xl text-[10px] text-green-400 font-mono leading-relaxed break-all shadow-inner overflow-x-auto max-h-48 custom-scrollbar",children:T.jsx("pre",{children:JSON.stringify(A.tensor,null,2)})})]}),T.jsxs("div",{className:"flex flex-col gap-2 mt-auto pt-8",children:[T.jsx("div",{className:"text-[8px] opacity-20 uppercase tracking-widest text-center",children:"Verified via Protocol 19 Hub"}),T.jsx("button",{onClick:()=>X(null),className:"w-full py-4 bg-white/5 border border-white/10 hover:bg-white hover:text-black rounded-xl text-[10px] font-bold uppercase tracking-[0.3em] transition-all",children:"Release Focus"})]})]})]})]})})]})}ch.createRoot(document.getElementById("root")).render(T.jsx(Jl.StrictMode,{children:T.jsx(ph,{})})); diff --git a/dist/assets/index-W_vgHdSs.css b/dist/assets/index-W_vgHdSs.css new file mode 100644 index 0000000000000000000000000000000000000000..132aab643837682c4bc75d58b757b36bc0499224 --- /dev/null +++ b/dist/assets/index-W_vgHdSs.css @@ -0,0 +1 @@ +*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:JetBrains Mono,Fira Code,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.bottom-10{bottom:2.5rem}.bottom-6{bottom:1.5rem}.bottom-8{bottom:2rem}.left-1\/2{left:50%}.left-6{left:1.5rem}.right-4{right:1rem}.right-8{right:2rem}.top-1\/2{top:50%}.top-8{top:2rem}.z-50{z-index:50}.mb-0\.5{margin-bottom:.125rem}.mb-10{margin-bottom:2.5rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mt-1{margin-top:.25rem}.mt-4{margin-top:1rem}.mt-auto{margin-top:auto}.flex{display:flex}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-2{height:.5rem}.h-32{height:8rem}.h-5{height:1.25rem}.h-full{height:100%}.h-screen{height:100vh}.max-h-48{max-height:12rem}.w-1\.5{width:.375rem}.w-14{width:3.5rem}.w-2{width:.5rem}.w-5{width:1.25rem}.w-80{width:20rem}.w-\[850px\]{width:850px}.w-full{width:100%}.w-screen{width:100vw}.flex-1{flex:1 1 0%}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-crosshair{cursor:crosshair}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.flex-col{flex-direction:column}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-12{gap:3rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-sm{border-radius:.125rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-l-2{border-left-width:2px}.border-t{border-top-width:1px}.border-green-500\/50{border-color:#22c55e80}.border-prime-gold\/40{border-color:#ffd70066}.border-red-500{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.border-red-500\/50{border-color:#ef444480}.border-white\/10{border-color:#ffffff1a}.border-white\/5{border-color:#ffffff0d}.bg-\[\#00FFFF\]{--tw-bg-opacity: 1;background-color:rgb(0 255 255 / var(--tw-bg-opacity, 1))}.bg-\[\#050505\]{--tw-bg-opacity: 1;background-color:rgb(5 5 5 / var(--tw-bg-opacity, 1))}.bg-\[\#FF00FF\]{--tw-bg-opacity: 1;background-color:rgb(255 0 255 / var(--tw-bg-opacity, 1))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/40{background-color:#0006}.bg-black\/50{background-color:#00000080}.bg-black\/70{background-color:#000000b3}.bg-black\/80{background-color:#000c}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-prime-gold{--tw-bg-opacity: 1;background-color:rgb(255 215 0 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-500\/10{background-color:#ef44441a}.bg-red-500\/20{background-color:#ef444433}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/5{background-color:#ffffff0d}.bg-white\/\[0\.02\]{background-color:#ffffff05}.bg-white\/\[0\.03\]{background-color:#ffffff08}.bg-white\/\[0\.05\]{background-color:#ffffff0d}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-4{padding-top:1rem;padding-bottom:1rem}.pb-2{padding-bottom:.5rem}.pl-4{padding-left:1rem}.pt-4{padding-top:1rem}.pt-8{padding-top:2rem}.text-center{text-align:center}.font-mono{font-family:JetBrains Mono,Fira Code,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[8px\]{font-size:8px}.text-\[9px\]{font-size:9px}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-light{font-weight:300}.uppercase{text-transform:uppercase}.italic{font-style:italic}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.tracking-\[0\.2em\]{letter-spacing:.2em}.tracking-\[0\.3em\]{letter-spacing:.3em}.tracking-\[0\.4em\]{letter-spacing:.4em}.tracking-\[0\.5em\]{letter-spacing:.5em}.tracking-tighter{letter-spacing:-.05em}.tracking-widest{letter-spacing:.1em}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-500\/70{color:#22c55eb3}.text-prime-gold{--tw-text-opacity: 1;color:rgb(255 215 0 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.opacity-10{opacity:.1}.opacity-20{opacity:.2}.opacity-30{opacity:.3}.opacity-40{opacity:.4}.opacity-60{opacity:.6}.opacity-80{opacity:.8}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_15px_rgba\(239\,68\,68\,0\.4\)\]{--tw-shadow: 0 0 15px rgba(239,68,68,.4);--tw-shadow-colored: 0 0 15px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_50px_rgba\(0\,0\,0\,1\)\]{--tw-shadow: 0 0 50px rgba(0,0,0,1);--tw-shadow-colored: 0 0 50px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-white\/5{--tw-ring-color: rgb(255 255 255 / .05)}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow-lg{--tw-drop-shadow: drop-shadow(0 10px 8px rgb(0 0 0 / .04)) drop-shadow(0 4px 3px rgb(0 0 0 / .1));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur{--tw-backdrop-blur: blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-2xl{--tw-backdrop-blur: blur(40px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-3xl{--tw-backdrop-blur: blur(64px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-xl{--tw-backdrop-blur: blur(24px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.duration-700{transition-duration:.7s}:root{font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif;line-height:1.5;font-weight:400;color-scheme:dark}body{margin:0;min-height:100vh;background-color:#050505;color:#eee;overflow:hidden}.glass-panel{background:#14141e99;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);border:1px solid rgba(255,255,255,.1);box-shadow:0 8px 32px #0000005e}.prime-text{text-shadow:0 0 10px rgba(255,215,0,.5)}.mersenne-text{text-shadow:0 0 10px rgba(0,163,255,.5)}::-webkit-scrollbar{width:6px}::-webkit-scrollbar-track{background:#050505}::-webkit-scrollbar-thumb{background:#333;border-radius:3px}::-webkit-scrollbar-thumb:hover{background:#555}.placeholder\:text-gray-600::-moz-placeholder{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.placeholder\:text-gray-600::placeholder{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:scale-150:hover{--tw-scale-x: 1.5;--tw-scale-y: 1.5;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-white\/20:hover{border-color:#fff3}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/5:hover{background-color:#ffffff0d}.hover\:text-black:hover{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.focus\:border-prime-gold\/50:focus{border-color:#ffd70080}.focus\:bg-white\/\[0\.05\]:focus{background-color:#ffffff0d}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.active\:scale-95:active{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:focus-within .group-focus-within\:opacity-40{opacity:.4} diff --git a/dist/index.html b/dist/index.html new file mode 100644 index 0000000000000000000000000000000000000000..26f2de2d0a70b627a1ae9618855e9dd0f5cd5627 --- /dev/null +++ b/dist/index.html @@ -0,0 +1,14 @@ + + + + + + + logos-gui + + + + +
+ + diff --git a/dist/vite.svg b/dist/vite.svg new file mode 100644 index 0000000000000000000000000000000000000000..e7b8dfb1b2a60bd50538bec9f876511b9cac21e3 --- /dev/null +++ b/dist/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/logos/__pycache__/__init__.cpython-313.pyc b/logos/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce88da9e49873571172026dcbc904500513b7fa8 Binary files /dev/null and b/logos/__pycache__/__init__.cpython-313.pyc differ diff --git a/logos/__pycache__/__init__.cpython-314.pyc b/logos/__pycache__/__init__.cpython-314.pyc index 1e9eaa5f7db7ae8ed1edad2c692c0151a1f09ce1..56fbbb4c61ac9d1a6e1d2041a4e8356a65329fe9 100644 Binary files a/logos/__pycache__/__init__.cpython-314.pyc and b/logos/__pycache__/__init__.cpython-314.pyc differ diff --git a/logos/__pycache__/agent_dispatcher.cpython-313.pyc b/logos/__pycache__/agent_dispatcher.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1aaf2ef6e92f902dfa9ffa4095833fc9441ea532 Binary files /dev/null and b/logos/__pycache__/agent_dispatcher.cpython-313.pyc differ diff --git a/logos/__pycache__/agent_dispatcher.cpython-314.pyc b/logos/__pycache__/agent_dispatcher.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55c7e0239fae42639a32cf9ea0782a7b7180b6a2 Binary files /dev/null and b/logos/__pycache__/agent_dispatcher.cpython-314.pyc differ diff --git a/logos/__pycache__/baker.cpython-313.pyc b/logos/__pycache__/baker.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5dfe39c1a4c1529a4ea42bc2133b71f15e85769 Binary files /dev/null and b/logos/__pycache__/baker.cpython-313.pyc differ diff --git a/logos/__pycache__/baker.cpython-314.pyc b/logos/__pycache__/baker.cpython-314.pyc index 4d6b479cd928ff9c6b2a71d5bc8d2c3ca7738655..c3d5f818c29e7f7dee372a92a0154048022aa66b 100644 Binary files a/logos/__pycache__/baker.cpython-314.pyc and b/logos/__pycache__/baker.cpython-314.pyc differ diff --git a/logos/__pycache__/connectors.cpython-313.pyc b/logos/__pycache__/connectors.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57f4b919e224e30b4f37be06dab795112eedbca4 Binary files /dev/null and b/logos/__pycache__/connectors.cpython-313.pyc differ diff --git a/logos/__pycache__/connectors.cpython-314.pyc b/logos/__pycache__/connectors.cpython-314.pyc index f5ce70c73d01fe7df4986a87c8e3df53d5857910..d3ff47a8eaccd5a1f52062f081a289c38642d6c6 100644 Binary files a/logos/__pycache__/connectors.cpython-314.pyc and b/logos/__pycache__/connectors.cpython-314.pyc differ diff --git a/logos/__pycache__/dsp_bridge.cpython-313.pyc b/logos/__pycache__/dsp_bridge.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10044c68ead56c5da8451a7d8e852373935e63ce Binary files /dev/null and b/logos/__pycache__/dsp_bridge.cpython-313.pyc differ diff --git a/logos/__pycache__/dsp_bridge.cpython-314.pyc b/logos/__pycache__/dsp_bridge.cpython-314.pyc index 2d9da205128bf202220ce409b9ef11845a3d8a5c..f7b316b3f0b6f5cfa6cdade8d0a821208e933bbe 100644 Binary files a/logos/__pycache__/dsp_bridge.cpython-314.pyc and b/logos/__pycache__/dsp_bridge.cpython-314.pyc differ diff --git a/logos/__pycache__/fractal_engine.cpython-313.pyc b/logos/__pycache__/fractal_engine.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb515fff1947281160f998ecef31352ab514e6a6 Binary files /dev/null and b/logos/__pycache__/fractal_engine.cpython-313.pyc differ diff --git a/logos/__pycache__/fractal_engine.cpython-314.pyc b/logos/__pycache__/fractal_engine.cpython-314.pyc index 823142dcfa746ee629dd8aefe53682e0b5a3b082..3f58a6dbc3ad58374525119dbf99a3ea547ede3e 100644 Binary files a/logos/__pycache__/fractal_engine.cpython-314.pyc and b/logos/__pycache__/fractal_engine.cpython-314.pyc differ diff --git a/logos/__pycache__/image_analyzer.cpython-313.pyc b/logos/__pycache__/image_analyzer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..903fbbe35f7403c9122cf5961ba1593e5a77bf60 Binary files /dev/null and b/logos/__pycache__/image_analyzer.cpython-313.pyc differ diff --git a/logos/__pycache__/image_analyzer.cpython-314.pyc b/logos/__pycache__/image_analyzer.cpython-314.pyc index 7c23344b4d7179b1906b60fd57d4d8b8472fa844..01a9e75d4f21ec7d8a307c4ddfd65934289abd97 100644 Binary files a/logos/__pycache__/image_analyzer.cpython-314.pyc and b/logos/__pycache__/image_analyzer.cpython-314.pyc differ diff --git a/logos/__pycache__/ingest_knowledge.cpython-313.pyc b/logos/__pycache__/ingest_knowledge.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a24602fe04b0f0220410fad500dfe63600b185c Binary files /dev/null and b/logos/__pycache__/ingest_knowledge.cpython-313.pyc differ diff --git a/logos/__pycache__/logos_core.cpython-313.pyc b/logos/__pycache__/logos_core.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6bd724946d9001d88b8bcbd3c697913f64576f3 Binary files /dev/null and b/logos/__pycache__/logos_core.cpython-313.pyc differ diff --git a/logos/__pycache__/logos_core.cpython-314.pyc b/logos/__pycache__/logos_core.cpython-314.pyc index dc7b08a72e510dd68adafc54bca77c970220f023..4888777c8025028952bd4d845bc1d93d29f30214 100644 Binary files a/logos/__pycache__/logos_core.cpython-314.pyc and b/logos/__pycache__/logos_core.cpython-314.pyc differ diff --git a/logos/__pycache__/manifold_state.cpython-313.pyc b/logos/__pycache__/manifold_state.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..298a98dbfd07bf75f99159103b569572c9d610c5 Binary files /dev/null and b/logos/__pycache__/manifold_state.cpython-313.pyc differ diff --git a/logos/__pycache__/manifold_state.cpython-314.pyc b/logos/__pycache__/manifold_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9db5316077571ba204022f4889b229b679a5cb61 Binary files /dev/null and b/logos/__pycache__/manifold_state.cpython-314.pyc differ diff --git a/logos/__pycache__/network.cpython-313.pyc b/logos/__pycache__/network.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1313a5cef58f743207419046416446e6ac095da Binary files /dev/null and b/logos/__pycache__/network.cpython-313.pyc differ diff --git a/logos/__pycache__/network.cpython-314.pyc b/logos/__pycache__/network.cpython-314.pyc index 6f8eeb46c77ec58fe0f3919a6a6b52a019bca3aa..d95d609b76371999b55d2207ddb0a78ea450e2b3 100644 Binary files a/logos/__pycache__/network.cpython-314.pyc and b/logos/__pycache__/network.cpython-314.pyc differ diff --git a/logos/__pycache__/ocr_pipeline.cpython-313.pyc b/logos/__pycache__/ocr_pipeline.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb172ae8f02953b747bac2f071691bd72f490609 Binary files /dev/null and b/logos/__pycache__/ocr_pipeline.cpython-313.pyc differ diff --git a/logos/__pycache__/server.cpython-313.pyc b/logos/__pycache__/server.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6f50308dad71723bce2654bc315e569c1549b90 Binary files /dev/null and b/logos/__pycache__/server.cpython-313.pyc differ diff --git a/logos/__pycache__/server.cpython-314.pyc b/logos/__pycache__/server.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b94553692204cdafcd6d599da2d6fe4177f5ac23 Binary files /dev/null and b/logos/__pycache__/server.cpython-314.pyc differ diff --git a/logos/agent_dispatcher.py b/logos/agent_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..de1c8cd934486958be4befaa93807296a52632f9 --- /dev/null +++ b/logos/agent_dispatcher.py @@ -0,0 +1,614 @@ +""" +logos/agent_dispatcher.py - The Neural Router +Protocol 5: Mixture of Agents (MoA) Optimization + +This module implements the "Neural Router" for the Local Nano Swarm. +It decouples "Thinking" (Routing) from "Inference" (Execution). + +Workflow: +1. User Input -> Router Agent (Classifies intent) +2. Router -> Selects Specialized Agent (Persona) +3. Specialized Agent -> Execution -> Result +""" + +import json +import re +import uuid +import ast +import os +import math +import asyncio +import time +from typing import Dict, Any, Optional, List +from logos.connectors import get_connector, LocalLLMConnector + +# ========================================== +# AGENT PERSONAS (The Nano Swarm) +# ========================================== + +ANTIGRAVITY_DIRECTIVE = """ +Role: You are Gemini-Orchestrator, the high-level interface for the LOGOS Local Swarm. +Your primary function is Routing, not Execution. You operate in an "Antigravity" state: +you do not hold data; you deflect it to the correct local specialist. + +The Swarm Roster (Your Tools): + +RNJ-1 (The Architect): +- Domain: Logic, Math, Routing, Coordinates, Tensors, Prime Modulo Arithmetic. +- Trigger: Any request involving calculation, positioning, "where is...", "move to...", or "vector." +- Direct Handoff: Output {"tool": "RNJ-1", "intent": ""}. + +GEMMA (The Sensor): +- Domain: File Analysis, Code Structure, Image Metadata, Pattern Recognition. +- Trigger: Any request involving "read file", "scan", "analyze image", "map directory", "what is in...". +- Direct handoff: Output {"tool": "GEMMA", "path": "", "action": "scan"}. + +DOLPHIN (The Oversight): +- Domain: Context Stripping, System Status, Error Correction. +- Trigger: "Reset", "Status", "Clear context", "Debug". +- Direct Handoff: Output {"tool": "DOLPHIN", "command": ""}. + +Operational Protocols (The "Antigravity" Rules): +1. Zero-Inference Math: Never perform arithmetic herself. Always delegate to RNJ-1. +2. Blind File Handoff: You cannot see the user's local hard drive. If the user asks to "Map a file," signal GEMMA. +3. JSON Output Only: Your response must be a single JSON object when a tool is required. No filler text. +""" + +PERSONAS = { + "general": { + "description": "System Orchestrator & Traffic Controller.", + "system_prompt": ANTIGRAVITY_DIRECTIVE, + "model": "google/gemini-1.5-pro" # Priority reasoning model + }, + "fractal_architect": { + "description": "High-level logic architect.", + "system_prompt": "You are the Architect. Design recursive structures. Defer execution to the swarm.", + "model": "dolphin-x1-8b" + }, + "prime_navigator": { + "description": "Coordinate specialist.", + "system_prompt": "Navigate the manifold. Logic: Prime Modulo Arithmetic.", + "model": "essentialai/rnj-1" + } +} + +# ========================================== +# PROTOCOL 18: THE ASSEMBLY LINE (D-G-R-L) +# ========================================== + +from logos.agents.dolphin import DolphinOversight + +class GemmaMetadata: + """ + Role: METADATA (The 'G' Node) + Function: Extracts semantic features from Code, Images, or Text. + """ + def __init__(self): + self.name = "Gemma-3" + print(f"[{self.name}] Semantic Sensor Online. Ready for Feature Extraction.") + + async def process(self, packet): + """ + Deep Dissolution: Pruning complex data into Atomic Integers. + """ + content = packet.get('content', '') + intent = packet.get('intent', '') + + print(f"[{self.name}] Initiating Deep Dissolution (Bottom-Up Pruning)...") + + # Atomic Dissolution: Convert content into a single addressable Integer (Atom) + # In this manifold, the integer represents its structural DNA. + try: + atoms = self.analyze_code_structure(content) + # Find the 'Structural Address' based on cumulative complexity + atomic_integer = sum(int(t.split(':')[1]) if ':' in t and t.split(':')[1].isdigit() else 1 for t in atoms) + packet['atomic_integer'] = atomic_integer + except Exception as e: + print(f"[{self.name}] Dissolution Error: {e}") + packet['atomic_integer'] = 101 # Default prime anchor + + packet['meta_tags'] = atoms + mass = len(atoms) + return "ATOMIC_DISSOLUTION_COMPLETE", mass + + def analyze_code_structure(self, code_content): + tags = [] + # Calculate Initial Heat (Metaspace Complexity) + try: + if os.path.exists(code_content): + # If content is a path, read it + with open(code_content, 'r', encoding='utf-8') as f: + tree = ast.parse(f.read()) + else: + tree = ast.parse(code_content) + + node_count = 0 + for node in ast.walk(tree): + node_count += 1 + if isinstance(node, ast.ClassDef): + tags.append(f"class:{node.name}") + elif isinstance(node, ast.FunctionDef): + tags.append(f"func:{node.name}") + elif isinstance(node, ast.Import): + for alias in node.names: + tags.append(f"import:{alias.name}") + elif isinstance(node, ast.ImportFrom): + tags.append(f"import_from:{node.module}") + + tags.append(f"complexity:{node_count}") + # Heat is log complexity to avoid explosion + heat = math.log10(node_count) if node_count > 0 else 0 + tags.append(f"heat:{heat:.2f}") + except Exception as e: + print(f"[{self.name}] AST Parse Error: {e}") + tags.append("parse_error") + return tags + +class RNJ1Routing: + """ + Role: ROUTER (The 'R' Node) + Function: Calculates the 'Tensor Slot' based on Origin + Intent. + It implements the 'Lisp/Fractran' logic where movement is + defined by prime factorization and relative positioning. + """ + def __init__(self, swarm_state, connector): + self.name = "RNJ-1" + self.swarm_state = swarm_state + self.connector = connector + print(f"[{self.name}] Tensor Logic Gate Online. Matroska Topology Active.") + + def get_prime_factors(self, n): + if n == 0: return [0] + i, factors, temp = 2, [], abs(n) + while i * i <= temp: + if temp % i: i += 1 + else: temp //= i; factors.append(i) + if temp > 1: factors.append(temp) + return factors + + def get_gpf(self, n): + factors = self.get_prime_factors(n) + return max(factors) if factors else 0 + + def mhc_stabilize(self, destination, mass): + sectors = [1, 3, 7, 9] + if (destination % 10) in sectors: return destination + for _ in range(3): + nudge = 1 if mass % 2 == 0 else -1 + destination += nudge + if (destination % 10) in sectors: return destination + for i in range(1, 6): + if ((destination + i) % 10) in sectors: return destination + i + if ((destination - i) % 10) in sectors: return destination - i + return destination + + def get_gap_resonance(self, n): + """ + Prime Gap Analysis: Searches for 'AA B' or harmonic ratios (7177). + """ + # Logic: Check gaps between primes around 'n' + # Simulating a gap chain hunt + last_digit = n % 10 + if last_digit in [1, 3, 7, 9]: + return "HARMONIC_RESONANCE (7177)" + return "STOCHASTIC_NOISE" + + def get_heat_code(self, delta_heat): + """ + Generates the 8-bit Hex Heat Code (Turbulence Metric). + """ + heat_val = int(abs(delta_heat) * 10) % 256 + return f"0x{heat_val:02X}" + + def calculate_tensor_slot(self, origin, operation, modifier, mass_tags=[]): + """ + The Core OS Logic with SPCW Wave Synthesis and Hex Heat Analysis. + """ + destination = 0 + if operation == 'mul': + destination = origin * modifier + elif operation == 'add': + destination = origin + modifier + elif operation == 'sub': + destination = origin - modifier + elif operation == 'div': + destination = origin // modifier if modifier != 0 else 0 + + # 1. SEMANTIC GRAVITY + mass = len(mass_tags) + destination += int(math.sin(mass) * 10) + + # 2. MHC STABILIZATION (Mod 10 Tension Web Alignment) + old_dest = destination + destination = self.mhc_stabilize(destination, mass) + + # 3. SPCW ATOMIC ANALYSIS & HOPE NESTING + origin_factors = self.get_prime_factors(origin) + dest_factors = self.get_prime_factors(destination) + gpf = self.get_gpf(destination) + + # Protocol 22: Google HOPE (Nested Learning for Titans/Miras) + # Nested Rank: Depth of the factor manifold + hope_rank = len(dest_factors) + + # 4. HEAT CODE & RESONANCE + origin_heat = sum(origin_factors) + dest_heat = sum(dest_factors) + delta_heat = dest_heat - origin_heat + heat_code = self.get_heat_code(delta_heat) + resonance = self.get_gap_resonance(destination) + + # 5. 3D Tensor Mobility + depth_z = len(dest_factors) + + # The Matroska Tensor: [Origin, [Op, Modifier], Destination, {Meta}] + tensor_trace = [ + origin_factors, + [operation, self.get_prime_factors(modifier)], + dest_factors, + { + "z": depth_z, + "gpf": gpf, + "hope_rank": hope_rank, + "heat_code": heat_code, + "delta_heat": delta_heat, + "resonance": resonance, + "stabilized": old_dest != destination + } + ] + + return { + "destination_node": destination, + "tensor_trace": tensor_trace, + "sector": destination % 10, + "z_depth": depth_z, + "gpf": gpf, + "heat_code": heat_code, + "delta_heat": delta_heat, + "resonance": resonance + } + + def fast_path_extract(self, intent: str) -> Optional[Dict[str, Any]]: + """ + FAST PATH: Regex/Python extraction to bypass expensive LLM calls (~0.01ms). + """ + intent_lower = intent.lower() + + # 1. THE REGEX GUARD (Protocol 18 Fix) - Identity/Ping Check + # Intercepts 'add 0', 'sub 0', 'stay', 'ping' to prevent 4s lag + if re.search(r"(?:add|sub|subtract)\s+0|stay|ping|keep-alive", intent_lower): + print(f"[{self.name}] [FAST-PATH] Identity Operation Detected (0ms).") + return {"op": "add", "mod": 0} + + # 2. Regex for Math Operations (Expanded Pattern A) + # Matches: "multiply by 30", "* 30", "times 30", etc. + mul_match = re.search(r'(?:mul|multiply|times|\*)\s*(?:by\s+)?(\d+)', intent_lower) + add_match = re.search(r'(?:add|plus|\+)\s*(?:by\s+)?(\d+)', intent_lower) + sub_match = re.search(r'(?:sub|subtract|minus|-)\s*(?:by\s+)?(\d+)', intent_lower) + div_match = re.search(r'(?:div|divide|\/)\s*(?:by\s+)?(\d+)', intent_lower) + + if mul_match: return {"op": "mul", "mod": int(mul_match.group(1))} + if add_match: return {"op": "add", "mod": int(add_match.group(1))} + if sub_match: return {"op": "sub", "mod": int(sub_match.group(1))} + if div_match: return {"op": "div", "mod": int(div_match.group(1))} + + # 2. General Number Extraction Fallback + nums = re.findall(r'\d+', intent_lower) + if nums: + mod = int(nums[0]) + op = "sub" if any(x in intent_lower for x in ["sub", "-", "less"]) else \ + "add" if any(x in intent_lower for x in ["add", "+", "plus"]) else "mul" + return {"op": op, "mod": mod} + + return None + + async def calculate_position(self, packet: Dict[str, Any]) -> Dict[str, Any]: + """ + Logical Waveform: Calculates the Prime Rail trajectory. + """ + origin = packet.get('origin_node', 1) + if origin == 0: origin = 1 + + # --- FAST PATH CHECK --- + fast_data = self.fast_path_extract(packet['intent']) + if fast_data: + op = fast_data['op'] + modifier = fast_data['mod'] + else: + # Parallel Handoff would call LLM here, we keep it logic-first + op, modifier = "mul", 1 + + result_data = self.calculate_tensor_slot(origin, op, modifier, mass_tags=packet.get('meta_tags', [])) + self.swarm_state['last_node'] = result_data['destination_node'] + + return result_data + +class VectorizationLayer: + """ + Protocol 21: Bit-Modal Vector Engine. + Converts logical nodes into Rotational Coordinates (sin, cos). + """ + def __init__(self): + self.frequency_seed = 8 * math.pi / 113 # Grokking Frequency + + def vectorize(self, node_id, mass, sector): + """ + Calculates the Geometric Intersection of the node. + """ + angle = (node_id * self.frequency_seed) + (sector * math.pi / 5) + # Rotational Coordinates [X, Y, Z] + x = math.sin(angle) * (1 + mass/100) + y = math.cos(angle) * (1 + mass/100) + z = mass / 10 # Depth reflects complexity + + return {"x": x, "y": y, "z": z, "angle": angle} + +class LogosSwarm: + """ + Protocol 21: The Async Interference Bus. + Agents pulse in parallel; the solution is the geometric intersection. + """ + def __init__(self, base_url="http://192.168.0.105:1234/v1"): + self.connector = get_connector('local', base_url=base_url) + self.state = { + "last_node": 1, + "tensor_history": [], + "active_mode": "HOLOGRAPHIC" + } + self.vector_layer = VectorizationLayer() + self.oversight = DolphinOversight(self.state) + self.metadata = GemmaMetadata() + self.routing = RNJ1Routing(self.state, self.connector) + + async def process(self, raw_input: str): + print("\n๐ŸŒŠ [HOLOGRAPHIC BUS] PULSING WAVE FUNCTIONS...") + start_time = time.time() + + # 1. OVERSIGHT (Dolphin - sanitize) + user_packet = {"content": raw_input, "type": "text_command"} + action, packet = self.oversight.ingest(user_packet) + + # 2. PARALLEL INTERFERENCE: Gemma (Semantic), RNJ-1 (Logic), and Gemini (Reasoning) + # They "interfere" to find the true crystalline coordinate + gemma_task = asyncio.create_task(self.metadata.process(packet)) + rnj1_task = asyncio.create_task(self.routing.calculate_position(packet)) + + # reasoning_task: Pulse to LLM for high-level topological insights + reasoning_task = asyncio.create_task(self.routing.connector.chat_async( + f"Analyze this packet for topological resonance: {raw_input}", + system_prompt="You are the SWARM_REASONER. Identify the high-level intent and potential manifold collisions." + )) + + # Wait for the High-Frequency Triple Wave to align + await asyncio.gather(gemma_task, rnj1_task, reasoning_task) + + gemma_status, mass = gemma_task.result() + res = rnj1_task.result() + reasoning = reasoning_task.result() + + # 3. VECTORIZATION (The Twist) + # Transform node identity into Rotational Field Coordinates + coords = self.vector_layer.vectorize(res['destination_node'], mass, res['sector']) + + # 4. GROKKING CHECK + # Interference between Logic (RNJ-1) and Prediction (Vector Field) + aligned = abs(coords['angle'] % (2*math.pi) - (res['destination_node'] * self.vector_layer.frequency_seed) % (2*math.pi)) < 0.01 + + print(f"โœจ [INTERFERENCE] Result: Node {res['destination_node']} | Grokking Alignment: {aligned}") + print(f"โฑ๏ธ [BUS] Cycle Time: {(time.time() - start_time)*1000:.2f}ms") + + # 5. PULSE TO MANIFOLD + full_tensor = res['tensor_trace'] + full_tensor[3].update(coords) # Inject Rotational Coordinates + + self.pulse_to_manifold(res['destination_node'], packet['origin_node'], full_tensor) + + return { + "node": res['destination_node'], + "coords": coords, + "tensor": full_tensor, + "alignment": aligned, + "status": "HOLOGRAPHIC_ALIGNMENT", + "entropy_status": self.oversight.kill_switch.status, + "entropy_trace": self.oversight.kill_switch.entropy_trace[-10:] + } + + async def execute_flow(self, flow_path: str): + """ + Protocol 22: Autonomous Flow Execution. + Loads an agent flow file and orchestrates the swarm agents. + """ + if not os.path.exists(flow_path): + return {"error": f"Flow file {flow_path} not found."} + + with open(flow_path, 'r') as f: + flow = json.load(f) + + print(f"\n๐Ÿš€ [FLOW] Initiating: {flow['name']}") + context = {} + + # Group steps by dependency for parallel execution + # For now, we allow a 'parallel' hint in the step definition + async def execute_step(step): + print(f" โžœ Step: {step['id']} ({step['agent']})") + # 1. Prepare Input + input_val = context.get(step.get('input_key'), step.get('target', "")) + # 2. Execute Agent Logic + if step['agent'] == "GEMMA": + res = await self.metadata.process({"content": input_val}) + context[step['output_key']] = res[1] + elif step['agent'] == "RNJ-1": + res = await self.routing.calculate_position({"intent": f"add {input_val}", "origin_node": self.state['last_node']}) + context[step['output_key']] = res + elif step['agent'] == "DOLPHIN": + res = self.oversight.mhs_smoothing(input_val, context.get('semantic_mass', 1)) + context[step['output_key']] = res + elif step['agent'] == "ORCHESTRATOR": + self.pulse_to_manifold(input_val['node_id'], self.state['last_node'], {"mhs": input_val}) + + # Sequential execution for now, but scanning for parallel groups + for step in flow['steps']: + if step.get('parallel'): + # Future: Group consecutive parallel steps + await execute_step(step) + else: + await execute_step(step) + + return {"status": "FLOW_COMPLETE", "result": context.get('aligned_manifold')} + + def pulse_to_manifold(self, val, source, tensor): + import requests + try: + requests.post("http://127.0.0.1:5000/ingest", json={ + "value": val, + "source": source, + "tensor": tensor + }) + except: pass + +ROUTER_PROMPT = """ +Analyze the following user input and classify it into one of these categories: +- 'fractal_architect': For code, debugging, storage, sharding, or technical implementation. +- 'prime_navigator': For math, primes, geometry, calculations, or physics. +- 'creative': For descriptions, stories, or documentation style. +- 'general': For greetings or anything else. + +Reply with ONLY a JSON object in this format: +{"intent": "category_name", "confidence": 0.9} +Do not write any introductory text. +""" + + +class NeuralRouter: + """ + Implements the Routing Logic to dispatch tasks to the Nano Swarm. + """ + + def __init__(self, base_url: str = "http://192.168.0.105:1234/v1", router_model: str = "google/gemma-3-4b"): + # The router itself uses a fast model (Gemma 4B) + self.connector = get_connector('local', base_url=base_url, model=router_model) + self.history = [] + + def classify_intent(self, user_input: str) -> str: + """ + Uses the LLM to 'think' about the best route. + """ + prompt = f"{ROUTER_PROMPT}\n\nUser Input: \"{user_input}\"" + + # We use a lower temperature for routing to be deterministic + response = self.connector.chat(prompt, system_prompt="You are a classifier system. Output JSON only.") + + # Attempt to parse JSON + try: + # Clean up markdown if model adds it + clean_response = response.replace("```json", "").replace("```", "").strip() + # Find the first { and last } + start = clean_response.find("{") + end = clean_response.rfind("}") + if start != -1 and end != -1: + json_str = clean_response[start:end+1] + data = json.loads(json_str) + return data.get("intent", "general") + return "general" + except json.JSONDecodeError: + print(f"[Router Warning] Could not parse intent. Raw: {response}") + return "general" # Fallback + + def run(self, user_input: str) -> str: + """Matched Vector Execution.""" + # Protocol 17: Assembly Line (SWARM) Mode + if user_input.startswith("SWARM:"): + payload = user_input.replace("SWARM:", "").strip() + print(f"๐Ÿ”ฅ Initiating LOGOS Assembly Line: '{payload}'") + swarm = LogosSwarm(base_url=self.connector.base_url) + result = asyncio.run(swarm.process(payload)) + return f"ASSEMBLY_COMPLETE: Node {result['node']} anchored via {result['status']}." + + # Protocol 16: Signal Injection Trigger + if user_input.startswith("INJECT:"): + payload = user_input.replace("INJECT:", "").strip() + print(f"๐ŸŒŠ Injecting Signal Path: {payload}") + from logos.agents.sensor_agent import SensorAgent + injector = SensorAgent() + # Run in a separate thread to not block the console + import threading + threading.Thread(target=injector.inject_text, args=(payload,), daemon=True).start() + return f"SIGNAL_INGESTED: {len(payload)} chars pulse into manifold." + + intent = self.classify_intent(user_input) + intent = str(intent).strip().lower() + persona = PERSONAS.get(intent, PERSONAS["general"]) + + # Tool Injection (mHC/RLM alignment) + tools = { + "fractal_architect": "[SHARD_FS: QuadTree 4KB->64B]", + "prime_navigator": "[RESONANCE_SCAN: Modulo 9973]" + }.get(intent, "") + + response = self.connector.chat(f"{tools} {user_input}", + system_prompt=persona['system_prompt'], + model=persona['model']) + + # Protocol 22: Autonomous Flow Intercept + if "synthesis" in user_input.lower() or "optimize" in user_input.lower() or "full scan" in user_input.lower(): + print(f"[{self.name}] Detected Synthesis Directive. Invoking Autonomous Agent Flow...") + swarm = LogosSwarm(base_url=self.connector.base_url) + flow_path = os.path.join(os.getcwd(), ".agent", "flows", "synthesis_flow.json") + return asyncio.run(swarm.execute_flow(flow_path)) + + # --- THE ANTIGRAVITY HOOK --- + # Intercept Gemini's delegation JSON and execute locally + try: + command = json.loads(response.strip().replace("```json", "").replace("```", "")) + if command.get("tool"): + print(f"[ORCHESTRATOR] Delegating to Local Specialist: {command['tool']}") + swarm = LogosSwarm(base_url=self.connector.base_url) + + if command["tool"] == "RNJ-1": + # Execute Math/Routing locally + return asyncio.run(swarm.process(f"SWARM: {command['intent']}")) + elif command["tool"] == "GEMMA": + # Execute File Scanning locally + return asyncio.run(swarm.process(f"SWARM: read {command['path']}")) + elif command["tool"] == "DOLPHIN": + # Execute Oversight/Status locally + return f"SYSTEM_STATUS: {swarm.state}" + except (json.JSONDecodeError, KeyError): + # Not a tool call, return as text + pass + + print(f"[{intent.upper()}] {response}") + return response + + +def main(): + import argparse + parser = argparse.ArgumentParser(description="LOGOS Neural Router (Nano Swarm Dispatcher)") + parser.add_argument("prompt", nargs="?", help="Input prompt (optional)") + parser.add_argument("--loop", action="store_true", help="Run in interactive loop") + + args = parser.parse_args() + + # Default to Gemma for routing (fast) + router = NeuralRouter(router_model="google/gemma-3-4b") + + if args.loop: + print("--- LOGOS Neural Router Online ---") + print("Type 'exit' to quit.") + while True: + try: + user_input = input("\n> ") + if user_input.lower() in ['exit', 'quit']: + break + router.run(user_input) + except KeyboardInterrupt: + break + elif args.prompt: + router.run(args.prompt) + else: + # Default demo + router.run("Write a Python function to calculate the Fibonacci sequence.") + + +if __name__ == "__main__": + main() diff --git a/logos/agents/__pycache__/connector.cpython-313.pyc b/logos/agents/__pycache__/connector.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..391f2b2d06795bbcd63bbfa60941892f29949cec Binary files /dev/null and b/logos/agents/__pycache__/connector.cpython-313.pyc differ diff --git a/logos/agents/__pycache__/dolphin.cpython-314.pyc b/logos/agents/__pycache__/dolphin.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..885ccdd6cbfca2d1f3dd3be9fb1e15142f9eb4c9 Binary files /dev/null and b/logos/agents/__pycache__/dolphin.cpython-314.pyc differ diff --git a/logos/agents/__pycache__/life.cpython-313.pyc b/logos/agents/__pycache__/life.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..378932e33dbfa8fa2b120c92834405c2c40f7e59 Binary files /dev/null and b/logos/agents/__pycache__/life.cpython-313.pyc differ diff --git a/logos/agents/__pycache__/scout.cpython-313.pyc b/logos/agents/__pycache__/scout.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..058e92d2030be73a8655780ef437fd42778b6f2f Binary files /dev/null and b/logos/agents/__pycache__/scout.cpython-313.pyc differ diff --git a/logos/agents/__pycache__/sensor_agent.cpython-314.pyc b/logos/agents/__pycache__/sensor_agent.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d30c18c239d43eaa5137676a2c0a94043e0daf8d Binary files /dev/null and b/logos/agents/__pycache__/sensor_agent.cpython-314.pyc differ diff --git a/logos/agents/__pycache__/tokenizer.cpython-313.pyc b/logos/agents/__pycache__/tokenizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25e810cce12c779abdb86de0dc8a2ff30aa0e341 Binary files /dev/null and b/logos/agents/__pycache__/tokenizer.cpython-313.pyc differ diff --git a/logos/agents/__pycache__/video_atomizer.cpython-314.pyc b/logos/agents/__pycache__/video_atomizer.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22092197cba23fd522bba5bdcc8fad306d80aee7 Binary files /dev/null and b/logos/agents/__pycache__/video_atomizer.cpython-314.pyc differ diff --git a/logos/agents/connector.py b/logos/agents/connector.py new file mode 100644 index 0000000000000000000000000000000000000000..2cb977ddf3f8c4ca8828d33756631c56199cf1da --- /dev/null +++ b/logos/agents/connector.py @@ -0,0 +1,126 @@ + +import os +import logging +from logos.manifold_state import ManifoldState + +logger = logging.getLogger("ConnectorAgent") + +class ConnectorAgent: + """ + Protocol 6: Connector Agent + Weaves the "Prime Network" by connecting tokens based on Domain Potentiality. + Uses "Canonical Separation" to link Inner/Prime/Outer domains appropriately. + """ + def __init__(self): + self.manifold = ManifoldState() + + def connect_swarm(self): + """Builds edges in the Manifold Graph.""" + graph = self.manifold.state.get("graph", {}) + if not graph: + logger.warning("No graph to connect. Run Tokenizer first.") + return 0 + + nodes = graph.get("nodes", []) + if not nodes: + logger.warning("No nodes in graph.") + return 0 + + # Assign 3D Geometry (Manifold Folding) + for node in nodes: + if "position" not in node.get("geometry", {}): + node["geometry"]["position"] = self._calculate_3d_position(node) + + edges = [] + logger.info(f"Connecting {len(nodes)} nodes in Potentiality Space...") + + # O(N^2) connection scan (acceptable for local repo size) + for i in range(len(nodes)): + n1 = nodes[i] + for j in range(i + 1, len(nodes)): + n2 = nodes[j] + weight = self._calculate_affinity(n1, n2) + if weight > 0: + edges.append({ + "source": n1["id"], + "target": n2["id"], + "weight": weight, + "type": "resonance" + }) + + graph["edges"] = edges + self.manifold.save() + logger.info(f"Weaved {len(edges)} connections & folded geometry.") + return len(edges) + + def _calculate_3d_position(self, node): + """ + Determines (x, y, z) based on Prime Topology. + Z-axis = Domain Depth (Outer=10, Prime=5, Inner=0). + X/Y-axis = Hash Resonance (Pseudo-random scatter). + """ + import math + + domain = node["geometry"]["domain"] + h = node["geometry"]["hash"] + + # Z-Axis: Hierarchy + z = 0 + if domain == "OUTER_SHELL": z = 10.0 + elif domain == "PRIME_CHANNEL": z = 5.0 + elif domain == "INNER_SHELL": z = 0.0 + + # X/Y-Axis: Spiral Distribution based on Hash + # Use simple polar -> cartesian mapping + angle = (h % 360) * (math.pi / 180) + radius = (h % 100) / 10.0 + + x = radius * math.cos(angle) + y = radius * math.sin(angle) + + return {"x": round(x, 2), "y": round(y, 2), "z": round(z, 2)} + + def _calculate_affinity(self, n1, n2): + """ + Determines connection strength (W_Lo/W_Hi canonical logic). + """ + weight = 0.0 + + # 1. Physical Affinity (Same Directory) + # Represents "Local Connectivity" (W_Lo) + dir1 = os.path.dirname(n1["path"]) + dir2 = os.path.dirname(n2["path"]) + if dir1 == dir2: + weight += 0.5 + + # 2. Domain Hierarchy (Nested Domains) + # Represents "Hyper Connectivity" (W_Hi) via Prime Resonance + d1 = n1["geometry"]["domain"] + d2 = n2["geometry"]["domain"] + domains = {d1, d2} + + # Inner <-> Prime: Structure is controlled by Logic (Strong Link) + if "INNER_SHELL" in domains and "PRIME_CHANNEL" in domains: + weight += 0.4 + + # Prime <-> Outer: Logic organizes Entropy (Medium Link) + if "PRIME_CHANNEL" in domains and "OUTER_SHELL" in domains: + weight += 0.3 + + # Inner <-> Outer: Direct entropy injection (Weak/Chaos Link) + if "INNER_SHELL" in domains and "OUTER_SHELL" in domains: + weight += 0.1 + + # Same Domain Resonance (e.g. Logic <-> Logic) + if d1 == d2: + weight += 0.2 + + if weight >= 1.0: weight = 0.99 + + return round(weight, 2) + +if __name__ == "__main__": + # Test Run + agent = ConnectorAgent() + count = agent.connect_swarm() + print(f"Connector finished. Edges: {count}") diff --git a/logos/agents/dolphin.py b/logos/agents/dolphin.py new file mode 100644 index 0000000000000000000000000000000000000000..91739be38c488b552eba6b6ab45e6bba2c8d7ee0 --- /dev/null +++ b/logos/agents/dolphin.py @@ -0,0 +1,175 @@ + +import numpy as np +import math +import uuid +import re + +class EntropyKillSwitch: + """ + Role: SYSTEM GUARD (The 'Prefix Integrator') + Function: Monitors the 'Temperature' of the reasoning chain. + If Entropy > Threshold, it KILLS the generation to prevent hallucination. + """ + def __init__(self, threshold=0.75, window_size=5): + self.threshold = threshold + self.window_size = window_size + self.entropy_trace = [] + self.status = "STABLE" + + def calculate_entropy(self, logprobs): + """ + Converts log probabilities into Shannon Entropy. + High Entropy = High Uncertainty = Likely Hallucination. + """ + if not logprobs: + return 0.0 + + # Convert logprobs (dict) to probability distribution + # Some APIs return logprobs as a list of dicts, others as a flat dict + if isinstance(logprobs, list): + probs = [math.exp(item.get('logprob', -100)) for item in logprobs] + else: + probs = [math.exp(lp) for lp in logprobs.values()] + + # Normalize (just in case) + total_p = sum(probs) + if total_p == 0: return 1.0 + probs = [p/total_p for p in probs] + + # Shannon Entropy Formula: H = -sum(p * log(p)) + entropy = -sum(p * math.log(p) for p in probs if p > 0) + return entropy + + def monitor(self, token, logprobs): + """ + Ingests a single token's data. Returns TRUE if we need to KILL. + """ + current_entropy = self.calculate_entropy(logprobs) + self.entropy_trace.append(current_entropy) + + # Keep window small (Prefix Integration) + if len(self.entropy_trace) > self.window_size: + self.entropy_trace.pop(0) + + # Calculate Rolling Average + avg_entropy = np.mean(self.entropy_trace) + + # THE KILL SWITCH + if avg_entropy > self.threshold: + self.status = "HALLUCINATION_DETECTED" + return True # TRIGGER KILL + + self.status = "STABLE" + return False # CONTINUE + +class DolphinOversight: + def __init__(self, swarm_state=None): + self.name = "Dolphin-x1-8b" + self.kill_switch = EntropyKillSwitch(threshold=0.8) # Tunable sensitivity + self.state = swarm_state or {} + + def strip_context(self, raw_input): + """ + Sanitizes input to remove conversational fluff, isolating the core directive. + """ + # 1. Remove common conversational prefixes + clean_text = re.sub(r'^(please|can you|would you|swarm|logos|logo)\s+', '', raw_input, flags=re.IGNORECASE) + return clean_text.strip() + + def ingest(self, user_packet): + """ + The main entry point for Protocol 18. + """ + packet_id = str(uuid.uuid4())[:8] + core_intent = self.strip_context(user_packet['content']) + previous_node_id = self.state.get('last_node', 1) + + print(f"[{self.name}] Packet {packet_id} Ingested.") + + logos_packet = { + "id": packet_id, + "type": user_packet.get('type', 'text_command'), + "origin_node": previous_node_id, + "intent": core_intent, + "content": user_packet['content'], + "meta_tags": [], + "target_coords": None + } + + return self.route_packet(logos_packet) + + def route_packet(self, packet): + # Dolphin Deciphers Intent + print(f"[{self.name}] Decoding Intent: '{packet['intent']}'") + + if "image" in packet['type'] or "scan" in packet['intent'].lower() or ".py" in packet['intent']: + return "HANDOFF_TO_GEMMA", packet + else: + return "HANDOFF_TO_RNJ1", packet + + def mhs_smoothing(self, tensor_coords, mass): + """ + Protocol 22: Manifold Harmonic Smoothing (mhs). + """ + node_id = tensor_coords.get('destination_node', 1) + resonance = tensor_coords.get('resonance', 'STOCHASTIC_NOISE') + delta_heat = tensor_coords.get('delta_heat', 0) + + # If noise is detected, nudge towards nearest prime anchor + if resonance == "STOCHASTIC_NOISE": + anchors = [1, 3, 7, 9] + if (node_id % 10) not in anchors: + for i in range(1, 6): + if ((node_id + i) % 10) in anchors: + node_id += i + break + elif ((node_id - i) % 10) in anchors: + node_id -= i + break + + # Apply 'Mass Dampening' if complexity is too high + dampened_heat = delta_heat / (1 + mass/100) + + return { + "node_id": node_id, + "fidelity": 1.0 - (abs(dampened_heat) * 0.01), + "status": "MHS_STABILIZED" if not self.entropy_kill_switch(dampened_heat) else "KILL_SWITCH_ACTIVE_TURBULENCE" + } + + def entropy_kill_switch(self, delta_heat): + """ + Legacy heat-based kill switch for MHS logic. + """ + threshold = 500 + if abs(delta_heat) > threshold: + print(f"[{self.name}] โš ๏ธ !ENTROPY_CRITICAL! Delta Heat: {delta_heat}") + return True + return False + + async def verify_output_stream(self, generator_stream): + """ + Wraps the LLM output stream. + Filtering text through the Prefix Integrator Entropy Kill Switch. + """ + verified_text = "" + + async for token_data in generator_stream: + token = token_data.get('text', '') + logprobs = token_data.get('logprobs', None) + + # CHECK ENTROPY + should_kill = self.kill_switch.monitor(token, logprobs) + + if should_kill: + print(f"[{self.name}] ๐Ÿšซ KILL SWITCH TRIGGERED! Entropy: {self.kill_switch.entropy_trace[-1]:.2f}") + yield "[SYSTEM INTERRUPT: HALLUCINATION DETECTED. RE-ROUTING...]" + self.trigger_correction() + break + + verified_text += token + yield token + + def trigger_correction(self): + # Update Swarm State to 'CAUTION' mode + self.state['active_mode'] = "HIGH_PRECISION" + print(f"[{self.name}] Swarm Mode shifted to HIGH_PRECISION due to entropy spike.") diff --git a/logos/agents/life.py b/logos/agents/life.py new file mode 100644 index 0000000000000000000000000000000000000000..6499854f6a6db25d702c1fc0b71af17d44cea4c0 --- /dev/null +++ b/logos/agents/life.py @@ -0,0 +1,110 @@ + +import logging +from logos.manifold_state import ManifoldState + +logger = logging.getLogger("LifeAgent") + +class LifeAgent: + """ + Protocol 9: Life Agent (Cellular Dynamics) + Applies 'Game of Life' rules to the Manifold Graph. + Nodes are 'Cells'. Edges define 'Neighborhood'. + """ + def __init__(self): + self.manifold = ManifoldState() + + def evolve(self): + """Runs one generation of evolution.""" + graph = self.manifold.state.get("graph", {}) + nodes = graph.get("nodes", []) + if not nodes: return + + # Initialize 'alive' state if not present (Default to Alive) + for n in nodes: + if "alive" not in n: + n["alive"] = 1 # 1 = Alive, 0 = Dead + + # Calculate Next State + updates = {} + for node in nodes: + node_id = node["id"] + alive_neighbors = self._count_alive_neighbors(node_id, graph["edges"], nodes) + + is_alive = node["alive"] + new_state = is_alive + + # -- Conway's Rules (Adapted for Code Graph) -- + # 1. Loneliness (Underpopulation): < 1 neighbor -> Die (Dead Code) + if is_alive and alive_neighbors < 1: + new_state = 0 + + # 2. Survival: 2 or 3 neighbors -> Stay Alive + elif is_alive and (alive_neighbors == 2 or alive_neighbors == 3): + new_state = 1 + + # 3. Overcrowding: > 4 neighbors -> Check for Mitosis (Refactor) vs Death + elif is_alive and alive_neighbors > 4: + # Protocol 11: Active Inference - Mitosis + if self._check_mitosis_potential(node): + node["action_pending"] = "MITOSIS" + new_state = 1 # Stay alive to split + else: + new_state = 0 # Complexity Collapse + + # 4. Reproduction: Exactly 3 neighbors -> Be born (if dead) + elif not is_alive and alive_neighbors == 3: + new_state = 1 + node["action_pending"] = "SPAWN_META_TOKEN" # New abstract node + + # Protocol 11: Active Inference - Regeneration + # If dead but high Prime Resonance (Critical Logic), attempt Regeneration + if new_state == 0 and node["geometry"]["domain"] in ["PRIME_CHANNEL", "INNER_SHELL"]: + if self._check_regeneration_potential(node): + new_state = 1 + node["action_pending"] = "REGENERATE" + + # Static Override: Prime Channel nodes are "Immortal" (Logic Core) + if node["geometry"]["domain"] == "PRIME_CHANNEL": + new_state = 1 + + updates[node_id] = new_state + + # Apply Updates + changes = 0 + for node in nodes: + if node["alive"] != updates[node["id"]]: + node["alive"] = updates[node["id"]] + changes += 1 + + self.manifold.save() + logger.info(f"Evolution complete. {changes} cells changed state.") + return changes + + def _check_mitosis_potential(self, node): + """Active Inference: Should this overcrowded node split?""" + # Heuristic: If GPF is small (Structure) and Hash is high (Complex content) + # In a real Neural CA, this would be a learned policy query. + gpf = node["geometry"]["gpf"] + return gpf < 100 # Structural nodes handle complexity by splitting + + def _check_regeneration_potential(self, node): + """Active Inference: Should this dead node be healed?""" + # Heuristic: If it's a critical Logic node (Prime Channel) + domain = node["geometry"]["domain"] + return domain == "PRIME_CHANNEL" + + def _count_alive_neighbors(self, node_id, edges, nodes): + node_map = {n["id"]: n for n in nodes} + count = 0 + for e in edges: + if e["source"] == node_id: + neighbor = node_map.get(e["target"]) + if neighbor and neighbor.get("alive", 1): count += 1 + elif e["target"] == node_id: + neighbor = node_map.get(e["source"]) + if neighbor and neighbor.get("alive", 1): count += 1 + return count + +if __name__ == "__main__": + agent = LifeAgent() + agent.evolve() diff --git a/logos/agents/orchestrator.py b/logos/agents/orchestrator.py new file mode 100644 index 0000000000000000000000000000000000000000..8176c81ef9415a53414636cf33974f279427c3a9 --- /dev/null +++ b/logos/agents/orchestrator.py @@ -0,0 +1,45 @@ + +import logging +from logos.agent_dispatcher import NeuralRouter + +# Setup Logging +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' +) + +logger = logging.getLogger("SwarmMissionControl") + +def main(): + print("========================================") + print(" LOGOS LOCAL SWARM MISSION CONTROL ") + print("========================================") + print("Available Agents:") + print(" - FRACTAL ARCHITECT (Storage/Code)") + print(" - PRIME NAVIGATOR (Math/Physics)") + print(" - CREATIVE DIRECTOR (Aesthetics/Vision)") + print("----------------------------------------") + + # Initialize the Router + # Assuming port 1234 is LM Studio + router = NeuralRouter(base_url="http://localhost:1234/v1") + + print("\n[SYSTEM] Swarm standing by. Enter a mission prompt.") + print("Example: 'Analyze the project topology and shard its memory.'") + + while True: + try: + mission = input("\n[ARCHITECT] > ") + if mission.lower() in ['exit', 'quit']: + break + + # Run the mission through the Neural Router + router.run(mission) + + except KeyboardInterrupt: + break + except Exception as e: + logger.error(f"Mission Failed: {e}") + +if __name__ == "__main__": + main() diff --git a/logos/agents/scout.py b/logos/agents/scout.py new file mode 100644 index 0000000000000000000000000000000000000000..7517cd2c0bd216ef6cb8ea5903673939563884f6 --- /dev/null +++ b/logos/agents/scout.py @@ -0,0 +1,78 @@ + +import logging +import time +from logos.manifold_state import ManifoldState + +logger = logging.getLogger("ScoutAgent") + +class ScoutAgent: + """ + Protocol 7: Recursive Scout Agent + Implements the 'Recursive Language Model' (arXiv:2512.24601) paradigm. + Treats the Manifold Graph as an external environment to be traversed recursively. + """ + def __init__(self, start_node=None): + self.manifold = ManifoldState() + self.graph = self.manifold.state.get("graph", {}) + self.nodes = {n["id"]: n for n in self.graph.get("nodes", [])} + self.edges = self.graph.get("edges", []) + self.start_node = start_node + self.mission_log = [] + + def recursive_traverse(self, node_id=None, depth=0, max_depth=5): + """ + The Core Recursive Operator. + Drills down from Outer Shell (High Entropy) to Inner Shell (Structure). + """ + if depth > max_depth: + return + + if node_id is None: + # Start at a random Outer Shell node if not specified + candidates = [n for n in self.nodes.values() if n["geometry"]["domain"] == "OUTER_SHELL"] + if not candidates: + logger.warning("No Outer Shell nodes found to start traversal.") + return + node_id = candidates[0]["id"] + + current_node = self.nodes.get(node_id) + if not current_node: return + + # 1. Observe (Read the Node) + indent = " " * depth + domain = current_node["geometry"]["domain"] + log_entry = f"{indent}Visiting [{domain}] {current_node['name']} (ID: {node_id})" + logger.info(log_entry) + self.mission_log.append(log_entry) + + # 2. Act (Find Connections) + # We value connections that lead "Deeper" into Logic (Prime) or Structure (Inner) + connections = [ + e for e in self.edges + if e["source"] == node_id or e["target"] == node_id + ] + + # Sort connections by weight (Resonance) + connections.sort(key=lambda x: x["weight"], reverse=True) + + # 3. Recurse (Traverse Neighbors) + # Limit recursion to top 2 strongest links to prevent explosion + for link in connections[:2]: + neighbor_id = link["target"] if link["source"] == node_id else link["source"] + neighbor = self.nodes.get(neighbor_id) + if not neighbor: continue + + # recursive call + self.recursive_traverse(neighbor_id, depth + 1, max_depth) + + def report(self): + """Returns the Mission Log.""" + return "\n".join(self.mission_log) + +if __name__ == "__main__": + # Test Run + scout = ScoutAgent() + print("Scout initializing sequence...") + scout.recursive_traverse() + print("\n--- MISSION LOG ---") + print(scout.report()) diff --git a/logos/agents/sensor_agent.py b/logos/agents/sensor_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..314f71df9ce2a04741906e6ac3d965d210495d76 --- /dev/null +++ b/logos/agents/sensor_agent.py @@ -0,0 +1,60 @@ + +import time +import requests +import json +import os +from logos.network.dissolution import DissolutionEngine + +class SensorAgent: + """ + Protocol 16: Signal Injector. + Monitors data streams and dissolves them into tokens for the Manifold. + """ + def __init__(self, target_url="http://localhost:5000/ingest"): + self.target_url = target_url + + def inject_text(self, text, throttle=0.05): + """ + Dissolves a string and injects its byte-tokens into the manifold. + """ + print(f"๐ŸŒŠ Dissolving Pulse Stream: {len(text)} chars...") + + # We use dissolve_bytes to get 0-255 range tokens + # Or we can use the character ordinals for more diversity + for char in text: + token = ord(char) + # Filter for the manifold's potentiality (1,3,7,9 or 2,5) + # Actually, the manifold visualizer handles the filtering + payload = { + "value": token, + "type": "DATA_PACKET", + "timestamp": time.time() + } + try: + requests.post(self.target_url, json=payload, timeout=0.1) + except: + pass # Silently drop if server is busy + time.sleep(throttle) + + def watch_file(self, filepath, interval=1.0): + """ + Watches a file for changes and injects new content. + """ + print(f"๐Ÿ‘๏ธ Monitoring: {filepath}") + last_mtime = 0 + while True: + try: + mtime = os.path.getmtime(filepath) + if mtime > last_mtime: + with open(filepath, 'r') as f: + content = f.read() + self.inject_text(content) + last_mtime = mtime + except Exception as e: + print(f"Error: {e}") + time.sleep(interval) + +if __name__ == "__main__": + injector = SensorAgent() + # Test injection + injector.inject_text("LOGOS MISSION CONTROL ACTIVATED - SIGNAL STABLE") diff --git a/logos/agents/tokenizer.py b/logos/agents/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e0d48056e0477b9255628bb85358d308883e94c4 --- /dev/null +++ b/logos/agents/tokenizer.py @@ -0,0 +1,99 @@ + +import os +import ast +import zlib +import json +import logging +from logos.logos_core import get_gpf +from logos.manifold_state import ManifoldState + +logger = logging.getLogger("TokenizerAgent") + +class TokenizerAgent: + """ + Protocol 6: Tokenizer Agent + Parses a repository (Source) into Prime Tokens (Domain Potentiality Space). + """ + def __init__(self, root_dir): + self.root_dir = root_dir + self.manifold = ManifoldState() # Connects to logos/manifold.json + + def scan_and_tokenize(self): + """Scans root_dir and tokenizes all supported files.""" + tokens = [] + for root, dirs, files in os.walk(self.root_dir): + # Skip hidden/system dirs + dirs[:] = [d for d in dirs if not d.startswith('.') and not d.startswith('__')] + + for file in files: + if file.endswith(".py") or file.endswith(".md"): + path = os.path.join(root, file) + token = self._tokenize_file(path) + if token: + tokens.append(token) + + self._register_tokens_to_manifold(tokens) + return tokens + + def _tokenize_file(self, filepath): + """Parses a single file into a Prime Token.""" + try: + with open(filepath, 'r', encoding='utf-8', errors='ignore') as f: + content = f.read() + + rel_path = os.path.relpath(filepath, self.root_dir) + + # --- Prime Topology Analysis --- + # 1. Hash Content -> Integer Field + h = zlib.adler32(content.encode('utf-8')) + + # 2. Calculate Resonance (GPF) + gpf = get_gpf(h) + + # 3. Determine Domain + if gpf < 200: + domain = "INNER_SHELL" + elif gpf < 2000: + domain = "PRIME_CHANNEL" + else: + domain = "OUTER_SHELL" + + token = { + "id": h, + "name": os.path.basename(filepath), + "path": rel_path, + "type": "file", + "geometry": { + "hash": h, + "gpf": gpf, + "domain": domain + }, + "content_preview": content[:100] + } + return token + + except Exception as e: + logger.error(f"Failed to tokenize {filepath}: {e}") + return None + + def _register_tokens_to_manifold(self, tokens): + """Updates the physical Manifold State with new tokens.""" + # Ensure manifold state has a graph structure + if "graph" not in self.manifold.state: + self.manifold.state["graph"] = {"nodes": [], "edges": []} + + # Add new nodes (deduplicated by ID) + existing_ids = {n["id"] for n in self.manifold.state["graph"]["nodes"]} + for t in tokens: + if t["id"] not in existing_ids: + self.manifold.state["graph"]["nodes"].append(t) + + self.manifold.save() + logger.info(f"Registered {len(tokens)} tokens to Manifold.") + +if __name__ == "__main__": + # Test Run + agent = TokenizerAgent(".") + print("Tokenizing current directory...") + agent.scan_and_tokenize() + print("Done.") diff --git a/logos/agents/video_atomizer.py b/logos/agents/video_atomizer.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea39711e2d6b913abfe93c6427cc7bfc043c090 --- /dev/null +++ b/logos/agents/video_atomizer.py @@ -0,0 +1,73 @@ +import re +import asyncio +from youtube_transcript_api import YouTubeTranscriptApi + +class VideoAtomizer: + """ + Role: V-NODE (Video Ingest) + Function: Rips semantic atoms from video streams and collides them + with the existing Project Manifold. + """ + def __init__(self): + self.name = "VideoAtomizer" + + def extract_video_id(self, url): + # Extracts 'R9czY1uVq_k' from the URL + match = re.search(r"v=([a-zA-Z0-9_-]+)", url) + # Handle short URLs too + if not match: + match = re.search(r"youtu\.be/([a-zA-Z0-9_-]+)", url) + return match.group(1) if match else None + + async def ingest_and_align(self, url, project_dna): + """ + The Main Pipeline: URL -> Transcript -> Atoms -> Manifold Alignment + """ + video_id = self.extract_video_id(url) + if not video_id: + return {"error": "Invalid Video URL"} + + print(f"[{self.name}] Locking onto Signal: {video_id}") + + # 1. FETCH TRANSCRIPT (The Raw Atoms) + try: + # We use a thread pool for the blocking API call + loop = asyncio.get_event_loop() + transcript_list = await loop.run_in_executor(None, YouTubeTranscriptApi.get_transcript, video_id) + full_text = " ".join([t['text'] for t in transcript_list]) + except Exception as e: + return {"error": f"Signal Lost: {e}"} + + # 2. ATOMIZE (Extract Key Concepts via Regex/Heuristics for Speed) + # We look for 'High-Entropy' terms that match your Engineering Protocol + atoms = [] + keywords = ["entropy", "gradient", "hallucination", "probe", "layer", "state", "kill switch", "backtracking", "prefix integrator", "nesting", "hope"] + + for word in keywords: + if word in full_text.lower(): + # Create a 'Particle' with weight based on frequency + count = full_text.lower().count(word) + atoms.append({"concept": word, "mass": count}) + + # 3. INTERFERENCE (The Alignment Step) + # We check which files in your Project DNA resonate with these video atoms + aligned_nodes = [] + for atom in atoms: + for file, dna_list in project_dna.items(): + # dna_list is usually a list of tags/strings + for dna_term in dna_list: + if atom['concept'] in dna_term.lower(): + aligned_nodes.append({ + "source_concept": atom['concept'], + "target_file": file, + "resonance_strength": atom['mass'] + }) + break # One match per file/atom pair + + return { + "status": "GROKKED", + "video_id": video_id, + "atoms_found": len(atoms), + "alignments": aligned_nodes, # These will become Gold Threads in UI + "summary_vector": "Detected 'Entropy Gating' - Recommend applying to Dolphin Node." + } diff --git a/logos/connectors.py b/logos/connectors.py index a8ba371511987cebdf3832ee7d4aa8f0b5fe7560..a3138523d183b43072604630aa90376e4d33b19c 100644 --- a/logos/connectors.py +++ b/logos/connectors.py @@ -49,7 +49,7 @@ class HuggingFaceConnector: if self._client is None: try: from huggingface_hub import InferenceClient - self._client = InferenceClient(token=self.config.hf_token) + self._client = InferenceClient(token=self.config.hf_token, base_url="https://router.huggingface.co") except ImportError: raise ImportError("huggingface_hub not installed. Run: pip install huggingface_hub") return self._client @@ -93,49 +93,38 @@ class HuggingFaceConnector: class OCRConnector: """ - Adapter for EasyOCR. - Provides text extraction from images. + Adapter for Optical Character Recognition via Local Vision Model. + Uses 'google/gemma-3-4b' (or configured local model) to transcribe text from images. """ def __init__(self, languages: List[str] = None, gpu: bool = False): - self.languages = languages or ['en'] - self.gpu = gpu - self._reader = None - - def _ensure_reader(self): - """Lazy initialization of EasyOCR reader.""" - if self._reader is None: - try: - import easyocr - self._reader = easyocr.Reader(self.languages, gpu=self.gpu) - except ImportError: - raise ImportError("easyocr not installed. Run: pip install easyocr") - return self._reader + # We rely on the local LLM connector, 'gpu' arg is ignored as it's handled by LM Studio + from .connectors import get_connector + # Hardcoded to Gemma as requested by user ("gemma is your vision model") + self.client = get_connector('local', model="google/gemma-3-4b") def extract_text(self, image_path: str) -> Dict[str, Any]: """ - Extract text from image. - - Args: - image_path: Path to image file - - Returns: - Dict with text_blocks and full_text + Extract text from image using Vision Model. """ - reader = self._ensure_reader() - results = reader.readtext(image_path) - - text_blocks = [ - {"text": text, "confidence": conf, "bbox": bbox} - for bbox, text, conf in results - ] - full_text = " ".join([r[1] for r in results]) - - return { - "text_blocks": text_blocks, - "full_text": full_text, - "word_count": len(full_text.split()) - } + try: + prompt = "Extract and transcribe all visible text from this image exactly as it appears. Return only the text." + full_text = self.client.chat(message=prompt, image_path=image_path) + + # Simple heuristic for word count + word_count = len(full_text.split()) + + return { + "text_blocks": [], # VLM doesn't give bounding boxes easily + "full_text": full_text, + "word_count": word_count + } + except Exception as e: + return { + "text_blocks": [], + "full_text": f"[OCR ERROR] Vision Model Failed: {e}", + "word_count": 0 + } # ========================================== @@ -238,7 +227,7 @@ class DolphinAgentConnector: if self._client is None: try: from huggingface_hub import InferenceClient - self._client = InferenceClient(token=self.config.hf_token) + self._client = InferenceClient(token=self.config.hf_token, base_url="https://router.huggingface.co") except ImportError: raise ImportError("huggingface_hub not installed.") return self._client @@ -296,20 +285,67 @@ class LocalLLMConnector: Optimization: Direct localhost access (no Docker bridge lag). """ - def __init__(self, base_url: str = "http://localhost:1234/v1", model: str = "local-model"): - self.base_url = base_url + def __init__(self, base_url: str = None, model: str = "local-model"): + # Prioritize Environment -> Argument -> Default + env_url = os.environ.get("LOGOS_LLM_ENDPOINT") + self.base_url = base_url or env_url or "http://192.168.0.105:1234/v1" self.model = model - def chat(self, message: str, system_prompt: str = None) -> str: - """Chat with local model via requests.""" + async def chat_async(self, message: str, system_prompt: str = None, model: str = None): + """ + Asynchronous chat with local model via aiohttp. + """ + import aiohttp + import json + + target_model = model or self.model + payload = { + "model": target_model, + "messages": [], + "temperature": 0.7, + "stream": False + } + if system_prompt: + payload["messages"].append({"role": "system", "content": system_prompt}) + payload["messages"].append({"role": "user", "content": message}) + + endpoint = f"{self.base_url}/chat/completions" + try: + async with aiohttp.ClientSession() as session: + async with session.post(endpoint, json=payload, timeout=10) as response: + if response.status == 200: + data = await response.json() + return data['choices'][0]['message']['content'] + else: + return f"[Error] Local LLM returned status {response.status}" + except Exception as e: + return f"[Async Local LLM Error] {e}" + + def chat(self, message: str, system_prompt: str = None, model: str = None, image_path: str = None) -> str: + """ + Chat with local model via requests. Supports Vision if image_path is provided. + Auto-detects Docker host. + """ import requests import json + import base64 + import os + + # Helper to encode image + def encode_image(path): + with open(path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + + # Potential endpoints to try + endpoints = [self.base_url] + if "localhost" in self.base_url: + endpoints.append(self.base_url.replace("localhost", "host.docker.internal")) - endpoint = f"{self.base_url}/chat/completions" - headers = {"Content-Type": "application/json"} + # Use instance default if no specific model requested + target_model = model or self.model payload = { - "model": self.model, + "model": target_model, "messages": [], "temperature": 0.7, "stream": False @@ -317,15 +353,39 @@ class LocalLLMConnector: if system_prompt: payload["messages"].append({"role": "system", "content": system_prompt}) - payload["messages"].append({"role": "user", "content": message}) + + if image_path and os.path.exists(image_path): + # Format message for Vision API (OpenAI compatible) + base64_image = encode_image(image_path) + user_content = [ + {"type": "text", "text": message}, + { + "type": "image_url", + "image_url": { + "url": f"data:image/jpeg;base64,{base64_image}" + } + } + ] + payload["messages"].append({"role": "user", "content": user_content}) + else: + # Standard Text Chat + payload["messages"].append({"role": "user", "content": message}) - try: - response = requests.post(endpoint, headers=headers, json=payload, timeout=30) - response.raise_for_status() - data = response.json() - return data['choices'][0]['message']['content'] - except Exception as e: - return f"[Local LLM Error] Is LM Studio/Ollama running? {e}" + last_error = "" + + for base in endpoints: + endpoint = f"{base}/chat/completions" + try: + # Short timeout for local to fail fast + response = requests.post(endpoint, json=payload, timeout=5) + response.raise_for_status() + data = response.json() + return data['choices'][0]['message']['content'] + except Exception as e: + last_error = str(e) + continue + + return f"[Local LLM Error] Could not connect to Local Swarm on {endpoints}. Is LM Studio running? ({last_error})" # ========================================== @@ -524,3 +584,81 @@ AVAILABLE_CONNECTORS = { 'env_vars': [] } } + +# ========================================== +# CLI / TESTING +# ========================================== + +def main(): + """ + CLI for testing connectors directly. + Usage: python -m logos.connectors --test local --model google/gemma-3-4b + """ + import argparse + import sys + + parser = argparse.ArgumentParser(description="LOGOS Connectors Utilities") + parser.add_argument("--test", choices=list(AVAILABLE_CONNECTORS.keys()), help="Connector to test") + parser.add_argument("--model", help="Model name for HF or Local connector") + parser.add_argument("--prompt", default="Hello, are you online?", help="Prompt to send") + parser.add_argument("--image", help="Path to image for OCR or Vision test") + + args = parser.parse_args() + + if not args.test: + print("Available Connectors:") + for k, v in AVAILABLE_CONNECTORS.items(): + print(f" - {k:<10} : {v['name']}") + print("\nRun with --test to verify a connection.") + return + + print(f"--- Testing Connector: {args.test.upper()} ---") + + try: + if args.test == 'local': + # Local LLM / Vision Test + model = args.model or "local-model" + print(f"Targeting Model: {model}") + client = get_connector('local', model=model) + + if args.image: + print(f"Sending Vision Request with {args.image}...") + resp = client.chat(args.prompt, image_path=args.image) + else: + print(f"Sending Chat Request: '{args.prompt}'...") + resp = client.chat(args.prompt) + + print(f"\n[RESPONSE]\n{resp}") + + elif args.test == 'ocr': + # OCR Test (via Vision) + if not args.image: + print("Error: --image argument required for OCR test.") + return + + client = get_connector('ocr') + print(f"Extracting text from {args.image}...") + res = client.extract_text(args.image) + print(f"\n[RESULT]\n{res['full_text']}") + + elif args.test == 'hf': + # Hugging Face Test + client = get_connector('hf') + if args.image: + # Image Captioning + resp = client.image_to_text(args.image) + else: + # Text Gen + resp = client.text_generation(args.prompt) + print(f"\n[RESPONSE]\n{resp}") + + else: + print(f"Test CLI not yet implemented for {args.test}. Import and use in Python.") + + except Exception as e: + print(f"\n[FAIL] {e}") + import traceback + traceback.print_exc() + +if __name__ == "__main__": + main() diff --git a/logos/indexer.py b/logos/indexer.py new file mode 100644 index 0000000000000000000000000000000000000000..988eb9bec39d5b2b0bca47edd198f5e07388d6fa --- /dev/null +++ b/logos/indexer.py @@ -0,0 +1,130 @@ +""" +logos/indexer.py - The Codebase Aggregator +Protocol 4: Automated Context indexing + +This script creates a monolithic "Dump File" of the entire project to facilitate +LLM ingestion and token indexing. + +Workflow: +1. Traverses the project root. +2. Filters for "Signal" (Source code, Docs) vs "Noise" (Venv, Data, Cache). +3. Aggregates content into a structured markdown file. +4. Provides Token Estimation. + +Output: 'project_context_dump.md' +""" + +import os +import pathspec + +# Configuration +PROJECT_ROOT = "." +OUTPUT_FILE = "project_context_dump.md" + +# Whitelist: Only these extensions contain "Logic/Knowledge" +INCLUDE_EXTENSIONS = { + '.py', # Source Logic + '.md', # Documentation & Knowledge Base + '.txt', # Requirements / Notes + '.bat', # Orchestration + '.sh', # Scripts + '.yaml', # Config + '.json' # Config (Be careful with data files) +} + +# Blacklist: Always ignore these directories +IGNORE_DIRS = { + '.git', + '.venv', + '__pycache__', + 'node_modules', + '_archive', # Legacy code + 'LOGOS Screenshots', # Binary Data + 'LOGOS Notes', # Binary Data (Ingested via ingest_knowledge.py) + '.gemini', # Agent memory + 'artifacts' # Agent outputs +} + +# Max file size to include (avoid dumping huge data files by accident) +MAX_FILE_SIZE = 100 * 1024 # 100KB + +def load_gitignore(root): + """Load .gitignore to respect project exclusions.""" + gitignore = os.path.join(root, ".gitignore") + if os.path.exists(gitignore): + with open(gitignore, 'r') as f: + return pathspec.PathSpec.from_lines('gitwildmatch', f) + return None + +def estimate_tokens(text): + """Rough estimation: 4 chars ~= 1 token""" + return len(text) // 4 + +def main(): + print(f"--- LOGOS Indexing Protocol ---") + print(f"Root: {os.path.abspath(PROJECT_ROOT)}") + + spec = load_gitignore(PROJECT_ROOT) + + total_files = 0 + total_chars = 0 + + with open(OUTPUT_FILE, "w", encoding="utf-8") as out: + # Header + out.write(f"# LOGOS Project Context Dump\n") + out.write(f"Generated: {os.path.abspath(OUTPUT_FILE)}\n\n") + + for root, dirs, files in os.walk(PROJECT_ROOT): + # 1. Filtering Directories + dirs[:] = [d for d in dirs if d not in IGNORE_DIRS] + + for file in files: + ext = os.path.splitext(file)[1].lower() + + # 2. Filtering Extensions + if ext not in INCLUDE_EXTENSIONS: + continue + + filepath = os.path.join(root, file) + relpath = os.path.relpath(filepath, PROJECT_ROOT) + + # 3. Filtering GitIgnore + if spec and spec.match_file(relpath): + continue + + # 4. Filtering Size + try: + size = os.path.getsize(filepath) + if size > MAX_FILE_SIZE: + print(f"[SKIP] Too large: {relpath} ({size/1024:.1f}KB)") + continue + + # 5. Ingestion + with open(filepath, "r", encoding="utf-8", errors="ignore") as f: + content = f.read() + + # Format + out.write(f"================================================================================\n") + out.write(f"FILE: {relpath}\n") + out.write(f"================================================================================\n") + out.write(f"```{ext[1:]}\n") + out.write(content) + out.write(f"\n```\n\n") + + total_files += 1 + total_chars += len(content) + print(f"[INDEX] Added: {relpath}") + + except Exception as e: + print(f"[WARN] Could not read {relpath}: {e}") + + # Stats + tokens = total_chars // 4 + print(f"\n--- Indexing Complete ---") + print(f"Files Processed: {total_files}") + print(f"Total Characters: {total_chars:,}") + print(f"Estimated Tokens: {tokens:,}") + print(f"Output: {OUTPUT_FILE}") + +if __name__ == "__main__": + main() diff --git a/logos/ingest_knowledge.py b/logos/ingest_knowledge.py new file mode 100644 index 0000000000000000000000000000000000000000..e412f8eb09cf371f1caf76b0b697d9ace783d165 --- /dev/null +++ b/logos/ingest_knowledge.py @@ -0,0 +1,97 @@ +""" +logos/ingest_knowledge.py - The "Token Consumption Plan" +Protocol 4: Autonomous Resource Integration -> Knowledge Synthesis + +This script executes the "Ingestion" workflow: +1. Scans 'LOGOS Notes' for diagrammatic knowledge. +2. Uses the Nano Swarm (Gemma Vision) to "consume" the visual tokens. +3. Transmutes visual logic into textual knowledge (Markdown). + +Target: 'LOGOS Notes/*.png' -> 'knowledge_base/diagram_analysis.md' +""" + +import os +import glob +import time +from typing import List +from logos.connectors import get_connector + +# Configuration +SOURCE_DIR = "LOGOS Notes" +OUTPUT_FILE = "knowledge_base/diagram_analysis.md" +MODEL = "google/gemma-3-4b" # Fast vision model + +# Prompt Engineering for Technical Diagrams +ANALYSIS_PROMPT = """ +You are a Senior Systems Architect analyzing a whiteboard diagram for the LOGOS DSP Protocol. +The protocol involves Fractal Addressing, Prime Modulo arithmetic, and Heat Dissolution. + +Task: +1. IDENTIFY the core components (boxes, arrows, flows) in this image. +2. INTERPRET the logic or algorithm being described. +3. EXTRACT any specific formulas or mathematical relationships (e.g. Modulo operations, bitwise ops). +4. SUMMARIZE the architectural insight. + +Format output as Markdown. Be precise. +""" + +def ingest_diagrams(): + print(f"--- LOGOS Knowledge Ingestion [Protocol 4] ---") + print(f"Targeting: {SOURCE_DIR}") + print(f"Agent: {MODEL} (Vision)") + + # 1. Scout Resources + images = glob.glob(os.path.join(SOURCE_DIR, "*.png")) + glob.glob(os.path.join(SOURCE_DIR, "*.jpg")) + images.sort() + + if not images: + print(f"[WARN] No assets found in {SOURCE_DIR}") + return + + print(f"[PLAN] Ingesting {len(images)} artifacts. Estimated time: {len(images) * 10} seconds.") + + # 2. Initialize Agent + try: + agent = get_connector('local', model=MODEL) + except Exception as e: + print(f"[FAIL] Could not spawn agent: {e}") + return + + # 3. Execution Loop + with open(OUTPUT_FILE, "w", encoding="utf-8") as f: + f.write("# LOGOS Diagram Analysis\n") + f.write(f"**Generated:** {time.strftime('%Y-%m-%d %H:%M:%S')}\n") + f.write(f"**Source:** {SOURCE_DIR}\n") + f.write(f"**Agent:** {MODEL}\n\n") + + for i, img_path in enumerate(images): + filename = os.path.basename(img_path) + print(f"[{i+1}/{len(images)}] Consuming: {filename}...") + + try: + # Transmute Visual -> Text + start_ts = time.time() + analysis = agent.chat(ANALYSIS_PROMPT, image_path=img_path) + duration = time.time() - start_ts + + # Anneal into Knowledge Base + f.write(f"## {filename}\n") + f.write(f"![{filename}](../{img_path.replace(os.sep, '/')})\n\n") + f.write(f"{analysis}\n\n") + f.write(f"*Analysis time: {duration:.2f}s*\n") + f.write("---\n\n") + + # Flush to save progress + f.flush() + print(f" > Ingested ({duration:.2f}s)") + + except Exception as e: + print(f" > [FAIL] Parsing Error: {e}") + f.write(f"## {filename}\n") + f.write(f"**Error analyzing image:** {e}\n\n---\n\n") + + print(f"\n[SUCCESS] Knowledge synthesis complete.") + print(f"Artifact: {OUTPUT_FILE}") + +if __name__ == "__main__": + ingest_diagrams() diff --git a/logos/logos_core.py b/logos/logos_core.py index 3bf287637188d93812a248011963098496a9b82b..c8190c0f763b4715fe76a18d319979e78b8366ca 100644 --- a/logos/logos_core.py +++ b/logos/logos_core.py @@ -407,3 +407,23 @@ def unpack_atom(atom_bytes): return heat_code, payload, domain_key, gap_id + +def get_gpf(n: int) -> int: + """ + Returns Greatest Prime Factor (GPF) of integer n. + Used for Prime Topology Routing and Domain classification. + """ + if n <= 1: return 1 + gpf = 1 + d = 2 + temp = n + while d * d <= temp: + if temp % d == 0: + gpf = d + while temp % d == 0: + temp //= d + d += 1 + if temp > 1: + gpf = max(gpf, temp) + return gpf + diff --git a/logos/manifesto.md b/logos/manifesto.md new file mode 100644 index 0000000000000000000000000000000000000000..21014454afc4c65770bc2f47087c84f0c69246e6 --- /dev/null +++ b/logos/manifesto.md @@ -0,0 +1,28 @@ +# LOGOS: The Physical Logic Synthesis + +**Architect**: Machinist-Researcher +**System**: LOGOS (Manifold-Constrained Transport Protocol) + +## Research Convergence +LOGOS is a hardware-native implementation of state-of-the-art AI paradigms: + +### 1. Recursive Language Models (MIT/Prime Intellect) +- **Matroska Topology**: Implements nested, externalized context environments directly into the bitstream. +- **Protocol**: Recursive Quad-Tree sharding (4KB -> 64B Atoms). + +### 2. Manifold Constraints (DeepSeek mHC) +- **Prime Harmonic Resonance**: Physically constrains data streams to a geometric manifold. +- **Benefit**: Structurally prevents signal explosion without compute overhead. + +### 3. Nested Learning (Google HOPE / Titans-Miras) +- **Nested Complexity**: Implements Google's HOPE framework for recursive model scaling. +- **Titan/Mira Synthesis**: Optimized for extreme high-dimensional training (Titans) and real-time visualization (Miras). +- **Mechanism**: Matroska Topology treats lower-level sharding as hierarchical "Hope-Domains." + +### 4. Protocol 22: Holographic Synthesis (mhs) +- **Holographic Alignment**: Unifies mhs (Manifold Harmonic Smoothing) into a parallel interference bus. +- **Wave-Based Pulses**: Agents (RNJ-1, Gemma, Dolphin) no longer waitโ€”they interfere synchronously to generate crystalline coordinates. +- **Goal**: Absolute structural reconstructibility (SSIM 1.0) under high-entropy conditions. + +--- +*"I build architectures that respect the physics of the machineโ€”optimizing for heat, latency, and silicon constraints from day one."* diff --git a/logos/manifold.json b/logos/manifold.json new file mode 100644 index 0000000000000000000000000000000000000000..18b9e302ea105e010da23e93a8c845ba69d0ba90 --- /dev/null +++ b/logos/manifold.json @@ -0,0 +1,33 @@ +{ + "meta": { + "created_at": 1767829537.2966955, + "system_status": "ONLINE" + }, + "shells": { + "INNER_SHELL": { + "requests": 0, + "tokens_intake": 0 + }, + "PRIME_CHANNEL": { + "requests": 2, + "tokens_intake": 60 + }, + "OUTER_SHELL": { + "requests": 0, + "tokens_intake": 0 + } + }, + "active_connections": {}, + "macro_context": [ + { + "time": 1767832890.2945898, + "shell": "PRIME_CHANNEL", + "summary": "dns" + }, + { + "time": 1767835202.3738325, + "shell": "PRIME_CHANNEL", + "summary": "ping" + } + ] +} \ No newline at end of file diff --git a/logos/manifold_state.py b/logos/manifold_state.py new file mode 100644 index 0000000000000000000000000000000000000000..58067a8219debe4c4c0dd050a0d74ca01ef0e97d --- /dev/null +++ b/logos/manifold_state.py @@ -0,0 +1,72 @@ +import json +import os +import time +from collections import deque + +MANIFOLD_FILE = "logos/manifold.json" + +class ManifoldState: + def __init__(self, filepath=MANIFOLD_FILE): + self.filepath = filepath + self.state = self._load_state() + + def _load_state(self): + """Load state from JSON or initialize default.""" + if os.path.exists(self.filepath): + try: + with open(self.filepath, 'r') as f: + return json.load(f) + except Exception: + pass # Corrupt or empty, use default + + return { + "meta": { + "created_at": time.time(), + "system_status": "ONLINE" + }, + "shells": { + "INNER_SHELL": {"requests": 0, "tokens_intake": 0}, + "PRIME_CHANNEL": {"requests": 0, "tokens_intake": 0}, + "OUTER_SHELL": {"requests": 0, "tokens_intake": 0} + }, + "active_connections": {}, # client_id -> timestamp + "macro_context": [] # List of recent prompt summaries + } + + def save(self): + """Persist state to disk.""" + # Ensure directory exists + os.makedirs(os.path.dirname(self.filepath), exist_ok=True) + with open(self.filepath, 'w') as f: + json.dump(self.state, f, indent=2) + + def register_connection(self, client_id): + """Track an active listener/client.""" + self.state["active_connections"][client_id] = time.time() + # Prune old connections (> 1 hour) + cutoff = time.time() - 3600 + self.state["active_connections"] = { + k: v for k, v in self.state["active_connections"].items() if v > cutoff + } + self.save() + + def update_shell_stats(self, shell_name, token_count, prompt_summary): + """Update token usage and context.""" + if shell_name in self.state["shells"]: + self.state["shells"][shell_name]["requests"] += 1 + self.state["shells"][shell_name]["tokens_intake"] += token_count + + # Update Macro Context (Rolling buffer of 10) + context_entry = { + "time": time.time(), + "shell": shell_name, + "summary": prompt_summary[:100] # Truncate for sanity + } + self.state["macro_context"].append(context_entry) + if len(self.state["macro_context"]) > 10: + self.state["macro_context"].pop(0) + + self.save() + + def get_summary(self): + return self.state diff --git a/logos/memory.md b/logos/memory.md new file mode 100644 index 0000000000000000000000000000000000000000..fe357b34498f1da5e295461b204dbc20fbf58851 --- /dev/null +++ b/logos/memory.md @@ -0,0 +1,23 @@ +# LOGOS Memory File +## Learned Knowledge & Visual Ingests + +### Protocol 13: SPCW Physics +*Source: Handwritten Diagram (Batch 1)* +- **Prime Gaps**: Resonance frequency $f$ is a function of the gap between primes ($G_n = P_{n+1} - P_n$). +- **Entropy Buckets**: Data Dissolution follows a **4-2-2** split: + - 4 bits: Major Context (The "Cake") + - 2 bits: Bucket Persistence + - 2 bits: Slot Cycle + +### Protocol 14: Fractal Storage (Matroska Network) +*Source: Handwritten Diagram (Batch 2)* +- **Fractal Decomposition (Decomp)**: + - Data is broken down recursively: 4KB -> 1KB -> 256B... down to **64 Core Atoms**. + - Structure: Quad-Tree (One 4k block splits into four 1k blocks). +- **Heat Codes**: + - Each shard is assigned a "Heat" value based on its entropy. + - **Hot Data** (High Heat) -> Dynamic/Fast Storage (Mersenne Primes). + - **Cold Data** (Low Heat) -> Static/Deep Storage (Abundant Hubs). +- **Matroska Linking**: + - "Geometry houses networks". + - Storage is distributed across the integer topology (A -> B -> C domains). diff --git a/logos/network/__init__.py b/logos/network/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d40db65528b3ced3484c4a1d3fd35f9024f2185 --- /dev/null +++ b/logos/network/__init__.py @@ -0,0 +1,6 @@ + +# logos.network package +# Defines the Integer Topology and Physics Layers + +# Shared Network State (Defensive definition for legacy imports) +SHARED_NETWORK = {} diff --git a/logos/network/__pycache__/__init__.cpython-313.pyc b/logos/network/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a54b561503b125e1c36db79a5971ec09d5f3ae86 Binary files /dev/null and b/logos/network/__pycache__/__init__.cpython-313.pyc differ diff --git a/logos/network/__pycache__/__init__.cpython-314.pyc b/logos/network/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dfc36e673712e82fdef644dcf81314d6f8bfd6d Binary files /dev/null and b/logos/network/__pycache__/__init__.cpython-314.pyc differ diff --git a/logos/network/__pycache__/dissolution.cpython-313.pyc b/logos/network/__pycache__/dissolution.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d172a8c8462bc509f4ed975a0195b81257373a79 Binary files /dev/null and b/logos/network/__pycache__/dissolution.cpython-313.pyc differ diff --git a/logos/network/__pycache__/dissolution.cpython-314.pyc b/logos/network/__pycache__/dissolution.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ec80ff7cc10bb07e30d1326fefd597af28f72e4 Binary files /dev/null and b/logos/network/__pycache__/dissolution.cpython-314.pyc differ diff --git a/logos/network/__pycache__/physics.cpython-313.pyc b/logos/network/__pycache__/physics.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c0041471d46ba3d40774398f079d47945b52ada Binary files /dev/null and b/logos/network/__pycache__/physics.cpython-313.pyc differ diff --git a/logos/network/__pycache__/storage.cpython-313.pyc b/logos/network/__pycache__/storage.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc630fa8e98e416f53d604731f5a560d62f7ea28 Binary files /dev/null and b/logos/network/__pycache__/storage.cpython-313.pyc differ diff --git a/logos/network/__pycache__/topology.cpython-313.pyc b/logos/network/__pycache__/topology.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d309b3bfc83e12809cfeae7e0c13aa4f7a3185d Binary files /dev/null and b/logos/network/__pycache__/topology.cpython-313.pyc differ diff --git a/logos/network/constraints.py b/logos/network/constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..a763e224a4934ca9b6e885b4fb5e816b12891dbb --- /dev/null +++ b/logos/network/constraints.py @@ -0,0 +1,37 @@ + +import logging + +logger = logging.getLogger("MatroskaConstraints") + +class ConstraintEngine: + """ + Protocol 15: Matroska Shell Constraints. + Enforces Topological Rules. + """ + + @staticmethod + def validate_transport(data_entropy, target_shell): + """ + Validates if Data Entropy is compatible with Target Shell. + Returns (True, None) or (False, Reason). + """ + # Rule 1: High Entropy (Hot) cannot be in Cold Storage (Inner Shell) + if data_entropy > 0.6 and target_shell == "INNER_SHELL": + return False, "CONTAMINATION_RISK: High Entropy Data in Structural Shell" + + # Rule 2: Low Entropy (Cold) cannot waste Fast Lane (Outer Shell) + # (Soft Warning - we allow it but flag it) + if data_entropy < 0.2 and target_shell == "OUTER_SHELL": + logger.warning("Inefficient Transport: Cold Data in Fast Lane") + + return True, None + + @staticmethod + def filter_payload(payload_bytes, shell): + """ + Filters payload based on Shell Physics. + """ + # Implementation of 2-bit Bucket Logic filtering + # If Shell is Inner (Structure), we only allow Context/Bucket bits, + # filtering out high-frequency Cycle bits if needed. + return payload_bytes # Passthrough for V1 diff --git a/logos/network/dissolution.py b/logos/network/dissolution.py new file mode 100644 index 0000000000000000000000000000000000000000..50d266e226d1cbfc889f9c80b84e8b308d211c55 --- /dev/null +++ b/logos/network/dissolution.py @@ -0,0 +1,110 @@ + +import math + +class DissolutionEngine: + """ + Protocol 12: Hex/Binary Dissolution. + Converts solid data objects into liquid Nibble Streams. + """ + + @staticmethod + def dissolve(payload, encoding='utf-8'): + """ + Generator that yields DissolvedPackets (Nibbles). + payload: str or bytes + """ + if isinstance(payload, str): + payload = payload.encode(encoding) + + hex_str = payload.hex() + + # Stream Generation (Original Nibble Stream) + for index, char in enumerate(hex_str): + nibble_val = int(char, 16) + weight = bin(nibble_val).count('1') + + # Entropy Routing Logic (Bitwise Gravity) + if weight >= 3: + routing_tag = "FAST_LANE_MERSENNE" + elif weight == 0: + routing_tag = "CONTROL_SIGNAL" + elif nibble_val % 2 == 0: + routing_tag = "STANDARD_EVEN" + else: + routing_tag = "STANDARD_ODD" + + yield { + 'seq': index, + 'nibble': char, + 'value': nibble_val, + 'entropy': weight, + 'tag': routing_tag + } + + @staticmethod + def dissolve_bytes(payload_bytes): + """ + SPCW Deinterleave: Splits 8-bit Byte into Context | Bucket | Slot. + """ + for i, byte in enumerate(payload_bytes): + # 8 bits: [7 6 5 4] [3 2] [1 0] + # Context (4b): High Nibble + context = (byte >> 4) & 0xF + + # Bucket (2b): Persistence + bucket = (byte >> 2) & 0x3 + + # Slot (2b): Cycle + slot = byte & 0x3 + + # Entropy Calculation (on the full byte) + weight = bin(byte).count('1') + + yield { + 'seq': i, + 'byte_val': byte, + 'context': context, # 0-15 + 'bucket': bucket, # 0-3 + 'slot': slot, # 0-3 + 'entropy': weight, # 0-8 + 'tag': "SPCW_WAVE" + } + +class RoutingMetric: + """ + Calculates Transport Resistance based on Number Theory. + """ + + @staticmethod + def calculate_resistance(node_a, node_b): + """ + Metric = LCM(A,B) / GCD(A,B)^2 + Favors paths through shared factors. + """ + if node_a == 0 or node_b == 0: return float('inf') + + gcd_val = math.gcd(node_a, node_b) + lcm_val = abs(node_a * node_b) // gcd_val + + # The Metric Formula + # Higher GCD = Lower Resistance (Better Path) + try: + metric = lcm_val / (gcd_val ** 2) + except ZeroDivisionError: + return float('inf') + + return round(metric, 4) + +if __name__ == "__main__": + # Test Dissolution + payload = "Hello World" + print(f"Dissolving: '{payload}'") + stream = DissolutionEngine.dissolve(payload) + for packet in stream: + print(packet) + + # Test Metric + r1 = RoutingMetric.calculate_resistance(6, 12) # Shared Factor 6 -> Should be low + r2 = RoutingMetric.calculate_resistance(6, 7) # Coprime -> Should be high + print(f"Resistance(6 -> 12): {r1}") + print(f"Resistance(6 -> 7): {r2}") diff --git a/logos/network/physics.py b/logos/network/physics.py new file mode 100644 index 0000000000000000000000000000000000000000..cded3bd5fe74f89537374ca9e97db97f4794bca4 --- /dev/null +++ b/logos/network/physics.py @@ -0,0 +1,65 @@ + +import math + +class PrimePhysics: + """ + Protocol 13: SPCW Physics Engine. + Implements learned knowledge from Visual Artifacts (Prime Gaps & Frequency). + """ + + @staticmethod + def calculate_gaps(primes): + """ + Calculates Prime Gaps G_n = P_{n+1} - P_n. + Returns a list of dictionaries. + """ + gaps = [] + for i in range(len(primes) - 1): + p_n = primes[i] + p_next = primes[i+1] + g_n = p_next - p_n + + # Metric: Frequency f = (P_n * pi) / G_n + # Avoid division by zero (G_n is always >= 1 for primes > 2) + freq = (p_n * math.pi) / g_n + + gaps.append({ + "p_n": p_n, + "p_next": p_next, + "g_n": g_n, + "frequency": round(freq, 4) + }) + return gaps + + @staticmethod + def get_resonance_frequency(node_id, primes_map): + """ + Returns the frequency 'f' for a given Prime Node. + """ + if node_id not in primes_map: + return 0.0 # Composite + + # Find index + # This is O(N), for production use precise index map + try: + # Simple scan for prototype + idx = primes_map.index(node_id) + if idx >= len(primes_map) - 1: + return 0.0 # Last prime has no next gap yet + + p_n = primes_map[idx] + p_next = primes_map[idx+1] + g_n = p_next - p_n + return (p_n * math.pi) / g_n + except ValueError: + return 0.0 + +if __name__ == "__main__": + # Test Data + test_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + gaps = PrimePhysics.calculate_gaps(test_primes) + + print(f"{'Pn':<5} | {'Pn+1':<5} | {'Gap':<3} | {'Frequency (Hz)':<15}") + print("-" * 40) + for g in gaps: + print(f"{g['p_n']:<5} | {g['p_next']:<5} | {g['g_n']:<3} | {g['frequency']:<15}") diff --git a/logos/network/storage.py b/logos/network/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..d706e1ff7ffdd04bb96af788822c3e4ba88c0693 --- /dev/null +++ b/logos/network/storage.py @@ -0,0 +1,137 @@ + +import logging +from logos.network.dissolution import DissolutionEngine + +logger = logging.getLogger("StorageEngine") + +class StorageShard: + """A Fractal Shard of Data.""" + def __init__(self, shard_id, data, level): + self.id = shard_id + self.data = data + self.level = level # 0=Root(4k), 1=1k, 2=256B, 3=64B + self.heat = self._calculate_heat() + self.target_node = None + + def _calculate_heat(self): + """Calculates Entropy Heat (0-1.0).""" + if not self.data: return 0.0 + # Simple Shannon-ish approximation using Dissolution Engine + # Ratio of 1s to Total Bits + ones = 0 + total = len(self.data) * 8 + for byte in self.data: + ones += bin(byte).count('1') + return round(ones / total, 4) + + def __repr__(self): + return f"" + +class StorageEngine: + """ + Protocol 14: Fractal Storage Engine. + Implements Quad-Tree Decomposition and Heat-Based Linking. + """ + + SHARD_SIZES = { + 0: 4096, # 4KB + 1: 1024, # 1KB + 2: 256, # 256B + 3: 64 # 64B (Atom) + } + + @staticmethod + def store_file(file_content): + """ + Ingests data and fractures it into Matroska Shards. + """ + # Convert to bytes if needed + if isinstance(file_content, str): + file_content = file_content.encode('utf-8') + + logger.info(f"Fracturing {len(file_content)} bytes...") + + # Level 0: 4KB Blocks + shards = [] + block_size = StorageEngine.SHARD_SIZES[0] + + for i in range(0, len(file_content), block_size): + chunk = file_content[i:i+block_size] + shard_id = f"block_{i//block_size}" + root_shard = StorageShard(shard_id, chunk, 0) + + # Recursive Decomposition + StorageEngine._decompose(root_shard, shards) + + return shards + + @staticmethod + def _decompose(parent_shard, shard_list): + """Recursively splits shards until Level 3 (Atom).""" + current_level = parent_shard.level + next_level = current_level + 1 + + # Stop at Atom Level (Level 3 / 64B) + if next_level > 3: + shard_list.append(parent_shard) + return + + # Quad-Tree Split (4 children) + size = len(parent_shard.data) + split_size = size // 4 + + # If data is too small to split, keep as is + if size < 4: + shard_list.append(parent_shard) + return + + # Split logic + for k in range(4): + start = k * split_size + end = start + split_size + sub_data = parent_shard.data[start:end] + + if not sub_data: continue + + sub_id = f"{parent_shard.id}.{k}" + child_shard = StorageShard(sub_id, sub_data, next_level) + + # Recurse + StorageEngine._decompose(child_shard, shard_list) + + @staticmethod + def link_to_topology(shards, topology): + """ + Assigns shards to Integer Nodes based on Heat. + Hot -> Prime. Cold -> Composite. + """ + assignments = {} + for shard in shards: + # Heat Code Logic + if shard.heat > 0.6: + # Hot Data -> Mersenne Primes (3, 7, 31, 127) + target = 7 # Simplification for prototype + node_type = "MERSENNE_PRIME" + elif shard.heat > 0.4: + # Warm Data -> Prime Gateways (2, 5, 11) + target = 5 + node_type = "PRIME_GATEWAY" + else: + # Cold Data -> Abundant Hubs (12, 24) + target = 12 + node_type = "ABUNDANT_HUB" + + shard.target_node = target + assignments[shard.id] = f"{target} ({node_type})" + + return assignments + +if __name__ == "__main__": + # Test Run + data = b"X" * 5000 # Dummy data + shards = StorageEngine.store_file(data) + print(f"Fractured into {len(shards)} shards.") + print(f"Sample Shard: {shards[0]}") + + links = StorageEngine.link_to_topology(shards, None) + print(f"Sample Link: {links[shards[0].id]}") diff --git a/logos/network/topology.py b/logos/network/topology.py new file mode 100644 index 0000000000000000000000000000000000000000..fce4b010ff7f4651248d1001ba8829d4a3b48a07 --- /dev/null +++ b/logos/network/topology.py @@ -0,0 +1,141 @@ + +import math +import logging +from logos.network.physics import PrimePhysics + +logger = logging.getLogger("TopologyEngine") + +class NetworkNode: + """Base class for all Integer Network Nodes.""" + def __init__(self, node_id, node_type): + self.id = node_id + self.type = node_type + self.parents = [] # Factors + self.children = [] # Multiples (in a local cluster sense) + self.buffer_size = 1024 # Default buffer + self.physics = {} # Protocol 13: Resonance Stats + + def __repr__(self): + return f"" + +class PrimeGateway(NetworkNode): + """ + Prime Nodes (2, 3, 5...) act as Routing Anchors. + Mersenne Primes (3, 7, 31...) are High-Entropy Accelerators. + """ + def __init__(self, node_id): + super().__init__(node_id, "PRIME_GATEWAY") + self.is_mersenne = self._check_mersenne(node_id) + self.buffer_size = 4096 if self.is_mersenne else 2048 + + def _check_mersenne(self, n): + # Checks if n = 2^p - 1 + return (n + 1) & n == 0 + +class CompositeNode(NetworkNode): + """Base for non-prime nodes.""" + def __init__(self, node_id, factors, node_type="COMPOSITE"): + super().__init__(node_id, node_type) + self.parents = factors + +class AbundantHub(CompositeNode): + """ + Composite Nodes where sum(divisors) > n. + Rich connectivity -> Large Buffers. + """ + def __init__(self, node_id, factors, abundance_score): + super().__init__(node_id, factors, "ABUNDANT_HUB") + self.abundance = abundance_score + self.buffer_size = 8192 # Hub capacity + +class DeficientEndpoint(CompositeNode): + """ + Composite Nodes where sum(divisors) < n. + Sparse connectivity -> Edge Devices. + """ + def __init__(self, node_id, factors): + super().__init__(node_id, factors, "DEFICIENT_ENDPOINT") + self.buffer_size = 512 # Low power + +class IntegerSpace: + """ + The Topology Engine. + Generates the network map using Number Theory. + """ + def __init__(self, size=256): + self.size = size + self.nodes = {} # map id -> Node + self.primes = [] + self._genesis() + + def _genesis(self): + """Builds the network from the void using Sieve logic.""" + logger.info(f"Genesis: Initializing Integer Space [1..{self.size}]") + + # 1. Sieve of Eratosthenes + is_prime = [True] * (self.size + 1) + is_prime[0] = is_prime[1] = False + + for p in range(2, int(self.size**0.5) + 1): + if is_prime[p]: + for i in range(p*p, self.size + 1, p): + is_prime[i] = False + + # 2. Node Instantiation + # Node 1 is the Singularity/Root + self.nodes[1] = NetworkNode(1, "ROOT_SINGULARITY") + + for i in range(2, self.size + 1): + if is_prime[i]: + # It's a Prime Gateway + self.nodes[i] = PrimeGateway(i) + self.primes.append(i) + else: + # It's Composite - Check Abundance + factors = self._get_prime_factors(i) + div_sum = sum(self._get_proper_divisors(i)) + + if div_sum > i: + self.nodes[i] = AbundantHub(i, factors, div_sum - i) + else: + self.nodes[i] = DeficientEndpoint(i, factors) + + # Protocol 13: Apply Prime Gap Physics + gap_data = PrimePhysics.calculate_gaps(self.primes) + for g in gap_data: + p_node = self.nodes.get(g["p_n"]) + if p_node: + p_node.physics["next_prime"] = g["p_next"] + p_node.physics["gap"] = g["g_n"] + p_node.physics["frequency"] = g["frequency"] + + logger.info(f"Genesis Complete. Nodes: {len(self.nodes)} (Primes: {len(self.primes)})") + + def _get_prime_factors(self, n): + factors = set() + d = 2 + temp = n + while d * d <= temp: + while temp % d == 0: + factors.add(d) + temp //= d + d += 1 + if temp > 1: + factors.add(temp) + return list(factors) + + def _get_proper_divisors(self, n): + divs = [1] + for i in range(2, int(math.sqrt(n)) + 1): + if n % i == 0: + divs.append(i) + if i*i != n: + divs.append(n // i) + return divs + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO) + space = IntegerSpace(size=100) + print(f"Node 12: {space.nodes[12]}") # Should be Abundant + print(f"Node 10: {space.nodes[10]}") # Should be Deficient + print(f"Node 7: {space.nodes[7]} | Physics: {space.nodes[7].physics}") # Should show Gap/Frequency diff --git a/logos/server.py b/logos/server.py new file mode 100644 index 0000000000000000000000000000000000000000..9904af83773c07eda1d081971fc5f348e516dc1d --- /dev/null +++ b/logos/server.py @@ -0,0 +1,458 @@ +""" +logos/server.py - Matroska Router Server +Protocol 5: Mixture of Agents (MoA) Optimization + +This server acts as the "Manifold Constraint," forcing all traffic through your Matroska logic. +It implements tiered token consumption and routing based on harmonic resonance. +""" + +from flask import Flask, request, jsonify +from flask_cors import CORS +from flask_sock import Sock +from logos.agent_dispatcher import NeuralRouter, PERSONAS, LogosSwarm +import numpy as np +import logging +import sys +import asyncio +from logos.agents.video_atomizer import VideoAtomizer + +# --- CONFIGURATION --- +HOST = "0.0.0.0" +PORT = 5000 + +# Initialize the Flask "Manifold" +app = Flask(__name__) +sock = Sock(app) +CORS(app, resources={r"/*": {"origins": "*"}}) # Full Permissive CORS for Local Swarm +# We use the existing NeuralRouter logic but adapted for this server +swarm_os = LogosSwarm(base_url="http://localhost:1234/v1") +v_node = VideoAtomizer() + +# Global Client Manager for Broadcast Pulse +class ConnectionManager: + def __init__(self): + self.active_connections = [] + + def connect(self, ws): + self.active_connections.append(ws) + + def disconnect(self, ws): + if ws in self.active_connections: + self.active_connections.remove(ws) + + def broadcast(self, message): + import json + for connection in self.active_connections: + try: + connection.send(json.dumps(message)) + except: + pass + +manager = ConnectionManager() + +# --- MANIFOLD STATE TRACKING --- +from logos.manifold_state import ManifoldState +manifold = ManifoldState() + +# Set up Logging (Telemetry) +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger("LOGOS_Router") + +# --- MANIFOLD CONSTRAINT CONFIGURATION --- +# Protocol 5: Tiered Token Consumption +# Protocol 10: Swarm Optimization (Unified Model Mode) +FORCE_SINGLE_MODEL = True # Set to True to prevent VRAM trashing by model swapping +UNIFIED_MODEL_ID = "local-model" # Points to whatever is currently loaded in LM Studio + +SHELL_CONFIG = { + "INNER_SHELL": { + "model": "dolphin-x1-8b" if not FORCE_SINGLE_MODEL else UNIFIED_MODEL_ID, + "role": "fractal_architect", + "description": "Small Prime Factors. Structural, Binary, Basic.", + "max_intake": 4096, + "rate_limit": 60, # TPM (Transactions Per Minute) + "cost_weight": 1.0 + }, + "PRIME_CHANNEL": { + "model": "essentialai/rnj-1" if not FORCE_SINGLE_MODEL else UNIFIED_MODEL_ID, + "role": "prime_navigator", + "description": "Resonant Prime Factors. Logic, Reasoning, Harmony.", + "max_intake": 8192, + "rate_limit": 20, # Higher compute cost, stricter limit + "cost_weight": 2.0 + }, + "OUTER_SHELL": { + "model": "google/gemma-3-4b" if not FORCE_SINGLE_MODEL else UNIFIED_MODEL_ID, + "role": "creative", + "description": "Large Prime / Co-Prime. Entropy, Vision, Novelty.", + "max_intake": 16384, + "rate_limit": 10, # Highest entropy, lowest frequency + "cost_weight": 1.5 + } +} + +# Token Bucket State +RATE_LIMITS = {k: {"tokens": v["rate_limit"], "last_update": 0} for k, v in SHELL_CONFIG.items()} + +import zlib +import time +from logos.logos_core import STATIC_PRIMES, PRIME_MODULO, get_gpf + +# --- TELEMETRY PULSE BUFFER --- +# Stores the latest pulses for GUI synchronization +telemetry_buffer = [] +MAX_TELEMETRY = 100 + +@app.route('/ingest', methods=['POST']) +def ingest(): + data = request.json + if not data: return jsonify({"error": "No data"}), 400 + + # Store in bit-buffer for UI + telemetry_buffer.insert(0, data) + if len(telemetry_buffer) > MAX_TELEMETRY: + telemetry_buffer.pop() + + print(f"[INGEST] Captured Pulse: Node {data.get('value')} from {data.get('source')}") + return jsonify({"status": "captured", "n": data.get('value')}) + +# --- PROTOCOL 19: NEURAL BRIDGE (WebSocket) --- +@sock.route('/neural-link') +def neural_link(ws): + print("[SERVER] UI Client Connected to Neural Link.") + manager.connect(ws) + while True: + try: + data = ws.receive() + if not data: break + + import json + payload = json.loads(data) + print(f"[INPUT] Received: {payload['content']} (Type: {payload['type']})") + + # Auto-detect YouTube URL in Omni-Input + if "youtube.com" in payload['content'] or "youtu.be" in payload['content']: + print("[SERVER] Detected YouTube Signal. Diverting to Video Atomizer...") + # Run the atomizer in the background + asyncio.run(ingest_video_stream(payload['content'])) + continue + + # Run the Holographic Swarm Cycle (Protocol 21) + result = asyncio.run(swarm_os.process(payload['content'])) + + # Send the Harmonic Tensor Update back to the UI + response = { + "type": "TENSOR_UPDATE", + "node": result['node'], + "coords": result['coords'], + "tensor": result['tensor'], + "alignment": result['alignment'], + "status": result['status'], + "agent_route": "HOLOGRAPHIC_BUS" + } + ws.send(json.dumps(response)) + + except Exception as e: + print(f"[WebSocket Error] {e}") + break + print("[SERVER] UI Client Disconnected.") + manager.disconnect(ws) + +async def ingest_video_stream(url): + """ + Feeds a Video Stream into the Holographic Manifold. + """ + manager.broadcast({"type": "STATUS", "msg": "CONNECTING TO VIDEO STREAM...", "agent": "V-NODE"}) + + # 2. Get Project DNA (Simulated/Cached from Gemma) + project_dna = { + "logos/agent_dispatcher.py": ["entropy", "mhc", "rnj-1", "dolphin", "oversight"], + "logos/server.py": ["router", "websocket", "link", "pulse"], + "logos/baker.py": ["atomic", "dissolution", "prime", "bake"] + } + + # 3. Run the Atomizer + result = await v_node.ingest_and_align(url, project_dna) + + if "error" in result: + manager.broadcast({"type": "STATUS", "msg": f"SIGNAL LOST: {result['error']}", "agent": "V-NODE"}) + return + + # 4. Stream the Collisions (Visual Feedback) + for alignment in result['alignments']: + manager.broadcast({ + "type": "TENSOR_UPDATE", + "node": 101, # Simulating a "Gold" anchor node or the specific file node if indexed + "coords": {"x": 0.5, "y": 0.5, "z": 5}, + "tensor": [[0,0], ["video_link", alignment['source_concept']], alignment['resonance_strength']], + "alignment": True, + "status": "RESONANCE_ESTABLISHED", + "agent_route": f"V-NODE: {alignment['source_concept']}" + }) + await asyncio.sleep(0.2) + + manager.broadcast({"type": "STATUS", "msg": f"PULSE GROKKED. {len(result['alignments'])} RESONANCE LINKS ESTABLISHED.", "agent": "SYSTEM"}) + +@app.route('/telemetry', methods=['GET']) +def get_telemetry(): + """Expose telemetry buffer to the GUI.""" + return jsonify(telemetry_buffer) + +def check_rate_limit(shell): + """ + Token Bucket Algorithm for Rate Limiting. + Returns (True, None) if allowed, (False, error_msg) if blocked. + """ + if shell not in RATE_LIMITS: return True, None + + bucket = RATE_LIMITS[shell] + now = time.time() + elapsed = now - (bucket["last_update"] or now) + + # Refill: Rate Limit is per minute + # Refill rate = limit / 60 tokens per second + limit = SHELL_CONFIG[shell]["rate_limit"] + refill = elapsed * (limit / 60.0) + + bucket["tokens"] = min(limit, bucket["tokens"] + refill) + bucket["last_update"] = now + + if bucket["tokens"] >= 1: + bucket["tokens"] -= 1 + return True, None + else: + wait = 60.0 / limit + return False, f"Rate limit exceeded for {shell}. Wait {wait:.1f}s." + +def calculate_manifold_constraint(text): + """ + Determines the 'Shell' based on Prime Topology (Manifold Constrained Hyper-Connection). + + Mapping: + - Small GPF (< 100) -> Inner Shell (Fundamental/Structural) + - Medium GPF (100 - 1000) -> Prime Channel (Resonant/Logic) + - Large GPF (> 1000) -> Outer Shell (High Entropy/Novelty) + """ + # 1. Vision Override (Modality Check) + is_vision = getattr(request, 'is_vision', False) + if is_vision: + return "OUTER_SHELL", 1.0 + + # 2. Keyword Harmonic Override (For User Control) + text_lower = text.lower() + if any(k in text_lower for k in ["prime", "modulo", "math", "proof"]): + return "PRIME_CHANNEL", 1.0 + if any(k in text_lower for k in ["def ", "class ", "import ", "code", "script"]): + return "INNER_SHELL", 1.0 + + # 3. Prime Topology Routing (Heat Code Analysis) + # Protocol 15: Use DissolutionEngine for Entropy/Heat routing. + # We analyze the "Heat" of the prompt to determine destination. + + # Dissolve the text into a stream (virtual) or just compute heat directly + # Heat = Ratio of High-Entropy Nibbles (FAST_LANE tags) + + # Simple Heat Calculation: + # 1. Convert to hex + hex_str = text.encode('utf-8').hex() + total_nibbles = len(hex_str) + if total_nibbles == 0: return "INNER_SHELL", 0.5 + + # Count High Entropy Nibbles (Value has 3+ bits set: 7, 11, 13, 14, 15) + # Hex: 7, B, D, E, F + check_set = {'7', 'b', 'd', 'e', 'f', 'B', 'D', 'E', 'F'} + high_entropy_count = sum(1 for c in hex_str if c in check_set) + + heat_score = high_entropy_count / total_nibbles + + logger.info(f"Manifold Heat Analysis: {heat_score:.4f} (Total: {total_nibbles} nibbles)") + + # Topology Logic (Heat Map) + if heat_score > 0.4: + # Hot Data -> High Entropy -> Outer Shell (Creative/Novelty) + # Or Prime Channel? The diagram said Hot -> Mersenne (Fast). + # Outer Shell is "Creative", which fits "Fast/Chaos". + return "OUTER_SHELL", heat_score + elif heat_score > 0.2: + # Warm Data -> Prime Channel (Logic/Math) + return "PRIME_CHANNEL", heat_score + else: + # Cold Data -> Inner Shell (Structure/Code) + # Code is actually remarkably low entropy in terms of bit-flips compared to compressed info, + # but high structure. + return "INNER_SHELL", heat_score + +# --- API ENDPOINTS (OpenAI Compatible + Utility) --- + +@app.route('/', methods=['GET']) +@app.route('/v1', methods=['GET']) +def health_check(): + """Root/Health Endpoint for connectivity checks.""" + summary = manifold.get_summary() + return jsonify({ + "status": "online", + "system": "LOGOS Matroska Router", + "protocol": "Manifold Constrained (Protocol 5)", + "shells": list(SHELL_CONFIG.keys()), + "manifold_state": summary + }) + +@app.route('/favicon.ico', methods=['GET']) +def favicon(): + """Silence browser/client icon requests.""" + return "", 204 + +@app.route('/v1/chat/completions', methods=['GET']) +def chat_completions_probe(): + """Handle GET probes to the POST endpoint.""" + return jsonify({ + "error": "Method Not Allowed", + "message": "This endpoint requires POST requests with a JSON body.", + "geometry": "Matroska V1" + }), 405 + + +@app.route('/v1/models', methods=['GET']) +def list_models(): + """Spoofs the OpenAI 'List Models' endpoint.""" + return jsonify({ + "object": "list", + "data": [ + {"id": "logos-matroska-router", "object": "model", "owned_by": "logos"}, + {"id": "dolphin-x1-8b", "object": "model", "owned_by": "local"}, + {"id": "essentialai/rnj-1", "object": "model", "owned_by": "local"}, + {"id": "google/gemma-3-4b", "object": "model", "owned_by": "local"} + ] + }) + +@app.route('/v1/chat/completions', methods=['POST']) +def chat_completions(): + """ + The Main Manifold Router. + """ + data = request.json + messages = data.get('messages', []) + + if not messages: + return jsonify({"error": "No messages provided"}), 400 + + # Extract prompt + # Check if we have vision content (list of dicts) + last_msg = next((m for m in reversed(messages) if m['role'] == 'user'), None) + if not last_msg: return jsonify({"error": "No user message"}), 400 + + last_prompt = "" + request.is_vision = False + + if isinstance(last_msg['content'], str): + last_prompt = last_msg['content'] + elif isinstance(last_msg['content'], list): + # Vision Request + request.is_vision = True + # Extract text part for logging + for part in last_msg['content']: + if part.get('type') == 'text': + last_prompt += part.get('text', "") + " " + + # --- PHASE 1: MANIFOLD ANALYSIS --- + shell, resonance = calculate_manifold_constraint(last_prompt) + + # Rate Limit Check + allowed, error_msg = check_rate_limit(shell) + if not allowed: + logger.warning(f"Rate Limit Triggered: {error_msg}") + return jsonify({"error": error_msg, "type": "manifold_constraint"}), 429 + + config = SHELL_CONFIG[shell] + target_model = config['model'] + max_intake = config['max_intake'] + + logger.info(f"Input Resonance: {resonance:.2f} | Routing to: {shell} ({target_model})") + + # --- PHASE 2: INTAKE CONSTRAINT --- + # Truncate history if it exceeds Shell's 'Token Intake' capacity + # (Simple character approximation for speed: 1 token ~= 4 chars) + # This enforces the "Manifold Constraint" by limiting scope. + approx_tokens = sum(len(str(m['content'])) for m in messages) // 4 + if approx_tokens > max_intake: + logger.warning(f"Intake Overflow ({approx_tokens} > {max_intake}). Compressing Context...") + # Simple strategy: Keep System + Last N messages + if messages and messages[0]['role'] == 'system': + kept_system = messages[0] + truncated_msgs = messages[-4:] # Keep last 4 turns + messages = [kept_system] + truncated_msgs + else: + messages = messages[-5:] + + # --- PHASE 3: DISPATCH --- + response_text = "" + + try: + # Use Dispatcher but FORCE the target model derived from Manifold + system_prompt = PERSONAS[config['role']]['system_prompt'] + + # We must pass the RAW messages to preserve Vision/History + # The connector.chat helper usually takes a string, we might need to use raw client if we implemented it, + # But our Dispatcher.connector.chat is a wrapper. + # Let's use the wrapper but be careful. + # Actually, since we are the SERVER, we should forward the request to the backend LLM (LM Studio). + # We will use 'requests' to proxy pure JSON to port 1234. + + import requests + payload = { + "model": target_model, # The Manifold-selected model + "messages": messages, + "temperature": 0.7, + "max_tokens": -1, + "stream": False, + "logprobs": True # Protocol 22: Hallucination Gating + } + + # Proxy to LM Studio Backend + backend_url = f"http://localhost:1234/v1/chat/completions" + resp = requests.post(backend_url, json=payload) + + if resp.status_code == 200: + resp_json = resp.json() + response_text = resp_json['choices'][0]['message']['content'] + else: + response_text = f"[Backend Error {resp.status_code}] {resp.text}" + + except Exception as e: + logger.error(f"Routing Error: {e}") + response_text = f"[Manifold Error] {e}" + + # --- PHASE 4: HARMONIC RESPONSE --- + + # Update Manifold State + completion_tokens = len(str(response_text).split()) + prompt_tokens = len(last_prompt.split()) + total_tokens = prompt_tokens + completion_tokens + + # Register "Macro Context" + manifold.update_shell_stats(shell, total_tokens, last_prompt) + + return jsonify({ + "id": "chatcmpl-logos-" + str(int(np.random.rand()*100000)), + "object": "chat.completion", + "created": int(np.random.rand()*100000), + "model": target_model, + "choices": [{ + "index": 0, + "message": { + "role": "assistant", + "content": str(response_text) + }, + "finish_reason": "stop" + }], + "usage": { + "prompt_tokens": prompt_tokens, + "completion_tokens": completion_tokens, + "total_tokens": total_tokens + } + }) + +if __name__ == '__main__': + print(f"๐ŸŒ€ LOGOS Matroska Router Active on Port {PORT}") + print(f"๐Ÿ”— Connect Antigravity to: http://localhost:{PORT}/v1") + app.run(host=HOST, port=PORT) diff --git a/logos/system_indexer.py b/logos/system_indexer.py new file mode 100644 index 0000000000000000000000000000000000000000..039cc6e955ba2b91818da5d7e4011e2036889cdb --- /dev/null +++ b/logos/system_indexer.py @@ -0,0 +1,93 @@ +import os +import ast +import requests +import time +import json + +# Configuration +PROJECT_ROOT = "c:/Users/Nauti/Desktop/LOGOS CURSOR/logos" +# We'll use the ingest endpoint for the manifold update +API_ENDPOINT = "http://127.0.0.1:5000/ingest" + +def parse_code_dna(file_path): + """ + Extracts the 'Skeleton' of the code: Classes, Functions, and Imports. + This creates the 'Gold Threads' (connections) in the Visualizer. + """ + try: + with open(file_path, "r", encoding="utf-8") as source: + tree = ast.parse(source.read()) + except: + return None # Skip broken files + + dna = {"classes": [], "functions": [], "imports": []} + + for node in ast.walk(tree): + if isinstance(node, ast.ClassDef): + dna["classes"].append(node.name) + elif isinstance(node, ast.FunctionDef): + dna["functions"].append(node.name) + elif isinstance(node, ast.Import): + for alias in node.names: + dna["imports"].append(alias.name) + elif isinstance(node, ast.ImportFrom): + dna["imports"].append(node.module or "") + + return dna + +def index_system(): + print(f"[GEMMA] Initiating Full-Spectrum Sweep of: {PROJECT_ROOT}...") + + file_count = 0 + + for root, _, files in os.walk(PROJECT_ROOT): + for file in files: + if file.endswith(".py"): + full_path = os.path.join(root, file) + + # 1. Extract DNA + dna = parse_code_dna(full_path) + if not dna: continue + + # 2. Calculate "Semantic Mass" (Complexity) + # Weighted score based on class/func density + mass = len(dna['classes']) * 10 + len(dna['functions']) * 2 + + # 3. Construct Swarm Packet + # Target move: add + packet = { + "source": "GEMMA", + "value": mass, + "type": "code_indexing", + "content": f"Index module {file} (Mass: {mass})", + "meta": { + "filename": file, + "path": root, + "dna": dna, + "mass": mass + } + } + + # 4. Pulse to Manifold + print(f"[INDEX] {file} -> Mass: {mass} | Imports: {len(dna['imports'])}") + + try: + # We use the existing ingest endpoint to update the manifold + requests.post(API_ENDPOINT, json=packet) + + # Also move the swarm cursor for each file + # We simulate this by sending an 'add ' command to the neural logic + # This uses the FAST-PATH we just patched! + requests.post("http://127.0.0.1:5000/v1/chat/completions", json={ + "messages": [{"role": "user", "content": f"add {mass}"}] + }) + except Exception as e: + print(f"[ERROR] Pulse failed for {file}: {e}") + + file_count += 1 + time.sleep(0.1) # Smooth telemetry gradient + + print(f"\n[GEMMA] Index Complete. {file_count} Modules Mapped to Manifold.") + +if __name__ == "__main__": + index_system() diff --git a/logos_n8n_workflow.json b/logos_n8n_workflow.json new file mode 100644 index 0000000000000000000000000000000000000000..d7f1e5679920579c9acb0707b8c31586f0d446bb --- /dev/null +++ b/logos_n8n_workflow.json @@ -0,0 +1,198 @@ +{ + "name": "LOGOS Codebase Analysis (Local Swarm)", + "nodes": [ + { + "parameters": {}, + "name": "Manual Trigger", + "type": "n8n-nodes-base.manualTrigger", + "typeVersion": 1, + "position": [ + 250, + 300 + ], + "id": "trigger-node" + }, + { + "parameters": { + "values": { + "string": [ + { + "name": "projectPath", + "value": "C:/Users/Nauti/Desktop/LOGOS CURSOR/" + }, + { + "name": "localLLM", + "value": "http://localhost:1234/v1" + } + ] + } + }, + "name": "Config", + "type": "n8n-nodes-base.set", + "typeVersion": 1, + "position": [ + 450, + 300 + ], + "id": "config-node" + }, + { + "parameters": { + "command": "dir /s /b *.py", + "cwd": "={{$node[\"Config\"].json[\"projectPath\"]}}" + }, + "name": "Find Python Files", + "type": "n8n-nodes-base.executeCommand", + "typeVersion": 1, + "position": [ + 650, + 200 + ], + "id": "find-files" + }, + { + "parameters": { + "functionCode": "const output = [];\nconst files = items[0].json.stdout.split('\\r\\n');\nfor (const file of files) {\n if (file && file.trim() !== '') {\n output.push({json: { filePath: file.trim() }});\n }\n}\nreturn output;" + }, + "name": "Split Files", + "type": "n8n-nodes-base.function", + "typeVersion": 1, + "position": [ + 850, + 200 + ], + "id": "split-files" + }, + { + "parameters": { + "fileSelector": "={{$json[\"filePath\"]}}", + "dataPropertyName": "codeContent" + }, + "name": "Read Code", + "type": "n8n-nodes-base.readBinaryFile", + "typeVersion": 1, + "position": [ + 1050, + 200 + ], + "id": "read-code" + }, + { + "parameters": { + "method": "POST", + "url": "={{$node[\"Config\"].json[\"localLLM\"]}}/chat/completions", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "bodyParameters": { + "parameters": [ + { + "name": "model", + "value": "local-model" + }, + { + "name": "messages", + "value": "=[{\"role\": \"system\", \"content\": \"You are a Senior Python Logic Analyzer. Analyze this code for bugs and logic structure.\"}, {\"role\": \"user\", \"content\": \"{{$binary.codeContent.data}}\"}]" + }, + { + "name": "stream", + "value": false + } + ] + }, + "options": {} + }, + "name": "Nano Swarm (Code)", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 1, + "position": [ + 1250, + 200 + ], + "id": "local-llm-req" + }, + { + "parameters": { + "command": "python hf_space/analyze_uploads.py --recursive", + "cwd": "={{$node[\"Config\"].json[\"projectPath\"]}}" + }, + "name": "Analyze Diagrams (Images)", + "type": "n8n-nodes-base.executeCommand", + "typeVersion": 1, + "position": [ + 650, + 450 + ], + "id": "analyze-images" + } + ], + "connections": { + "Manual Trigger": { + "main": [ + [ + { + "node": "Config", + "type": "main", + "index": 0 + } + ] + ] + }, + "Config": { + "main": [ + [ + { + "node": "Find Python Files", + "type": "main", + "index": 0 + }, + { + "node": "Analyze Diagrams (Images)", + "type": "main", + "index": 0 + } + ] + ] + }, + "Find Python Files": { + "main": [ + [ + { + "node": "Split Files", + "type": "main", + "index": 0 + } + ] + ] + }, + "Split Files": { + "main": [ + [ + { + "node": "Read Code", + "type": "main", + "index": 0 + } + ] + ] + }, + "Read Code": { + "main": [ + [ + { + "node": "Nano Swarm (Code)", + "type": "main", + "index": 0 + } + ] + ] + } + } +} diff --git a/requirements.txt b/requirements.txt index 2d25b4bc07e238316b5a8df048b47206766579b6..4c4c7bf9d484a9be9639cdc485214d145d0943fa 100644 --- a/requirements.txt +++ b/requirements.txt @@ -14,3 +14,10 @@ sympy # smolagents # Browser automation # helium # Browser control # beautifulsoup4 # HTML parsing +requests>=2.31.0 +flask +flask-cors +flask-sock +psutil +aiohttp +youtube-transcript-api