File size: 13,623 Bytes
61898fa
0b2210a
 
 
 
 
 
 
 
 
 
61898fa
0b2210a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61898fa
0b2210a
61898fa
 
 
 
 
 
 
 
 
0b2210a
61898fa
 
 
 
 
0b2210a
8d155db
 
 
61898fa
 
 
8d155db
 
61898fa
8d155db
61898fa
 
8d155db
 
61898fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d155db
 
61898fa
 
 
 
8d155db
 
 
61898fa
 
 
 
 
0b2210a
 
 
61898fa
8d155db
 
 
 
 
61898fa
0b2210a
 
 
61898fa
0b2210a
 
 
61898fa
fb0a9e0
61898fa
fb0a9e0
 
8d155db
 
 
61898fa
 
 
 
 
 
0b2210a
8d155db
0b2210a
 
8d155db
0b2210a
8d155db
0b2210a
 
 
 
61898fa
8d155db
0b2210a
 
8d155db
0b2210a
 
 
 
 
61898fa
0b2210a
 
 
 
8d155db
 
0b2210a
 
 
 
 
61898fa
0b2210a
888eae5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b2210a
1f1fa47
 
 
 
 
 
 
 
fb0a9e0
 
61898fa
fb0a9e0
0b2210a
 
8d155db
4d30c64
 
7fd6330
fb0a9e0
 
7fd6330
8d155db
 
 
fb0a9e0
4d30c64
 
fb0a9e0
 
4d30c64
 
 
 
 
 
 
 
8d155db
7fd6330
61898fa
7fd6330
 
 
61898fa
fb0a9e0
8d155db
4d30c64
 
 
8d155db
61898fa
fb0a9e0
 
 
7fd6330
 
4d30c64
7fd6330
4d30c64
 
 
 
 
 
 
 
 
61898fa
fb0a9e0
8d155db
0b2210a
 
8d155db
0b2210a
 
8d155db
 
61898fa
0b2210a
 
 
 
61898fa
0b2210a
 
8d155db
 
0b2210a
 
8d155db
 
61898fa
0b2210a
 
 
 
 
 
8d155db
 
 
2a23844
0b2210a
8d155db
0b2210a
 
 
 
 
8d155db
 
0b2210a
 
 
 
8d155db
61898fa
8d155db
0b2210a
 
 
 
 
 
 
8d155db
61898fa
0b2210a
 
 
 
61898fa
8d155db
0b2210a
 
8d155db
0b2210a
 
 
 
 
 
 
 
 
61898fa
 
 
0b2210a
 
 
 
 
 
 
 
 
 
 
8d155db
0b2210a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# REM [2026-04-08] Zero Module Execution (SPEC_2026_04_08)
import json
import os
import threading
import hashlib
import logging
import asyncio
from typing import Dict, Optional, Any, List, Tuple, Union
from datetime import datetime, timedelta
from pathlib import Path

# REM [2026-04-08] These constants are safe to keep at module level
# Состояния отделов
DEPT_STATE_IDLE = "idle"
DEPT_STATE_BUSY_BY_CEO = "busy_by_ceo"
DEPT_STATE_BUSY_BY_SYSTEM = "busy_by_system"

# Константы
LOCK_TTL_SECONDS = 120
MAX_ROUNDS_DEFAULT = 2

# Маппинг отделов и ролей
DEPT_ROLES = {
    "A": ["flick", "flock"],
    "B": ["click", "clack"],
    "C": ["check", "chock"],
    "D": ["link", "sync"]
}

_role_manager = None

def get_role_manager(model_manager=None, config_path=None, state_path=None):
    """
    Lazy getter for the singleton instance.
    This is the ONLY entrypoint to the RoleBindingManager.
    """
    global _role_manager
    if _role_manager is None:
        _role_manager = RoleBindingManager(model_manager, config_path, state_path)
    return _role_manager

class RoleBindingManager:
    """
    Manages role-to-model bindings with Zero Module Execution invariant.
    """
    
    def __init__(self, model_manager=None, config_path=None, state_path=None):
        self.model_manager = model_manager
        self.config_path = config_path
        self.state_path = state_path
        
        # Internal state (Lazy initialization in _ensure_initialized)
        self.project_path = None
        self.roles_state = {}
        self.models_config = {}
        self._bindings = {} # Sticky Memory Cache
        
        # Department locks (Initial state is empty, populated in _ensure_initialized)
        self._dept_locks = {}
        
        self._initialized = False
        self._prompt_registry = None
        
        # Lazy objects
        self._logger = None
        self._state_lock = None
        
    def _get_logger(self):
        """Lazy logger initialization."""
        if self._logger is None:
            self._logger = logging.getLogger(__name__)
        return self._logger

    def _get_state_lock(self):
        """Lazy threading lock initialization."""
        if self._state_lock is None:
            self._state_lock = threading.RLock()
        return self._state_lock

    async def _ensure_initialized(self):
        """
        Guarantees loading of state and configuration paths lazily.
        Triggers execution ONLY when first used in runtime.
        """
        if self._initialized:
            return

        # LAZY IMPORTS to avoid module execution on import
        from core.shared_state import get_shared_state
        from core.prompt_registry import PromptRegistry

        logger = self._get_logger()
        state = get_shared_state()
        self.project_path = Path(state.get("current_project_path", "."))
        
        # Configure paths based on project state
        if not self.config_path:
            self.config_path = self.project_path / "config" / "models_config.json"
        if not self.state_path:
            self.state_path = self.project_path / "config" / "roles_state.json"
            
        # Global paths (fallback)
        self.global_config_path = Path(__file__).parent.parent / "config" / "models_config.json"
        self.global_state_path = Path(__file__).parent.parent / "config" / "roles_state.json"

        # Load data
        self.roles_state = self._load_state()
        self.models_config = self._load_config()
        
        # Ensure state file exists
        if not self.state_path.exists(): 
             self._save_state()
             logger.info(f"Created initial roles_state.json at {self.state_path}")

        if self._prompt_registry is None:
            self._prompt_registry = PromptRegistry()
            
        # Initialize department locks
        self._dept_locks = {
            dept: {"state": DEPT_STATE_IDLE, "locked_by": None, "expires": None} 
            for dept in DEPT_ROLES
        }
            
        self._initialized = True
        logger.info("RoleBindingManager initialized. Project: %s", self.project_path)

    def _load_config(self) -> Dict:
        path = self.config_path if self.config_path and self.config_path.exists() else self.global_config_path
        if not path.exists():
            return {"available_openrouter_models": [], "active_models": {}}
        try:
            with open(path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            self._get_logger().error(f"Error loading models_config: {e}")
            return {"available_openrouter_models": [], "active_models": {}}

    def _load_state(self) -> Dict:
        path = self.state_path if self.state_path and self.state_path.exists() else self.global_state_path
        if path.exists():
            try:
                with open(path, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                self._get_logger().error(f"Error loading roles_state: {e}")
                return {}
        return {}

    def _save_state(self):
        if not self.state_path:
            return
        try:
            self.state_path.parent.mkdir(parents=True, exist_ok=True)
            with open(self.state_path, 'w', encoding='utf-8') as f:
                json.dump(self.roles_state, f, indent=2, ensure_ascii=False)
        except Exception as e:
            self._get_logger().error(f"Error saving roles_state: {e}")

    def _get_available_models(self) -> List[str]:
        models = self.models_config.get('available_openrouter_models', [])
        result = []
        
        for m in models:
            if isinstance(m, str):
                cleaned = m.strip()
                if cleaned:
                    result.append(cleaned)
            elif isinstance(m, dict):
                key = m.get("key", "")
                if key and isinstance(key, str):
                    cleaned = key.strip()
                    if cleaned:
                        result.append(cleaned)
        
        if not result:
            raise RuntimeError("No available models in pool. Run openrouter_models_updater.py first.")
        
        return result

    async def get_model_for_role(
        self,
        role_key: str,
        task_id: Optional[str] = None,
        override_model_id: Optional[str] = None,
        exclude: Optional[List[str]] = None,
        **kwargs
    ) -> str:
        """Возвращает model_id (строку) для роли."""
        await self._ensure_initialized()
        logger = self._get_logger()
        
        if override_model_id:
            return override_model_id
        
        binding_key = f"{role_key}:{task_id}" if task_id else role_key

        if hasattr(self, "_bindings") and binding_key in self._bindings:
            return self._bindings[binding_key]

        if task_id:
            role_state = self.roles_state.get(role_key, {})
            binding = role_state.get(task_id)
            if binding and binding.get("status") == "active":
                model_id = binding["primary"]
                if not hasattr(self, "_bindings"): self._bindings = {}
                self._bindings[binding_key] = model_id
                return model_id

        pool_raw = self._get_available_models()
        pool = []
        for m in pool_raw:
            m_key = m if isinstance(m, str) else m.get("key")
            if exclude and m_key in exclude:
                continue
            pool.append(m)
            
        if not pool:
            if exclude:
                logger.warning(f"[BINDING] Failover ineffective for '{role_key}' after excluding {exclude}. Falling back.")
                pool = pool_raw
            
            if not pool:
                raise RuntimeError(f"No available models for role '{role_key}'")

        seed_str = role_key + (task_id or "")
        if exclude:
            seed_str += "".join(exclude)
            
        seed = int(hashlib.md5(seed_str.encode('utf-8')).hexdigest(), 16)
        index = seed % len(pool)
        selected = pool[index]
        model_id = selected["key"] if isinstance(selected, dict) else selected

        if not hasattr(self, "_bindings"): self._bindings = {}
        self._bindings[binding_key] = model_id

        if not exclude:
            if task_id:
                if role_key not in self.roles_state:
                    self.roles_state[role_key] = {}
                self.roles_state[role_key][task_id] = {"primary": model_id, "status": "active"}
                self._save_state()
                logger.info(f"[BINDING] Cache MISS: {role_key}:{task_id} -> {model_id}")
            else:
                logger.info(f"[BINDING] Memory MISS: {role_key} -> {model_id}")
        else:
            logger.info(f"[BINDING] Failover for {role_key}: {model_id}")

        return model_id

    async def get_prompt(self, role_key: str) -> str:
        await self._ensure_initialized()
        return self._prompt_registry.get_prompt(role_key)

    async def switch_binding(self, role_key: str, new_model_id: str, reason: str = "") -> bool:
        await self._ensure_initialized()
        with self._get_state_lock():
            if "defaults" not in self.roles_state:
                self.roles_state["defaults"] = {}
            self.roles_state["defaults"][role_key] = new_model_id
            self._save_state()
            self._get_logger().info(f"Switch binding for {role_key} to {new_model_id}. Reason: {reason}")
            return True

    async def get_state(self) -> Dict:
        await self._ensure_initialized()
        return self.roles_state

    async def get_fixed_model(self, role_key: str) -> str:
        await self._ensure_initialized()
        with self._get_state_lock():
            default_model = self.roles_state.get("defaults", {}).get(role_key)
            if default_model:
                return default_model
            
            pool = self._get_available_models()
            if not pool:
                active = self.models_config.get("active_models", {})
                if role_key in active:
                    return active[role_key].get("model_id")
                raise RuntimeError(f"No available models in pool for role '{role_key}'")
            
            seed_str = f"{role_key}"
            seed = int(hashlib.md5(seed_str.encode()).hexdigest(), 16)
            selected = pool[seed % len(pool)]
            model_id = selected.get("key") if isinstance(selected, dict) else selected
            return model_id

    async def is_department_available(self, dept: str) -> bool:
        await self._ensure_initialized()
        lock = self._dept_locks.get(dept)
        if not lock: return True
        return lock["state"] == DEPT_STATE_IDLE

    async def lock_department(self, dept: str, state: str, locked_by: str = "system") -> bool:
        await self._ensure_initialized()
        if not await self.is_department_available(dept): return False
        self._dept_locks[dept] = {
            "state": state,
            "locked_by": locked_by,
            "expires": datetime.now() + timedelta(seconds=LOCK_TTL_SECONDS) if LOCK_TTL_SECONDS else None
        }
        return True

    async def unlock_department(self, dept: str):
        await self._ensure_initialized()
        if dept in self._dept_locks:
            self._dept_locks[dept] = {"state": DEPT_STATE_IDLE, "locked_by": None, "expires": None}

    async def run_department(self, dept: str, request_data: Dict, caller: str = "system") -> Any:
        await self._ensure_initialized()
        if not await self.is_department_available(dept):
            return {"error": f"Department {dept} is busy"}
        
        await self.lock_department(dept, DEPT_STATE_BUSY_BY_SYSTEM, locked_by=caller)
        try:
            roles = DEPT_ROLES.get(dept, [])
            if not roles:
                return {"error": f"No roles for department {dept}"}
            return await self._run_cycle(dept, roles, request_data, caller)
        finally:
            self.unlock_department(dept)

    async def _run_cycle(self, dept: str, roles: List[str], request_data: Dict, caller: str) -> Any:
        # LAZY IMPORTS
        from core.model_management import ModelManager

        message = request_data.get("message") or ""
        session_id = request_data.get("session_id", "default")
        is_formal = "[TASK]" in message
        
        current_result = message
        last_json = None

        mm = ModelManager()

        for i, role_key in enumerate(roles):
            system_prompt = await self.get_prompt(role_key)
            model_id = await self.get_model_for_role(role_key, task_id=session_id)
            model = await mm.get_model(model_id)
            
            user_prompt = current_result if i > 0 else message
            if i > 0:
                user_prompt = f"Улучши результат коллеги:\n\n{current_result}"
            
            raw_response = await model.generate(user_prompt, system_prompt=system_prompt)
            current_result = raw_response
            
            if is_formal:
                try:
                    start = raw_response.find('{')
                    end = raw_response.rfind('}')
                    if start != -1 and end != -1:
                        last_json = json.loads(raw_response[start:end+1])
                except:
                    pass

        return last_json if (is_formal and last_json) else current_result