quasar-core 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. bridge.py +629 -0
  2. bridge_history.py +997 -0
  3. quasar_core-0.1.0.dist-info/METADATA +280 -0
  4. quasar_core-0.1.0.dist-info/RECORD +48 -0
  5. quasar_core-0.1.0.dist-info/WHEEL +4 -0
  6. quasar_core-0.1.0.dist-info/entry_points.txt +2 -0
  7. quasar_core-0.1.0.dist-info/licenses/LICENSE +667 -0
  8. quasar_launcher.py +66 -0
  9. quasar_node/dist/cli.js +62000 -0
  10. quasar_node/package.json +40 -0
  11. src/__init__.py +7 -0
  12. src/agents/__init__.py +15 -0
  13. src/agents/evaluator.py +591 -0
  14. src/agents/operator.py +979 -0
  15. src/agents/strategist.py +1015 -0
  16. src/agents/utils/__init__.py +168 -0
  17. src/agents/utils/bridge.py +77 -0
  18. src/agents/utils/errors.py +230 -0
  19. src/agents/utils/logging.py +291 -0
  20. src/agents/utils/streaming.py +381 -0
  21. src/agents/utils/system.py +373 -0
  22. src/agents/utils/text.py +156 -0
  23. src/agents/utils/tool_helpers.py +1189 -0
  24. src/agents.py +15 -0
  25. src/checkpoint.py +105 -0
  26. src/debug_logger.py +170 -0
  27. src/graph.py +291 -0
  28. src/llm_config.py +115 -0
  29. src/pending_execution.py +63 -0
  30. src/rag/__init__.py +66 -0
  31. src/rag/docs_downloader.py +366 -0
  32. src/rag/embeddings.py +175 -0
  33. src/rag/index_downloader.py +207 -0
  34. src/rag/query.py +192 -0
  35. src/rag/vectorstore.py +142 -0
  36. src/results.py +244 -0
  37. src/revert.py +537 -0
  38. src/runner.py +323 -0
  39. src/state.py +40 -0
  40. src/tools/__init__.py +75 -0
  41. src/tools/base.py +199 -0
  42. src/tools/execution.py +651 -0
  43. src/tools/execution_check.py +41 -0
  44. src/tools/filesystem.py +873 -0
  45. src/tools/rag_tools.py +68 -0
  46. src/tools/termination.py +25 -0
  47. src/tools/web.py +102 -0
  48. src/usage_tracker.py +870 -0
bridge.py ADDED
@@ -0,0 +1,629 @@
1
+
2
+ import sys
3
+ import os
4
+ import json
5
+ import io
6
+ import threading
7
+ import traceback
8
+ import signal
9
+
10
+ # Global interrupt event for coordinated interruption
11
+ interrupt_event = threading.Event()
12
+
13
+ if __name__ == "__main__":
14
+ # Alias this module as 'bridge' so that 'import bridge' anywhere in the application
15
+ # returns this same module instance with the shared interrupt_event and other state.
16
+ # This prevents creating a second separate instance of the bridge module.
17
+ sys.modules["bridge"] = sys.modules["__main__"]
18
+
19
+ def _save_stats_on_interrupt(signum, frame):
20
+ """Signal handler to save usage stats and report on SIGINT/SIGTERM.
21
+
22
+ For graceful SIGINT/SIGTERM, we generate the report immediately and kill
23
+ any running subprocesses (like mpirun/LAMMPS) by killing their process group.
24
+ For SIGKILL, the report is generated on next startup.
25
+ """
26
+ # Signal that an interrupt has occurred so other threads/tools can stop
27
+ interrupt_event.set()
28
+
29
+ try:
30
+ # FIRST: Kill any running subprocess before anything else
31
+ # This ensures child processes (mpirun, LAMMPS, etc.) are terminated
32
+ try:
33
+ from src.tools.execution import interrupt_running_execution, has_running_process
34
+ if has_running_process():
35
+ interrupt_running_execution()
36
+ except Exception:
37
+ pass # Continue even if this fails
38
+
39
+ from src.usage_tracker import save_stats_to_checkpoint, generate_report, set_run_status, end_run
40
+ from src.tools.base import LOGS_DIR
41
+
42
+ # Set status to interrupted
43
+ set_run_status("interrupted")
44
+
45
+ # Save token stats to checkpoint
46
+ save_stats_to_checkpoint()
47
+
48
+ # Generate and save usage report (for graceful SIGINT)
49
+ try:
50
+ report_content = generate_report()
51
+ report_path = LOGS_DIR / "usage_report.md"
52
+ report_path.write_text(report_content, encoding='utf-8')
53
+ except Exception:
54
+ pass
55
+
56
+ # End run timing
57
+ end_run()
58
+ except Exception:
59
+ pass # Fail silently - we're in a signal handler
60
+
61
+ # Re-raise to propagate the interrupt
62
+ raise KeyboardInterrupt("Interrupted by SIGINT")
63
+
64
+ # Register signal handlers before anything else
65
+ try:
66
+ if threading.current_thread() is threading.main_thread():
67
+ signal.signal(signal.SIGINT, _save_stats_on_interrupt)
68
+ signal.signal(signal.SIGTERM, _save_stats_on_interrupt)
69
+ except (ValueError, AttributeError):
70
+ pass # Not in main thread or signal module issues
71
+
72
+
73
+ # Cache stdout fd at module load time
74
+ _STDOUT_FD = os.dup(sys.stdout.fileno())
75
+
76
+ # Optional debug logging
77
+ try:
78
+ from src.debug_logger import log_bridge_send, log_custom
79
+ _HAS_DEBUG_LOGGER = True
80
+ except ImportError:
81
+ _HAS_DEBUG_LOGGER = False
82
+
83
+ def send_json(type_: str, payload: dict):
84
+ """Send a structured JSON message to stdout."""
85
+ if _HAS_DEBUG_LOGGER:
86
+ log_bridge_send(type_, payload)
87
+ message = json.dumps({"type": type_, "payload": payload}) + "\n"
88
+ try:
89
+ os.write(_STDOUT_FD, message.encode('utf-8'))
90
+ except OSError:
91
+ pass
92
+
93
+ # --- Agent Event API ---
94
+ # These functions are called directly by agents to send events to Node.js CLI
95
+
96
+ def send_agent_event(agent: str, event: str, status: str = "", is_error: bool = False, output: str = ""):
97
+ """Send agent lifecycle event (start, update, complete)."""
98
+ payload = {
99
+ "agent": agent,
100
+ "event": event,
101
+ "status": status,
102
+ "is_error": is_error
103
+ }
104
+ if output:
105
+ payload["output"] = output
106
+ send_json("agent_event", payload)
107
+
108
+ def send_plan_stream(content: str, is_complete: bool = False, parsed_plan: list = None, is_replanning: bool = False):
109
+ """Send streaming execution plan content.
110
+
111
+ Args:
112
+ content: Raw streaming content (for display during streaming)
113
+ is_complete: Whether the plan is complete
114
+ parsed_plan: Optional list of parsed task strings (sent when complete)
115
+ is_replanning: Whether this is a replanning operation (vs initial plan or review)
116
+ """
117
+ payload = {
118
+ "content": content,
119
+ "is_complete": is_complete
120
+ }
121
+ if parsed_plan is not None:
122
+ payload["parsed_plan"] = parsed_plan
123
+ if is_replanning:
124
+ payload["_isReplanning"] = True
125
+ send_json("plan_stream", payload)
126
+
127
+ def send_system_status(status: str):
128
+ """Send system lifecycle status (running, completed)."""
129
+ send_json("system_status", {"status": status})
130
+
131
+ def send_checkpoint_status(is_resuming: bool, task_num: int = 0, total_tasks: int = 0):
132
+ """Send checkpoint resume status to CLI."""
133
+ send_json("checkpoint_status", {
134
+ "is_resuming": is_resuming,
135
+ "task_num": task_num,
136
+ "total_tasks": total_tasks
137
+ })
138
+
139
+ def send_cleanup_status(status: str, message: str = ""):
140
+ """Send cleanup/archiving status to CLI.
141
+
142
+ Args:
143
+ status: One of "starting", "complete", or "error"
144
+ message: Optional status message
145
+ """
146
+ send_json("cleanup_status", {
147
+ "status": status,
148
+ "message": message
149
+ })
150
+
151
+ def send_text_stream(agent: str, content: str, is_complete: bool = False):
152
+ """Send streaming LLM text content to CLI.
153
+
154
+ Args:
155
+ agent: Agent name (e.g., 'operator', 'evaluator')
156
+ content: Accumulated text content
157
+ is_complete: Whether the streaming is complete
158
+ """
159
+ send_json("text_stream", {
160
+ "agent": agent,
161
+ "content": content,
162
+ "is_complete": is_complete
163
+ })
164
+
165
+ def send_thought_stream(agent: str, content: str, is_complete: bool = False):
166
+ """Send streaming LLM thought content to CLI.
167
+
168
+ Args:
169
+ agent: Agent name (e.g., 'operator', 'evaluator')
170
+ content: Accumulated thought content
171
+ is_complete: Whether the streaming is complete
172
+ """
173
+ send_json("thought_stream", {
174
+ "agent": agent,
175
+ "content": content,
176
+ "is_complete": is_complete
177
+ })
178
+
179
+ # --- Environment Setup ---
180
+ from dotenv import load_dotenv
181
+ load_dotenv()
182
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
183
+ os.environ["TRANSFORMERS_VERBOSITY"] = "error"
184
+ os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
185
+ os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1"
186
+ os.environ["TQDM_DISABLE"] = "1"
187
+ os.environ["TERM"] = "xterm-256color"
188
+
189
+ # --- Import System ---
190
+ from src import runner
191
+ from src.llm_config import initialize_llm, initialize_llm_for_agent
192
+ from src.usage_tracker import generate_report, reset as reset_usage_tracker
193
+ from src.tools.base import LOGS_DIR
194
+
195
+
196
+ class BridgeConsole:
197
+ """Console that routes prints to the Node.js UI."""
198
+
199
+ def print(self, *objects, **kwargs):
200
+ content = " ".join(str(obj) for obj in objects)
201
+ if content.strip():
202
+ send_json("log", {"text": content})
203
+
204
+ def input(self, prompt: str = "", *args, **kwargs):
205
+ return ""
206
+
207
+
208
+ # Patch input function to avoid blocking
209
+ def patched_get_input(console, prompt, *args, **kwargs):
210
+ return ""
211
+
212
+ # Override stdout to avoid interfering with JSON framing
213
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", line_buffering=True)
214
+
215
+
216
+
217
+
218
+ def _read_previous_input_from_conversation():
219
+ """Read previous input from conversation.md file."""
220
+ from src.tools.base import LOGS_DIR
221
+ conv_file = LOGS_DIR / "conversation.md"
222
+ if conv_file.exists():
223
+ try:
224
+ content = conv_file.read_text(encoding='utf-8')
225
+ # Parse markdown format - look for ## [User]: Request header
226
+ lines = content.split('\n')
227
+ in_user_request = False
228
+ user_input_lines = []
229
+
230
+ for line in lines:
231
+ if line.startswith("## [User]: Request"):
232
+ in_user_request = True
233
+ continue
234
+ elif in_user_request:
235
+ # Stop at any markdown header or separator
236
+ if line.strip() == "---" or line.startswith("#"):
237
+ break
238
+ if line.strip(): # Collect non-empty lines
239
+ user_input_lines.append(line)
240
+
241
+ if user_input_lines:
242
+ result = '\n'.join(user_input_lines).strip()
243
+
244
+ # If it's the auto-improve message, return a clean label
245
+ from src.runner import AUTO_IMPROVE_MESSAGE
246
+ if result == AUTO_IMPROVE_MESSAGE:
247
+ return "Auto-improve"
248
+
249
+ return result
250
+
251
+ # Fallback: try old formats for backward compatibility
252
+ for line in lines:
253
+ if line.startswith("You: "):
254
+ result = line[5:].strip()
255
+ from src.runner import AUTO_IMPROVE_MESSAGE
256
+ if result == AUTO_IMPROVE_MESSAGE:
257
+ return "Auto-improve"
258
+ return result
259
+ except Exception:
260
+ pass
261
+ return ""
262
+
263
+
264
+ def main():
265
+ send_json("ready", {})
266
+
267
+ try:
268
+ llm, model_name = initialize_llm()
269
+
270
+ # Initialize per-agent LLM overrides (falls back to primary if not configured)
271
+ strategist_llm, strategist_model = initialize_llm_for_agent("strategist", llm, model_name)
272
+ operator_llm, operator_model = initialize_llm_for_agent("operator", llm, model_name)
273
+ evaluator_llm, evaluator_model = initialize_llm_for_agent("evaluator", llm, model_name)
274
+
275
+ agent_llms = {
276
+ "strategist": strategist_llm,
277
+ "operator": operator_llm,
278
+ "evaluator": evaluator_llm,
279
+ }
280
+
281
+ # Report model info including any per-agent overrides
282
+ model_info = {"model": model_name}
283
+ if strategist_model != model_name:
284
+ model_info["strategist_model"] = strategist_model
285
+ if operator_model != model_name:
286
+ model_info["operator_model"] = operator_model
287
+ if evaluator_model != model_name:
288
+ model_info["evaluator_model"] = evaluator_model
289
+
290
+ send_json("init", model_info)
291
+ except Exception as e:
292
+ send_json("error", {"message": str(e)})
293
+ return
294
+
295
+ # Initialize RAG system
296
+ enable_rag = os.getenv("ENABLE_RAG", "true").lower() in ("true", "1", "yes", "on")
297
+ skip_rag = os.getenv("SKIP_RAG", "false").lower() in ("true", "1", "yes", "on")
298
+
299
+ if enable_rag and not skip_rag:
300
+ try:
301
+ # Create status tracker callback
302
+ def status_tracker(message: str):
303
+ send_json("rag_status", {"status": "loading", "message": "Initializing QUASAR RAG System", "detail": message})
304
+
305
+ send_json("rag_status", {"status": "initializing", "message": "Initializing QUASAR RAG System"})
306
+
307
+ from src.rag import initialize_embeddings, initialize_rag
308
+ from src.tools.base import WORKSPACE_DIR
309
+
310
+ # Pass status_tracker to initialization functions
311
+ # Note: The function signature updates for initialize_embeddings and initialize_rag will be done in subsequent steps
312
+ initialize_embeddings(workspace_dir=WORKSPACE_DIR, status_tracker=status_tracker)
313
+ initialize_rag(workspace_dir=WORKSPACE_DIR, status_tracker=status_tracker)
314
+ send_json("rag_status", {"status": "done", "message": "Initialized QUASAR RAG System"})
315
+ except Exception as e:
316
+ send_json("rag_status", {"status": "error", "message": str(e)})
317
+
318
+ send_json("system_ready", {})
319
+
320
+ exec_thread = None
321
+ while True:
322
+ try:
323
+ line = sys.stdin.readline()
324
+ if not line:
325
+ break
326
+
327
+ data = json.loads(line)
328
+ command = data.get("command")
329
+
330
+ if command == "prompt":
331
+ prompt = data.get("content", "")
332
+ restart = data.get("restart", False)
333
+
334
+ if _HAS_DEBUG_LOGGER:
335
+ log_custom("BRIDGE", "Prompt command received", {
336
+ "prompt_length": len(prompt) if prompt else 0,
337
+ "restart": restart
338
+ })
339
+
340
+ def run_prompt_in_thread():
341
+ send_system_status("running")
342
+ run_error = None
343
+ try:
344
+ runner.process_prompt(prompt, llm, if_restart=restart, agent_llms=agent_llms)
345
+ except KeyboardInterrupt:
346
+ # Handled interruption
347
+ send_json("done", {"status": "interrupted"})
348
+ send_system_status("completed")
349
+ return
350
+ except RuntimeError as e:
351
+ if "cannot schedule new futures" in str(e):
352
+ # This happens when interpreter is shutting down, treat as interrupt
353
+ send_json("done", {"status": "interrupted"})
354
+ send_system_status("completed")
355
+ return
356
+ # Re-raise other RuntimeErrors
357
+ raise e
358
+ except Exception as e:
359
+ run_error = e
360
+ tb = traceback.format_exc()
361
+ send_json("error", {"message": str(e), "traceback": tb})
362
+
363
+ send_system_status("completed")
364
+
365
+ # usage_report.md generation moved to runner.py to ensure it is archived
366
+
367
+ # Read and send final summary if it exists
368
+ # Only send if checkpoint exists (active run), otherwise completed_run_info will handle it
369
+ try:
370
+ from src.tools.base import WORKSPACE_DIR
371
+ from src.checkpoint import checkpoint_file_exists
372
+ from src.results import final_results_exists_and_not_empty
373
+
374
+ # Only send final_summary if checkpoint exists (active run completion)
375
+ # If no checkpoint but final_results exists, completed_run_info will send it instead
376
+ has_checkpoint = checkpoint_file_exists()
377
+ if has_checkpoint:
378
+ summary_path = WORKSPACE_DIR / "final_results" / "summary.md"
379
+ if summary_path.exists():
380
+ summary_content = summary_path.read_text(encoding='utf-8')
381
+ if summary_content.strip():
382
+ send_json("final_summary", {"content": summary_content})
383
+ # If no checkpoint but final_results exists, let completed_run_info handle it
384
+ # (which is sent when CLI calls check_checkpoint)
385
+ except Exception:
386
+ pass
387
+
388
+ # Send appropriate done status based on whether run succeeded or errored
389
+ # "completed" = successful run, "error" = exception occurred
390
+ # Both should trigger EXIT_ON_COMPLETION, but "interrupted" should not
391
+ if run_error:
392
+ send_json("done", {"status": "error"})
393
+ else:
394
+ send_json("done", {"status": "completed"})
395
+
396
+ if _HAS_DEBUG_LOGGER:
397
+ log_custom("BRIDGE", "Prompt command completed")
398
+
399
+ # Start execution in a separate thread so main loop remains responsive to interrupts
400
+ exec_thread = threading.Thread(target=run_prompt_in_thread)
401
+ exec_thread.daemon = True
402
+ exec_thread.start()
403
+
404
+ elif command == "check_checkpoint":
405
+ from src.checkpoint import checkpoint_file_exists, get_thread_config, create_checkpoint_infrastructure
406
+ from src.results import final_results_exists_and_not_empty, archive_exists_without_checkpoint
407
+ from src.tools.base import WORKSPACE_DIR
408
+ from src.graph import build_graph
409
+ from bridge_history import extract_checkpoint_history
410
+ from src.usage_tracker import generate_interrupted_report_if_needed
411
+
412
+ exists = checkpoint_file_exists()
413
+
414
+ # Generate usage report for any interrupted run BEFORE loading checkpoint history
415
+ # This ensures interrupted runs get their reports even if killed with SIGKILL
416
+ if exists:
417
+ try:
418
+ generated = generate_interrupted_report_if_needed()
419
+ if generated and _HAS_DEBUG_LOGGER:
420
+ log_custom("BRIDGE", "Generated usage report for interrupted run")
421
+ except Exception as e:
422
+ if _HAS_DEBUG_LOGGER:
423
+ log_custom("BRIDGE", f"Failed to generate interrupted report: {e}")
424
+ previous_input = ""
425
+ history = None
426
+
427
+ if exists:
428
+ previous_input = _read_previous_input_from_conversation()
429
+
430
+ # Extract history from checkpoint state
431
+ try:
432
+ graph_builder = build_graph(llm)
433
+ graph = create_checkpoint_infrastructure(graph_builder)
434
+ config = get_thread_config()
435
+ state = graph.get_state(config)
436
+
437
+ if state and state.values:
438
+ # Use is_replanning from state (most reliable)
439
+ is_replan = state.values.get('is_replanning', False)
440
+ history = extract_checkpoint_history(state.values, state.values.get('messages', []), is_replan=is_replan)
441
+ except Exception:
442
+ traceback.print_exc()
443
+
444
+ send_json("checkpoint_info", {
445
+ "exists": exists,
446
+ "previous_input": previous_input,
447
+ "history": history
448
+ })
449
+
450
+ # Check for completed run state (no checkpoint but archive with runs exists)
451
+ # Note: Use archive_exists_without_checkpoint() instead of final_results_exists_and_not_empty()
452
+ # because after a run completes, final_results is moved to archive/run_N/
453
+ if not exists and (archive_exists_without_checkpoint() or final_results_exists_and_not_empty()):
454
+ summary_content = ""
455
+ summary_path = WORKSPACE_DIR / "final_results" / "summary.md"
456
+
457
+ # If local summary doesn't exist, check the latest archive
458
+ if not summary_path.exists():
459
+ try:
460
+ archive_dir = WORKSPACE_DIR / "archive"
461
+ if archive_dir.exists():
462
+ max_run_num = 0
463
+ latest_run_dir = None
464
+
465
+ for item in archive_dir.iterdir():
466
+ if item.is_dir() and item.name.startswith("run_"):
467
+ try:
468
+ run_num = int(item.name.split("_", 1)[1])
469
+ if run_num > max_run_num:
470
+ max_run_num = run_num
471
+ latest_run_dir = item
472
+ except (ValueError, IndexError):
473
+ continue
474
+
475
+ if latest_run_dir:
476
+ archive_summary = latest_run_dir / "final_results" / "summary.md"
477
+ if archive_summary.exists():
478
+ summary_path = archive_summary
479
+ except Exception:
480
+ pass
481
+
482
+ if summary_path.exists():
483
+ try:
484
+ summary_content = summary_path.read_text(encoding='utf-8')
485
+ except Exception:
486
+ pass
487
+
488
+ prev_input = _read_previous_input_from_conversation()
489
+
490
+ send_json("completed_run_info", {
491
+ "exists": True,
492
+ "summary": summary_content,
493
+ "previous_input": prev_input
494
+ })
495
+
496
+ elif command == "fresh_start":
497
+ # Clean workspace for fresh start (deletes archives too)
498
+ from src.results import cleanup_workspace_for_fresh_start
499
+ from src.checkpoint import delete_checkpoint
500
+
501
+ try:
502
+ cleanup_workspace_for_fresh_start()
503
+ delete_checkpoint()
504
+ send_json("fresh_start_complete", {"success": True})
505
+ except Exception as e:
506
+ send_json("fresh_start_complete", {"success": False, "error": str(e)})
507
+
508
+ elif command == "clear_checkpoint":
509
+ # Clear checkpoint and workspace but keep archives
510
+ from src.results import cleanup_workspace_keep_archive, archive_exists_without_checkpoint
511
+ from src.checkpoint import delete_checkpoint
512
+ from src.tools.base import WORKSPACE_DIR
513
+
514
+ try:
515
+ cleanup_workspace_keep_archive()
516
+ delete_checkpoint()
517
+
518
+ # Check if archives exist - if so, show completed_run_info prompt
519
+ if archive_exists_without_checkpoint():
520
+ # Get summary from latest archive
521
+ summary_content = ""
522
+ try:
523
+ archive_dir = WORKSPACE_DIR / "archive"
524
+ if archive_dir.exists():
525
+ max_run_num = 0
526
+ latest_run_dir = None
527
+
528
+ for item in archive_dir.iterdir():
529
+ if item.is_dir() and item.name.startswith("run_"):
530
+ try:
531
+ run_num = int(item.name.split("_", 1)[1])
532
+ if run_num > max_run_num:
533
+ max_run_num = run_num
534
+ latest_run_dir = item
535
+ except (ValueError, IndexError):
536
+ continue
537
+
538
+ if latest_run_dir:
539
+ archive_summary = latest_run_dir / "final_results" / "summary.md"
540
+ if archive_summary.exists():
541
+ summary_content = archive_summary.read_text(encoding='utf-8')
542
+ except Exception:
543
+ pass
544
+
545
+ send_json("completed_run_info", {
546
+ "exists": True,
547
+ "summary": summary_content,
548
+ "previous_input": ""
549
+ })
550
+ else:
551
+ # No archives - just confirm checkpoint cleared
552
+ send_json("clear_checkpoint_complete", {"success": True})
553
+ except Exception as e:
554
+ send_json("clear_checkpoint_complete", {"success": False, "error": str(e)})
555
+
556
+ elif command == "archive_and_continue":
557
+ # Archive current workspace (move to archive/run_N) and prepare for improvement
558
+ from src.results import setup_final_results_folder
559
+
560
+ try:
561
+ setup_final_results_folder()
562
+ send_json("archive_complete", {"success": True})
563
+ except Exception as e:
564
+ send_json("archive_complete", {"success": False, "error": str(e)})
565
+
566
+ elif command == "interrupt":
567
+ interrupt_event.set()
568
+
569
+ # FIRST: Kill any running subprocess immediately
570
+ # This is critical because the CLI may send SIGKILL right after this,
571
+ # and we need to ensure child processes (mpirun, LAMMPS, etc.) are terminated
572
+ # before the bridge process dies.
573
+ try:
574
+ from src.tools.execution import interrupt_running_execution, has_running_process
575
+ if has_running_process():
576
+ interrupt_running_execution()
577
+ except Exception as e:
578
+ if _HAS_DEBUG_LOGGER:
579
+ log_custom("BRIDGE", f"Failed to kill subprocess on interrupt: {e}")
580
+
581
+ # Report generation and stats saving
582
+ # We do this here to ensure immediate feedback even if worker thread is slow to stop
583
+ try:
584
+ from src.usage_tracker import save_stats_to_checkpoint, generate_report, set_run_status, end_run
585
+ from src.tools.base import LOGS_DIR
586
+
587
+ # Set status to interrupted
588
+ set_run_status("interrupted")
589
+
590
+ # Save token stats to checkpoint
591
+ save_stats_to_checkpoint()
592
+
593
+ # Generate and save usage report (for graceful interruption)
594
+ try:
595
+ report_content = generate_report()
596
+ report_path = LOGS_DIR / "usage_report.md"
597
+ report_path.write_text(report_content, encoding='utf-8')
598
+ except Exception:
599
+ pass
600
+
601
+ # End run timing
602
+ end_run()
603
+ except Exception as e:
604
+ if _HAS_DEBUG_LOGGER:
605
+ log_custom("BRIDGE", f"Failed to save stats on interrupt: {e}")
606
+
607
+ send_json("interrupt_acknowledged", {"success": True})
608
+
609
+ elif command == "exit":
610
+ break
611
+
612
+ except json.JSONDecodeError:
613
+ continue
614
+ except KeyboardInterrupt:
615
+ # Stats already saved by signal handler, just send done and exit
616
+ send_json("done", {"status": "interrupted"})
617
+
618
+ # Wait for execution thread to finish/cleanup if it's running
619
+ # This prevents premature interpreter shutdown while thread is still active
620
+ if exec_thread and exec_thread.is_alive():
621
+ exec_thread.join(timeout=3.0)
622
+
623
+ break
624
+ except Exception as e:
625
+ tb = traceback.format_exc()
626
+ send_json("error", {"message": str(e), "traceback": tb})
627
+
628
+ if __name__ == "__main__":
629
+ main()