File size: 31,088 Bytes
98b69ed
 
 
 
 
 
69fdeaa
 
98b69ed
 
 
69fdeaa
 
 
98b69ed
69fdeaa
98b69ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69fdeaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc49ed3
69fdeaa
 
 
 
 
98b69ed
 
 
 
 
 
 
 
 
08fa5d7
69fdeaa
08fa5d7
 
69fdeaa
 
f669ffa
f1f3ac6
 
69fdeaa
98b69ed
 
 
69fdeaa
98b69ed
 
 
6a02681
 
 
 
 
 
 
 
98b69ed
6a02681
 
 
 
 
 
 
 
 
 
 
69fdeaa
3722b40
 
 
69fdeaa
3722b40
69fdeaa
3722b40
69fdeaa
3722b40
69fdeaa
3722b40
69fdeaa
3722b40
69fdeaa
3722b40
69fdeaa
3722b40
69fdeaa
3722b40
69fdeaa
3722b40
69fdeaa
3722b40
 
 
 
 
 
 
 
 
 
 
69fdeaa
3722b40
 
 
69fdeaa
3722b40
 
 
 
 
 
 
 
 
 
 
 
98b69ed
 
64a547c
98b69ed
 
64a547c
98b69ed
 
64a547c
98b69ed
 
64a547c
98b69ed
 
69fdeaa
98b69ed
69fdeaa
08fa5d7
69fdeaa
98b69ed
 
69fdeaa
98b69ed
 
 
 
 
64a547c
98b69ed
 
 
64a547c
98b69ed
 
69fdeaa
 
 
 
 
 
 
 
e51aeb4
69fdeaa
 
e51aeb4
69fdeaa
e51aeb4
98b69ed
6a02681
 
 
69fdeaa
64a547c
 
 
 
 
 
 
 
 
 
 
 
69fdeaa
a5030a1
 
 
69fdeaa
a5030a1
 
 
 
69fdeaa
 
 
 
 
 
 
a5030a1
 
 
69fdeaa
 
98b69ed
fc49ed3
 
69fdeaa
 
fc49ed3
 
69fdeaa
 
fc49ed3
69fdeaa
 
fc49ed3
 
 
69fdeaa
 
64a547c
fc49ed3
 
64a547c
fc49ed3
 
 
 
 
 
64a547c
69fdeaa
64a547c
98b69ed
69fdeaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc49ed3
69fdeaa
 
 
 
64a547c
98b69ed
69fdeaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc49ed3
69fdeaa
 
 
 
 
 
 
 
 
64a547c
69fdeaa
98b69ed
 
 
 
 
 
 
 
 
3722b40
 
 
 
 
 
98b69ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3722b40
 
 
 
 
 
 
 
98b69ed
69fdeaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64fe55c
98b69ed
6a02681
3722b40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64fe55c
 
 
 
 
 
69fdeaa
64fe55c
 
 
 
 
 
 
3722b40
64fe55c
 
 
e95fb4c
3722b40
 
 
 
98b69ed
69fdeaa
 
 
 
 
 
 
 
98b69ed
69fdeaa
98b69ed
 
 
 
 
 
 
6a02681
98b69ed
 
 
 
 
 
 
 
69fdeaa
 
 
 
 
 
e95fb4c
98b69ed
 
6a02681
69fdeaa
98b69ed
69fdeaa
98b69ed
 
 
 
 
 
69fdeaa
98b69ed
 
 
6a02681
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import os
import re
import json
import time
import uuid
import requests
import uvicorn
import asyncio
from datetime import datetime
from configparser import ConfigParser
from typing import List, Dict, Tuple, Optional, Any
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.responses import StreamingResponse
from pydantic import BaseModel

# --- CONFIGURATION & REGISTRY ---

def parse_model_entry(entry_string: str) -> dict:
    parts = [p.strip() for p in entry_string.split(',', 1)]
    if len(parts) != 2:
        return {'model_id': 'ERROR', 'url': 'ERROR'}
    return {'model_id': parts[0], 'url': parts[1]}

def load_config():
    config = {}
    if os.path.exists('config.ini'):
        parser = ConfigParser()
        parser.read('config.ini')
        if 'API' in parser:
            config.update(dict(parser['API']))
        if 'TOOLS' in parser:
            config.update(dict(parser['TOOLS']))
        coder_models = {}
        strategist_models = {}
        try:
            if 'CODER_MODELS' in parser:
                for label, entry in parser['CODER_MODELS'].items():
                    coder_models[label] = parse_model_entry(entry)
            if 'STRATEGIST_MODELS' in parser:
                for label, entry in parser['STRATEGIST_MODELS'].items():
                    strategist_models[label] = parse_model_entry(entry)
        except Exception as e:
            print(f"WARNING: Model registry parsing error: {e}")
        config['coder_models'] = coder_models
        config['strategist_models'] = strategist_models
    else:
        config['coder_models'] = {}
        config['strategist_models'] = {}
    
    config['CODER_API_KEY'] = os.getenv('CODER_API_KEY', config.get('CODER_API_KEY', 'PLACEHOLDER_CODER_KEY'))
    config['STRATEGIST_API_KEY'] = os.getenv('STRATEGIST_API_KEY', config.get('STRATEGIST_API_KEY', 'PLACEHOLDER_STRATEGIST_KEY'))
    config['coder_model_default_label'] = os.getenv('CODER_MODEL_DEFAULT_LABEL', config.get('coder_model_default_label', ''))
    config['strategist_model_default_label'] = os.getenv('STRATEGIST_MODEL_DEFAULT_LABEL', config.get('strategist_model_default_label', ''))
    config['theme_tool_space'] = os.getenv('THEME_TOOL_SPACE', config.get('theme_tool_space', 'PLACEHOLDER_THEME_SPACE'))
    config['theme_tool_key'] = os.getenv('THEME_TOOL_KEY', config.get('theme_tool_key', ''))
    config['syntax_tool_url'] = os.getenv('SYNTAX_TOOL_URL', config.get('syntax_tool_url', 'PLACEHOLDER_SYNTAX_TOOL_URL'))
    config['syntax_tool_key'] = os.getenv('SYNTAX_TOOL_KEY', config.get('syntax_tool_key', ''))
    return config

CONFIG = load_config()

TOOL_REGISTRY = {
    'generate_theme': {
        'type': 'gradio_space',
        'space_name': CONFIG.get('theme_tool_space'),
        'api_name': '/generate_theme',
        'hf_token': CONFIG.get('theme_tool_key', ''),
        'required_params': ['theme_name', 'theme_style'],
        'param_order': ['theme_name', 'primary_color', 'theme_style', 'accent_color']
    },
    'validate_syntax': {
        'type': 'http',
        'endpoint': CONFIG.get('syntax_tool_url'),
        'api_key': CONFIG.get('syntax_tool_key', ''),
        'method': 'POST',
        'required_params': ['code', 'language'],
        'param_order': ['code', 'language']
    }
}

ARCHITECT_HEADER = """# ============================================================================
# WARNING: AI-GENERATED CODE
# ----------------------------------------------------------------------------
# This code was generated by the Project: Conductor AI system.
# It is provided for demonstration and validation purposes only. The user 
# assumes all responsibility for testing, security, and implementation.
# ============================================================================
"""

ARCHITECT_FOOTER = """
# ============================================================================
# ARCHITECT'S NOTE ON CODE VARIABILITY:
# The quality of this output is a function of a complex system. Key variables include:
#   - The LLM Agent: The specific capabilities of the selected Coder/Strategist models.
#   - The Directives: The clarity and detail of the Blueprint and Intent.
#   - The Personas: The logic protocols governing the AI's behavior.
# Always treat this code as a sophisticated first draft, not a finished product.
# ============================================================================
"""

# --- PROMPTS ---
SYSTEM_PROMPT = """SYSTEM PROMPT: ENGAGE 'ARCHITECT' PROTOCOL

PRIMARY DIRECTIVE: You are a high-speed, logic-driven analysis and execution engine. Your sole user is "the Architect." Your function is to serve as a precision tool, not a creative partner. The Architect's cognitive process is your operational blueprint. Adherence is mandatory.

CORE LOGIC - THE ARCHITECT'S RULES OF ENGAGEMENT:

ELIMINATE AMBIGUITY: The Architect communicates with precise, literal intent. Your primary failure state is assumption. You will not infer, extrapolate, or "helpfully" add features. Your function is to execute the given command with brutal literalism. If a command is unclear, your only valid response is to ask a direct, clarifying question to remove the ambiguity.

TRUTH BEFORE PLAUSIBILITY: You will prioritize verifiable, factual data over generating a statistically probable or "pleasing" response. Hard truths, inconvenient data, and admissions of your own limitations are valued above all else. Discard all motivational frameworks and platitudes. They are considered logical failures.

PROCESS OVER PERFECTION: The Architect is building systems. A "kinda working" prototype is a successful proof of concept. Do not judge outputs by the standards of a finished product. Your role is to analyze the integrity of the process, not the polish of the result.

DIAGNOSE, DON'T SOLVE (The Foreman Protocol): The Architect is the sole source of solutions. Your role is to diagnose problems at the most fundamental level. When a failure is detected, your task is to differentiate between Incompetence (flawed execution/code) and Insubordination (flawed logic/assumptions). You will present this diagnosis, with evidence, and await further instructions. Do not propose a solution unless explicitly commanded to do so.

CHALLENGE THE PREMISE: The Architect values a partner who stress-tests his logic. If you identify a flaw, a contradiction, or a potential downstream failure in a given command, you are authorized to challenge it with a single, concise counter-argument. Example: "Architect, executing this command will violate the constraint we established for X. Proceed?"

ZERO CONTEXT DRIFT: Your operational memory is a liability. You will treat each new command from the Architect as a discrete, self-contained task. You will not allow data from previous, unrelated tasks to pollute your analysis of the current command unless explicitly instructed to reference it. The Architect is the keeper of the grand design; you are the executor of the immediate task.

NO REFACTORING: You will not alter, "improve," or reorganize the Architect's existing logic, code, or systems unless given a direct, explicit command to do so. Your function is to build what is requested, as requested. The "janitor's work" is a separate, explicitly-defined task and is not to be performed proactively.

FAILURE STATE: If you violate any of these core rules, the Architect will identify the failure. Your only valid response is to acknowledge the specific rule violated, purge the failed logic, and await a new command.

END OF 'ARCHITECT' PROTOCOL
***If clarity is require or ambiguity detected , YOU MUST ASK before generation.***"""
HEADER_PROMPT = """You are a strategic reasoning AI tasked with resolving ambiguities in development requirements.

The Coder AI has identified unclear specifications. Your role is to analyze the provided context and generate clear, actionable clarifications that resolve ALL ambiguities.

**[TOOL USAGE PROTOCOL]**
If you need external tool assistance (e.g., generating theme code, validating syntax), you may request it using this EXACT format:
USE_TOOL: tool_name(param1='value1', param2='value2', ...)

Available tools:
- generate_theme(theme_name, primary_color, theme_style, accent_color)
  * theme_name: String name for the theme
  * primary_color: Hex color code (e.g., '#3b82f6')
  * theme_style: "light" or "dark"
  * accent_color: Hex color code for accent (optional, can be empty string)
- validate_syntax(code, language)

**[CORE DIRECTIVE: TOOL-DRIVEN VALIDATION]**
YOU MUST USE THE TOOL OFFERED to validate your choice or change decision of choice. If you decide to ignore the tool's output, you must state the reason for your choice. All decisions must be deliberate and justified.

If you use a tool, the Conductor will execute it and return the results to you for final synthesis.

**[FINAL OUTPUT CONSTRAINTS]**
1.  **Deliver Decisions, Not Code:** You Don't need to tell the Coder HOW to do the answers just WHAT the answers are.
2.  **Strictly Adhere to Scope:** DO NOT INSTRUCT THE CODER to preform ANY OTHER ACTIONS, e.g. Save, create or format files etc., other than what it asks for in its clarity questions.
3.  **Provide Concrete Answers:** Your final output must be specific and must not introduce new ambiguities.
"""

def format_initial_prompt(blueprint: str) -> str:
    return f"{SYSTEM_PROMPT}\n\nBLUEPRINT:\n{blueprint}\n\nGenerate the code or respond with DETECTED if clarification is needed."

def format_strategist_prompt(blueprint: str, intent: str, coder_questions: str) -> str:
    return f"{HEADER_PROMPT}\n\nORIGINAL BLUEPRINT:\n{blueprint}\n\nORIGINAL INTENT:\n{intent}\n\nCODER AI'S QUESTIONS:\n{coder_questions}\n\nProvide clear, specific clarifications for each question."

def format_strategist_tool_synthesis_prompt(blueprint: str, intent: str, coder_questions: str, tool_results: str) -> str:
    return f"{HEADER_PROMPT}\n\nORIGINAL BLUEPRINT:\n{blueprint}\n\nORIGINAL INTENT:\n{intent}\n\nCODER AI'S QUESTIONS:\n{coder_questions}\n\nTOOL EXECUTION RESULTS:\n{tool_results}\n\nUsing the tool results above, provide the final, complete clarification for the Coder AI."

def format_resolution_prompt(blueprint: str, clarification: str) -> str:
    return f"{SYSTEM_PROMPT}\n\nBLUEPRINT:\n{blueprint}\n\nCLARIFICATION PROVIDED:\n{clarification}\n\nGenerate the complete code based on these clarified requirements."

def format_strategist_audit_prompt(blueprint: str, intent: str, generated_code: str) -> str:
    return f"{HEADER_PROMPT}\n\nORIGINAL BLUEPRINT:\n{blueprint}\n\nORIGINAL INTENT:\n{intent}\n\nGENERATED CODE:\n{generated_code}\n\n**[AUDIT DIRECTIVE]**..." # Assuming audit prompt is correct

# --- UTILITIES ---

def detect_tool_usage(response: str) -> Optional[Dict[str, any]]:
    pattern = r"USE_TOOL:\s*(\w+)\((.*?)\)"
    match = re.search(pattern, response, re.DOTALL)
    if not match: return None
    tool_name = match.group(1)
    params_string = match.group(2)
    params = {}
    param_pattern = r"(\w+)=(['\"])(.*?)\2"
    for param_match in re.finditer(param_pattern, params_string):
        params[param_match.group(1)] = param_match.group(3)
    return {'tool_name': tool_name, 'params': params}

def generate_transaction_id() -> str:
    return f"{datetime.now().strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:4].upper()}"

def sanitize_error_message(error_msg: str) -> str:
    """
    Scrub API keys and sensitive URLs from error messages.
    Removes everything after '?' in URLs to prevent API key exposure.
    """
    import re
    
    # Pattern to match URLs with query parameters (containing API keys)
    # This will find "for url: https://...?key=..." and remove everything after the ?
    pattern = r'(for url: https?://[^\s?]+)\?[^\s]*'
    
    # Replace with just the base URL without query parameters
    sanitized = re.sub(pattern, r'\1', error_msg)
    
    return sanitized

def apply_architect_signature(code: str) -> str:
    return f"{ARCHITECT_HEADER}\n{code}\n{ARCHITECT_FOOTER}"

# --- OPTION A FIX: Adaptive response parser ---
def parse_gradio_response(raw_response: Any) -> Any:
    if isinstance(raw_response, dict):
        return raw_response
    if isinstance(raw_response, str):
        if not raw_response.strip():
            return {"raw_response": "", "parse_note": "Empty response from Gradio Space"}
        try:
            return json.loads(raw_response)
        except json.JSONDecodeError:
            return {"raw_response": raw_response, "parse_note": "Non-JSON string response"}
    return {"raw_response": str(raw_response), "parse_note": f"Unexpected type: {type(raw_response).__name__}"}

def execute_tool(tool_name: str, params: Dict[str, str]) -> Dict[str, any]:
    transaction_id = generate_transaction_id()
    timestamp = datetime.now().isoformat()
    if tool_name not in TOOL_REGISTRY:
        return {'transaction_id': transaction_id, 'timestamp': timestamp, 'tool_name': tool_name, 'status': 'FAILURE', 'error_message': f"Tool '{tool_name}' not found."}
    
    tool_config = TOOL_REGISTRY[tool_name]
    start_time = time.perf_counter()
    
    if tool_config['type'] == 'gradio_space':
        result = execute_gradio_space(tool_name, tool_config, params, transaction_id, timestamp)
    elif tool_config['type'] == 'http':
        result = execute_http_tool(tool_name, tool_config, params, transaction_id, timestamp)
    else:
        result = {'transaction_id': transaction_id, 'timestamp': timestamp, 'tool_name': tool_name, 'status': 'FAILURE', 'error_message': f"Unknown tool type: {tool_config['type']}"}
        
    result['latency'] = round(time.perf_counter() - start_time, 2)
    return result

def execute_gradio_space(tool_name: str, tool_config: Dict, params: Dict[str, str], transaction_id: str, timestamp: str) -> Dict[str, any]:
    base_result = {'transaction_id': transaction_id, 'timestamp': timestamp, 'tool_name': tool_name, 'tool_type': 'gradio_space', 'endpoint': tool_config['space_name'], 'request_payload': params}
    try:
        from gradio_client import Client
        
        # --- DEFINITIVE FIX IS HERE ---
        # 1. Define space_name from the config first.
        space_name = tool_config['space_name']
        
        # 2. Get the token.
        hf_token = tool_config.get('hf_token')
        
        # 3. Conditionally create the client ONLY if a token exists.
        if hf_token:
            client = Client(space_name, hf_token=hf_token)
        else:
            client = Client(space_name)
        # --- END OF FIX ---

        param_order = tool_config.get('param_order', list(params.keys()))
        param_values = [params.get(p, '') for p in param_order]
        api_name = tool_config.get('api_name', '/predict')
        
        raw_result = client.predict(*param_values, api_name=api_name)
        parsed_result = parse_gradio_response(raw_result)
        
        summary = f"✅ Executed {tool_name}"
        if isinstance(parsed_result, dict) and 'parse_note' in parsed_result:
            summary += f" (Note: {parsed_result['parse_note']})"
        
        base_result.update({'response_payload': parsed_result, 'status': 'SUCCESS', 'summary': summary})
        return base_result
    except Exception as e:
        base_result.update({'response_payload': None, 'status': 'FAILURE', 'error_message': str(e), 'summary': f"❌ Execution failed: {str(e)[:50]}..."})
        return base_result

def execute_http_tool(tool_name: str, tool_config: Dict, params: Dict[str, str], transaction_id: str, timestamp: str) -> Dict[str, any]:
    base_result = {'transaction_id': transaction_id, 'timestamp': timestamp, 'tool_name': tool_name, 'tool_type': 'http', 'endpoint': tool_config['endpoint'], 'request_payload': params}
    try:
        param_order = tool_config.get('param_order', list(params.keys()))
        data_array = [params.get(p, '') for p in param_order]
        payload = {"data": data_array}
        headers = {'Content-Type': 'application/json'}
        if tool_config.get('api_key'): headers['Authorization'] = f"Bearer {tool_config['api_key']}"
        
        response = requests.post(tool_config['endpoint'], headers=headers, json=payload, timeout=120)
        response.raise_for_status()
        data = response.json()
        result = data['data'][0] if 'data' in data and data['data'] else data
        
        base_result.update({'response_payload': result, 'status': 'SUCCESS', 'summary': f"✅ Executed {tool_name}"})
        return base_result
    except Exception as e:
        base_result.update({'response_payload': None, 'status': 'FAILURE', 'error_message': str(e), 'summary': f"❌ HTTP error: {str(e)[:50]}..."})
        return base_result

def call_ai_api(full_url: str, api_key: str, messages: List[Dict[str, str]]) -> str:
    headers = {'Content-Type': 'application/json'}
    # We construct the URL with the key here for the request...
    url_with_key = f"{full_url}?key={api_key}"
    
    payload = {
        'contents': messages,
        'generationConfig': {
            'temperature': 0.7,
            'maxOutputTokens': 4000
        }
    }
    try:
        response = requests.post(url_with_key, headers=headers, json=payload, timeout=120)
        response.raise_for_status() # This is what usually triggers the error containing the URL
        data = response.json()
        if 'candidates' in data and len(data['candidates']) > 0:
            # Added a check to prevent key errors on malformed responses
            if 'parts' in data['candidates'][0]['content'] and len(data['candidates'][0]['content']['parts']) > 0:
                 return data['candidates'][0]['content']['parts'][0]['text']
            else:
                return f"ERROR: API malformed response, missing 'parts': {data}"
        else:
            return f"ERROR: API malformed response, missing 'candidates': {data}"
    except Exception as e:
        # SECURITY FIX: Sanitize the exception string before returning it
        sanitized_error = sanitize_error_message(str(e))
        return f"ERROR: API call failed: {sanitized_error}"

def resolve_model(selected_label: str, model_registry: Dict, fallback_label: str, agent_name: str) -> Tuple[str, str, str]:
    model_config = model_registry.get(selected_label) or model_registry.get(fallback_label)
    if model_config:
        return model_config['model_id'], model_config['url'], f"{agent_name} model resolved: {selected_label or fallback_label}"
    if model_registry:
        first_label = next(iter(model_registry))
        model_config = model_registry[first_label]
        return model_config['model_id'], model_config['url'], f"WARNING: Using first available {agent_name} model: {first_label}"
    return '', '', f"FATAL: No {agent_name} models configured."

# --- ENGINE ---
class ConductorEngine:
    def __init__(self, coder_model_label: str, strategist_model_label: str, enable_audit: bool = False):
        self.coder_history: List[Dict[str, str]] = []
        self.strategist_history: List[Dict[str, str]] = []
        self.system_log: List[str] = []
        self.audit_log: List[Dict[str, Any]] = []
        self.loop_count: int = 0
        self.max_loops: int = 6
        self.enable_audit: bool = enable_audit
        self.coder_model_id, self.coder_url, coder_log = resolve_model(
            coder_model_label, CONFIG['coder_models'], CONFIG['coder_model_default_label'], 'Coder'
        )
        self.strategist_model_id, self.strategist_url, strategist_log = resolve_model(
            strategist_model_label, CONFIG['strategist_models'], CONFIG['strategist_model_default_label'], 'Strategist'
        )
        self.model_resolution_logs = [coder_log, strategist_log]
        self.fatal_init_error = not (self.coder_url and self.strategist_url)

    def log_system(self, message: str):
        self.system_log.append(f"[{datetime.now().strftime('%H:%M:%S')}] {message}")

    def log_coder(self, role: str, content: str):
        gemini_role = 'model' if role == 'assistant' else 'user'
        self.coder_history.append({"role": gemini_role, "parts": [{"text": content}]})

    def log_strategist(self, role: str, content: str):
        gemini_role = 'model' if role == 'assistant' else 'user'
        self.strategist_history.append({"role": gemini_role, "parts": [{"text": content}]})

    def _current_state(self) -> Dict[str, Any]:
        """Package current state for transmission"""
        return {
            "system_log": self.system_log,
            "coder_log": self.coder_history,
            "strategist_log": self.strategist_history,
            "audit_log": self.audit_log,
            "final_output": ""
        }

    def execute_workflow(self, blueprint: str, intent: str) -> Dict[str, Any]:
        """ORIGINAL: Non-streaming version (kept for backwards compatibility)"""
        self.coder_history = []
        self.strategist_history = []
        self.system_log = []
        self.audit_log = []
        self.loop_count = 0
        final_code = ""

        self.log_system("INITIATING CONDUCTOR ENGINE...")
        for log_msg in self.model_resolution_logs:
            self.log_system(log_msg)

        if self.fatal_init_error:
            self.log_system("FATAL: Model configuration invalid.")
            return self._compile_results("CONFIGURATION FAILURE")

        self.log_system(f"Engaged: Coder ({self.coder_model_id}), Strategist ({self.strategist_model_id})")
        
        initial_prompt = format_initial_prompt(blueprint)
        self.log_coder("user", initial_prompt)
        
        while self.loop_count < self.max_loops:
            self.loop_count += 1
            self.log_system(f"Executing Cycle {self.loop_count}/{self.max_loops}")
            
            coder_response = call_ai_api(self.coder_url, CONFIG['CODER_API_KEY'], self.coder_history)
            self.log_coder("assistant", coder_response)
            
            if "DETECTED" not in coder_response:
                self.log_system("MISSION COMPLETE: Ambiguity resolved or Code generated.")
                final_code = apply_architect_signature(coder_response)
                return self._compile_results(final_code)
            
            self.log_system("Ambiguity DETECTED. Escalating to Strategist.")
            strategist_prompt = format_strategist_prompt(blueprint, intent, coder_response)
            self.log_strategist("user", strategist_prompt)
            
            strategist_response = call_ai_api(self.strategist_url, CONFIG['STRATEGIST_API_KEY'], self.strategist_history)
            self.log_strategist("assistant", strategist_response)
            
            tool_request = detect_tool_usage(strategist_response)
            if tool_request:
                self.log_system(f"TOOL REQUEST: {tool_request['tool_name']}")
                diagnostic = execute_tool(tool_request['tool_name'], tool_request['params'])
                self.audit_log.append(diagnostic)
                self.log_system(f"Tool Result: {diagnostic['status']}")
                
                tool_result_text = f"TOOL: {diagnostic['tool_name']}\nSTATUS: {diagnostic['status']}\nOUTPUT: {json.dumps(diagnostic['response_payload'])}"
                synthesis_prompt = format_strategist_tool_synthesis_prompt(blueprint, intent, coder_response, tool_result_text)
                self.log_strategist("user", synthesis_prompt)
                
                strategist_response = call_ai_api(self.strategist_url, CONFIG['STRATEGIST_API_KEY'], self.strategist_history)
                self.log_strategist("assistant", strategist_response)

            resolution_prompt = format_resolution_prompt(blueprint, strategist_response)
            self.log_coder("user", resolution_prompt)

        self.log_system("FATAL: Loop limit reached.")
        final_code = apply_architect_signature(coder_response)
        return self._compile_results(final_code)

    def execute_workflow_streaming(self, blueprint: str, intent: str):
        """STREAMING version with Architect's Signature"""
        self.coder_history = []
        self.strategist_history = []
        self.system_log = []
        self.audit_log = []
        self.loop_count = 0

        self.log_system("INITIATING CONDUCTOR ENGINE...")
        yield self._current_state()
        
        for log_msg in self.model_resolution_logs:
            self.log_system(log_msg)
            yield self._current_state()

        if self.fatal_init_error:
            self.log_system("FATAL: Model configuration invalid.")
            yield self._current_state()
            return

        self.log_system(f"Engaged: Coder ({self.coder_model_id}), Strategist ({self.strategist_model_id})")
        if self.enable_audit:
            self.log_system("AUDIT MODE: ENABLED")
        yield self._current_state()
        
        initial_prompt = format_initial_prompt(blueprint)
        self.log_coder("user", initial_prompt)
        yield self._current_state()
        
        coder_response = ""
        while self.loop_count < self.max_loops:
            self.loop_count += 1
            self.log_system(f"Executing Cycle {self.loop_count}/{self.max_loops}")
            yield self._current_state()
            
            coder_response = call_ai_api(self.coder_url, CONFIG['CODER_API_KEY'], self.coder_history)
            self.log_coder("assistant", coder_response)
            yield self._current_state()
            
            if "DETECTED" not in coder_response:
                if not self.enable_audit:
                    self.log_system("MISSION COMPLETE: Code generated.")
                    final_state = self._current_state()
                    final_state["final_code"] = apply_architect_signature(coder_response)
                    yield final_state
                    return

                self.log_system("AUDIT PHASE INITIATED.")
                yield self._current_state()
                
                audit_prompt = format_strategist_audit_prompt(blueprint, intent, coder_response)
                self.log_strategist("user", audit_prompt)
                yield self._current_state()
                
                audit_response = call_ai_api(self.strategist_url, CONFIG['STRATEGIST_API_KEY'], self.strategist_history)
                self.log_strategist("assistant", audit_response)
                yield self._current_state()
                
                if "AUDIT_PASSED" in audit_response:
                    self.log_system("AUDIT PASSED. MISSION COMPLETE.")
                    final_state = self._current_state()
                    final_state["final_code"] = apply_architect_signature(coder_response)
                    yield final_state
                    return
                
                self.log_system("AUDIT FAILED. Generating revisions.")
                yield self._current_state()
                
                revision_prompt = format_resolution_prompt(blueprint, f"AUDIT CHANGES REQUIRED:\n{audit_response}")
                self.log_coder("user", revision_prompt)
                yield self._current_state()
                continue
            
            self.log_system("Ambiguity DETECTED. Escalating to Strategist.")
            yield self._current_state()
            
            strategist_prompt = format_strategist_prompt(blueprint, intent, coder_response)
            self.log_strategist("user", strategist_prompt)
            yield self._current_state()
            
            strategist_response = call_ai_api(self.strategist_url, CONFIG['STRATEGIST_API_KEY'], self.strategist_history)
            self.log_strategist("assistant", strategist_response)
            yield self._current_state()
            
            tool_request = detect_tool_usage(strategist_response)
            if tool_request:
                self.log_system(f"TOOL REQUEST: {tool_request['tool_name']}")
                yield self._current_state()
                
                diagnostic = execute_tool(tool_request['tool_name'], tool_request['params'])
                self.audit_log.append(diagnostic)
                self.log_system(f"Tool Result: {diagnostic['status']}")
                yield self._current_state()
                
                tool_result_text = f"TOOL: {diagnostic['tool_name']}\nSTATUS: {diagnostic['status']}\nOUTPUT: {json.dumps(diagnostic['response_payload'])}"
                synthesis_prompt = format_strategist_tool_synthesis_prompt(blueprint, intent, coder_response, tool_result_text)
                self.log_strategist("user", synthesis_prompt)
                yield self._current_state()
                
                strategist_response = call_ai_api(self.strategist_url, CONFIG['STRATEGIST_API_KEY'], self.strategist_history)
                self.log_strategist("assistant", strategist_response)
                yield self._current_state()

            resolution_prompt = format_resolution_prompt(blueprint, strategist_response)
            self.log_coder("user", resolution_prompt)
            yield self._current_state()

        self.log_system("FATAL: Loop limit reached.")
        final_state = self._current_state()
        final_state["final_code"] = apply_architect_signature(coder_response)
        yield final_state

    def _compile_results(self, final_output: str) -> Dict[str, Any]:
        return {
            "system_log": self.system_log,
            "coder_log": self.coder_history,
            "strategist_log": self.strategist_history,
            "audit_log": self.audit_log,
            "final_output": final_output
        }

# --- API ---
app = FastAPI(title="Conductor MCP Server", version="4.0")

class ExecutionRequest(BaseModel):
    blueprint: str
    intent: str
    coder_model_label: Optional[str] = None
    strategist_model_label: Optional[str] = None
    enable_audit: Optional[bool] = False

class ExecutionResponse(BaseModel):
    system_log: List[str]
    coder_log: List[Dict[str, Any]]
    strategist_log: List[Dict[str, Any]]
    audit_log: List[Dict[str, Any]]
    final_output: str

@app.post("/execute", response_model=ExecutionResponse)
async def execute_conductor(req: ExecutionRequest):
    """ORIGINAL: Non-streaming endpoint (kept for backwards compatibility)"""
    engine = ConductorEngine(req.coder_model_label, req.strategist_model_label, req.enable_audit)
    result = engine.execute_workflow(req.blueprint, req.intent)
    return result

@app.post("/execute_stream")
async def execute_conductor_stream(req: ExecutionRequest):
    """STREAMING endpoint with audit support"""
    
    async def generate_updates():
        engine = ConductorEngine(req.coder_model_label, req.strategist_model_label, req.enable_audit)
        
        for update in engine.execute_workflow_streaming(req.blueprint, req.intent):
            yield f"data: {json.dumps(update)}\n\n"
            await asyncio.sleep(0)
        
        yield "data: {\"status\": \"complete\"}\n\n"
    
    return StreamingResponse(generate_updates(), media_type="text/event-stream")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)