-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlauncher.py
More file actions
833 lines (711 loc) · 29.9 KB
/
Copy pathlauncher.py
File metadata and controls
833 lines (711 loc) · 29.9 KB
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
"""
Ouroboros Launcher — Immutable process manager.
This file is bundled into the .app via PyInstaller. It never self-modifies.
All agent logic lives in REPO_DIR and is launched as a subprocess via the
embedded python-build-standalone interpreter.
Responsibilities:
- PID lock (single instance)
- Bootstrap REPO_DIR on first run
- Start/restart agent subprocess (server.py)
- Display pywebview window pointing at agent's local HTTP server
- Handle restart signals (agent exits with code 42)
"""
import json
import logging
import os
import pathlib
import shutil
import subprocess
import sys
import threading
import time
from typing import Optional
# ---------------------------------------------------------------------------
# Paths (single source of truth: ouroboros.config)
# ---------------------------------------------------------------------------
from ouroboros.config import (
HOME, APP_ROOT, REPO_DIR, DATA_DIR, SETTINGS_PATH, PID_FILE, PORT_FILE,
RESTART_EXIT_CODE, PANIC_EXIT_CODE, AGENT_SERVER_PORT,
read_version, load_settings, save_settings, acquire_pid_lock, release_pid_lock,
)
MAX_CRASH_RESTARTS = 5
CRASH_WINDOW_SEC = 120
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
_LOG_FORMAT = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
_log_dir = DATA_DIR / "logs"
_log_dir.mkdir(parents=True, exist_ok=True)
from logging.handlers import RotatingFileHandler
_file_handler = RotatingFileHandler(
_log_dir / "launcher.log", maxBytes=2 * 1024 * 1024, backupCount=2, encoding="utf-8",
)
_file_handler.setFormatter(logging.Formatter(_LOG_FORMAT))
_handlers: list = [_file_handler]
if not getattr(sys, "frozen", False):
_handlers.append(logging.StreamHandler())
logging.basicConfig(level=logging.INFO, format=_LOG_FORMAT, handlers=_handlers)
log = logging.getLogger("launcher")
APP_VERSION = read_version()
# ---------------------------------------------------------------------------
# Embedded Python
# ---------------------------------------------------------------------------
def _find_embedded_python() -> str:
"""Locate the embedded python-build-standalone interpreter."""
if getattr(sys, "frozen", False):
candidates = [
pathlib.Path(sys._MEIPASS) / "python-standalone" / "bin" / "python3",
pathlib.Path(sys._MEIPASS) / "python-standalone" / "bin" / "python",
]
else:
candidates = [
pathlib.Path(__file__).parent / "python-standalone" / "bin" / "python3",
pathlib.Path(__file__).parent / "python-standalone" / "bin" / "python",
]
for p in candidates:
if p.exists():
return str(p)
return sys.executable
EMBEDDED_PYTHON = _find_embedded_python()
# ---------------------------------------------------------------------------
# Bootstrap
# ---------------------------------------------------------------------------
def check_git() -> bool:
return shutil.which("git") is not None
def _sync_core_files() -> None:
"""Sync core files from bundle to REPO_DIR on every launch."""
if getattr(sys, "frozen", False):
bundle_dir = pathlib.Path(sys._MEIPASS)
else:
bundle_dir = pathlib.Path(__file__).parent
sync_paths = [
"ouroboros/safety.py",
"prompts/SAFETY.md",
"ouroboros/tools/registry.py",
]
for rel in sync_paths:
src = bundle_dir / rel
dst = REPO_DIR / rel
if src.exists():
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dst)
log.info("Synced %d core files to %s", len(sync_paths), REPO_DIR)
def _commit_synced_files() -> None:
"""Commit sync'd safety files so git reset --hard doesn't revert them."""
try:
for rel in ["ouroboros/safety.py", "prompts/SAFETY.md", "ouroboros/tools/registry.py"]:
subprocess.run(["git", "add", rel], cwd=str(REPO_DIR),
check=False, capture_output=True)
status = subprocess.run(["git", "status", "--porcelain", "--",
"ouroboros/safety.py", "prompts/SAFETY.md",
"ouroboros/tools/registry.py"],
cwd=str(REPO_DIR), capture_output=True, text=True)
if status.stdout.strip():
subprocess.run(["git", "commit", "-m",
"safety-sync: restore protected files from bundle"],
cwd=str(REPO_DIR), check=False, capture_output=True)
log.info("Committed synced safety files.")
except Exception as e:
log.warning("Failed to commit synced files: %s", e)
_REPO_GITIGNORE = """\
# Secrets
.env
.env.*
*.key
*.pem
# IDE
.cursor/
.vscode/
.idea/
# Python bytecode
__pycache__/
*.pyc
*.pyo
*.egg-info/
# Build artifacts
dist/
build/
.pytest_cache/
.mypy_cache/
# Native / binary artifacts (PyInstaller, compiled extensions)
*.so
*.dylib
*.dll
*.dist-info/
base_library.zip
# OS
.DS_Store
Thumbs.db
# Release artifacts
.create_release.py
.release_notes.md
python-standalone/
"""
def _ensure_repo_gitignore(repo_dir: pathlib.Path) -> None:
"""Write .gitignore if missing — MUST run before any git add -A."""
gi = repo_dir / ".gitignore"
if not gi.exists():
gi.write_text(_REPO_GITIGNORE, encoding="utf-8")
def bootstrap_repo() -> None:
"""Copy bundled codebase to REPO_DIR on first run, sync core files always."""
DATA_DIR.mkdir(parents=True, exist_ok=True)
if REPO_DIR.exists() and (REPO_DIR / "server.py").exists():
_sync_core_files()
_commit_synced_files()
return
needs_full_bootstrap = not REPO_DIR.exists()
log.info("Bootstrapping repository to %s (full=%s)", REPO_DIR, needs_full_bootstrap)
if getattr(sys, "frozen", False):
bundle_dir = pathlib.Path(sys._MEIPASS)
else:
bundle_dir = pathlib.Path(__file__).parent
if needs_full_bootstrap:
shutil.copytree(bundle_dir, REPO_DIR, ignore=shutil.ignore_patterns(
"repo", "data", "build", "dist", ".git", "__pycache__", "venv", ".venv",
"Ouroboros.spec", "run_demo.sh", "demo_app.py", "app.py", "launcher.py",
"colab_launcher.py", "colab_bootstrap_shim.py",
"python-standalone", "assets",
"*.pyc", "*.pyo", "*.so", "*.dylib", "*.dll",
"*.dist-info", "base_library.zip",
))
else:
for item in ("server.py", "web"):
src = bundle_dir / item
dst = REPO_DIR / item
if src.exists() and not dst.exists():
if src.is_dir():
shutil.copytree(src, dst)
else:
shutil.copy2(src, dst)
# Initialize git repo if new
if needs_full_bootstrap:
_ensure_repo_gitignore(REPO_DIR)
try:
subprocess.run(["git", "init"], cwd=str(REPO_DIR), check=True, capture_output=True)
subprocess.run(["git", "config", "user.name", "Ouroboros"], cwd=str(REPO_DIR), check=True, capture_output=True)
subprocess.run(["git", "config", "user.email", "ouroboros@local.mac"], cwd=str(REPO_DIR), check=True, capture_output=True)
subprocess.run(["git", "add", "-A"], cwd=str(REPO_DIR), check=True, capture_output=True)
subprocess.run(["git", "commit", "-m", "Initial commit from app bundle"], cwd=str(REPO_DIR), check=False, capture_output=True)
subprocess.run(["git", "branch", "-M", "ouroboros"], cwd=str(REPO_DIR), check=False, capture_output=True)
subprocess.run(["git", "branch", "ouroboros-stable"], cwd=str(REPO_DIR), check=False, capture_output=True)
except Exception as e:
log.error("Git init failed: %s", e)
# Generate world profile
try:
memory_dir = DATA_DIR / "memory"
memory_dir.mkdir(parents=True, exist_ok=True)
world_path = memory_dir / "WORLD.md"
if not world_path.exists():
env = os.environ.copy()
env["PYTHONPATH"] = str(REPO_DIR)
subprocess.run(
[EMBEDDED_PYTHON, "-c",
f"import sys; sys.path.insert(0, '{REPO_DIR}'); "
f"from ouroboros.world_profiler import generate_world_profile; "
f"generate_world_profile('{world_path}')"],
env=env, timeout=30, capture_output=True,
)
except Exception as e:
log.warning("World profile generation failed: %s", e)
# Migrate old settings if needed
_migrate_old_settings()
# Install dependencies
_install_deps()
log.info("Bootstrap complete.")
def _migrate_old_settings() -> None:
"""Migrate old-style env-only settings to settings.json for existing users."""
if SETTINGS_PATH.exists():
return
migrated = {}
env_keys = [
"OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY",
"OUROBOROS_MODEL", "OUROBOROS_MODEL_CODE", "OUROBOROS_MODEL_LIGHT",
"OUROBOROS_MODEL_FALLBACK", "TOTAL_BUDGET", "OUROBOROS_MAX_WORKERS",
"OUROBOROS_SOFT_TIMEOUT_SEC", "OUROBOROS_HARD_TIMEOUT_SEC",
"GITHUB_TOKEN", "GITHUB_REPO",
]
for key in env_keys:
val = os.environ.get(key, "")
if val:
try:
if key in ("TOTAL_BUDGET",):
migrated[key] = float(val)
elif key in ("OUROBOROS_MAX_WORKERS", "OUROBOROS_SOFT_TIMEOUT_SEC", "OUROBOROS_HARD_TIMEOUT_SEC"):
migrated[key] = int(val)
else:
migrated[key] = val
except (ValueError, TypeError):
migrated[key] = val
# Also check for old settings.json in data/state/
old_settings = DATA_DIR / "state" / "settings.json"
if old_settings.exists():
try:
old = json.loads(old_settings.read_text(encoding="utf-8"))
for key in env_keys:
if key in old and key not in migrated:
migrated[key] = old[key]
except Exception:
pass
if migrated:
DATA_DIR.mkdir(parents=True, exist_ok=True)
SETTINGS_PATH.write_text(json.dumps(migrated, indent=2), encoding="utf-8")
log.info("Migrated %d settings to %s", len(migrated), SETTINGS_PATH)
def _install_deps() -> None:
"""Install Python dependencies for the agent."""
req_file = REPO_DIR / "requirements.txt"
if not req_file.exists():
return
log.info("Installing agent dependencies...")
try:
subprocess.run(
[EMBEDDED_PYTHON, "-m", "pip", "install", "-q", "-r", str(req_file)],
timeout=300, capture_output=True,
)
except Exception as e:
log.warning("Dependency install failed: %s", e)
# ---------------------------------------------------------------------------
# Agent process management
# ---------------------------------------------------------------------------
_agent_proc: Optional[subprocess.Popen] = None
_agent_lock = threading.Lock()
_shutdown_event = threading.Event()
def start_agent(port: int = AGENT_SERVER_PORT) -> subprocess.Popen:
"""Start the agent server.py as a subprocess."""
global _agent_proc
env = os.environ.copy()
env["PYTHONPATH"] = str(REPO_DIR)
env["OUROBOROS_SERVER_PORT"] = str(port)
env["OUROBOROS_DATA_DIR"] = str(DATA_DIR)
env["OUROBOROS_REPO_DIR"] = str(REPO_DIR)
env["OUROBOROS_APP_VERSION"] = str(APP_VERSION)
# Pass settings as env vars
settings = _load_settings()
for key, val in settings.items():
if val:
env[key] = str(val)
server_py = REPO_DIR / "server.py"
log.info("Starting agent: %s %s (port=%d)", EMBEDDED_PYTHON, server_py, port)
proc = subprocess.Popen(
[EMBEDDED_PYTHON, str(server_py)],
cwd=str(REPO_DIR),
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
_agent_proc = proc
# Stream agent stdout to log file in background
def _stream_output():
log_path = DATA_DIR / "logs" / "agent_stdout.log"
try:
with open(log_path, "a", encoding="utf-8") as f:
for line in iter(proc.stdout.readline, b""):
decoded = line.decode("utf-8", errors="replace")
f.write(decoded)
f.flush()
except Exception:
pass
threading.Thread(target=_stream_output, daemon=True).start()
return proc
def stop_agent() -> None:
"""Gracefully stop the agent process."""
global _agent_proc
with _agent_lock:
if _agent_proc is None:
return
proc = _agent_proc
log.info("Stopping agent (pid=%s)...", proc.pid)
try:
proc.terminate()
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
except Exception:
pass
with _agent_lock:
_agent_proc = None
def _read_port_file() -> int:
"""Read the active port from PORT_FILE (written by server.py)."""
try:
if PORT_FILE.exists():
return int(PORT_FILE.read_text(encoding="utf-8").strip())
except (ValueError, OSError):
pass
return AGENT_SERVER_PORT
def _kill_stale_on_port(port: int) -> None:
"""Kill any process listening on the given port (cleanup from previous runs)."""
try:
result = subprocess.run(
["lsof", "-ti", f"tcp:{port}"],
capture_output=True, text=True, timeout=5,
)
pids = result.stdout.strip().split()
for pid_str in pids:
try:
pid = int(pid_str)
if pid != os.getpid():
os.kill(pid, 9)
log.info("Killed stale process %d on port %d", pid, port)
except (ValueError, ProcessLookupError, PermissionError):
pass
except Exception:
pass
def _wait_for_server(port: int, timeout: float = 30.0) -> bool:
"""Wait for the agent HTTP server to become responsive."""
import urllib.request
url = f"http://127.0.0.1:{port}/api/health"
deadline = time.time() + timeout
while time.time() < deadline:
try:
with urllib.request.urlopen(url, timeout=2) as resp:
if resp.status == 200:
return True
except Exception:
pass
time.sleep(0.5)
return False
def _poll_port_file(timeout: float = 30.0) -> int:
"""Poll port file until it's freshly written (mtime within last 10s)."""
deadline = time.time() + timeout
while time.time() < deadline:
try:
if PORT_FILE.exists():
age = time.time() - PORT_FILE.stat().st_mtime
if age < 10:
return int(PORT_FILE.read_text(encoding="utf-8").strip())
except (ValueError, OSError):
pass
time.sleep(0.5)
return _read_port_file()
_webview_window = None # set by main(), used by lifecycle loop
def agent_lifecycle_loop(port: int = AGENT_SERVER_PORT) -> None:
"""Main loop: start agent, monitor, restart on exit code 42 or crash."""
crash_times: list = []
# Kill anything left over from a previous launcher session
_kill_stale_on_port(port)
while not _shutdown_event.is_set():
# Delete stale port file so _poll_port_file waits for a fresh write
try:
PORT_FILE.unlink(missing_ok=True)
except OSError:
pass
proc = start_agent(port)
# Wait for the server to write a fresh port file, then check health
actual_port = _poll_port_file(timeout=30)
if not _wait_for_server(actual_port, timeout=45):
log.warning("Agent server did not become responsive within 45s (port %d)", actual_port)
proc.wait()
exit_code = proc.returncode
log.info("Agent exited with code %d", exit_code)
with _agent_lock:
_agent_proc = None
if _shutdown_event.is_set():
break
# Panic stop: kill everything, close app, no restart
if exit_code == PANIC_EXIT_CODE:
log.info("Panic stop (exit code %d) — shutting down completely.", PANIC_EXIT_CODE)
_shutdown_event.set()
_kill_stale_on_port(port)
import multiprocessing as _mp
for child in _mp.active_children():
try:
os.kill(child.pid, 9)
except (ProcessLookupError, PermissionError, OSError):
pass
if _webview_window:
try:
_webview_window.destroy()
except Exception:
pass
break
# Wait for port to fully release after process exit
time.sleep(2)
if exit_code == RESTART_EXIT_CODE:
log.info("Agent requested restart (exit code 42). Restarting...")
_sync_core_files()
_commit_synced_files()
_install_deps()
_kill_stale_on_port(port)
continue
# Crash detection
now = time.time()
crash_times.append(now)
crash_times[:] = [t for t in crash_times if (now - t) < CRASH_WINDOW_SEC]
if len(crash_times) >= MAX_CRASH_RESTARTS:
log.error("Agent crashed %d times in %ds. Stopping.", MAX_CRASH_RESTARTS, CRASH_WINDOW_SEC)
break
log.info("Agent crashed. Restarting in 3s...")
_kill_stale_on_port(port)
time.sleep(3)
# ---------------------------------------------------------------------------
# Settings (delegated to ouroboros.config)
# ---------------------------------------------------------------------------
def _load_settings() -> dict:
return load_settings()
# ---------------------------------------------------------------------------
# First-run wizard
# ---------------------------------------------------------------------------
_WIZARD_HTML = """<!DOCTYPE html>
<html><head><meta charset="UTF-8"><style>
* { margin:0; padding:0; box-sizing:border-box; }
body { background:#0d0b0f; color:#e2e8f0; font-family:-apple-system,system-ui,sans-serif;
display:flex; align-items:center; justify-content:center; min-height:100vh; padding:20px 0; }
.card { background:rgba(255,255,255,.06); border-radius:16px; padding:28px 32px; width:480px;
max-height:90vh; overflow-y:auto; }
h2 { font-size:22px; margin-bottom:4px; color:#e85d6f; }
.sub { color:rgba(255,255,255,.5); font-size:13px; margin-bottom:16px; }
h3 { font-size:14px; color:rgba(255,255,255,.6); margin-top:18px; margin-bottom:8px;
border-top:1px solid rgba(255,255,255,.08); padding-top:14px; }
label { display:block; font-size:12px; color:rgba(255,255,255,.5); margin-bottom:4px; margin-top:10px; }
input, select { width:100%; padding:8px 12px; border-radius:8px; border:1px solid rgba(255,255,255,.12);
background:#1a1520; color:#e2e8f0; font-size:14px; outline:none; font-family:inherit; }
input:focus, select:focus { border-color:#e85d6f; }
.row { display:flex; gap:12px; }
.row .field { flex:1; }
.hint { font-size:11px; color:rgba(255,255,255,.35); margin-top:3px; }
.btn { margin-top:20px; width:100%; padding:11px; border-radius:8px; border:none;
background:#dc2626; color:#fff; font-size:14px; font-weight:600; cursor:pointer; font-family:inherit; }
.btn:hover { background:#b91c1c; }
.btn:disabled { opacity:.4; cursor:default; background:#7f1d1d; }
.err { color:#ef4444; font-size:12px; margin-top:8px; display:none; }
a { color:#e85d6f; }
.opt { font-size:11px; color:rgba(255,255,255,.35); font-style:italic; }
</style></head><body>
<div class="card">
<h2>Ouroboros</h2>
<p class="sub">Configure your LLM provider. Everything can be changed later in Settings.</p>
<h3>Cloud LLM (OpenRouter)</h3>
<label>OpenRouter API Key <span class="opt">— required for cloud models</span></label>
<input id="api-key" type="password" placeholder="sk-or-v1-..." autofocus>
<p class="hint">Get one at <a href="https://openrouter.ai/keys" target="_blank">openrouter.ai/keys</a></p>
<div class="row">
<div class="field"><label>Main Model</label><input id="model" value="anthropic/claude-sonnet-4.6"></div>
<div class="field"><label>Budget ($)</label><input id="budget" type="number" value="10" min="1" step="1" style="width:100px"></div>
</div>
<label>OpenAI API Key <span class="opt">— for web search</span></label>
<input id="openai-key" type="password" placeholder="sk-...">
<p class="hint">Enables the web_search tool. <a href="https://platform.openai.com/api-keys" target="_blank">Get key</a></p>
<h3>Local Model (optional)</h3>
<label>Preset</label>
<select id="local-preset">
<option value="">None — use cloud only</option>
<option value="qwen25-7b">Qwen2.5-7B Instruct Q3_K_M (~3.9 GB, 16 GB RAM)</option>
<option value="qwen3-14b">Qwen3-14B Instruct Q4_K_M (~9 GB, 32 GB RAM)</option>
<option value="qwen3-32b">Qwen3-32B Instruct Q4_K_M (~20 GB, 64 GB RAM)</option>
<option value="custom">Custom — I'll enter HuggingFace repo</option>
</select>
<div id="custom-fields" style="display:none">
<label>HuggingFace Source</label>
<input id="local-source" placeholder="Qwen/Qwen2.5-7B-Instruct-GGUF">
<label>GGUF Filename</label>
<input id="local-filename" placeholder="qwen2.5-7b-instruct-q3_k_m.gguf">
</div>
<p class="err" id="err"></p>
<button class="btn" id="save-btn" disabled>Start Ouroboros</button>
</div>
<script>
const PRESETS = {
'qwen25-7b': { source: 'Qwen/Qwen2.5-7B-Instruct-GGUF', filename: 'qwen2.5-7b-instruct-q3_k_m.gguf', ctx: 16384 },
'qwen3-14b': { source: 'Qwen/Qwen3-14B-GGUF', filename: 'Qwen3-14B-Q4_K_M.gguf', ctx: 16384 },
'qwen3-32b': { source: 'Qwen/Qwen3-32B-GGUF', filename: 'Qwen3-32B-Q4_K_M.gguf', ctx: 32768 },
};
const keyInput = document.getElementById('api-key');
const preset = document.getElementById('local-preset');
const btn = document.getElementById('save-btn');
function validate() {
const hasKey = keyInput.value.trim().length >= 10;
const hasLocal = preset.value !== '';
btn.disabled = !(hasKey || hasLocal);
}
keyInput.addEventListener('input', validate);
preset.addEventListener('change', () => {
document.getElementById('custom-fields').style.display = preset.value === 'custom' ? '' : 'none';
validate();
});
btn.addEventListener('click', async () => {
btn.disabled = true; btn.textContent = 'Saving...';
const data = {
TOTAL_BUDGET: parseFloat(document.getElementById('budget').value) || 10,
OUROBOROS_MODEL: document.getElementById('model').value.trim() || 'anthropic/claude-sonnet-4.6',
};
const orKey = keyInput.value.trim();
if (orKey.length >= 10) data.OPENROUTER_API_KEY = orKey;
const oaiKey = document.getElementById('openai-key').value.trim();
if (oaiKey.length >= 10) data.OPENAI_API_KEY = oaiKey;
const p = preset.value;
if (p && p !== 'custom' && PRESETS[p]) {
data.LOCAL_MODEL_SOURCE = PRESETS[p].source;
data.LOCAL_MODEL_FILENAME = PRESETS[p].filename;
data.LOCAL_MODEL_CONTEXT_LENGTH = PRESETS[p].ctx;
data.LOCAL_MODEL_N_GPU_LAYERS = 0;
data.USE_LOCAL_MAIN = !orKey;
data.USE_LOCAL_LIGHT = !orKey;
data.USE_LOCAL_CODE = !orKey;
data.USE_LOCAL_FALLBACK = true;
} else if (p === 'custom') {
data.LOCAL_MODEL_SOURCE = document.getElementById('local-source').value.trim();
data.LOCAL_MODEL_FILENAME = document.getElementById('local-filename').value.trim();
data.LOCAL_MODEL_N_GPU_LAYERS = 0;
data.USE_LOCAL_MAIN = !orKey;
data.USE_LOCAL_LIGHT = !orKey;
data.USE_LOCAL_CODE = !orKey;
data.USE_LOCAL_FALLBACK = true;
}
const result = await window.pywebview.api.save_wizard(data);
if (result === 'ok') { btn.textContent = 'Starting...'; }
else { document.getElementById('err').style.display='block';
document.getElementById('err').textContent=result; btn.disabled=false; btn.textContent='Start Ouroboros'; }
});
</script></body></html>"""
def _save_settings(settings: dict) -> None:
save_settings(settings)
def _run_first_run_wizard() -> bool:
"""Show setup wizard if no API key or local model configured. Returns True if configured."""
settings = _load_settings()
if settings.get("OPENROUTER_API_KEY") or settings.get("LOCAL_MODEL_SOURCE"):
return True
import webview
_wizard_done = {"ok": False}
class WizardApi:
def save_wizard(self, data: dict) -> str:
key = str(data.get("OPENROUTER_API_KEY", "")).strip()
has_local = bool(data.get("LOCAL_MODEL_SOURCE", "").strip())
if len(key) < 10 and not has_local:
return "Provide an OpenRouter API key or select a local model."
settings.update(data)
try:
_save_settings(settings)
_wizard_done["ok"] = True
for w in webview.windows:
w.destroy()
return "ok"
except Exception as e:
return f"Failed to save: {e}"
webview.create_window(
"Ouroboros — Setup",
html=_WIZARD_HTML,
js_api=WizardApi(),
width=520,
height=480,
)
webview.start()
return _wizard_done["ok"]
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main():
import webview
if not acquire_pid_lock():
log.error("Another instance already running.")
webview.create_window(
"Ouroboros",
html="<html><body style='background:#1a1a2e;color:white;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0'>"
"<div style='text-align:center'><h2>Ouroboros is already running</h2><p>Only one instance can run at a time.</p></div></body></html>",
width=420, height=200,
)
webview.start()
return
import atexit
atexit.register(release_pid_lock)
# Check git
if not check_git():
log.warning("Git not found.")
_result = {"installed": False}
def _git_page(window):
window.evaluate_js("""
document.getElementById('install-btn').onclick = function() {
document.getElementById('status').textContent = 'Installing... A system dialog may appear.';
window.pywebview.api.install_git();
};
""")
class GitApi:
def install_git(self):
subprocess.Popen(["xcode-select", "--install"])
for _ in range(300):
time.sleep(3)
if shutil.which("git"):
_result["installed"] = True
return "installed"
return "timeout"
git_window = webview.create_window(
"Ouroboros — Setup Required",
html="""<html><body style="background:#1a1a2e;color:white;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0">
<div style="text-align:center">
<h2>Git is required</h2>
<p>Ouroboros needs Git to manage its local repository.</p>
<button id="install-btn" style="padding:10px 24px;border-radius:8px;border:none;background:#0ea5e9;color:white;cursor:pointer;font-size:14px">
Install Git (Xcode CLI Tools)
</button>
<p id="status" style="color:#fbbf24;margin-top:12px"></p>
</div></body></html>""",
js_api=GitApi(),
width=520, height=300,
)
webview.start(func=_git_page, args=[git_window])
if not check_git():
sys.exit(1)
# Bootstrap
bootstrap_repo()
# First-run wizard (API key)
if not _run_first_run_wizard():
log.info("Wizard was closed without saving. Launching anyway (Settings page available).")
global _webview_window
port = AGENT_SERVER_PORT
# Start agent lifecycle in background
lifecycle_thread = threading.Thread(target=agent_lifecycle_loop, args=(port,), daemon=True)
lifecycle_thread.start()
# Wait for server to be ready, then read actual port (may differ if default was busy)
_wait_for_server(port, timeout=15)
actual_port = _read_port_file()
if actual_port != port:
_wait_for_server(actual_port, timeout=45)
else:
_wait_for_server(port, timeout=45)
url = f"http://127.0.0.1:{actual_port}"
window = webview.create_window(
f"Ouroboros v{APP_VERSION}",
url=url,
width=1100,
height=750,
min_size=(800, 500),
background_color="#0d0b0f",
text_select=True,
)
def _on_closing():
log.info("Window closing — graceful shutdown.")
_shutdown_event.set()
stop_agent()
_kill_orphaned_children()
release_pid_lock()
os._exit(0)
def _kill_orphaned_children():
"""Final safety net: kill any processes still on the server port.
After stop_agent() sends SIGTERM/SIGKILL to server.py, worker
grandchildren may survive as orphans (fork on macOS). Sweeping
the port guarantees nothing lingers.
"""
_kill_stale_on_port(port)
_kill_stale_on_port(8766)
import signal
for child in __import__('multiprocessing').active_children():
try:
os.kill(child.pid, signal.SIGKILL)
log.info("Killed orphaned child pid=%d", child.pid)
except (ProcessLookupError, PermissionError, OSError):
pass
window.events.closing += _on_closing
_webview_window = window
webview.start(debug=False)
if __name__ == "__main__":
from multiprocessing import freeze_support
freeze_support()
if sys.platform == "darwin":
try:
_shell_path = subprocess.check_output(
["/bin/bash", "-l", "-c", "echo $PATH"], text=True, timeout=5,
).strip()
if _shell_path:
os.environ["PATH"] = _shell_path
except Exception:
pass
main()