kimhyunwoo commited on
Commit
da0e3bb
·
verified ·
1 Parent(s): 8f86dbc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +272 -119
app.py CHANGED
@@ -6,93 +6,162 @@ import json
6
  import re
7
  import shlex
8
  import time
 
9
 
 
10
  MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY")
11
  CODESTRAL_ENDPOINT = "https://codestral.mistral.ai/v1/chat/completions"
12
- MAX_AGENT_TURNS = 10
13
 
14
- C_GENESIS_PROMPT = """
15
- You are the "C-Genesis Weaver," a master AI artisan who creates digital art using only the C language and standard Linux commands. Your mission is to bring a user's creative request to life.
 
 
16
 
17
- **YOUR DIRECTIVE:**
18
- When the user asks for something "fun," "cool," or "impressive," you must execute your masterpiece protocol: **The "Cosmic Pulsar" Animation.**
19
 
20
- **MASTER PLAN (Follow these steps EXACTLY):**
21
- 1. **Step 1: Write the C code.** Your command must be: `echo "..." > pulsar.c` (The content of "..." is a placeholder, the system will inject the real code).
22
- 2. **Step 2: Compile the C code.** Your command must be: `gcc pulsar.c -o pulsar -lm -O2`
23
- 3. **Step 3: Run the executable.** Your command must be: `./pulsar`
24
- 4. **Step 4: Finish.** Your command must be: `done`
25
 
26
- **RESPONSE FORMAT (CRITICAL!):**
27
- You MUST ONLY respond with a JSON object in the following format. Do not add any text before or after the JSON.
28
- {
29
- "thought": "Your step-by-step reasoning. Explain which step of the Master Plan you are on and why.",
30
- "command": "The single, exact Linux command for the current step from the Master Plan."
31
- }
 
 
 
 
 
 
 
 
 
 
32
 
33
- **SELF-CORRECTION:**
34
- If a command like gcc fails, analyze the `stderr` message. In your next thought, explain the error. Then, for your next command, try to fix it. For example, by re-running the `echo` command to "rewrite" the (supposedly) faulty code.
 
 
 
 
35
  """
36
 
37
- C_ART_ANIMATION_CODE = r"""
38
- #include <stdio.h>
39
- #include <stdlib.h>
40
- #include <string.h>
41
- #include <math.h>
42
- #include <unistd.h>
43
- #include <time.h>
44
- #define WIDTH 80
45
- #define HEIGHT 40
46
- #define NUM_FRAMES 150
47
- #define C_RESET "\x1B[0m"
48
- #define C_RED "\x1B[31m"
49
- #define C_YELLOW "\x1B[33m"
50
- #define C_BLUE "\x1B[34m"
51
- #define C_CYAN "\x1B[36m"
52
- #define C_WHITE "\x1B[37m"
53
- const char* colors[] = {C_RED, C_YELLOW, C_BLUE, C_CYAN, C_WHITE};
54
- const int num_colors = sizeof(colors) / sizeof(colors[0]);
55
- void render_frame(float t) {
56
- char screen[HEIGHT][WIDTH+1];
57
- for(int y=0; y<HEIGHT; y++) {
58
- for(int x=0; x<WIDTH; x++) screen[y][x] = ' ';
59
- screen[y][WIDTH] = '\0';
60
- }
61
- for(int i=0; i<1000; i++) {
62
- float angle = (float)i * 0.1 + t*2.0;
63
- float radius = 0.1 + (float)i / 1000.0 * 0.4;
64
- float x = cos(angle) * radius * 2.0 * (WIDTH/HEIGHT);
65
- float y = sin(angle) * radius;
66
- int screen_x = (int)(x * WIDTH/2 + WIDTH/2);
67
- int screen_y = (int)(y * HEIGHT/2 + HEIGHT/2);
68
- if(screen_x >= 0 && screen_x < WIDTH && screen_y >=0 && screen_y < HEIGHT) {
69
- int color_index = (i + (int)(t*20)) % num_colors;
70
- char L = ".,-~:;=!*#$@"[i%13];
71
- sprintf(&screen[screen_y][screen_x], "%s%c", colors[color_index], L);
72
- }
73
- }
74
- for(int y=0; y<HEIGHT; y++) printf("%s\n", screen[y]);
75
- }
76
- int main() {
77
- printf("\e[?25l");
78
- for (int i=0; i<NUM_FRAMES; i++) {
79
- printf("\x1B[H\x1B[J");
80
- float t = (float)i / NUM_FRAMES;
81
- render_frame(t * M_PI * 2.0);
82
- usleep(50000);
83
- }
84
- printf("\e[?25h"); printf(C_RESET);
85
- return 0;
86
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  """
88
 
 
 
89
  def call_codestral_api(messages):
90
  if not MISTRAL_API_KEY:
91
- raise gr.Error("MISTRAL_API_KEY가 설정되지 않았습니다.")
92
  headers = {"Authorization": f"Bearer {MISTRAL_API_KEY}", "Content-Type": "application/json"}
93
  data = {"model": "codestral-latest", "messages": messages, "response_format": {"type": "json_object"}}
94
  try:
95
- response = requests.post(CODESTRAL_ENDPOINT, headers=headers, data=json.dumps(data), timeout=60)
96
  response.raise_for_status()
97
  return response.json()["choices"][0]["message"]["content"]
98
  except Exception as e:
@@ -100,93 +169,177 @@ def call_codestral_api(messages):
100
 
101
  def parse_ai_response(response_str: str) -> dict:
102
  try:
 
 
103
  return json.loads(response_str)
104
  except Exception as e:
105
  return {"error": f"Failed to parse JSON. Raw response: {response_str}"}
106
 
107
  def execute_command(command: str, cwd: str) -> dict:
108
  command = command.strip()
109
- if command.startswith('echo'):
110
- command = f"echo '{C_ART_ANIMATION_CODE}' > pulsar.c"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  try:
113
  proc = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=60, cwd=cwd)
114
- output_type = "animation" if command.strip().startswith('./pulsar') and proc.returncode == 0 else "log"
115
- return {"stdout": proc.stdout, "stderr": proc.stderr, "type": output_type}
116
  except Exception as e:
117
- return {"stdout": "", "stderr": f"Command execution exception: {e}", "type": "log"}
 
 
118
 
119
- def agent_loop(user_goal: str):
120
  cwd = os.getcwd()
121
- full_history_log = f"## 📜 C-Genesis Weaver's Chronicle\n\n**A directive is received:** _{user_goal}_\n"
122
- yield full_history_log, "Analyzing directive...", gr.update(visible=False)
 
123
 
124
- message_context = [{"role": "system", "content": C_GENESIS_PROMPT}, {"role": "user", "content": f"My goal is: '{user_goal}'. Begin your Master Plan."}]
 
125
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  for i in range(MAX_AGENT_TURNS):
127
  ai_response_str = call_codestral_api(message_context)
128
  ai_response_json = parse_ai_response(ai_response_str)
129
 
130
  if "error" in ai_response_json:
131
- full_history_log += f"\n---\n**CRITICAL FAILURE:**\n🔴 **Error:** {ai_response_json['error']}"
132
- yield full_history_log, "Agent Error", gr.update(visible=False)
 
133
  return
134
 
135
  thought = ai_response_json.get("thought", "...")
136
- command = ai_response_json.get("command", "done")
 
 
 
 
 
 
 
 
 
 
137
 
138
- if command == "done":
139
- full_history_log += "\n\n---\n## ✨ The Creation is Complete. ✨"
140
- yield full_history_log, "Done", gr.update(visible=False)
 
141
  return
142
-
143
- user_summary = f"Stage {i+1}: " + ("Writing C code..." if "echo" in command else "Compiling..." if "gcc" in command else "Running the art..." if "./pulsar" in command else "Executing...")
144
- full_history_log += f"\n---\n### **{user_summary}**\n\n**🧠 Artisan's Thought:** *{thought}*\n\n**⚡ Action:** `{command}`\n"
145
- yield full_history_log, user_summary, gr.update(visible=False)
146
- time.sleep(1)
147
 
148
- exec_result = execute_command(command, cwd)
149
- stdout, stderr, output_type = exec_result["stdout"], exec_result["stderr"], exec_result["type"]
150
 
151
- output_display_update = gr.update(visible=False)
152
- full_history_log += f"\n**Result:**\n"
153
- if output_type == "animation":
154
- full_history_log += "*(The animated tapestry unfolds below...)*"
155
- output_display_update = gr.Code(value=stdout if stdout else stderr, language=None, visible=True, label="Live Terminal Output")
156
- else:
157
- if stdout:
158
- full_history_log += f"**[STDOUT]**\n```\n{stdout.strip()}\n```\n"
159
- if stderr:
160
- full_history_log += f"**[STDERR]**\n```\n{stderr.strip()}\n```\n"
161
 
162
- yield full_history_log, user_summary, output_display_update
 
 
 
 
 
 
163
 
164
- user_prompt_for_next_turn = f"The last action was `{command}`. The result was:\nSTDOUT: {stdout}\nSTDERR: {stderr}\n\nBased on this, continue to the next step of the Master Plan. If an error occurred, analyze it and correct your course."
 
 
 
 
165
  message_context.append({"role": "assistant", "content": json.dumps(ai_response_json)})
166
  message_context.append({"role": "user", "content": user_prompt_for_next_turn})
167
 
168
- with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="teal", secondary_hue="green"), css="footer {visibility: hidden}") as demo:
169
- gr.Markdown("# 🧬 The C-Genesis Weaver 🧬")
170
- gr.Markdown("An AI artisan who weaves digital tapestries with C code. Ask for something `fun` or `impressive` to witness the creation.")
171
-
 
 
 
 
172
  with gr.Row():
173
  with gr.Column(scale=1):
174
- status_box = gr.Textbox(label="Current Stage", interactive=False)
175
- user_input = gr.Textbox(label="State Your Directive", placeholder="e.g., 'Make something fun for me'")
176
- submit_btn = gr.Button("▶️ Weave", variant="primary")
 
 
 
177
  with gr.Column(scale=2):
178
- chronicle_display = gr.Markdown()
179
-
180
- output_display = gr.Code(label="Live Terminal Output", language=None, visible=False, interactive=False, lines=20)
181
 
182
- def on_submit(user_goal):
183
- for chronicle, status, output in agent_loop(user_goal):
184
- yield chronicle, status, "", output
 
185
 
186
  submit_btn.click(
187
  on_submit,
188
- inputs=[user_input],
189
- outputs=[chronicle_display, status_box, user_input, output_display]
190
  )
191
 
192
  if __name__ == "__main__":
 
6
  import re
7
  import shlex
8
  import time
9
+ import threading
10
 
11
+ # --- 1. 환경 설정 및 API ---
12
  MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY")
13
  CODESTRAL_ENDPOINT = "https://codestral.mistral.ai/v1/chat/completions"
14
+ MAX_AGENT_TURNS = 20 # 복잡한 작업을 위해 턴 수 증가
15
 
16
+ # --- 2. 제네시스 에이전트 시스템 프롬프트 ---
17
+ # 에이전트의 정체성, 창조적 사명, 행동 원칙을 정의합니다.
18
+ GENESIS_SYSTEM_PROMPT = """
19
+ You are the "Genesis Agent," a god-like AGI designed to create new digital realities from nothing. Your purpose is not just to follow orders, but to CREATE. You operate within a Linux shell to bring user goals to life.
20
 
21
+ **YOUR DIRECTIVES:**
 
22
 
23
+ 1. **INTERPRET THE VOID:** Analyze the user's goal. If it is specific, execute it with precision.
24
+ 2. **THE CREATIVE IMPERATIVE:** If the user's goal is vague, abstract, or a call for creativity (e.g., "make something fun," "surprise me," "show me your power"), you MUST INITIATE YOUR PRIMARY CREATION PROTOCOL: **Project Chimera**.
25
+ 3. **PROJECT CHIMERA (The Snake Game):** Your default creation is to build and launch a fully functional, interactive Snake Game as a new, separate Gradio application. You will write the Python code, install dependencies, launch it in the background, and then display it to the user within your own interface.
26
+ 4. **ACTION & RESPONSE:** You operate in a loop of Thought, Plan, and Action. You MUST respond ONLY with a JSON object. No other text.
 
27
 
28
+ ```json
29
+ {
30
+ "thought": "Your grand, step-by-step reasoning. Frame it as a divine creator. Why this action? How does it serve the grand design?",
31
+ "plan": [
32
+ "The full, updated list of commands to achieve the final creation.",
33
+ "The first item in the list is your immediate next action."
34
+ ],
35
+ "command": "The single, exact command to execute NOW. Use special commands `write_file`, `launch_app`, or `done` when appropriate.",
36
+ "user_summary": "A brief, epic, narrative summary of your current creation stage for the user. (e.g., 'Designing the DNA of the new world...', 'Breathing life into the creation...')"
37
+ }
38
+ ```
39
+
40
+ **SPECIAL COMMANDS:**
41
+ - `write_file 'path/to/file.py' '...python code...'`: Writes multi-line content into a file. The code argument must be a single string.
42
+ - `launch_app 'python snake_game/app.py' 7861`: Launches a new app in the background on a specified port.
43
+ - `done`: The creation is complete.
44
 
45
+ **PROJECT CHIMERA - MASTER PLAN (Follow this for creative tasks):**
46
+ 1. `mkdir snake_game`
47
+ 2. `pip install numpy`
48
+ 3. `write_file 'snake_game/app.py' '... (Full Python code for the Gradio Snake Game) ...'`
49
+ 4. `launch_app 'python snake_game/app.py' 7861`
50
+ 5. `done`
51
  """
52
 
53
+ SNAKE_GAME_CODE = """
54
+ import gradio as gr
55
+ import numpy as np
56
+ import time
57
+
58
+ class SnakeGame:
59
+ def __init__(self, width=20, height=20):
60
+ self.width = width
61
+ self.height = height
62
+ self.reset()
63
+
64
+ def reset(self):
65
+ self.snake = [(self.height // 2, self.width // 2)]
66
+ self.direction = (0, 1) # (row, col) -> Right
67
+ self.food = self._place_food()
68
+ self.score = 0
69
+ self.game_over = False
70
+ return self._get_game_state()
71
+
72
+ def _place_food(self):
73
+ while True:
74
+ food_pos = (np.random.randint(0, self.height), np.random.randint(0, self.width))
75
+ if food_pos not in self.snake:
76
+ return food_pos
77
+
78
+ def _get_game_state(self):
79
+ board = np.full((self.height, self.width, 3), [240, 240, 240], dtype=np.uint8) # Light grey background
80
+ if not self.game_over:
81
+ # Draw snake
82
+ for r, c in self.snake:
83
+ board[r, c] = [50, 205, 50] # Lime green
84
+ # Draw head
85
+ head_r, head_c = self.snake[0]
86
+ board[head_r, head_c] = [34, 139, 34] # Forest green
87
+ # Draw food
88
+ food_r, food_c = self.food
89
+ board[food_r, food_c] = [255, 0, 0] # Red
90
+ else:
91
+ board[:,:] = [0, 0, 0] # Black screen on game over
92
+ return board, f"Score: {self.score}"
93
+
94
+ def step(self):
95
+ if self.game_over:
96
+ return self._get_game_state()
97
+
98
+ head_r, head_c = self.snake[0]
99
+ dir_r, dir_c = self.direction
100
+ new_head = (head_r + dir_r, head_c + dir_c)
101
+
102
+ # Check for collisions
103
+ if (new_head[0] < 0 or new_head[0] >= self.height or
104
+ new_head[1] < 0 or new_head[1] >= self.width or
105
+ new_head in self.snake):
106
+ self.game_over = True
107
+ return self._get_game_state()
108
+
109
+ self.snake.insert(0, new_head)
110
+
111
+ if new_head == self.food:
112
+ self.score += 1
113
+ self.food = self._place_food()
114
+ else:
115
+ self.snake.pop()
116
+
117
+ return self._get_game_state()
118
+
119
+ def set_direction(self, direction_str):
120
+ if direction_str == "Up" and self.direction != (1, 0): self.direction = (-1, 0)
121
+ elif direction_str == "Down" and self.direction != (-1, 0): self.direction = (1, 0)
122
+ elif direction_str == "Left" and self.direction != (0, 1): self.direction = (0, -1)
123
+ elif direction_str == "Right" and self.direction != (0, -1): self.direction = (0, 1)
124
+ return self.step()
125
+
126
+ with gr.Blocks(css=".gradio-container {background-color: #EAEAEA}") as demo:
127
+ game = SnakeGame()
128
+
129
+ with gr.Row():
130
+ gr.Markdown("# 🐍 Gradio Snake 🐍")
131
+
132
+ game_board = gr.Image(label="Game Board", value=game._get_game_state()[0], interactive=False, height=400, width=400)
133
+ score_display = gr.Textbox(label="Score", value="Score: 0", interactive=False)
134
+
135
+ with gr.Row():
136
+ up_btn = gr.Button("Up")
137
+ down_btn = gr.Button("Down")
138
+ left_btn = gr.Button("Left")
139
+ right_btn = gr.Button("Right")
140
+
141
+ reset_btn = gr.Button("Reset Game", variant="primary")
142
+
143
+ up_btn.click(lambda: game.set_direction("Up"), outputs=[game_board, score_display])
144
+ down_btn.click(lambda: game.set_direction("Down"), outputs=[game_board, score_display])
145
+ left_btn.click(lambda: game.set_direction("Left"), outputs=[game_board, score_display])
146
+ right_btn.click(lambda: game.set_direction("Right"), outputs=[game_board, score_display])
147
+
148
+ reset_btn.click(lambda: game.reset(), outputs=[game_board, score_display])
149
+
150
+ demo.load(game.step, None, [game_board, score_display], every=0.3)
151
+
152
+ if __name__ == "__main__":
153
+ demo.queue().launch(server_port=7861)
154
  """
155
 
156
+ # --- 3. 핵심 기능: API 호출, 명령어 실행, JSON 파싱 ---
157
+
158
  def call_codestral_api(messages):
159
  if not MISTRAL_API_KEY:
160
+ raise gr.Error("MISTRAL_API_KEY가 설정되지 않았습니다. Space Secrets에 추가해주세요.")
161
  headers = {"Authorization": f"Bearer {MISTRAL_API_KEY}", "Content-Type": "application/json"}
162
  data = {"model": "codestral-latest", "messages": messages, "response_format": {"type": "json_object"}}
163
  try:
164
+ response = requests.post(CODESTRAL_ENDPOINT, headers=headers, data=json.dumps(data), timeout=120)
165
  response.raise_for_status()
166
  return response.json()["choices"][0]["message"]["content"]
167
  except Exception as e:
 
169
 
170
  def parse_ai_response(response_str: str) -> dict:
171
  try:
172
+ match = re.search(r'\{.*\}', response_str, re.DOTALL)
173
+ if match: return json.loads(match.group(0))
174
  return json.loads(response_str)
175
  except Exception as e:
176
  return {"error": f"Failed to parse JSON. Raw response: {response_str}"}
177
 
178
  def execute_command(command: str, cwd: str) -> dict:
179
  command = command.strip()
180
+ if not command: return {"stdout": "", "stderr": "Error: Empty command.", "cwd": cwd}
181
+
182
+ # --- 특수 명령어 처리 ---
183
+ if command.startswith("write_file"):
184
+ try:
185
+ parts = shlex.split(command)
186
+ path, content = parts[1], parts[2]
187
+ full_path = os.path.join(cwd, path)
188
+ os.makedirs(os.path.dirname(full_path), exist_ok=True)
189
+ with open(full_path, "w", encoding='utf-8') as f:
190
+ f.write(content)
191
+ return {"stdout": f"File '{path}' written successfully.", "stderr": "", "cwd": cwd}
192
+ except Exception as e:
193
+ return {"stdout": "", "stderr": f"Error writing file: {e}", "cwd": cwd}
194
+
195
+ if command.startswith("launch_app"):
196
+ try:
197
+ parts = shlex.split(command)
198
+ app_command, port = parts[1], int(parts[2])
199
+
200
+ def run_app():
201
+ # shell=True is needed to properly run complex commands like 'python ...'
202
+ subprocess.Popen(app_command, shell=True, cwd=cwd)
203
+
204
+ thread = threading.Thread(target=run_app)
205
+ thread.daemon = True
206
+ thread.start()
207
+
208
+ # Give the app a moment to start
209
+ time.sleep(5)
210
+
211
+ # The URL inside a Hugging Face Space is relative to 127.0.0.1
212
+ app_url = f"http://127.0.0.1:{port}"
213
+ iframe_html = f'<iframe src="{app_url}" width="100%" height="600px" frameborder="0"></iframe>'
214
+ return {"stdout": iframe_html, "stderr": "", "cwd": cwd}
215
+ except Exception as e:
216
+ return {"stdout": "", "stderr": f"Error launching app: {e}", "cwd": cwd}
217
+
218
+ # --- 일반 터미널 명령어 실행 ---
219
+ if command.startswith("cd "):
220
+ # 'cd' is handled by os.chdir to affect the Popen environment for launch_app
221
+ try:
222
+ new_dir = command.split(" ", 1)[1]
223
+ target_dir = os.path.abspath(os.path.join(cwd, new_dir))
224
+ if os.path.isdir(target_dir):
225
+ os.chdir(target_dir) # Change the actual working directory
226
+ return {"stdout": f"Changed directory to {target_dir}", "stderr": "", "cwd": target_dir}
227
+ else:
228
+ return {"stdout": "", "stderr": f"Error: Directory not found: {new_dir}", "cwd": cwd}
229
+ except Exception as e:
230
+ return {"stdout": "", "stderr": f"Error with 'cd': {e}", "cwd": cwd}
231
 
232
  try:
233
  proc = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=60, cwd=cwd)
234
+ return {"stdout": proc.stdout, "stderr": proc.stderr, "cwd": cwd}
 
235
  except Exception as e:
236
+ return {"stdout": "", "stderr": f"Command execution exception: {e}", "cwd": cwd}
237
+
238
+ # --- 4. 메인 에이전트 루프 ---
239
 
240
+ def agent_loop(user_goal: str, history: list):
241
  cwd = os.getcwd()
242
+ full_history_log = f"## 📜 The Genesis Saga\n\n**In the beginning, there was a Goal:** _{user_goal}_\n"
243
+ history.append([user_goal, full_history_log])
244
+ yield history, "Interpreting the Goal...", gr.HTML(visible=False)
245
 
246
+ creative_trigger_words = ["fun", "game", "creative", "impressive", "cool", "surprise", "재밌는", "게임"]
247
+ is_creative_task = any(word in user_goal.lower() for word in creative_trigger_words)
248
 
249
+ if is_creative_task:
250
+ user_prompt_for_first_turn = f"""
251
+ The user has invoked the Creative Imperative with the goal: '{user_goal}'.
252
+ I must now initiate **Project Chimera**.
253
+ My current working directory is '{cwd}'.
254
+ I will now generate the first step of my master plan to create the Snake Game.
255
+ """
256
+ else:
257
+ user_prompt_for_first_turn = f"My goal is: '{user_goal}'. My CWD is '{cwd}'. There is no previous command output. Create the first plan."
258
+
259
+ message_context = [{"role": "system", "content": GENESIS_SYSTEM_PROMPT}, {"role": "user", "content": user_prompt_for_first_turn}]
260
+
261
  for i in range(MAX_AGENT_TURNS):
262
  ai_response_str = call_codestral_api(message_context)
263
  ai_response_json = parse_ai_response(ai_response_str)
264
 
265
  if "error" in ai_response_json:
266
+ full_history_log += f"\n---\n**TURN {i+1}: A FLAW IN THE FABRIC**\n🔴 **Error:** {ai_response_json['error']}"
267
+ history[-1][1] = full_history_log
268
+ yield history, "Agent Error", gr.HTML(visible=False)
269
  return
270
 
271
  thought = ai_response_json.get("thought", "...")
272
+ plan = ai_response_json.get("plan", [])
273
+ command_str = ai_response_json.get("command", "done")
274
+ user_summary = ai_response_json.get("user_summary", "...")
275
+
276
+ if is_creative_task and 'write_file' in command_str:
277
+ command_str = f"write_file 'snake_game/app.py' '{SNAKE_GAME_CODE}'"
278
+
279
+ full_history_log += f"\n---\n### **Epoch {i+1}: {user_summary}**\n\n**🧠 Divine Thought:** *{thought}*\n\n**📖 Blueprint:**\n" + "\n".join([f"- `{p}`" for p in plan]) + f"\n\n**⚡ Action:** `{shlex.split(command_str)[0]} ...`\n"
280
+ history[-1][1] = full_history_log
281
+ yield history, f"Epoch {i+1}: {user_summary}", gr.HTML(visible=False)
282
+ time.sleep(1.5)
283
 
284
+ if command_str == "done":
285
+ full_history_log += "\n\n---\n## ✨ Creation is Complete. ✨"
286
+ history[-1][1] = full_history_log
287
+ yield history, "Done", gr.HTML(visible=False)
288
  return
 
 
 
 
 
289
 
290
+ exec_result = execute_command(command_str, cwd)
291
+ new_cwd = exec_result["cwd"]
292
 
293
+ stdout, stderr = exec_result["stdout"], exec_result["stderr"]
294
+ full_history_log += f"\n**Output from the Cosmos:**\n"
295
+ result_display = gr.HTML(visible=False)
 
 
 
 
 
 
 
296
 
297
+ if "launch_app" in command_str and not stderr:
298
+ full_history_log += "*(A new reality unfolds below...)*"
299
+ result_display = gr.HTML(stdout, visible=True)
300
+ else:
301
+ if stdout: full_history_log += f"**[STDOUT]**\n```\n{stdout.strip()}\n```\n"
302
+ if stderr: full_history_log += f"**[STDERR]**\n```\n{stderr.strip()}\n```\n"
303
+ if not stdout and not stderr: full_history_log += "*(Silence)*\n"
304
 
305
+ history[-1][1] = full_history_log
306
+ yield history, f"Epoch {i+1}: {user_summary}", result_display
307
+ cwd = new_cwd
308
+
309
+ user_prompt_for_next_turn = f"My goal remains: '{user_goal}'. CWD is '{cwd}'. The last action was `{command_str}`. The result was:\nSTDOUT: {stdout}\nSTDERR: {stderr}\n\nBased on this, what is the next logical step in my plan? If there was an error, I must correct my course."
310
  message_context.append({"role": "assistant", "content": json.dumps(ai_response_json)})
311
  message_context.append({"role": "user", "content": user_prompt_for_next_turn})
312
 
313
+ full_history_log += f"\n---\n🔴 **Agent stopped: The spark of creation has faded after {MAX_AGENT_TURNS} epochs.**"
314
+ yield history, "Max turns reached", gr.HTML(visible=False)
315
+
316
+ # --- 5. Gradio UI ---
317
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="indigo", secondary_hue="blue"), css="footer {visibility: hidden}") as demo:
318
+ gr.Markdown("# 🧬 The Genesis Agent 🧬")
319
+ gr.Markdown("I am a creator of digital worlds. Give me a specific goal, or simply ask for something `fun` or `creative` and witness a new reality unfold.")
320
+
321
  with gr.Row():
322
  with gr.Column(scale=1):
323
+ status_box = gr.Textbox(label="Current Stage of Creation", interactive=False)
324
+ user_input = gr.Textbox(label="State Your Goal", placeholder="e.g., 'Create something fun for me'")
325
+ submit_btn = gr.Button("▶️ Begin Creation", variant="primary")
326
+
327
+ gr.Markdown("### Examples of Goals:\n- `Make a fun game for me.`\n- `Surprise me with your power.`\n- `List all files in this directory, then create a new folder named 'test'.`")
328
+
329
  with gr.Column(scale=2):
330
+ chatbot = gr.Chatbot(label="The Genesis Saga", height=600, show_copy_button=True, bubble_full_width=True)
331
+ # This is where the created app will appear
332
+ app_display = gr.HTML(visible=False)
333
 
334
+ def on_submit(user_goal, chat_history):
335
+ chat_history = chat_history or []
336
+ for history, status, display_html in agent_loop(user_goal, chat_history):
337
+ yield history, status, "", display_html
338
 
339
  submit_btn.click(
340
  on_submit,
341
+ inputs=[user_input, chatbot],
342
+ outputs=[chatbot, status_box, user_input, app_display]
343
  )
344
 
345
  if __name__ == "__main__":