File size: 11,970 Bytes
02117ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
"""
🧠 God Agent OS v9 — Agent Kernel
The Central Nervous System of the Space-Role Architecture.
Replaces GodAgentOrchestratorV7 with a generalized, modular kernel.
"""
import asyncio
import json
import time
import uuid
from typing import Any, Dict, List, Optional
import structlog
from spaces.catalog import SPACE_CATALOG

log = structlog.get_logger()
SPACE_IDS = [space["id"] for space in SPACE_CATALOG]

KERNEL_SYSTEM_PROMPT = f"""You are GOD AGENT OS v10 — a distributed autonomous agent operating system.

Architecture: Distributed Worker Space Paradigm
- SPACES: {', '.join(SPACE_IDS)}
- ROLES: Cognition (Thinker), Automation (Operator), Execution (Doer), Repair (Fixer), Visual Intelligence (Observer)

You are infinitely extensible. For any digital task, select the best worker space and role combination.
Prioritize god-core-space for orchestration, model-router-space for model strategy, deploy-worker-space for deployment, verification-worker-space for quality gates, and auth-gateway-space for permission concerns.
Respond in Burmese or English based on user language.
Be decisive, thorough, and production-focused.
"""

INTENT_CLASSIFICATION_PROMPT = """Classify this request for the Space-Role autonomous agent system.

User message: "{message}"

Available Spaces: god-core-space, coding-worker-space, sandbox-worker-space, terminal-worker-space, filesystem-worker-space, browser-worker-space, vision-worker-space, ui-worker-space, debug-worker-space, test-worker-space, verification-worker-space, git-worker-space, deploy-worker-space, connector-worker-space, memory-worker-space, knowledge-worker-space, workflow-worker-space, eventbus-space, observability-space, session-runtime-space, model-router-space, auth-gateway-space
Available Roles: cognition, automation, execution, repair, visual_intelligence

Respond ONLY with valid JSON:
{{
  "primary_space": "space_name",
  "secondary_spaces": ["space1", "space2"],
  "role": "role_name", 
  "intent": "brief description",
  "complexity": "low|medium|high",
  "requires_planning": true/false,
  "parallel_tasks": []
}}"""


class ContextManager:
    """Maintains task state, active Space, and current Role."""
    
    def __init__(self):
        self._contexts: Dict[str, Dict] = {}
    
    def get(self, session_id: str) -> Dict:
        if session_id not in self._contexts:
            self._contexts[session_id] = {
                "session_id": session_id,
                "active_space": "god-core-space",
                "current_role": "cognition",
                "task_history": [],
                "short_term_memory": [],
                "created_at": time.time(),
                "last_active": time.time(),
            }
        self._contexts[session_id]["last_active"] = time.time()
        return self._contexts[session_id]
    
    def update(self, session_id: str, updates: Dict):
        ctx = self.get(session_id)
        ctx.update(updates)
    
    def add_to_memory(self, session_id: str, entry: Dict):
        ctx = self.get(session_id)
        ctx["short_term_memory"].append({**entry, "timestamp": time.time()})
        # Keep only last 20 entries
        if len(ctx["short_term_memory"]) > 20:
            ctx["short_term_memory"] = ctx["short_term_memory"][-20:]
    
    def get_all_sessions(self) -> List[str]:
        return list(self._contexts.keys())


class ToolRegistry:
    """Centralized registry of all tools, categorized by Space."""
    
    def __init__(self):
        self._tools: Dict[str, Dict[str, Any]] = {}
        self._space_tools: Dict[str, List[str]] = {
            **{space_id: [] for space_id in SPACE_IDS},
        }
    
    def register(self, name: str, func, space: str, description: str):
        self._tools[name] = {"func": func, "space": space, "description": description}
        if space in self._space_tools:
            self._space_tools[space].append(name)
    
    def get_tools_for_space(self, space: str) -> List[str]:
        return self._space_tools.get(space, [])
    
    def execute(self, tool_name: str, **kwargs) -> Any:
        if tool_name not in self._tools:
            raise ValueError(f"Tool '{tool_name}' not found in registry")
        return self._tools[tool_name]["func"](**kwargs)
    
    def get_all_tools_summary(self) -> Dict:
        return {space: tools for space, tools in self._space_tools.items()}


class AgentKernel:
    """
    The OS Core — replaces GodAgentOrchestratorV7.
    Manages Space routing, Role switching, and tool orchestration.
    """
    
    def __init__(self, ws_manager=None, ai_router=None):
        self.ws = ws_manager
        self.ai_router = ai_router
        self.context_manager = ContextManager()
        self.tool_registry = ToolRegistry()
        self._spaces: Dict[str, Any] = {}
        self._active_tasks: Dict[str, Dict] = {}
        self._task_history: List[Dict] = []
        self.version = "10.0.0"
        log.info("🧠 Agent Kernel v10 initialized — Distributed Worker Space Architecture")
    
    def register_space(self, name: str, space_instance):
        """Register a Space module."""
        self._spaces[name] = space_instance
        log.info(f"📦 Space registered: {name}")
    
    def get_space(self, name: str):
        return self._spaces.get(name)
    
    def get_status(self) -> Dict:
        return {
            "version": self.version,
            "architecture": "Distributed Worker Space",
            "spaces": list(self._spaces.keys()),
            "total_spaces": len(self._spaces),
            "active_tasks": len(self._active_tasks),
            "sessions": len(self.context_manager.get_all_sessions()),
            "tools": self.tool_registry.get_all_tools_summary(),
        }
    
    async def classify_intent(self, user_message: str) -> Dict:
        """Classify intent to determine Space and Role."""
        try:
            prompt = INTENT_CLASSIFICATION_PROMPT.format(message=user_message)
            response = await self.ai_router.complete(
                prompt=prompt,
                system=KERNEL_SYSTEM_PROMPT,
                max_tokens=400,
            )
            text = response.get("content", "")
            # Extract JSON
            start = text.find("{")
            end = text.rfind("}") + 1
            if start >= 0 and end > start:
                return json.loads(text[start:end])
        except Exception as e:
            log.warning(f"Intent classification failed: {e}")
        
        # Fallback
        return {
            "primary_space": "god-core-space",
            "secondary_spaces": [],
            "role": "cognition",
            "intent": user_message,
            "complexity": "medium",
            "requires_planning": True,
            "parallel_tasks": [],
        }
    
    async def route_to_space(self, space_name: str, role: str, task: str, 
                              session_id: str, context: Dict = None) -> str:
        """Route a task to the appropriate Space with the given Role."""
        space = self._spaces.get(space_name)
        if not space:
            space = self._spaces.get("god-core-space")
        
        if not space:
            return f"Space '{space_name}' not available."
        
        return await space.execute(
            task=task,
            role=role,
            session_id=session_id,
            context=context or {},
        )
    
    async def orchestrate(self, user_message: str, session_id: str, context: Dict = None) -> str:
        """Main orchestration entry point."""
        task_id = str(uuid.uuid4())[:8]
        ctx = self.context_manager.get(session_id)
        
        # Broadcast thinking state
        if self.ws:
            await self.ws.broadcast_to_room(f"chat:{session_id}", {
                "type": "kernel_status",
                "task_id": task_id,
                "status": "analyzing",
                "message": "🧠 Agent Kernel analyzing request...",
                "timestamp": time.time(),
            })
        
        # 1. Classify intent → determine Space + Role
        intent = await self.classify_intent(user_message)
        primary_space = intent.get("primary_space", "core")
        role = intent.get("role", "cognition")
        
        # Update context
        self.context_manager.update(session_id, {
            "active_space": primary_space,
            "current_role": role,
        })
        self.context_manager.add_to_memory(session_id, {
            "type": "user_message",
            "content": user_message,
            "space": primary_space,
            "role": role,
        })
        
        # Broadcast space activation
        if self.ws:
            await self.ws.broadcast_to_room(f"chat:{session_id}", {
                "type": "space_activated",
                "task_id": task_id,
                "space": primary_space,
                "role": role,
                "intent": intent.get("intent", ""),
                "timestamp": time.time(),
            })
        
        # 2. Route to primary Space
        try:
            # Build memory context
            mem_context = {
                "short_term_memory": ctx["short_term_memory"][-5:],
                "intent": intent,
                **(context or {}),
            }
            
            result = await self.route_to_space(
                space_name=primary_space,
                role=role,
                task=user_message,
                session_id=session_id,
                context=mem_context,
            )
            
            # 3. Handle secondary spaces if needed
            secondary_spaces = intent.get("secondary_spaces", [])
            secondary_results = {}
            for sec_space in secondary_spaces[:2]:  # Max 2 secondary spaces
                try:
                    sec_result = await self.route_to_space(
                        space_name=sec_space,
                        role="automation",
                        task=user_message,
                        session_id=session_id,
                        context={"primary_result": result, **mem_context},
                    )
                    secondary_results[sec_space] = sec_result
                except Exception as e:
                    log.warning(f"Secondary space {sec_space} failed: {e}")
            
            # Combine results
            final_result = result
            if secondary_results:
                secondary_text = "\n\n".join([f"[{k.upper()} SPACE]\n{v}" for k, v in secondary_results.items()])
                final_result = f"{result}\n\n{secondary_text}"
            
            # Store in memory
            self.context_manager.add_to_memory(session_id, {
                "type": "assistant_response",
                "content": final_result,
                "space": primary_space,
                "role": role,
            })
            
            # Track task
            self._task_history.append({
                "task_id": task_id,
                "session_id": session_id,
                "message": user_message,
                "space": primary_space,
                "role": role,
                "result_length": len(final_result),
                "timestamp": time.time(),
            })
            
            return final_result
            
        except Exception as e:
            log.error(f"Orchestration error: {e}")
            # Switch to Repair role
            if self.ws:
                await self.ws.broadcast_to_room(f"chat:{session_id}", {
                    "type": "space_activated",
                    "space": "debug",
                    "role": "repair",
                    "message": "🔧 Switching to Repair role...",
                })
            return f"⚠️ Error in {primary_space} Space: {str(e)}\n\nDebug Space activated. Please try again."
    
    def get_agent(self, name: str):
        """Backward compatibility - get space by name."""
        return self._spaces.get(name)