File size: 22,373 Bytes
c2c2423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
STACK – Local Repository Agent with nomic-embed-text
Auto‑bootstraps venv + dependencies on first run.
"""

import os
import sys
import json
import math
import time
import threading
import hashlib
import subprocess
import venv
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Any

# ============================================================================
# 0. VENV BOOTSTRAP – prevent “externally-managed” errors
# ============================================================================
STACK_DIR = Path(__file__).resolve().parent
VENV_DIR = STACK_DIR / ".stack_venv"

def is_venv() -> bool:
    """Check if we are already running inside a virtual environment."""
    return (
        hasattr(sys, 'real_prefix')
        or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
    )

def create_venv():
    """Create the virtual environment and return the path to its Python binary."""
    print("[*] Creating virtual environment...")
    venv.create(str(VENV_DIR), with_pip=True)
    if os.name == 'nt':
        python = VENV_DIR / 'Scripts' / 'python.exe'
    else:
        python = VENV_DIR / 'bin' / 'python'
    return str(python)

def install_dependencies(python_exe: str):
    """Install required packages inside the virtual environment."""
    packages = ["ollama"]
    print(f"[*] Installing dependencies inside venv: {packages}")
    subprocess.check_call([python_exe, "-m", "pip", "install", "--upgrade", "pip"])
    subprocess.check_call([python_exe, "-m", "pip", "install"] + packages)

def relaunch_in_venv(python_exe: str):
    """Replace the current process with one running inside the venv."""
    print("[*] Relaunching inside virtual environment...")
    os.execv(python_exe, [python_exe, __file__] + sys.argv[1:])

# Bootstrap logic
if not is_venv():
    print("[!] Not running in a virtual environment.")
    if VENV_DIR.exists():
        # Venv exists – use it
        if os.name == 'nt':
            python_exe = str(VENV_DIR / 'Scripts' / 'python.exe')
        else:
            python_exe = str(VENV_DIR / 'bin' / 'python')
        if not Path(python_exe).exists():
            print("[!] Venv appears corrupt, recreating...")
            python_exe = create_venv()
            install_dependencies(python_exe)
        relaunch_in_venv(python_exe)
    else:
        # First run – create venv, install deps, relaunch
        python_exe = create_venv()
        install_dependencies(python_exe)
        relaunch_in_venv(python_exe)

# ============================================================================
# Now safely inside the venv – import ollama
# ============================================================================
import ollama

# ============================================================================
# 2. CONFIGURATION & PATHS
# ============================================================================
STACK_ROOT = os.path.abspath("./stack_system")
WORKSPACE = os.path.join(STACK_ROOT, "current_workspace")
TEMPLATES_DIR = os.path.join(STACK_ROOT, "templates")
MANIFEST_PATH = os.path.join(TEMPLATES_DIR, "manifest.json")
MEMORY_FILE = os.path.join(STACK_ROOT, ".stack_memory.json")
MAX_TOOL_DEPTH = 10

os.makedirs(WORKSPACE, exist_ok=True)
os.makedirs(TEMPLATES_DIR, exist_ok=True)

_manifest_lock = threading.RLock()

# ============================================================================
# 3. OLLAMA CONNECTION & MODEL MANAGEMENT
# ============================================================================
def check_ollama_running() -> bool:
    try:
        ollama.list()
        return True
    except Exception:
        return False

def start_ollama() -> bool:
    try:
        subprocess.Popen(["ollama", "serve"],
                         stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL)
        time.sleep(3)
        return check_ollama_running()
    except Exception:
        return False

def ensure_models() -> None:
    print("[*] Verifying Ollama models...")
    if not check_ollama_running():
        print("[!] Ollama not running. Attempting to start...")
        if not start_ollama():
            print("[!] Could not start Ollama. Please run 'ollama serve' manually.")
            sys.exit(1)

    required_models = ["nomic-embed-text"]
    try:
        installed = ollama.list()
        installed_names = [m.model for m in installed.models] if hasattr(installed, 'models') else []
    except Exception:
        installed_names = []

    for model in required_models:
        if model not in installed_names:
            print(f"[*] Pulling {model}...")
            try:
                ollama.pull(model)
                print(f"[✓] {model} ready")
            except Exception as e:
                print(f"[!] Failed to pull {model}: {e}")
                sys.exit(1)

def get_embedding(text: str) -> Optional[List[float]]:
    try:
        response = ollama.embed(model="nomic-embed-text", input=text)
        if hasattr(response, 'embeddings'):
            embeddings = response.embeddings
        elif isinstance(response, dict):
            embeddings = response.get('embeddings', [])
        else:
            return None
        if embeddings and len(embeddings) > 0:
            return embeddings[0] if isinstance(embeddings[0], list) else embeddings[0]
        return None
    except Exception as e:
        print(f"⚠️ Embedding error: {e}")
        return None

# ============================================================================
# 4. VECTOR SIMILARITY & MEMORY SYSTEM
# ============================================================================
def cosine_similarity(v1: List[float], v2: List[float]) -> float:
    if not v1 or not v2 or len(v1) != len(v2):
        return 0.0
    dot = sum(a * b for a, b in zip(v1, v2))
    mag1 = math.sqrt(sum(a * a for a in v1))
    mag2 = math.sqrt(sum(b * b for b in v2))
    if mag1 == 0 or mag2 == 0:
        return 0.0
    return dot / (mag1 * mag2)

def remember_action(action_summary: str, metadata: Dict = None) -> None:
    memory = []
    if os.path.exists(MEMORY_FILE):
        try:
            with open(MEMORY_FILE, 'r') as f:
                memory = json.load(f)
        except json.JSONDecodeError:
            memory = []
    vector = get_embedding(action_summary)
    if vector:
        entry = {
            "text": action_summary,
            "vector": vector,
            "timestamp": time.time(),
            "metadata": metadata or {}
        }
        memory.append(entry)
        if len(memory) > 1000:
            memory = memory[-1000:]
        with open(MEMORY_FILE, 'w') as f:
            json.dump(memory, f)

def query_memory(query: str, top_k: int = 3) -> List[str]:
    if not os.path.exists(MEMORY_FILE):
        return []
    try:
        with open(MEMORY_FILE, 'r') as f:
            memory = json.load(f)
    except (json.JSONDecodeError, IOError):
        return []
    query_vector = get_embedding(query)
    if not query_vector:
        return []
    scored = []
    for item in memory:
        if "vector" in item and item["vector"]:
            score = cosine_similarity(query_vector, item["vector"])
            scored.append((score, item["text"]))
    scored.sort(key=lambda x: x[0], reverse=True)
    return [text for score, text in scored[:top_k] if score > 0.3]

# ============================================================================
# 5. TEMPLATE MANAGEMENT & HOT RELOAD
# ============================================================================
DEFAULT_TEMPLATES = {
    "python_web_server": {
        "description": "minimal fastapi python web server with api routes",
        "files": {
            "app.py": "from fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get('/')\ndef root():\n    return {'status': 'STACK running'}\n",
            "requirements.txt": "fastapi\nuvicorn"
        }
    },
    "html_login_component": {
        "description": "modern tailwind css login form ui component",
        "files": {
            "login.html": """<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 flex items-center justify-center h-screen">
    <div class="bg-white p-8 rounded-lg shadow-md w-96">
        <h2 class="text-2xl font-bold mb-6">Login</h2>
        <input type="email" placeholder="Email" class="w-full p-2 border rounded mb-4">
        <input type="password" placeholder="Password" class="w-full p-2 border rounded mb-4">
        <button class="w-full bg-blue-500 text-white p-2 rounded hover:bg-blue-600">Sign In</button>
    </div>
</body>
</html>"""
        }
    }
}

def seed_initial_templates() -> None:
    if os.path.exists(MANIFEST_PATH):
        return
    print("[*] Seeding initial templates...")
    manifest = {}
    for name, data in DEFAULT_TEMPLATES.items():
        vector = get_embedding(data["description"])
        if vector:
            manifest[name] = {
                "description": data["description"],
                "vector": vector,
                "files": data["files"]
            }
            print(f"  ✓ {name}")
    with _manifest_lock:
        with open(MANIFEST_PATH, 'w') as f:
            json.dump(manifest, f, indent=2)

def scan_templates_folder() -> Dict:
    discovered = {}
    if not os.path.exists(TEMPLATES_DIR):
        return discovered
    for item in os.listdir(TEMPLATES_DIR):
        item_path = os.path.join(TEMPLATES_DIR, item)
        if not os.path.isdir(item_path):
            continue
        files_dict = {}
        description = f"code template for {item.replace('_', ' ')}"
        for root, _, files in os.walk(item_path):
            for filename in files:
                if filename == "description.txt":
                    try:
                        with open(os.path.join(root, filename), 'r') as f:
                            description = f.read().strip()
                    except Exception:
                        pass
                    continue
                file_path = os.path.join(root, filename)
                rel_path = os.path.relpath(file_path, item_path)
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        files_dict[rel_path] = f.read()
                except Exception:
                    pass
        if files_dict:
            discovered[item] = {
                "description": description,
                "files": files_dict
            }
    return discovered

def reload_manifest() -> None:
    raw_templates = scan_templates_folder()
    with _manifest_lock:
        manifest = {}
        if os.path.exists(MANIFEST_PATH):
            try:
                with open(MANIFEST_PATH, 'r') as f:
                    manifest = json.load(f)
            except json.JSONDecodeError:
                manifest = {}
        updated = False
        for name, data in raw_templates.items():
            if name not in manifest or manifest[name]["description"] != data["description"]:
                vector = get_embedding(data["description"])
                if vector:
                    manifest[name] = {
                        "description": data["description"],
                        "vector": vector,
                        "files": data["files"]
                    }
                    updated = True
                    print(f"  ✓ Updated template: {name}")
        if updated:
            with open(MANIFEST_PATH, 'w') as f:
                json.dump(manifest, f, indent=2)

def start_template_watcher() -> threading.Thread:
    def watcher():
        last_mtime = {}
        while True:
            time.sleep(2)
            try:
                current = {}
                if os.path.exists(TEMPLATES_DIR):
                    for root, _, files in os.walk(TEMPLATES_DIR):
                        for f in files:
                            path = os.path.join(root, f)
                            current[path] = os.path.getmtime(path)
                if current != last_mtime:
                    reload_manifest()
                    last_mtime = current
            except Exception:
                pass
    thread = threading.Thread(target=watcher, daemon=True)
    thread.start()
    return thread

# ============================================================================
# 6. SANDBOXED GIT & FILE OPERATIONS
# ============================================================================
def validate_workspace_path(target_path: str) -> bool:
    abs_target = os.path.abspath(os.path.join(WORKSPACE, target_path))
    abs_workspace = os.path.abspath(WORKSPACE)
    return abs_target.startswith(abs_workspace)

def run_git_safe(args: List[str], error_ok: bool = False) -> Tuple[bool, str]:
    try:
        result = subprocess.run(
            ["git"] + args,
            cwd=WORKSPACE,
            capture_output=True,
            text=True,
            timeout=30
        )
        if result.returncode == 0:
            return True, result.stdout or "OK"
        elif error_ok:
            return False, result.stderr
        else:
            return False, result.stderr
    except subprocess.TimeoutExpired:
        return False, "Git operation timed out"
    except Exception as e:
        return False, str(e)

def cmd_build(repo_name: str) -> str:
    global WORKSPACE
    new_workspace = os.path.join(STACK_ROOT, repo_name)
    try:
        os.makedirs(new_workspace, exist_ok=True)
        WORKSPACE = new_workspace
        success, msg = run_git_safe(["init"])
        if not success:
            return f"Git init failed: {msg}"
        success, msg = run_git_safe(["checkout", "-b", "main"])
        config_path = os.path.join(WORKSPACE, "STACK.json")
        with open(config_path, 'w') as f:
            json.dump({
                "name": repo_name,
                "created": time.time(),
                "managed_by": "STACK"
            }, f)
        run_git_safe(["add", "."])
        run_git_safe(["commit", "-m", "chore: initial STACK bootstrap"])
        remember_action(f"Created repository '{repo_name}'", {"action": "build", "repo": repo_name})
        return f"✓ Repository '{repo_name}' created at {WORKSPACE}"
    except Exception as e:
        return f"✗ Build failed: {e}"

def cmd_add(search_query: str) -> str:
    workspace_git = os.path.join(WORKSPACE, ".git")
    if not os.path.exists(workspace_git):
        return "✗ No active repository. Use '/build <name>' first"
    with _manifest_lock:
        if not os.path.exists(MANIFEST_PATH):
            return "✗ No templates available. Run '/import' or add to templates folder"
        try:
            with open(MANIFEST_PATH, 'r') as f:
                manifest = json.load(f)
        except Exception:
            return "✗ Corrupted manifest file"
    if not manifest:
        return "✗ Manifest is empty. Seed templates first"
    query_vector = get_embedding(search_query)
    if not query_vector:
        return "✗ Could not generate embedding for query"
    best_match = None
    best_score = -1.0
    for name, data in manifest.items():
        if "vector" in data:
            score = cosine_similarity(query_vector, data["vector"])
            if score > best_score:
                best_score = score
                best_match = (name, data["files"], data["description"])
    if best_score < 0.35:
        return f"✗ No good match (confidence: {best_score:.2f}). Try different phrasing"
    template_name, files, description = best_match
    branch_name = f"stack/{template_name}"
    success, msg = run_git_safe(["checkout", "-b", branch_name], error_ok=True)
    files_written = []
    for filename, content in files.items():
        target = os.path.join(WORKSPACE, filename)
        if not validate_workspace_path(filename):
            continue
        os.makedirs(os.path.dirname(target), exist_ok=True)
        with open(target, 'w', encoding='utf-8') as f:
            f.write(content)
        files_written.append(filename)
    run_git_safe(["add", "."])
    commit_msg = f"feat: add {template_name} via STACK\n\n{description}"
    run_git_safe(["commit", "-m", commit_msg])
    run_git_safe(["checkout", "main"])
    run_git_safe(["merge", branch_name])
    remember_action(f"Added template '{template_name}' to repository",
                    {"action": "add", "template": template_name, "files": files_written})
    return f"✓ Added '{template_name}' (confidence: {best_score:.2f})\n  Files: {', '.join(files_written)}"

def cmd_import(json_path: str) -> str:
    if not os.path.exists(json_path):
        return f"✗ File not found: {json_path}"
    try:
        with open(json_path, 'r', encoding='utf-8') as f:
            new_templates = json.load(f)
    except Exception as e:
        return f"✗ Invalid JSON: {e}"
    with _manifest_lock:
        manifest = {}
        if os.path.exists(MANIFEST_PATH):
            try:
                with open(MANIFEST_PATH, 'r') as f:
                    manifest = json.load(f)
            except Exception:
                pass
        imported = 0
        for name, data in new_templates.items():
            if "description" not in data or "files" not in data:
                continue
            vector = get_embedding(data["description"])
            if vector:
                manifest[name] = {
                    "description": data["description"],
                    "vector": vector,
                    "files": data["files"]
                }
                imported += 1
        with open(MANIFEST_PATH, 'w') as f:
            json.dump(manifest, f, indent=2)
    return f"✓ Imported {imported} templates from {json_path}"

def cmd_status() -> str:
    with _manifest_lock:
        manifest_count = 0
        if os.path.exists(MANIFEST_PATH):
            try:
                with open(MANIFEST_PATH, 'r') as f:
                    manifest_count = len(json.load(f))
            except Exception:
                pass
    has_git = os.path.exists(os.path.join(WORKSPACE, ".git"))
    lines = [
        f"STACK Status",
        f"  Workspace: {WORKSPACE}",
        f"  Git initialized: {'✓' if has_git else '✗'}",
        f"  Templates in manifest: {manifest_count}",
        f"  Ollama: {'✓' if check_ollama_running() else '✗'}"
    ]
    return "\n".join(lines)

def cmd_list_templates() -> str:
    with _manifest_lock:
        if not os.path.exists(MANIFEST_PATH):
            return "No templates found"
        try:
            with open(MANIFEST_PATH, 'r') as f:
                manifest = json.load(f)
        except Exception:
            return "Error reading manifest"
    if not manifest:
        return "No templates in manifest"
    lines = ["Available templates:"]
    for name, data in manifest.items():
        desc = data.get("description", "No description")[:60]
        lines.append(f"  • {name}: {desc}")
    return "\n".join(lines)

# ============================================================================
# 7. CLI INTERFACE
# ============================================================================
def print_banner() -> None:
    banner = """
  ███████╗████████╗ █████╗  ██████╗██╗  ██╗
  ██╔════╝╚══██╔══╝██╔══██╗██╔════╝██║ ██╔╝
  ███████╗   ██║   ███████║██║     █████╔╝ 
  ╚════██║   ██║   ██╔══██║██║     ██╔═██╗ 
  ███████║   ██║   ██║  ██║╚██████╗██║  ██╗
  ╚══════╝   ╚═╝   ╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝
        Embed-Driven Repository Architect
"""
    print(banner)

def print_commands() -> None:
    print("""
Commands:
  /build <name>        - Create new git repository workspace
  /add <description>   - Find matching template, inject into workspace
  /import <file.json>  - Import external template bundle
  /list                - List available templates
  /status              - Show system status
  /help                - Show this help
  /quit                - Exit STACK

Templates folder: ./stack_system/templates/
  - Add folders with code + description.txt for hot-reload
  - JSON imports also supported
""")

def main() -> None:
    print("[*] Initializing STACK...")
    ensure_models()
    seed_initial_templates()
    start_template_watcher()
    print_banner()
    print_commands()
    while True:
        try:
            user_input = input("\nSTACK > ").strip()
            if not user_input:
                continue
            if user_input.lower() in ["/quit", "/exit", "quit", "exit"]:
                print("[*] Goodbye!")
                break
            if user_input == "/help":
                print_commands()
                continue
            if user_input == "/status":
                print(cmd_status())
                continue
            if user_input == "/list":
                print(cmd_list_templates())
                continue
            if user_input.startswith("/build "):
                repo_name = user_input[7:].strip()
                if repo_name:
                    print(cmd_build(repo_name))
                else:
                    print("Usage: /build <repo_name>")
                continue
            if user_input.startswith("/add "):
                query = user_input[5:].strip()
                if query:
                    print(cmd_add(query))
                else:
                    print("Usage: /add <description>")
                continue
            if user_input.startswith("/import "):
                path = user_input[8:].strip()
                if path:
                    print(cmd_import(path))
                else:
                    print("Usage: /import <path/to/template.json>")
                continue
            print(f"Unknown command. Type /help for available commands.")
        except KeyboardInterrupt:
            print("\n[*] Interrupted. Goodbye!")
            break
        except EOFError:
            break
        except Exception as e:
            print(f"Error: {e}")

if __name__ == "__main__":
    main()