Oldmangrizzz commited on
Commit
1b8acbd
·
verified ·
1 Parent(s): c188b33

Upload genesis_launch.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. genesis_launch.py +311 -0
genesis_launch.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Enhanced Launch Script with Genesis Integration
4
+ Generated by Uatu Genesis Engine
5
+
6
+ Handles:
7
+ - Secure credential vault (local .env)
8
+ - Avatar generation via Flux (first boot)
9
+ - Construct narrative loading
10
+ - System context injection
11
+ """
12
+ import sys
13
+ import os
14
+ import time
15
+ import logging
16
+ from pathlib import Path
17
+
18
+ # Configure logging
19
+ logging.basicConfig(
20
+ level=logging.INFO,
21
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
22
+ )
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # Add agent-zero to path
26
+ agent_zero_path = Path(__file__).parent.parent.parent / "agent_zero_framework"
27
+ sys.path.insert(0, str(agent_zero_path))
28
+
29
+ def secure_boot_sequence():
30
+ """
31
+ Handles secure credential injection via local .env vault.
32
+ Ensures keys exist in memory but are not committed to git.
33
+ """
34
+ print("\n" + "="*60)
35
+ print(" 🛡️ GRIZZLY MEDICINE: SECURE BOOT PROTOCOL (V2.0)")
36
+ print("="*60)
37
+
38
+ # 1. Define Vault Paths
39
+ # Navigate up from persona directory to repo root
40
+ persona_dir = Path(__file__).parent
41
+ agent_zero_dir = persona_dir.parent.parent
42
+ repo_root = agent_zero_dir.parent
43
+ vault_path = repo_root / ".env"
44
+
45
+ # 2. Check for existing vault
46
+ if vault_path.exists():
47
+ print(">> DETECTED LOCAL VAULT (.env)")
48
+ print(">> DECRYPTING CREDENTIALS...")
49
+
50
+ # Use python-dotenv for robust parsing (handles quotes, escaping, etc.)
51
+ try:
52
+ from dotenv import dotenv_values
53
+ env_vars = dotenv_values(vault_path)
54
+
55
+ # Validate and inject environment variables
56
+ count = 0
57
+ allowed_keys = {
58
+ 'OPENROUTER_API_KEY', 'HF_TOKEN', 'HUGGING_FACE_HUB_TOKEN',
59
+ 'GITHUB_TOKEN', 'CONVEX_URL', 'CONVEX_ADMIN_KEY'
60
+ }
61
+
62
+ for key, value in env_vars.items():
63
+ # Only load whitelisted keys for security
64
+ if key in allowed_keys and value:
65
+ os.environ[key] = value
66
+ count += 1
67
+
68
+ print(f">> {count} KEYS INJECTED FROM .env")
69
+
70
+ # Also load .env.convex if it exists (auto-generated during genesis)
71
+ convex_vault_path = repo_root / ".env.convex"
72
+ if convex_vault_path.exists():
73
+ print(">> DETECTED CONVEX VAULT (.env.convex)")
74
+ convex_vars = dotenv_values(convex_vault_path)
75
+ convex_count = 0
76
+ for key, value in convex_vars.items():
77
+ if key in allowed_keys and value:
78
+ os.environ[key] = value
79
+ convex_count += 1
80
+ print(f">> {convex_count} CONVEX KEYS INJECTED")
81
+
82
+ time.sleep(1)
83
+ return
84
+ except ImportError:
85
+ # Fallback to manual parsing if python-dotenv not available
86
+ count = 0
87
+ with open(vault_path, "r", encoding='utf-8') as f:
88
+ for line in f:
89
+ line = line.strip()
90
+ # Skip empty lines and comments
91
+ if not line or line.startswith("#"):
92
+ continue
93
+ if "=" in line:
94
+ key, value = line.split("=", 1)
95
+ # Strip whitespace and remove quotes if present
96
+ key = key.strip()
97
+ value = value.strip().strip('"').strip("'")
98
+ # Validate key format (alphanumeric and underscores only)
99
+ if key and key.replace('_', '').isalnum():
100
+ os.environ[key] = value
101
+ count += 1
102
+
103
+ print(f">> {count} KEYS INJECTED FROM .env")
104
+
105
+ # Also load .env.convex if it exists (fallback parsing)
106
+ convex_vault_path = repo_root / ".env.convex"
107
+ if convex_vault_path.exists():
108
+ print(">> DETECTED CONVEX VAULT (.env.convex)")
109
+ convex_count = 0
110
+ with open(convex_vault_path, "r", encoding='utf-8') as f:
111
+ for line in f:
112
+ line = line.strip()
113
+ if not line or line.startswith("#"):
114
+ continue
115
+ if "=" in line:
116
+ key, value = line.split("=", 1)
117
+ key = key.strip()
118
+ value = value.strip().strip('"').strip("'")
119
+ if key and key.replace('_', '').isalnum():
120
+ os.environ[key] = value
121
+ convex_count += 1
122
+ print(f">> {convex_count} CONVEX KEYS INJECTED")
123
+
124
+ time.sleep(1)
125
+ return
126
+
127
+ # 3. First Run - Manual Entry
128
+ print("\n[FIRST RUN DETECTED - SYSTEM CONFIGURATION REQUIRED]")
129
+ print("Please enter credentials. They will be saved locally to .env")
130
+ print("and automatically added to .gitignore.\n")
131
+
132
+ # The Four Pillars
133
+ or_key = input("1. OpenRouter Key (The Brain): ").strip()
134
+ hf_key = input("2. Hugging Face Token (The Face): ").strip()
135
+ gh_key = input("3. GitHub Token (The Hands): ").strip()
136
+
137
+ print("\n[CONVEX SETUP]")
138
+ print(" Go to https://dashboard.convex.dev -> Create Project")
139
+ print(" Settings -> URL & Deploy Key")
140
+ convex_url = input("4. Convex Deployment URL (The Memory): ").strip()
141
+ convex_key = input("5. Convex Admin Key (Optional - for Admin): ").strip()
142
+
143
+ # Inject into current session immediately (only if non-empty)
144
+ if or_key: os.environ["OPENROUTER_API_KEY"] = or_key
145
+ if hf_key:
146
+ os.environ["HF_TOKEN"] = hf_key
147
+ os.environ["HUGGING_FACE_HUB_TOKEN"] = hf_key
148
+ if gh_key: os.environ["GITHUB_TOKEN"] = gh_key
149
+ if convex_url: os.environ["CONVEX_URL"] = convex_url
150
+ if convex_key: os.environ["CONVEX_ADMIN_KEY"] = convex_key
151
+
152
+ # 4. Save to Vault
153
+ save = input("\n>> SAVE CREDENTIALS TO LOCAL VAULT (.env)? [Y/N]: ").strip().upper()
154
+ if save == "Y":
155
+ # Use python-dotenv for robust writing (handles escaping automatically)
156
+ try:
157
+ from dotenv import set_key
158
+
159
+ # Write each credential safely with automatic escaping
160
+ if or_key:
161
+ set_key(vault_path, "OPENROUTER_API_KEY", or_key)
162
+ if hf_key:
163
+ set_key(vault_path, "HF_TOKEN", hf_key)
164
+ set_key(vault_path, "HUGGING_FACE_HUB_TOKEN", hf_key)
165
+ if gh_key:
166
+ set_key(vault_path, "GITHUB_TOKEN", gh_key)
167
+ if convex_url:
168
+ set_key(vault_path, "CONVEX_URL", convex_url)
169
+ if convex_key:
170
+ set_key(vault_path, "CONVEX_ADMIN_KEY", convex_key)
171
+
172
+ print(">> VAULT CREATED.")
173
+ except ImportError:
174
+ # Fallback to manual writing with proper escaping
175
+ with open(vault_path, "w", encoding='utf-8') as f:
176
+ # Escape double quotes in values
177
+ if or_key:
178
+ escaped_val = or_key.replace('"', '\\"')
179
+ f.write(f'OPENROUTER_API_KEY="{escaped_val}"\n')
180
+ if hf_key:
181
+ escaped_val = hf_key.replace('"', '\\"')
182
+ f.write(f'HF_TOKEN="{escaped_val}"\n')
183
+ f.write(f'HUGGING_FACE_HUB_TOKEN="{escaped_val}"\n')
184
+ if gh_key:
185
+ escaped_val = gh_key.replace('"', '\\"')
186
+ f.write(f'GITHUB_TOKEN="{escaped_val}"\n')
187
+ if convex_url:
188
+ escaped_val = convex_url.replace('"', '\\"')
189
+ f.write(f'CONVEX_URL="{escaped_val}"\n')
190
+ if convex_key:
191
+ escaped_val = convex_key.replace('"', '\\"')
192
+ f.write(f'CONVEX_ADMIN_KEY="{escaped_val}"\n')
193
+
194
+ print(">> VAULT CREATED.")
195
+
196
+ # 5. Secure the Vault (Update .gitignore)
197
+ gitignore_path = repo_root / ".gitignore"
198
+ if gitignore_path.exists():
199
+ with open(gitignore_path, "r", encoding='utf-8') as f:
200
+ content = f.read()
201
+ # Check if .env is already in gitignore (look for uncommented lines)
202
+ lines = content.split('\n')
203
+ has_env = False
204
+ for line in lines:
205
+ stripped = line.strip()
206
+ # Skip comments
207
+ if stripped.startswith('#'):
208
+ continue
209
+ # Check for .env patterns (with or without leading slash/wildcards)
210
+ if stripped in ['.env', '*.env', '**/.env', '/.env']:
211
+ has_env = True
212
+ break
213
+ if not has_env:
214
+ with open(gitignore_path, "a", encoding='utf-8') as f:
215
+ f.write("\n# Local Credential Vault\n.env\n")
216
+ print(">> .env ADDED TO .gitignore (SAFE FROM UPLOAD)")
217
+ else:
218
+ # Create gitignore if missing
219
+ with open(gitignore_path, "w", encoding='utf-8') as f:
220
+ f.write(".env\n")
221
+ print(">> .gitignore CREATED.")
222
+
223
+ else:
224
+ print(">> WARNING: RUNNING IN EPHEMERAL MODE. KEYS WILL VANISH ON EXIT.")
225
+
226
+ print("\n>> SYSTEMS ONLINE. WAKING DIGITAL PERSON...")
227
+ time.sleep(2)
228
+
229
+ def genesis_sequence():
230
+ """Execute the Genesis Sequence (first boot initialization)."""
231
+ try:
232
+ # Check for avatar
233
+ avatar_path = Path("/app/persona_data/avatar.png")
234
+ if not avatar_path.exists():
235
+ logger.info(">> GENESIS SEQUENCE: FORGING PHYSICAL FORM VIA FLUX...")
236
+
237
+ try:
238
+ from python.helpers.rsi_generator import ensure_avatar_exists
239
+ success = ensure_avatar_exists(
240
+ persona_path="/Users/grizzmed/Stark/uatu-engine/agent_zero_framework/agents/agent"
241
+ )
242
+ if success:
243
+ logger.info(">> AVATAR FORGED SUCCESSFULLY")
244
+ else:
245
+ logger.warning(">> AVATAR GENERATION FAILED (CONTINUING WITHOUT AVATAR)")
246
+ except Exception as e:
247
+ logger.error(f">> AVATAR GENERATION ERROR: {e}")
248
+ logger.warning(">> CONTINUING WITHOUT AVATAR")
249
+ else:
250
+ logger.info(">> AVATAR EXISTS: GENESIS COMPLETE")
251
+
252
+ # Load construct narrative if it exists
253
+ construct_path = Path(__file__).parent / "construct.txt"
254
+ if construct_path.exists():
255
+ logger.info(">> LOADING CONSTRUCT NARRATIVE...")
256
+ construct_text = construct_path.read_text()
257
+
258
+ # Store in environment for agent context initialization
259
+ os.environ["CONSTRUCT_NARRATIVE"] = construct_text
260
+ logger.info(">> CONSTRUCT NARRATIVE LOADED INTO SYSTEM CONTEXT")
261
+ else:
262
+ logger.info(">> NO CONSTRUCT NARRATIVE FOUND (OPTIONAL)")
263
+
264
+ except Exception as e:
265
+ logger.error(f"Genesis Sequence Error: {e}")
266
+ logger.warning("Continuing with launch despite errors...")
267
+
268
+ # Set persona-specific environment
269
+ os.environ["AGENT_PROMPTS_DIR"] = str(Path(__file__).parent / "prompts")
270
+ os.environ["WORKSHOP_PERSONA_LOCKED"] = "true"
271
+
272
+ # Execute Secure Boot Sequence FIRST
273
+ secure_boot_sequence()
274
+
275
+ # Verify critical credentials exist
276
+ if "OPENROUTER_API_KEY" not in os.environ:
277
+ logger.error("CRITICAL: OPENROUTER_API_KEY not found in environment")
278
+ logger.error("The persona cannot think without OpenRouter API access")
279
+ sys.exit(1)
280
+
281
+ if "HUGGING_FACE_HUB_TOKEN" not in os.environ and "HF_TOKEN" not in os.environ:
282
+ logger.warning("WARNING: HUGGING_FACE_HUB_TOKEN not found")
283
+ logger.warning("Some features may be limited without Hugging Face access")
284
+
285
+ # Execute Genesis Sequence
286
+ genesis_sequence()
287
+
288
+ # Import and run agent zero
289
+ try:
290
+ from run_ui import run
291
+
292
+ logger.info("=" * 80)
293
+ logger.info("⚙ THE WORKSHOP - GrizzlyMedicine R&D")
294
+ logger.info("=" * 80)
295
+ logger.info(f"Digital Person: Initializing from /Users/grizzmed/Stark/uatu-engine/agent_zero_framework/agents/agent")
296
+ logger.info(f"Container Status: DEDICATED (No persona switching)")
297
+ logger.info("=" * 80)
298
+
299
+ # Launch the UI
300
+ run()
301
+
302
+ except ImportError as e:
303
+ logger.error(f"Error importing agent-zero: {e}")
304
+ logger.error("Make sure agent-zero dependencies are installed:")
305
+ logger.error(" pip install -r agent_zero_framework/requirements.txt")
306
+ sys.exit(1)
307
+ except Exception as e:
308
+ logger.error(f"Error launching: {e}")
309
+ import traceback
310
+ traceback.print_exc()
311
+ sys.exit(1)