tags in the same pass.
+
+ Note:
+ The function also calls format_solution_tags_in_content() to handle
+ solution tags in the same processing pass.
+ """
+ import re
+
+ # Pattern to match ... blocks
+ execute_pattern = r"(.*?)"
+
+ def replace_execute_tag(match):
+ code_content = match.group(1).strip()
+ language, tool_name = detect_code_language_and_tool(code_content)
+ code_content = clean_code_content(code_content, language)
+
+ # Parse tools from the code content with module information
+ detected_tool_modules = parse_tool_calls_with_modules_func(code_content)
+
+ # Create the formatted block
+ formatted_block = create_tool_call_block(code_content, language, tool_name, detected_tool_modules)
+ return formatted_block
+
+ # Replace all execute tags with formatted tool call blocks
+ formatted_content = re.sub(execute_pattern, replace_execute_tag, content, flags=re.DOTALL)
+
+ # Also format solution tags
+ formatted_content = format_solution_tags_in_content(formatted_content)
+
+ return formatted_content
+
+
+def detect_code_language_and_tool(code_content: str) -> tuple[str, str]:
+ """Detect the programming language and tool name from code content.
+
+ This function analyzes code content to determine the programming language
+ and appropriate tool name based on language markers at the beginning of
+ the code block.
+
+ Args:
+ code_content: The code content to analyze for language markers
+
+ Returns:
+ Tuple containing (language, tool_name) where:
+ - language: The detected programming language ("python", "r", "bash")
+ - tool_name: The human-readable tool name for display
+
+ Example:
+ >>> detect_code_language_and_tool("#!R\nlibrary(ggplot2)")
+ ("r", "R REPL")
+ >>> detect_code_language_and_tool("#!BASH\necho 'hello'")
+ ("bash", "Bash Script")
+ """
+ if code_content.startswith("#!R") or code_content.startswith("# R code") or code_content.startswith("# R script"):
+ return "r", "R REPL"
+ elif code_content.startswith("#!BASH") or code_content.startswith("# Bash script"):
+ return "bash", "Bash Script"
+ elif code_content.startswith("#!CLI"):
+ return "bash", "CLI Command"
+ else:
+ return "python", "Python REPL"
+
+
+def clean_code_content(code_content: str, language: str) -> str:
+ """Clean code content by removing language markers.
+
+ This function removes language-specific markers from the beginning of code
+ content to prepare it for display in code blocks. The markers are used
+ internally for language detection but should not appear in the final output.
+
+ Args:
+ code_content: The raw code content that may contain language markers
+ language: The detected programming language ("python", "r", "bash")
+
+ Returns:
+ Cleaned code content with language markers removed
+
+ Example:
+ >>> clean_code_content("#!R\nlibrary(ggplot2)", "r")
+ "library(ggplot2)"
+ >>> clean_code_content("#!BASH\necho 'hello'", "bash")
+ "echo 'hello'"
+ """
+ import re
+
+ if language == "r":
+ return re.sub(r"^#!R|^# R code|^# R script", "", code_content, count=1).strip()
+ elif language == "bash":
+ if code_content.startswith("#!BASH") or code_content.startswith("# Bash script"):
+ return re.sub(r"^#!BASH|^# Bash script", "", code_content, count=1).strip()
+ elif code_content.startswith("#!CLI"):
+ return re.sub(r"^#!CLI", "", code_content, count=1).strip()
+ return code_content
+
+
+def create_tool_call_block(code_content: str, language: str, tool_name: str, detected_tool_modules: list) -> str:
+ """Create the HTML block for tool call highlighting.
+
+ This function generates a styled HTML block that displays code execution
+ information including the code itself, syntax highlighting, and a list of
+ tools that were used during execution.
+
+ Args:
+ code_content: The cleaned code content to display
+ language: The programming language for syntax highlighting
+ tool_name: The default tool name to display if no specific tools detected
+ detected_tool_modules: List of (tool_name, module_name) tuples for tools used
+
+ Returns:
+ HTML string containing a styled tool call block with code and tool information
+
+ Note:
+ The HTML uses CSS classes defined in get_pdf_css_content() for styling.
+ If no specific tools are detected, it falls back to a default tool name.
+ """
+ # Create the formatted block with code and tools used
+ formatted_block = f""""
+ return formatted_block
+
+
+def format_detected_tools(detected_tool_modules: list) -> str:
+ """Format detected tools with their modules for display.
+
+ This function takes a list of (tool_name, module_name) tuples and formats
+ them into a human-readable string for display in the tool call blocks.
+ It handles special cases for common tools and formats module names appropriately.
+
+ Args:
+ detected_tool_modules: List of (tool_name, module_name) tuples
+
+ Returns:
+ Comma-separated string of formatted tool descriptions
+
+ Example:
+ >>> format_detected_tools([("analyze_data", "biomni.tool"), ("pandas", "pandas")])
+ "biomni → analyze_data, pandas → pandas"
+ """
+ tool_descriptions = []
+ for tool_name, module_name in detected_tool_modules:
+ if tool_name == "python_repl":
+ tool_descriptions.append("Python REPL")
+ elif tool_name == "r_repl":
+ tool_descriptions.append("R REPL")
+ elif "bash" in tool_name.lower():
+ tool_descriptions.append("Bash Script")
+ else:
+ # Extract the last part of the module name for display
+ display_module = module_name.split(".")[-1] if "." in module_name else module_name
+ tool_descriptions.append(f"{display_module} → {tool_name}")
+
+ return ", ".join(sorted(tool_descriptions))
+
+
+def format_default_tool_name(language: str, tool_name: str) -> str:
+ """Format default tool name based on programming language.
+
+ This function generates HTML for displaying the default tool name when
+ no specific tools are detected in the code. It maps programming languages
+ to their appropriate default tool names.
+
+ Args:
+ language: The programming language ("python", "r", "bash")
+ tool_name: The detected tool name (used for bash CLI vs script distinction)
+
+ Returns:
+ HTML string containing a styled tools-used section
+
+ Note:
+ For bash, it distinguishes between CLI commands and bash scripts
+ based on the tool_name parameter.
+ """
+ if language == "r":
+ return """
+
+Tools Used: R REPL
+
"""
+ elif language == "bash":
+ if tool_name == "CLI Command":
+ return """
+
+Tools Used: CLI Command
+
"""
+ else:
+ return """
+
+Tools Used: Bash Script
+
"""
+ else:
+ return """
+
+Tools Used: Python REPL
+
"""
+
+
+def format_solution_tags_in_content(content: str) -> str:
+ """Format solution tags in content by extracting text and formatting as solution blocks.
+
+ This function processes content that contains ... tags and
+ converts them into styled HTML blocks that display solution content with appropriate
+ formatting and CSS classes.
+
+ Args:
+ content: The content string that may contain tags
+
+ Returns:
+ Formatted content with solution tags converted to styled solution blocks
+
+ Note:
+ The solution blocks use the "title-text summary" CSS class for consistent
+ styling with other content blocks in the markdown output.
+ """
+ import re
+
+ # Pattern to match ... blocks
+ solution_pattern = r"(.*?)"
+
+ def replace_solution_tag(match):
+ solution_content = match.group(1).strip()
+ # Format as regular text, not terminal
+ return f"""
+
+
+{solution_content}
+
+
"""
+
+ # Replace all solution tags with formatted solution blocks
+ formatted_content = re.sub(solution_pattern, replace_solution_tag, content, flags=re.DOTALL)
+
+ return formatted_content
+
+
+def format_observation_as_terminal(content: str) -> str | None:
+ """Format observation content with terminal-like styling.
+
+ This function processes observation content from the agent's execution results
+ and formats it as a styled terminal block. It handles both text and image content,
+ with length limits to ensure the output fits within PDF page constraints.
+
+ Args:
+ content: The observation content string, potentially containing tags
+
+ Returns:
+ Formatted HTML content with terminal styling, or None if observation is
+ empty, invalid, or contains only meaningless content
+
+ Note:
+ - Content is limited to 10,000 characters to fit within 2 A4 pages
+ - Handles both text and base64-encoded images
+ - Uses CSS classes for consistent styling with other content blocks
+ """
+ import re
+
+ # Character limit for 2 A4 pages (approximately 10,000 characters)
+ MAX_OBSERVATION_LENGTH = 10000
+
+ # Remove the tags and extract the content
+ observation_pattern = r"(.*?)"
+ observation_match = re.search(observation_pattern, content, re.DOTALL)
+
+ if observation_match:
+ observation_content = observation_match.group(1).strip()
+ else:
+ # Fallback if no observation tags found - check if content is meaningful
+ if not (content.strip() and content.strip() not in ["", "None", "null", "undefined"]):
+ return None
+ observation_content = content.strip()
+
+ # Skip empty observations
+ if not observation_content or observation_content in ["", "None", "null", "undefined"]:
+ return None
+
+ # Check if observation is too long for 2 pages
+ if len(observation_content) > MAX_OBSERVATION_LENGTH:
+ cropped_content = observation_content[:MAX_OBSERVATION_LENGTH]
+ truncation_notice = f"\n\n[Output truncated - content was too long to display here ({len(observation_content)} characters total)]"
+ observation_content = cropped_content + truncation_notice
+
+ # Check if it contains plot data (base64 images)
+ if "data:image/" in observation_content:
+ content_html = process_observation_with_images(observation_content)
+ else:
+ # Regular text output - format as terminal output
+ content_html = f"```terminal\n{observation_content}\n```"
+
+ return f""""""
+
+
+def process_observation_with_images(observation_content: str) -> str:
+ """Process observation content that contains both text and base64-encoded images.
+
+ This function handles observation content that includes both text output and
+ base64-encoded images (typically plots from data analysis). It separates the
+ text and image content and formats them appropriately for markdown display.
+
+ Args:
+ observation_content: The observation content containing both text and images
+
+ Returns:
+ HTML string containing formatted text (as terminal blocks) and images
+ (as markdown image tags)
+
+ Note:
+ The function uses "data:image/" as a delimiter to split content into
+ text and image parts, then processes each part separately.
+ """
+ # Split content into text and image parts
+ parts = observation_content.split("data:image/")
+ text_parts = []
+ image_parts = []
+
+ for i, part in enumerate(parts):
+ if i == 0:
+ # First part is text only
+ if part.strip():
+ text_parts.append(part.strip())
+ else:
+ # Find the end of the base64 data
+ end_markers = ["\n", "\r", " ", "\t", ">", "<", "]", ")", "}"]
+ image_end = len(part)
+ for marker in end_markers:
+ marker_pos = part.find(marker)
+ if marker_pos != -1 and marker_pos < image_end:
+ image_end = marker_pos
+
+ # Extract image data
+ image_data = "data:image/" + part[:image_end]
+ image_parts.append(image_data)
+
+ # Extract remaining text
+ remaining_text = part[image_end:].strip()
+ if remaining_text:
+ text_parts.append(remaining_text)
+
+ # Build the content
+ content_html = ""
+ if text_parts:
+ # Add text content as terminal output
+ text_content = "\n".join(text_parts)
+ content_html += f"```terminal\n{text_content}\n```\n\n"
+
+ if image_parts:
+ # Add image content
+ for image_data in image_parts:
+ content_html += f"\n\n"
+
+ return content_html
+
+
+def remove_emojis_from_text(text: str) -> str:
+ """Remove emojis from text for markdown/PDF output.
+
+ This function removes common emojis used in the system prompt and configuration
+ display from text content before it's converted to markdown or PDF. This ensures
+ clean, professional output while preserving emojis in the console display.
+
+ Args:
+ text: The text content that may contain emojis
+
+ Returns:
+ Text content with emojis removed
+
+ Note:
+ The function targets specific emojis used in the Biomni system:
+ - 🔧 for tools
+ - 📊 for data
+ - ⚙️ for software
+ - 📋 for configuration
+ - 🤖 for agent
+ """
+ import re
+
+ # Remove common emojis used in the system prompt, this makes conversion simpler
+ emoji_patterns = [
+ r"🔧\s*", # Tool emoji
+ r"📊\s*", # Data emoji
+ r"⚙️\s*", # Software emoji
+ r"📋\s*", # Config emoji
+ r"🤖\s*", # Agent emoji
+ ]
+
+ for pattern in emoji_patterns:
+ text = re.sub(pattern, "", text)
+
+ return text
+
+
+def format_lists_in_text(text: str) -> str:
+ """Format numbered lists and bullet points in text to proper markdown format.
+
+ This function processes text content to identify and format various types of lists,
+ including numbered lists with checkboxes, regular lists, and plan structures.
+ It also handles preprocessing tasks like removing bold formatting from plan titles
+ and removing emojis for clean PDF output.
+
+ Args:
+ text: The text content to process for list formatting
+
+ Returns:
+ Formatted text with properly structured lists and cleaned formatting
+
+ Note:
+ The function performs several preprocessing steps:
+ - Removes bold formatting from plan titles
+ - Removes emojis for PDF output
+ - Identifies and formats checkbox lists
+ - Processes regular text blocks
+ """
+ import re
+
+ # Preprocess to remove bold formatting from plan titles
+ # Remove **Plan:**, **Updated Plan:**, **Completed Plan:**, etc.
+ text = re.sub(r"\*\*([Pp]lan|Updated [Pp]lan|Completed [Pp]lan|Final [Pp]lan):\*\*", r"\1:", text)
+ # Also handle cases without colons
+ text = re.sub(r"\*\*([Pp]lan|Updated [Pp]lan|Completed [Pp]lan|Final [Pp]lan)\*\*", r"\1", text)
+ # Handle any other bold formatting patterns for plan titles
+ text = re.sub(r"([Pp]lan|Updated [Pp]lan|Completed [Pp]lan|Final [Pp]lan):", r"\1:", text)
+ text = re.sub(r"([Pp]lan|Updated [Pp]lan|Completed [Pp]lan|Final [Pp]lan)", r"\1", text)
+
+ # Remove emojis from the text for markdown/PDF output
+ text = remove_emojis_from_text(text)
+
+ lines = text.split("\n")
+ list_blocks = identify_list_blocks(lines)
+
+ # Process each block
+ result_blocks = []
+ for block_text, is_checkbox_list in list_blocks:
+ if is_checkbox_list:
+ result_blocks.append(format_single_list(block_text))
+ else:
+ result_blocks.append(block_text)
+
+ return "\n".join(result_blocks)
+
+
+def identify_list_blocks(lines: list) -> list[tuple[str, bool]]:
+ """Identify blocks of text that contain lists.
+
+ This function analyzes a list of text lines to identify contiguous blocks
+ that contain numbered lists with checkboxes. It groups lines into blocks
+ and marks whether each block contains a checkbox list or regular text.
+
+ Args:
+ lines: List of text lines to analyze
+
+ Returns:
+ List of tuples containing (block_text, is_checkbox_list) where:
+ - block_text: The text content of the block
+ - is_checkbox_list: True if the block contains numbered items with checkboxes
+
+ Note:
+ The function looks for patterns like "1. [ ]", "2. [✓]", "3. [✗]" to
+ identify checkbox sequences and groups them into separate blocks.
+ """
+ import re
+
+ list_blocks = []
+ current_block = []
+ in_checkbox_sequence = False
+
+ for line in lines:
+ line_stripped = line.strip()
+
+ # Check if this line starts a numbered item with checkbox
+ if re.match(r"^\d+\.\s*\[[ ✓✗]\]", line_stripped):
+ if not in_checkbox_sequence:
+ # Start of a new checkbox sequence
+ if current_block:
+ list_blocks.append(("\n".join(current_block), False))
+ current_block = [line]
+ in_checkbox_sequence = True
+ else:
+ # Continue the sequence
+ current_block.append(line)
+ else:
+ if in_checkbox_sequence:
+ # End of checkbox sequence
+ if current_block:
+ list_blocks.append(("\n".join(current_block), True))
+ current_block = []
+ in_checkbox_sequence = False
+ current_block.append(line)
+
+ # Handle the last block
+ if current_block:
+ if in_checkbox_sequence:
+ list_blocks.append(("\n".join(current_block), True))
+ else:
+ list_blocks.append(("\n".join(current_block), False))
+
+ return list_blocks
+
+
+def format_single_list(text: str) -> str:
+ """Format a single list block with checkboxes and plan titles.
+
+ This function processes a text block that may contain numbered lists with
+ checkboxes and plan titles. It converts checkbox symbols to HTML list items
+ and wraps the content in a styled container with appropriate CSS classes.
+
+ Args:
+ text: The text block to format, potentially containing numbered lists
+
+ Returns:
+ HTML string containing either a formatted list with plan title or
+ regular text if no list items are found
+
+ Note:
+ The function recognizes plan titles like "Plan", "Updated Plan", "Completed Plan"
+ and converts checkbox symbols (✓, ✗) to HTML format ([x], [ ]).
+ """
+ import re
+
+ lines = text.split("\n")
+ list_items = []
+ has_list_items = False
+ plan_title = "Plan" # Default title
+
+ for line in lines:
+ line = line.strip()
+ if not line:
+ continue
+
+ # Check for plan title patterns
+ if re.match(r"^(Plan|Updated Plan|Completed Plan)$", line, re.IGNORECASE):
+ plan_title = line
+ continue
+
+ # Check for numbered lists with checkboxes (1. [ ] or 1. [✓] or 1. [✗])
+ if re.match(r"^\d+\.\s*\[[ ✓✗]\]", line):
+ has_list_items = True
+ # Extract the content after the checkbox
+ content = re.sub(r"^\d+\.\s*\[[ ✓✗]\]\s*", "", line)
+
+ # Replace checkbox symbols with text format
+ if "[✓]" in line:
+ list_items.append(f"[x] {content}")
+ elif "[✗]" in line:
+ list_items.append(f"[ ] {content}")
+ else:
+ list_items.append(f"[ ] {content}")
+ else:
+ # Regular text - add as is (don't convert to list items)
+ list_items.append(line)
+
+ if has_list_items and list_items:
+ # This is a list - return with container div and styled title
+ return f"""
+
+
+
+{chr(10).join(list_items)}
+
+
+
"""
+ else:
+ # Regular text
+ return "\n".join(list_items)
+
+
+def convert_markdown_to_pdf(markdown_path: str, pdf_path: str) -> None:
+ """Convert markdown file to PDF using weasyprint or fallback libraries.
+
+ This function converts a markdown file to PDF format using multiple fallback
+ strategies. It prioritizes weasyprint for better layout control, then falls back
+ to markdown2pdf and finally pandoc if the preferred libraries are not available.
+
+ Args:
+ markdown_path: Path to the input markdown file
+ pdf_path: Path where the output PDF file should be saved
+
+ Raises:
+ ImportError: If no PDF conversion library is available
+ Exception: If PDF conversion fails for any other reason
+
+ Note:
+ The function uses minimal markdown extensions for better performance
+ and applies custom CSS styling for consistent formatting.
+ """
+ try:
+ # Try weasyprint first (better for complex layouts)
+ from weasyprint import HTML
+ from weasyprint.text.fonts import FontConfiguration
+
+ # Read markdown content
+ with open(markdown_path, encoding="utf-8") as f:
+ markdown_content = f.read()
+
+ # Convert markdown to HTML with minimal extensions for better performance
+ import markdown
+
+ # Use minimal extensions to improve performance
+ html_content = markdown.markdown(
+ markdown_content,
+ extensions=["fenced_code"], # Removed codehilite for better performance
+ )
+
+ # Add CSS styling
+ css_content = get_pdf_css_content()
+
+ # Create HTML document
+ html_doc = f"""
+
+
+
+
+ Biomni Conversation History
+
+
+
+ {html_content}
+
+
+ """
+
+ # Convert to PDF with performance optimizations
+ font_config = FontConfiguration()
+ html_obj = HTML(string=html_doc)
+ html_obj.write_pdf(pdf_path, font_config=font_config, optimize_images=True)
+
+ except ImportError:
+ # Fallback to markdown2pdf if weasyprint is not available
+ try:
+ from markdown2pdf import markdown2pdf
+
+ markdown2pdf(markdown_path, pdf_path)
+ except ImportError:
+ # Final fallback - try using pandoc if available
+ import subprocess
+
+ try:
+ subprocess.run(["pandoc", markdown_path, "-o", pdf_path], check=True)
+ except (subprocess.CalledProcessError, FileNotFoundError) as e:
+ raise ImportError(
+ "No PDF conversion library available. Please install weasyprint, markdown2pdf, or pandoc."
+ ) from e
+ except Exception as e:
+ raise Exception(f"PDF conversion failed: {e}") from e
+
+
+def get_pdf_css_content() -> str:
+ """Get the CSS content for PDF generation.
+
+ This function returns a comprehensive CSS stylesheet designed specifically
+ for PDF generation from markdown content. It includes styling for all
+ HTML elements that may appear in the converted markdown, with optimized
+ typography, spacing, and layout for print media.
+
+ Returns:
+ CSS string containing all styles needed for PDF generation
+
+ Note:
+ The CSS includes styles for:
+ - Typography and font families
+ - Headings and text formatting
+ - Code blocks and syntax highlighting
+ - Tables and lists
+ - Custom classes for tool calls, observations, and plans
+ - Print-optimized spacing and layout
+ """
+ return """
+ body {
+ /* Previously: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif, 'Noto Color Emoji', 'Apple Color Emoji', 'Segoe UI Emoji', 'Twemoji', 'EmojiOne Color' */
+ font-family: sans-serif;
+ font-size: 9pt;
+ line-height: 1.4;
+ max-width: 800px;
+ margin: 0 auto;
+ padding: 15px;
+ color: #333;
+ }
+ h1, h2, h3, h4, h5, h6 {
+ /* Previously: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif, 'Noto Color Emoji', 'Apple Color Emoji', 'Segoe UI Emoji', 'Twemoji', 'EmojiOne Color' */
+ font-family: sans-serif;
+ color: #2c3e50;
+ margin-top: 1em;
+ margin-bottom: 0.5em;
+ }
+ h1 {
+ border-bottom: 2px solid #3498db;
+ padding-bottom: 8px;
+ font-size: 16pt;
+ }
+ h2 {
+ border-bottom: 1px solid #bdc3c7;
+ padding-bottom: 3px;
+ font-size: 14pt;
+ }
+ h3 {
+ font-size: 12pt;
+ }
+ h4 {
+ font-size: 10pt;
+ margin-top: 0.8em;
+ margin-bottom: 0.3em;
+ }
+ h5, h6 {
+ font-size: 9pt;
+ margin-top: 0.6em;
+ margin-bottom: 0.2em;
+ }
+ code {
+ background-color: #f8f9fa;
+ padding: 1px 3px;
+ border-radius: 2px;
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
+ font-size: 8pt;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ }
+ pre {
+ background-color: #f8f9fa;
+ padding: 10px;
+ border-radius: 3px;
+ overflow-x: auto;
+ border-left: 3px solid #3498db;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ font-size: 8pt;
+ margin: 0.5em 0;
+ }
+ pre code {
+ background-color: transparent;
+ padding: 0;
+ border-radius: 0;
+ font-size: 8pt;
+ }
+ /* Code header styling */
+ strong {
+ font-size: 9pt;
+ font-weight: normal;
+ color: #6c757d;
+ font-style: italic;
+ }
+ blockquote {
+ border-left: 3px solid #bdc3c7;
+ margin: 0.5em 0;
+ padding-left: 15px;
+ color: #7f8c8d;
+ font-size: 8pt;
+ }
+ table {
+ border-collapse: collapse;
+ width: 100%;
+ margin: 0.5em 0;
+ font-size: 8pt;
+ }
+ th, td {
+ border: 1px solid #bdc3c7;
+ padding: 4px 8px;
+ text-align: left;
+ }
+ th {
+ background-color: #ecf0f1;
+ font-weight: bold;
+ }
+ img {
+ max-width: 100%;
+ height: auto;
+ display: block;
+ margin: 10px auto;
+ border: 1px solid #ddd;
+ border-radius: 3px;
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
+ }
+ p {
+ /* Previously: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif, 'Noto Color Emoji', 'Apple Color Emoji', 'Segoe UI Emoji', 'Twemoji', 'EmojiOne Color' */
+ font-family: sans-serif;
+ margin: 0.3em 0;
+ }
+ /* Tool call highlighting - matching observation and code formatting */
+ .tool-call-highlight {
+ background-color: #f8f9fa;
+ border: 1px solid #e9ecef;
+ border-radius: 3px;
+ padding: 0;
+ margin: 10px 0;
+ overflow: hidden;
+ }
+ .tool-call-header {
+ background-color: #e9ecef;
+ color: #495057;
+ padding: 8px 12px;
+ margin: 0;
+ font-weight: normal;
+ font-size: 9pt;
+ font-style: italic;
+ border-bottom: 1px solid #dee2e6;
+ }
+ .tool-call-input {
+ background-color: #f8f9fa;
+ border: none;
+ border-radius: 0;
+ padding: 10px 12px;
+ margin: 0;
+ color: #333;
+ font-size: 8pt;
+ line-height: 1.4;
+ }
+ .tool-call-input strong {
+ color: #495057;
+ font-weight: normal;
+ font-size: 8pt;
+ font-style: italic;
+ }
+ .tool-call-input pre {
+ background-color: #f8f9fa;
+ border: 1px solid #e9ecef;
+ border-radius: 3px;
+ padding: 10px;
+ margin: 0;
+ font-size: 8pt;
+ line-height: 1.4;
+ overflow-x: auto;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ }
+ .tool-call-input code {
+ background-color: transparent;
+ padding: 0;
+ border-radius: 0;
+ font-size: 8pt;
+ color: #2c3e50;
+ }
+ .tools-used {
+ background-color: #f8f9fa;
+ border-top: 1px solid #dee2e6;
+ padding: 8px 12px;
+ margin: 0;
+ font-size: 8pt;
+ color: #6c757d;
+ }
+ .tools-used strong {
+ color: #6c757d;
+ font-weight: normal;
+ font-size: 8pt;
+ font-style: italic;
+ }
+ /* Title-text styling - unified for observations, plans, and solutions */
+ .title-text {
+ background-color: #f8f9fa;
+ border: 1px solid #e9ecef;
+ border-radius: 3px;
+ padding: 0;
+ margin: 10px 0;
+ overflow: hidden;
+ }
+ .title-text-header {
+ background-color: #e9ecef;
+ color: #495057;
+ padding: 8px 12px;
+ margin: 0;
+ font-weight: normal;
+ font-size: 9pt;
+ font-style: italic;
+ border-bottom: 1px solid #dee2e6;
+ }
+ .title-text-header strong {
+ color: #495057;
+ font-weight: normal;
+ font-size: 9pt;
+ font-style: italic;
+ }
+ .title-text-content {
+ background-color: #f8f9fa;
+ border: none;
+ border-radius: 0;
+ padding: 10px 12px;
+ margin: 0;
+ color: #333;
+ font-size: 8pt;
+ line-height: 1.4;
+ }
+ /* Plan-specific styling - soft blue pastel */
+ .title-text.plan {
+ background-color: #e3f2fd;
+ border-color: #bbdefb;
+ }
+ .title-text.plan .title-text-header {
+ background-color: #bbdefb;
+ color: #1976d2;
+ }
+ .title-text.plan .title-text-content {
+ background-color: #e3f2fd;
+ }
+ .plan-title {
+ font-style: italic;
+ font-weight: normal;
+ color: #1565c0;
+ text-shadow: 0 1px 2px rgba(0,0,0,0.1);
+ }
+ .plan-title strong {
+ font-weight: normal;
+ }
+ /* Code execution-specific styling - matching title-text styling */
+ .tool-call-highlight {
+ background-color: #f8f9fa;
+ border-color: #e9ecef;
+ }
+ .tool-call-header {
+ background-color: #e9ecef;
+ color: #495057;
+ }
+ .tool-call-input {
+ background-color: #f8f9fa;
+ color: #333;
+ }
+ /* Observation-specific styling - soft purple pastel */
+ .title-text.observation {
+ background-color: #f3e5f5;
+ border-color: #e1bee7;
+ }
+ .title-text.observation .title-text-header {
+ background-color: #e1bee7;
+ color: #7b1fa2;
+ }
+ .title-text.observation .title-text-content {
+ background-color: #f3e5f5;
+ }
+ /* Summary and solution-specific styling - soft orange pastel, no overlay */
+ .title-text.summary {
+ background-color: #fff3e0;
+ border-color: #ffcc02;
+ }
+ .title-text.summary .title-text-header {
+ background-color: #ffcc02;
+ color: #f57c00;
+ }
+ .title-text.summary .title-text-content {
+ background-color: #fff3e0;
+ }
+ .title-text-content ul {
+ background-color: transparent;
+ border: none;
+ border-radius: 0;
+ padding: 0;
+ margin: 0;
+ color: #333;
+ font-size: 8pt;
+ line-height: 1.4;
+ }
+ .title-text-content li {
+ margin: 3px 0;
+ color: #333;
+ }
+ .title-text-content li strong {
+ color: #495057;
+ font-weight: normal;
+ font-size: 8pt;
+ font-style: italic;
+ }
+ .title-text-content li code {
+ background-color: #e9ecef;
+ color: #333;
+ padding: 1px 3px;
+ border-radius: 2px;
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
+ font-size: 7pt;
+ }
+ .title-text-content pre {
+ background-color: #f8f9fa;
+ border: 1px solid #e9ecef;
+ border-radius: 3px;
+ padding: 10px;
+ margin: 0;
+ font-size: 8pt;
+ line-height: 1.4;
+ overflow-x: auto;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ }
+ .title-text-content code {
+ background-color: transparent;
+ padding: 0;
+ border-radius: 0;
+ font-size: 8pt;
+ color: #2c3e50;
+ }
+ /* Parsing error display styling */
+ .parsing-error-box {
+ background-color: #ffebee;
+ border: 1px solid #f44336;
+ border-radius: 4px;
+ padding: 8px 12px;
+ margin: 8px 0;
+ font-size: 9pt;
+ color: #c62828;
+ box-shadow: 0 2px 4px rgba(244, 67, 54, 0.1);
+ }
+ .parsing-error-header {
+ font-weight: bold;
+ margin-bottom: 4px;
+ color: #d32f2f;
+ }
+ .parsing-error-content {
+ font-family: 'Courier New', monospace;
+ background-color: #ffcdd2;
+ padding: 4px 6px;
+ border-radius: 2px;
+ margin-top: 4px;
+ font-size: 8pt;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ }
+ """
diff --git a/Biomanus/biomni/version.py b/Biomanus/biomni/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e12f9073d99ef70cc114da06cac0f674c48f596
--- /dev/null
+++ b/Biomanus/biomni/version.py
@@ -0,0 +1 @@
+__version__ = "0.0.8" # pragma: no cover
diff --git a/Biomanus/biomni_env/README.md b/Biomanus/biomni_env/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..a561401c99fc0aca1df7d924e58c49ddcd73f396
--- /dev/null
+++ b/Biomanus/biomni_env/README.md
@@ -0,0 +1,74 @@
+# Biomni Environment Setup
+
+This directory contains scripts and configuration files to set up a comprehensive bioinformatics environment with various tools and packages.
+
+1. Clone the repository:
+ ```bash
+ git clone https://github.com/snap-stanford/Biomni.git
+ cd Biomni/biomni_env
+ ```
+
+2. Setting up the environment:
+- (a) If you want to use or try out the basic agent without the full E1 or install your own softwares, run the following script:
+
+```bash
+conda env create -f environment.yml
+```
+
+- (b) If you want to use the full environment E1, run the setup script (this script takes > 10 hours to setup, and requires a disk of at least 30 GB quota). Follow the prompts to install the desired components.
+
+```bash
+bash setup.sh
+```
+
+If you already installed the base version, and just wants to add the additional packages in the new release, you can simply do:
+
+```bash
+bash new_software_v005.sh
+```
+
+Note: we have only tested this setup.sh script with Ubuntu 22.04, 64 bit.
+
+- (c) If you want to use a reduced conda environment without R or CLI tools, run the following script:
+
+```bash
+conda env create -f fixed_env.yml
+```
+
+This contains most of the packages from environment.yml and bio_env.yml, and requires a disk of at elast 13GB quota.
+
+- (d) **Python 3.10 Environment for Copy Number Analysis**: If you specifically need to use the `analyze_copy_number_purity_ploidy_and_focal_events` function, we provide a Python 3.10 environment option. This function has specific dependency requirements that are best met with Python 3.10. To set up this environment:
+
+```bash
+conda env create -f bio_env_py310.yml
+```
+
+This environment is optimized for copy number variation analysis and includes the necessary packages for purity, ploidy, and focal event detection.
+
+3. Lastly, to activate the biomni environment:
+```bash
+conda activate biomni_e1
+```
+
+For the Python 3.10 environment specifically:
+```bash
+conda activate biomni_py310
+```
+
+### 📦 Langchain Package Support
+
+The Biomni environment comes with a minimal set of langchain packages by default:
+- `langchain-openai` - for OpenAI model support
+- `langchain-anthropic` - for Anthropic model support
+- `langchain-ollama` - for Ollama model support
+
+If you need support for other external models or services, you'll need to install additional langchain packages manually. For example:
+
+```bash
+# For AWS Bedrock support
+pip install langchain-aws
+
+# For Google Gemini support
+pip install langchain-google-genai
+
+```
diff --git a/Biomanus/biomni_env/bio_env.yml b/Biomanus/biomni_env/bio_env.yml
new file mode 100644
index 0000000000000000000000000000000000000000..5615e7f3492027c968a9e5ceefd6d7f67f80c8de
--- /dev/null
+++ b/Biomanus/biomni_env/bio_env.yml
@@ -0,0 +1,70 @@
+name: biomni_e1
+channels:
+ - conda-forge
+ - bioconda
+ - defaults
+dependencies:
+ - blast
+ - samtools
+ - bowtie2
+ - bwa
+ - bedtools
+ - fastqc
+ - trimmomatic
+ - mafft
+ - gseapy
+ - mageck
+ - plannotate
+ - pip:
+ - scanpy
+ - biopython
+ - biopandas
+ - biotite
+ - opencv-python
+ - rdkit
+ - macs2
+ - pymc3
+ - cryosparc-tools
+ - lifelines
+ - scikit-image
+ - googlesearch-python
+ - PyPDF2
+ - gget
+ - faiss-cpu
+ - cellxgene-census
+ - scikit-bio
+ - pymed
+ - arxiv
+ - scholarly
+ - umap-learn
+ - scrublet
+ - scvelo
+ - scvi-tools
+ - harmony-pytorch
+ - pyliftover
+ - pytdc==0.4.0
+ - pysam
+ - pyfaidx
+ - pyranges
+ - pybedtools
+ - openmm
+ - pystan
+ - igraph
+ - pyscenic
+ - cooler
+ - trackpy
+ - flowcytometrytools
+ - cellpose
+ - viennarna
+ - PyMassSpec
+ - python-libsbml
+ - cobra
+ - reportlab
+ #- flowkit
+ - hmmlearn
+ - msprime
+ - tskit
+ - cyvcf2
+ - pykalman
+ - community
+ - fanc
diff --git a/Biomanus/biomni_env/bio_env_py310.yml b/Biomanus/biomni_env/bio_env_py310.yml
new file mode 100644
index 0000000000000000000000000000000000000000..db0b40f4e1d0a93c5a0461c15a3c524f0799624b
--- /dev/null
+++ b/Biomanus/biomni_env/bio_env_py310.yml
@@ -0,0 +1,19 @@
+name: bio_env_py310
+channels:
+ - conda-forge
+ - bioconda
+ - defaults
+dependencies:
+ - python=3.10
+ - cnvkit
+ - samtools
+ - bedtools
+ - pip
+
+# Purpose: Python 3.10 compatibility environment for tools not yet supporting newer Python versions.
+# Automaticlly setup on setup.sh execution.
+# Contains tools that require Python 3.10 or earlier versions.
+# Can be create with:
+# micromamba create -f bio_env_py310.yml OR conda env create -f bio_env_py310.yml
+# Use tools via:
+# conda run -n bio_env_py310 ...
diff --git a/Biomanus/biomni_env/cli_tools_config.json b/Biomanus/biomni_env/cli_tools_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..19853c4e78c344401565e6ce193fb270e323aba5
--- /dev/null
+++ b/Biomanus/biomni_env/cli_tools_config.json
@@ -0,0 +1,94 @@
+{
+ "tools": [
+ {
+ "name": "PLINK 2.0",
+ "function_name": "install_plink2",
+ "description": "Whole genome association analysis toolset",
+ "website": "https://www.cog-genomics.org/plink/2.0/",
+ "downloads": {
+ "linux": "https://s3.amazonaws.com/plink2-assets/alpha6/plink2_linux_avx2_20250129.zip",
+ "macos_intel": "https://s3.amazonaws.com/plink2-assets/alpha6/plink2_mac_avx2_20250129.zip",
+ "macos_arm64": "https://s3.amazonaws.com/plink2-assets/alpha6/plink2_mac_arm64_20250129.zip"
+ },
+ "binary_path": "plink2",
+ "version_command": "--version"
+ },
+ {
+ "name": "IQ-TREE",
+ "function_name": "install_iqtree",
+ "description": "Efficient phylogenetic software by maximum likelihood",
+ "website": "http://www.iqtree.org/",
+ "downloads": {
+ "linux": "https://github.com/iqtree/iqtree2/releases/download/v2.2.2.7/iqtree-2.2.2.7-Linux.tar.gz",
+ "macos_intel": "https://github.com/iqtree/iqtree2/releases/download/v2.2.2.7/iqtree-2.2.2.7-MacOSX.zip",
+ "macos_arm64": "https://github.com/iqtree/iqtree2/releases/download/v2.2.2.7/iqtree-2.2.2.7-MacOSX.zip"
+ },
+ "binary_path": "bin/iqtree2",
+ "version_command": "--version"
+ },
+ {
+ "name": "GCTA",
+ "function_name": "install_gcta",
+ "description": "Genome-wide Complex Trait Analysis",
+ "website": "https://yanglab.westlake.edu.cn/software/gcta/",
+ "downloads": {
+ "linux": "https://yanglab.westlake.edu.cn/software/gcta/bin/gcta-1.94.4-linux-kernel-3-x86_64.zip",
+ "macos_intel": "https://yanglab.westlake.edu.cn/software/gcta/bin/gcta-1.94.1-macOS-x86_64.zip",
+ "macos_arm64": "https://yanglab.westlake.edu.cn/software/gcta/bin/gcta-1.94.3-macOS-arm64.zip"
+ },
+ "binary_path": "gcta64",
+ "version_command": ""
+ },
+ {
+ "name": "BWA",
+ "function_name": "install_bwa",
+ "description": "Burrow-Wheeler Aligner for short-read alignment",
+ "website": "https://github.com/lh3/bwa",
+ "downloads": {
+ "linux": "https://github.com/lh3/bwa.git",
+ "macos_intel": "https://github.com/lh3/bwa.git",
+ "macos_arm64": "https://github.com/lh3/bwa.git"
+ },
+ "binary_path": "bwa",
+ "version_command": ""
+ },
+ {
+ "name": "FastTree",
+ "function_name": "install_fasttree",
+ "description": "Approximately-Maximum-Likelihood phylogenetic trees from alignments",
+ "website": "https://morgannprice.github.io/fasttree/",
+ "downloads": {
+ "linux": "https://morgannprice.github.io/fasttree/FastTree.c",
+ "macos_intel": "https://morgannprice.github.io/fasttree/FastTree.c",
+ "macos_arm64": "https://morgannprice.github.io/fasttree/FastTree.c"
+ },
+ "binary_path": "FastTree",
+ "version_command": "-help | head -n 2"
+ },
+ {
+ "name": "MUSCLE",
+ "function_name": "install_muscle",
+ "description": "Multiple sequence alignment with high accuracy and performance",
+ "website": "https://github.com/rcedgar/muscle",
+ "downloads": {
+ "linux": "https://github.com/rcedgar/muscle/releases/download/v5.3/muscle-linux-x86.v5.3",
+ "macos_arm64": "https://github.com/rcedgar/muscle/releases/download/v5.3/muscle-osx-arm64.v5.3"
+ },
+ "binary_path": "muscle",
+ "version_command": "-version"
+ },
+ {
+ "name": "HOMER",
+ "function_name": "install_homer",
+ "description": "Software for motif discovery and next-gen sequencing analysis",
+ "website": "http://homer.ucsd.edu/homer/",
+ "downloads": {
+ "linux": "http://homer.ucsd.edu/homer/configureHomer.pl",
+ "macos_intel": "http://homer.ucsd.edu/homer/configureHomer.pl",
+ "macos_arm64": "http://homer.ucsd.edu/homer/configureHomer.pl"
+ },
+ "binary_path": "bin/findMotifs.pl",
+ "version_command": "-h"
+ }
+ ]
+}
diff --git a/Biomanus/biomni_env/environment.yml b/Biomanus/biomni_env/environment.yml
new file mode 100644
index 0000000000000000000000000000000000000000..5ddea13dbce382862ec193539ab77489c87b25db
--- /dev/null
+++ b/Biomanus/biomni_env/environment.yml
@@ -0,0 +1,39 @@
+name: biomni_e1
+channels:
+ - conda-forge
+ - defaults
+ - bioconda
+dependencies:
+ - python=3.11
+ - pip
+ - pip:
+ - numpy==2.1
+ - pandas
+ - matplotlib
+ - scipy
+ - statsmodels
+ - scikit-learn
+ - gradio
+ - langchain
+ - langgraph==0.3.18
+ - langchain-openai
+ - langchain-anthropic
+ - langchain-ollama
+ - langchain-community
+ - openai
+ - beautifulsoup4
+ - lxml
+ - tqdm
+ - seaborn
+ - networkx
+ - requests
+ - pyyaml
+ - jupyter
+ - notebook
+ - ipykernel
+ - pytest
+ - transformers
+ - sentencepiece
+ - mcp
+ - tooluniverse
+ - python-dotenv
diff --git a/Biomanus/biomni_env/fixed_env.yml b/Biomanus/biomni_env/fixed_env.yml
new file mode 100644
index 0000000000000000000000000000000000000000..40a1173656a2d35f47beab6db80cf9459ce9d1a4
--- /dev/null
+++ b/Biomanus/biomni_env/fixed_env.yml
@@ -0,0 +1,742 @@
+name: biomni_e1
+channels:
+ - bioconda
+ - conda-forge
+ - defaults
+dependencies:
+ - altair=5.5.0
+ - asttokens=3.0.0
+ - attrs=25.3.0
+ - aws-c-auth=0.9.0
+ - aws-c-cal=0.9.2
+ - aws-c-common=0.12.4
+ - aws-c-compression=0.3.1
+ - aws-c-event-stream=0.5.5
+ - aws-c-http=0.10.4
+ - aws-c-io=0.21.2
+ - aws-c-mqtt=0.13.3
+ - aws-c-s3=0.8.6
+ - aws-c-sdkutils=0.2.4
+ - aws-checksums=0.2.7
+ - aws-crt-cpp=0.33.1
+ - aws-sdk-cpp=1.11.606
+ - azure-core-cpp=1.16.0
+ - azure-identity-cpp=1.12.0
+ - azure-storage-blobs-cpp=12.14.0
+ - azure-storage-common-cpp=12.10.0
+ - azure-storage-files-datalake-cpp=12.12.0
+ - bedtools=2.31.1
+ - biopython=1.85
+ - blast=2.16.0
+ - blinker=1.9.0
+ - bokeh=3.7.3
+ - bowtie2=2.5.4
+ - brotli-bin=1.1.0
+ - brotli-python=1.1.0
+ - bwa=0.7.19
+ - bzip2=1.0.8
+ - c-ares=1.34.5
+ - ca-certificates=2025.8.3
+ - cairo=1.18.4
+ - certifi=2025.8.3
+ - cffi=1.17.1
+ - charset-normalizer=3.4.2
+ - contourpy=1.3.3
+ - curl=8.14.1
+ - cycler=0.12.1
+ - decorator=5.2.1
+ - diamond=2.1.13
+ - entrez-direct=22.4
+ - exceptiongroup=1.3.0
+ - executing=2.2.0
+ - fastqc=0.12.1
+ - font-ttf-dejavu-sans-mono=2.37
+ - font-ttf-inconsolata=3.000
+ - font-ttf-source-code-pro=2.038
+ - font-ttf-ubuntu=0.83
+ - fontconfig=2.15.0
+ - fonts-conda-ecosystem=1
+ - fonts-conda-forge=1
+ - fonttools=4.59.0
+ - freetype=2.13.3
+ - gflags=2.2.2
+ - giflib=5.2.2
+ - gitdb=4.0.12
+ - gitpython=3.1.45
+ - glog=0.7.1
+ - gmp=6.3.0
+ - graphite2=1.3.14
+ - gseapy=1.1.9
+ - h2=4.2.0
+ - harfbuzz=11.3.3
+ - hpack=4.1.0
+ - htslib=1.22.1
+ - hyperframe=6.1.0
+ - icu=75.1
+ - idna=3.10
+ - importlib-metadata=8.7.0
+ - infernal=1.1.5
+ - ipython=9.4.0
+ - ipython_pygments_lexers=1.1.1
+ - jedi=0.19.2
+ - jinja2=3.1.6
+ - jsonschema=4.25.0
+ - jsonschema-specifications=2025.4.1
+ - kiwisolver=1.4.8
+ - krb5=1.21.3
+ - lcms2=2.17
+ - lerc=4.0.0
+ - libabseil=20250512.1
+ - libarrow=21.0.0
+ - libarrow-acero=21.0.0
+ - libarrow-compute=21.0.0
+ - libarrow-dataset=21.0.0
+ - libarrow-substrait=21.0.0
+ - libasprintf=0.25.1
+ - libblas=3.9.0
+ - libbrotlicommon=1.1.0
+ - libbrotlidec=1.1.0
+ - libbrotlienc=1.1.0
+ - libcblas=3.9.0
+ - libcrc32c=1.1.2
+ - libcurl=8.14.1
+ - libdeflate=1.22
+ - libedit=3.1.20250104
+ - libev=4.33
+ - libevent=2.1.12
+ - libexpat=2.7.1
+ - libffi=3.4.6
+ - libfreetype=2.13.3
+ - libfreetype6=2.13.3
+ - libgettextpo=0.25.1
+ - libgfortran=15.1.0
+ - libgfortran5=15.1.0
+ - libglib=2.84.2
+ - libgoogle-cloud=2.39.0
+ - libgoogle-cloud-storage=2.39.0
+ - libgrpc=1.73.1
+ - libiconv=1.18
+ - libidn2=2.3.8
+ - libjpeg-turbo=3.1.0
+ - liblapack=3.9.0
+ - liblzma=5.8.1
+ - libnghttp2=1.64.0
+ - libopenblas=0.3.30
+ - libopentelemetry-cpp=1.21.0
+ - libopentelemetry-cpp-headers=1.21.0
+ - libparquet=21.0.0
+ - libpng=1.6.50
+ - libprotobuf=6.31.1
+ - libre2-11=2025.07.22
+ - libsqlite=3.50.4
+ - libssh2=1.11.1
+ - libthrift=0.22.0
+ - libtiff=4.7.0
+ - libunistring=0.9.10
+ - libutf8proc=2.10.0
+ - libwebp-base=1.6.0
+ - libxml2=2.13.8
+ - libzlib=1.3.1
+ - lz4-c=1.10.0
+ - mafft=7.526
+ # - mageck=0.5.9.5
+ - markupsafe=3.0.2
+ - matplotlib-base=3.10.5
+ - matplotlib-inline=0.1.7
+ - mpfr=4.2.1
+ - munkres=1.1.4
+ - narwhals=2.0.1
+ - ncbi-vdb=3.2.1
+ - ncurses=6.5
+ - nlohmann_json=3.12.0
+ - openjdk=23.0.2
+ - openjpeg=2.5.3
+ - openssl=3.5.1
+ - orc=2.1.3
+ - packaging=25.0
+ - pandas=2.3.1
+ - parso=0.8.4
+ - pcre2=10.45
+ - perl=5.32.1
+ - perl-archive-tar=3.04
+ - perl-carp=1.50
+ - perl-common-sense=3.75
+ - perl-compress-raw-bzip2=2.201
+ - perl-compress-raw-zlib=2.202
+ - perl-encode=3.21
+ - perl-exporter=5.74
+ - perl-exporter-tiny=1.002002
+ - perl-extutils-makemaker=7.70
+ - perl-io-compress=2.201
+ - perl-io-zlib=1.15
+ - perl-json=4.10
+ - perl-json-xs=4.03
+ - perl-list-moreutils=0.430
+ - perl-list-moreutils-xs=0.430
+ - perl-parent=0.243
+ - perl-pathtools=3.75
+ - perl-scalar-list-utils=1.70
+ - perl-storable=3.15
+ - perl-types-serialiser=1.01
+ - pexpect=4.9.0
+ - pickleshare=0.7.5
+ - pillow=11.3.0
+ - pip=25.2
+ - pixman=0.46.4
+ # - plannotate=1.2.0
+ - prometheus-cpp=1.3.0
+ - prompt-toolkit=3.0.51
+ - protobuf=6.31.1
+ - ptyprocess=0.7.0
+ - pure_eval=0.2.3
+ - pyarrow=21.0.0
+ - pyarrow-core=21.0.0
+ - pycparser=2.22
+ - pydeck=0.9.1
+ - pygments=2.19.2
+ - pyopengl=3.1.9
+ - pyparsing=3.2.3
+ - pysocks=1.7.1
+ - python=3.11.13
+ - python-dateutil=2.9.0.post0
+ - python-tzdata=2025.2
+ - python_abi=3.11
+ - pytz=2025.2
+ - pyyaml=6.0.2
+ - qhull=2020.2
+ - re2=2025.07.22
+ - readline=8.2
+ - referencing=0.36.2
+ - requests=2.32.4
+ - ripgrep=14.1.1
+ - rpds-py=0.26.0
+ - rpsbproc=0.5.0
+ - s2n=1.5.23
+ - samtools=1.22.1
+ - setuptools=80.9.0
+ - six=1.17.0
+ - smmap=5.0.2
+ - snappy=1.2.2
+ - stack_data=0.6.3
+ - streamlit=1.47.1
+ - tabulate=0.9.0
+ - tenacity=9.1.2
+ - tk=8.6.13
+ - toml=0.10.2
+ - tornado=6.5.1
+ - traitlets=5.14.3
+ - trimmomatic=0.39
+ - trnascan-se=2.0.12
+ - typing-extensions=4.14.1
+ - typing_extensions=4.14.1
+ - tzdata=2025b
+ - unicodedata2=16.0.0
+ - urllib3=2.5.0
+ - watchdog=6.0.0
+ - wcwidth=0.2.13
+ - wget=1.21.4
+ - wheel=0.45.1
+ - xyzservices=2025.4.0
+ - yaml=0.2.5
+ - zipp=3.23.0
+ - zlib=1.3.1
+ - zstd=1.5.7
+ - pip:
+ - absl-py==2.3.1
+ - adjusttext==1.3.0
+ - aiobotocore
+ - aiofiles==24.1.0
+ - aiohappyeyeballs==2.6.1
+ - aiohttp==3.12.15
+ - aioitertools==0.12.0
+ - aiosignal==1.4.0
+ - airr==1.5.1
+ - alabaster==1.0.0
+ - anndata==0.12.1
+ - annotated-types==0.7.0
+ - annoy==1.17.3
+ - anthropic==0.60.0
+ - anyio==4.9.0
+ - appdirs==1.4.4
+ - arboreto==0.1.6
+ - argon2-cffi==25.1.0
+ - argon2-cffi-bindings==25.1.0
+ - array-api-compat==1.12.0
+ - arrow==1.3.0
+ - arviz==0.22.0
+ - arxiv==2.2.0
+ - asciitree==0.3.3
+ - async-lru==2.0.5
+ - authlib==1.6.1
+ - autograd==1.8.0
+ - autograd-gamma==0.5.0
+ - awkward==2.8.6
+ - awkward-cpp==48
+ - babel==2.17.0
+ - beautifulsoup4==4.13.4
+ - bibtexparser==1.4.3
+ - biom-format==2.1.16
+ # - biomni==0.0.8
+ - biopandas==0.5.1
+ - biotite==1.4.0
+ - biotraj==1.2.2
+ - bleach==6.2.0
+ - blitzgsea==1.3.54
+ - blosc2==3.6.1
+ - boltons==25.0.0
+ - boto3
+ - botocore
+ - brotli==1.1.0
+ - cachetools==5.5.2
+ - cellpose==4.0.6
+ - cellxgene-census==1.17.0
+ - cftime==1.6.4.post1
+ - chex==0.1.90
+ - click==8.2.1
+ - clikit==0.6.2
+ - cloudpickle==3.1.1
+ - cobra==0.29.1
+ - colorcet==3.1.0
+ - coloredlogs==15.0.1
+ - comm==0.2.3
+ - community==1.0.0b1
+ - cooler==0.10.4
+ - crashtest==0.3.1
+ - cryosparc-tools==4.7.1
+ - cryptography==45.0.5
+ - ctxcore==0.2.0
+ - cyclopts==3.22.5
+ - cython==0.29.37
+ - cytoolz==1.0.1
+ - cyvcf2==0.31.1
+ - dask==2024.11.2
+ - dask-expr==1.1.19
+ - dask-image==2024.5.3
+ - dataclasses==0.6
+ - dataclasses-json==0.6.7
+ - datashader==0.18.1
+ - debugpy==1.8.15
+ - decoupler==2.1.1
+ - defusedxml==0.7.1
+ - demes==0.2.3
+ - depinfo==2.2.0
+ - deprecated==1.2.18
+ - deprecation==2.1.0
+ - dill==0.4.0
+ - diskcache==5.6.3
+ - distributed==2024.11.2
+ - distro==1.9.0
+ - dnspython==2.7.0
+ - docrep==0.3.2
+ - docstring-parser==0.17.0
+ - docutils==0.21.2
+ - domdf-python-tools==3.10.0
+ - drmaa==0.7.9
+ - email-validator==2.2.0
+ - enum-tools==0.13.0
+ - equinox==0.13.0
+ - et-xmlfile==2.0.0
+ - etils==1.13.0
+ - faiss-cpu==1.11.0.post1
+ - fake-useragent==2.2.0
+ - fanc==0.9.28
+ - fast-array-utils==1.2.1
+ - fastapi==0.116.1
+ - fasteners==0.19
+ - fastjsonschema==2.21.1
+ - fastmcp==2.11.0
+ - fastprogress==1.0.3
+ - fastremap==1.17.2
+ - fcsparser==0.2.4
+ - feedparser==6.0.11
+ - ffmpy==0.6.1
+ - filelock==3.18.0
+ - filetype==1.2.0
+ - fill-voids==2.1.0
+ - flask==3.1.1
+ - flax==0.11.0
+ - flowcytometrytools==0.5.1
+ - formulaic==1.2.0
+ - formulaic-contrasts==1.0.0
+ - fqdn==1.5.1
+ - free-proxy==1.1.3
+ - frozendict==2.4.6
+ - frozenlist==1.7.0
+ - fsspec==2025.7.0
+ - future==1.0.0
+ - fuzzywuzzy==0.18.0
+ - genomic-regions==0.0.10
+ - geopandas==1.1.1
+ - gget==0.29.2
+ - google-ai-generativelanguage==0.6.18
+ - google-api-core==2.25.1
+ - google-auth==2.40.3
+ - googleapis-common-protos==1.70.0
+ - googlesearch-python==1.3.0
+ - gradio==5.39.0
+ - gradio-client==1.11.0
+ - graphql-core==3.2.6
+ - greenlet==3.2.3
+ - gridmap==0.15.0
+ - groovy==0.1.2
+ - grpcio==1.74.0
+ - grpcio-status==1.74.0
+ - h11==0.16.0
+ - h5netcdf==1.6.3
+ - h5py==3.14.0
+ - harmony-pytorch==0.1.8
+ - hf-xet==1.1.5
+ - hmmlearn==0.3.3
+ - httpcore==1.0.9
+ # - httpstan==4.13.0
+ - httpx==0.28.1
+ - httpx-sse==0.4.1
+ - huggingface-hub==0.34.3
+ - humanfriendly==10.0
+ - humanize==4.12.3
+ - igraph==0.11.9
+ - imagecodecs==2025.8.2
+ - imageio==2.37.0
+ - imagesize==1.4.1
+ - importlib-resources==6.5.2
+ - inflect==7.5.0
+ - iniconfig==2.1.0
+ - interface-meta==1.3.0
+ - interlap==0.2.7
+ - intervaltree==3.1.0
+ - ipykernel==6.30.0
+ - ipywidgets==8.1.7
+ - isodate==0.7.2
+ - isoduration==20.11.0
+ - itsdangerous==2.2.0
+ - jax==0.6.2
+ - jaxlib==0.6.2
+ - jaxopt==0.8.5
+ - jaxtyping==0.3.2
+ - jiter==0.10.0
+ - jmespath==1.0.1
+ - joblib==1.5.1
+ - json5==0.12.0
+ - jsonpatch==1.33
+ - jsonpointer==3.0.0
+ - jsonschema-path==0.3.4
+ - jupyter==1.1.1
+ - jupyter-client==8.6.3
+ - jupyter-console==6.6.3
+ - jupyter-core==5.8.1
+ - jupyter-events==0.12.0
+ - jupyter-lsp==2.2.6
+ - jupyter-server==2.16.0
+ - jupyter-server-terminals==0.5.3
+ - jupyterlab==4.4.5
+ - jupyterlab-pygments==0.3.0
+ - jupyterlab-server==2.27.3
+ - jupyterlab-widgets==3.0.15
+ - lamin-utils==0.15.0
+ - langchain==0.3.27
+ - langchain-anthropic==0.3.18
+ - langchain-community==0.3.27
+ - langchain-core==0.3.72
+ # - langchain-google-genai==2.1.8
+ - langchain-ollama==0.3.6
+ - langchain-openai==0.3.28
+ - langchain-text-splitters==0.3.9
+ - langgraph==0.3.18
+ - langgraph-checkpoint==2.1.1
+ - langgraph-prebuilt==0.1.8
+ - langgraph-sdk==0.1.74
+ - langsmith==0.4.10
+ - lark==1.2.2
+ - lazy-loader==0.4
+ - lazy-object-proxy==1.11.0
+ - legacy-api-wrap==1.4.1
+ - legendkit==0.3.6
+ - levenshtein==0.27.1
+ - lifelines==0.30.0
+ - lightning==2.5.2
+ - lightning-utilities==0.15.0
+ - lineax==0.0.8
+ - llvmlite==0.44.0
+ - locket==1.0.0
+ - logomaker==0.8.7
+ - loompy==3.0.8
+ - looseversion==1.1.2
+ - lxml==6.0.0
+ - lz4==4.4.4
+ - macs2==2.2.9.1
+ - markdown==3.8.2
+ - markdown-it-py==3.0.0
+ - marshmallow==3.26.1
+ - marsilea==0.5.4
+ - matplotlib-scalebar==0.9.0
+ - mcp==1.12.3
+ - mdurl==0.1.2
+ - mistune==3.1.3
+ - ml-collections==1.1.0
+ - ml-dtypes==0.5.3
+ - mmtf-python==1.1.3
+ - more-itertools==10.7.0
+ - mpmath==1.3.0
+ - msgpack==1.1.1
+ - msgpack-numpy==0.4.8
+ - msprime==1.3.4
+ - mudata==0.3.2
+ - multidict==6.6.3
+ - multipledispatch==1.0.0
+ - multiprocess==0.70.18
+ - multiprocessing-on-dill==3.5.0a4
+ - multiscale-spatial-image==2.0.2
+ - muon==0.1.7
+ - mypy-extensions==1.1.0
+ - mysql-connector-python==9.4.0
+ - natsort==8.4.0
+ - nbclient==0.10.2
+ - nbconvert==7.16.6
+ - nbformat==5.10.4
+ - ncls==0.0.70
+ - ndindex==1.10.0
+ - nest-asyncio==1.6.0
+ - netcdf4==1.7.2
+ - networkx==3.5
+ - newick==1.10.0
+ - notebook==7.4.4
+ - notebook-shim==0.2.4
+ - numba==0.61.2
+ - numcodecs==0.15.1
+ - numexpr==2.11.0
+ - numpy==2.1.0
+ - numpy-groupies==0.11.3
+ - numpyro==0.18.0
+ # - nvidia-cublas-cu12==12.6.4.1
+ # - nvidia-cuda-cupti-cu12==12.6.80
+ # - nvidia-cuda-nvrtc-cu12==12.6.77
+ # - nvidia-cuda-runtime-cu12==12.6.77
+ # - nvidia-cudnn-cu12==9.5.1.17
+ # - nvidia-cufft-cu12==11.3.0.4
+ # - nvidia-cufile-cu12==1.11.1.6
+ # - nvidia-curand-cu12==10.3.7.77
+ # - nvidia-cusolver-cu12==11.7.1.2
+ # - nvidia-cusparse-cu12==12.5.4.2
+ # - nvidia-cusparselt-cu12==0.6.3
+ # - nvidia-nccl-cu12==2.26.2
+ # - nvidia-nvjitlink-cu12==12.6.85
+ # - nvidia-nvtx-cu12==12.6.77
+ - ollama==0.5.1
+ - ome-zarr==0.11.1
+ - omnipath==1.0.12
+ - openai==1.98.0
+ - openapi-core==0.19.5
+ - openapi-pydantic==0.5.1
+ - openapi-schema-validator==0.6.3
+ - openapi-spec-validator==0.7.2
+ - opencv-python==4.12.0.88
+ - opencv-python-headless==4.12.0.88
+ - openmm==8.3.1
+ - openpyxl==3.1.5
+ - opt-einsum==3.4.0
+ - optax==0.2.5
+ - optlang==1.8.3
+ - orbax-checkpoint==0.11.20
+ - orjson==3.11.1
+ - ormsgpack==1.10.0
+ - ott-jax==0.5.1
+ - outcome==1.3.0.post0
+ - overrides==7.7.0
+ - pandocfilters==1.5.1
+ - param==2.2.1
+ - parse==1.20.2
+ - partd==1.4.2
+ - pastel==0.2.1
+ - pathable==0.4.4
+ - patsy==1.0.1
+ - pertpy==1.0.1
+ - pims==0.7
+ - platformdirs==4.3.8
+ - pluggy==1.6.0
+ - ply==3.11
+ - pooch==1.8.2
+ - progressbar2==4.5.0
+ - prometheus-client==0.22.1
+ - propcache==0.3.2
+ - proto-plus==1.26.1
+ - psutil==7.0.0
+ - pubchempy==1.0.4
+ - py-cpuinfo==9.0.0
+ - pyarrow-hotfix==0.7
+ - pyasn1==0.6.1
+ - pyasn1-modules==0.4.2
+ - pybedtools==0.12.0
+ - pybigwig==0.3.24
+ - pyct==0.5.0
+ - pydantic==2.11.7
+ - pydantic-core==2.33.2
+ - pydantic-settings==2.10.1
+ - pydeseq2==0.5.2
+ - pydub==0.25.1
+ - pyfaidx==0.8.1.4
+ - pykalman==0.10.1
+ - pylev==1.4.0
+ - pyliftover==0.4.1
+ - pymassspec==2.6.0.post1
+ - pymc3==3.11.4
+ - pymed==0.8.9
+ - pymzml==2.5.11
+ - pynndescent==0.5.13
+ - pyogrio==0.11.1
+ - pyomo==6.9.2
+ - pypdf2==3.0.1
+ - pyperclip==1.9.0
+ - pyproj==3.7.1
+ - pyranges==0.1.4
+ - pyro-api==0.1.2
+ - pyro-ppl==1.9.1
+ - pysam==0.23.3
+ - pyscenic==0.12.1
+ - pysimdjson==6.0.2
+ # - pystan==3.10.0
+ - pytdc==0.4.0
+ - pytest==8.4.1
+ - python-dotenv==1.1.1
+ - python-json-logger==3.3.0
+ - python-levenshtein==0.27.1
+ - python-libsbml==5.20.5
+ - python-multipart==0.0.20
+ - python-utils==3.9.1
+ - pytorch-lightning==2.5.2
+ - pyzmq==27.0.1
+ - rapidfuzz==3.13.0
+ - rdkit==2025.3.5
+ - rdkit-pypi==2022.9.5
+ - regex==2025.7.34
+ - reportlab==4.4.3
+ - requests-toolbelt==1.0.0
+ - rfc3339-validator==0.1.4
+ - rfc3986-validator==0.1.1
+ - rfc3987-syntax==1.1.0
+ - rich==14.1.0
+ - rich-rst==1.3.1
+ - roifile==2025.5.10
+ - roman-numerals-py==3.1.0
+ - rsa==4.9.1
+ - ruamel-yaml==0.18.14
+ - ruamel-yaml-clib==0.2.12
+ - ruff==0.12.7
+ - s3fs==2025.7.0
+ - s3transfer==0.13.1
+ - safehttpx==0.1.6
+ - safetensors==0.5.3
+ - scanpy==1.11.4
+ - scholarly==1.7.11
+ - scikit-base==0.12.4
+ - scikit-bio==0.7.0
+ - scikit-image==0.25.2
+ - scikit-learn==1.7.1
+ - scikit-misc==0.5.1
+ - scipy==1.15.0
+ - scirpy==0.22.1
+ - scrublet==0.2.3
+ - scvelo==0.3.3
+ - scvi-tools==1.3.3
+ - sdjson==0.5.0
+ - seaborn==0.13.2
+ - segment-anything==1.0
+ - selenium==4.34.2
+ - semantic-version==2.10.0
+ - semver==3.0.4
+ - send2trash==1.8.3
+ - sentencepiece==0.2.0
+ - session-info==1.0.1
+ - session-info2==0.2
+ - sgmllib3k==1.0.0
+ - shapely==2.1.1
+ - shellingham==1.5.4
+ - simplejson==3.20.1
+ - slicerator==1.1.0
+ - sniffio==1.3.1
+ - snowballstemmer==3.0.1
+ - somacore==1.0.28
+ - sorted-nearest==0.0.39
+ - sortedcontainers==2.4.0
+ - soupsieve==2.7
+ - sparse==0.17.0
+ - sparsecca==0.3.1
+ - spatial-image==1.2.2
+ - spatialdata==0.4.0
+ - sphinx==8.2.3
+ - sphinx-rtd-theme==3.0.2
+ - sphinxcontrib-applehelp==2.0.0
+ - sphinxcontrib-devhelp==2.0.0
+ - sphinxcontrib-htmlhelp==2.1.0
+ - sphinxcontrib-jquery==4.1
+ - sphinxcontrib-jsmath==1.0.1
+ - sphinxcontrib-qthelp==2.0.0
+ - sphinxcontrib-serializinghtml==2.0.0
+ - sqlalchemy==2.0.42
+ - squarify==0.4.4
+ - squidpy==1.6.5
+ - sse-starlette==3.0.2
+ - starlette==0.47.2
+ - statsmodels==0.14.5
+ - stdlib-list==0.11.1
+ - swiglpk==5.0.12
+ - sympy==1.14.0
+ - tables==3.10.2
+ - tblib==3.1.0
+ - tensorboard==2.20.0
+ - tensorboard-data-server==0.7.2
+ - tensorstore==0.1.76
+ - terminado==0.18.1
+ - texttable==1.7.0
+ - theano-pymc==1.1.2
+ - threadpoolctl==3.6.0
+ - tifffile==2025.6.11
+ - tiktoken==0.9.0
+ - tiledbsoma==1.17.1
+ - tinycss2==1.4.0
+ - tokenizers==0.21.4
+ - tomlkit==0.13.3
+ - tooluniverse==0.2.0
+ - toolz==1.0.0
+ - torch==2.7.1
+ - torchmetrics==1.8.0
+ - torchvision==0.22.1
+ - tqdm==4.67.1
+ - trackpy==0.7
+ - transformers==4.54.1
+ - treescope==0.1.9
+ - trio==0.30.0
+ - trio-websocket==0.12.2
+ # - triton==3.3.1
+ - tskit==0.6.4
+ - typeguard==4.4.4
+ - typer==0.16.0
+ - types-python-dateutil==2.9.0.20250708
+ - typing-inspect==0.9.0
+ - typing-inspection==0.4.1
+ - umap-learn==0.5.9.post2
+ - uri-template==1.3.0
+ - uvicorn==0.35.0
+ - validators==0.35.0
+ - viennarna==2.7.0
+ - wadler-lindig==0.1.7
+ - webargs==8.7.0
+ - webcolors==24.11.1
+ - webencodings==0.5.1
+ - websocket-client==1.8.0
+ - websockets==15.0.1
+ - werkzeug==3.1.1
+ - widgetsnbextension==4.0.14
+ - wrapt==1.17.2
+ - wsproto==1.2.0
+ - xarray==2024.11.0
+ - xarray-dataclass==3.0.0
+ - xarray-dataclasses==1.9.1
+ - xarray-einstats==0.9.1
+ - xarray-schema==0.0.3
+ - xarray-spatial==0.4.0
+ - yamlordereddictloader==0.4.2
+ - yarl==1.20.1
+ - zarr==2.18.7
+ - zict==3.0.0
+ - zstandard==0.23.0
+ - mi-googlesearch-python==1.3.0.post1
diff --git a/Biomanus/biomni_env/install_cli_tools.sh b/Biomanus/biomni_env/install_cli_tools.sh
new file mode 100644
index 0000000000000000000000000000000000000000..51b4433c7f0570e87316b0a1e24736141857e026
--- /dev/null
+++ b/Biomanus/biomni_env/install_cli_tools.sh
@@ -0,0 +1,912 @@
+#!/bin/bash
+
+# Script to install command-line bioinformatics tools
+
+# Set up colors for output
+GREEN='\033[0;32m'
+RED='\033[0;31m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+NC='\033[0m' # No Color
+
+# Check for wget or fallback to curl
+if command -v wget &> /dev/null; then
+ DOWNLOADER="wget -v -O"
+elif command -v curl &> /dev/null; then
+ DOWNLOADER="curl -L -o"
+ echo -e "${YELLOW}Warning: wget not found, using curl instead.${NC}"
+else
+ echo -e "${RED}Error: Neither wget nor curl is installed.${NC}"
+ echo -e "${YELLOW}Please install one of them (e.g., brew install wget on macOS).${NC}"
+ exit 1
+fi
+
+# Check if jq is installed
+if ! command -v jq &> /dev/null; then
+ echo -e "${YELLOW}jq is not installed. Installing jq for JSON parsing...${NC}"
+ # Use conda to install jq (no sudo required)
+ conda install -y -c conda-forge jq
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to install jq with conda. Please install it manually.${NC}"
+ echo "Visit: https://stedolan.github.io/jq/download/"
+ exit 1
+ fi
+fi
+
+# Function to clean up old installations
+cleanup_old_installations() {
+ echo -e "${YELLOW}Checking for old installations...${NC}"
+
+ # Check for old installation in AFS
+ local old_afs_dir="/afs/cs.stanford.edu/u/$(whoami)/biomni_tools"
+ if [ -d "$old_afs_dir" ]; then
+ echo -e "${YELLOW}Found old installation in $old_afs_dir${NC}"
+ echo -e "${YELLOW}Removing old bin directory...${NC}"
+ rm -rf "$old_afs_dir/bin"
+ echo -e "${GREEN}Old bin directory removed.${NC}"
+ fi
+
+ # Check for old installation in HOME
+ local old_home_dir="$HOME/biomni_tools"
+ if [ -d "$old_home_dir" ] && [ "$old_home_dir" != "$TOOLS_DIR" ]; then
+ echo -e "${YELLOW}Found old installation in $old_home_dir${NC}"
+ echo -e "${YELLOW}Removing old bin directory...${NC}"
+ rm -rf "$old_home_dir/bin"
+ echo -e "${GREEN}Old bin directory removed.${NC}"
+ fi
+
+ # Clean up PATH
+ echo -e "${YELLOW}Cleaning up PATH...${NC}"
+ PATH=$(echo $PATH | tr ':' '\n' | grep -v "biomni_tools/bin" | tr '\n' ':' | sed 's/:$//')
+ export PATH="$TOOLS_DIR/bin:$PATH"
+ echo -e "${GREEN}PATH cleaned up.${NC}"
+}
+
+# Create a directory for CLI tools if it doesn't exist
+if [ -n "$BIOMNI_TOOLS_DIR" ]; then
+ TOOLS_DIR="$BIOMNI_TOOLS_DIR"
+else
+ TOOLS_DIR="$(pwd)/biomni_tools"
+fi
+
+# Clean up any existing installation if it exists
+if [ -d "$TOOLS_DIR" ]; then
+ echo -e "${YELLOW}Cleaning up existing installation in $TOOLS_DIR...${NC}"
+ # Remove bin directory to clean up symlinks
+ rm -rf "$TOOLS_DIR/bin"
+fi
+
+# Clean up old installations
+cleanup_old_installations
+
+# Create fresh directories
+mkdir -p "$TOOLS_DIR"
+mkdir -p "$TOOLS_DIR/bin"
+
+# Add the tools bin directory to PATH in the current session
+# Remove any old paths first to avoid duplicates
+PATH=$(echo $PATH | tr ':' '\n' | grep -v "biomni_tools/bin" | tr '\n' ':' | sed 's/:$//')
+export PATH="$TOOLS_DIR/bin:$PATH"
+
+# Clear the shell's command hash table to force it to re-search the PATH
+hash -r 2>/dev/null || rehash 2>/dev/null || true
+
+# Create a setup_path.sh file in the tools directory
+echo "#!/bin/bash" > "$TOOLS_DIR/setup_path.sh"
+echo "# Added by biomni setup" >> "$TOOLS_DIR/setup_path.sh"
+echo "# Remove any old paths first to avoid duplicates" >> "$TOOLS_DIR/setup_path.sh"
+echo "PATH=\$(echo \$PATH | tr ':' '\n' | grep -v \"biomni_tools/bin\" | tr '\n' ':' | sed 's/:$//')" >> "$TOOLS_DIR/setup_path.sh"
+echo "export PATH=\"$TOOLS_DIR/bin:\$PATH\"" >> "$TOOLS_DIR/setup_path.sh"
+echo "# Clear the shell's command hash table to force it to re-search the PATH" >> "$TOOLS_DIR/setup_path.sh"
+echo "hash -r 2>/dev/null || rehash 2>/dev/null || true" >> "$TOOLS_DIR/setup_path.sh"
+chmod +x "$TOOLS_DIR/setup_path.sh"
+
+# Config file path
+CONFIG_FILE="cli_tools_config.json"
+
+# Check if config file exists
+if [ ! -f "$CONFIG_FILE" ]; then
+ echo -e "${RED}Configuration file $CONFIG_FILE not found.${NC}"
+ exit 1
+fi
+
+# Function to download and install a tool
+install_tool() {
+ local tool_name=$1
+ local download_url=$2
+ local binary_path=$3
+ local version_cmd=$4
+ local tool_dir_name=$(echo "$tool_name" | tr '[:upper:]' '[:lower:]' | tr ' .' '_')
+ local binary_name=$(basename "$binary_path")
+
+ echo -e "\n${BLUE}=== Installing $tool_name ===${NC}"
+
+ # Check if the tool is already installed
+ if [ -f "$TOOLS_DIR/bin/$binary_name" ]; then
+ echo -e "${GREEN}$tool_name is already installed at $TOOLS_DIR/bin/$binary_name${NC}"
+ echo -e "${YELLOW}Testing installation...${NC}"
+
+ if [ -n "$version_cmd" ]; then
+ echo -e "${YELLOW}Running version command: $TOOLS_DIR/bin/$binary_name $version_cmd${NC}"
+ $TOOLS_DIR/bin/$binary_name $version_cmd
+ fi
+
+ echo -e "${GREEN}Skipping download and installation.${NC}"
+ return 0
+ fi
+
+ # Create directory for the tool
+ mkdir -p "$TOOLS_DIR/$tool_dir_name"
+
+ # Special handling for HOMER
+ if [ "$tool_name" = "HOMER" ]; then
+ echo -e "${YELLOW}Installing HOMER via Perl script...${NC}"
+
+ # Download the configuration script directly to the bin directory
+ $DOWNLOADER "$TOOLS_DIR/bin/configureHomer.pl" "$download_url"
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to download HOMER configuration script from $download_url${NC}"
+ return 1
+ fi
+
+ # Make the script executable
+ chmod +x "$TOOLS_DIR/bin/configureHomer.pl"
+
+ # Create a HOMER installation directory
+ mkdir -p "$TOOLS_DIR/$tool_dir_name/homer"
+
+ # Run the configuration script
+ echo -e "${YELLOW}Running HOMER configuration script...${NC}"
+ echo -e "${YELLOW}This will install HOMER to $TOOLS_DIR/$tool_dir_name/homer${NC}"
+
+ # Install HOMER with batch mode ("-b" flag for basic installation)
+ # Use -local to specify the absolute installation directory
+ "$TOOLS_DIR/bin/configureHomer.pl" -install -local "$TOOLS_DIR/$tool_dir_name/homer" -b
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to install HOMER.${NC}"
+ return 1
+ fi
+
+ # Create symlinks to HOMER binaries
+ echo -e "${YELLOW}Creating symlinks to HOMER binaries...${NC}"
+ for homer_bin in "$TOOLS_DIR/$tool_dir_name/homer/bin/"*; do
+ if [ -f "$homer_bin" ] && [ -x "$homer_bin" ]; then
+ ln -sf "$homer_bin" "$TOOLS_DIR/bin/$(basename "$homer_bin")"
+ fi
+ done
+
+ # Create a sourceable environment setup file
+ echo "#!/bin/bash" > "$TOOLS_DIR/$tool_dir_name/homer_env.sh"
+ echo "export PATH=\"$TOOLS_DIR/$tool_dir_name/homer/bin:\$PATH\"" >> "$TOOLS_DIR/$tool_dir_name/homer_env.sh"
+ echo "export HOMER=\"$TOOLS_DIR/$tool_dir_name/homer\"" >> "$TOOLS_DIR/$tool_dir_name/homer_env.sh"
+ chmod +x "$TOOLS_DIR/$tool_dir_name/homer_env.sh"
+
+ # Add the HOMER environment to the global setup_path.sh
+ echo "# HOMER environment" >> "$TOOLS_DIR/setup_path.sh"
+ echo "export PATH=\"$TOOLS_DIR/$tool_dir_name/homer/bin:\$PATH\"" >> "$TOOLS_DIR/setup_path.sh"
+ echo "export HOMER=\"$TOOLS_DIR/$tool_dir_name/homer\"" >> "$TOOLS_DIR/setup_path.sh"
+
+ echo -e "${GREEN}HOMER installed successfully!${NC}"
+ echo -e "${YELLOW}To use HOMER, you may need to source the environment file:${NC}"
+ echo -e "${GREEN}source $TOOLS_DIR/$tool_dir_name/homer_env.sh${NC}"
+ echo -e "${YELLOW}Or you can run configureHomer.pl directly from:${NC}"
+ echo -e "${GREEN}$TOOLS_DIR/bin/configureHomer.pl${NC}"
+ return 0
+
+ # Special handling for FastTree (requires compilation)
+ elif [ "$tool_name" = "FastTree" ]; then
+ echo -e "${YELLOW}Installing FastTree from source...${NC}"
+
+ # Download the source
+ $DOWNLOADER "$TOOLS_DIR/$tool_dir_name/FastTree.c" "$download_url"
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to download FastTree source from $download_url${NC}"
+ return 1
+ fi
+
+ # Compile FastTree
+ echo -e "${YELLOW}Compiling FastTree...${NC}"
+ echo -e "${YELLOW}This may take a few minutes.${NC}"
+
+ # Try to compile with SSE support first
+ (cd "$TOOLS_DIR/$tool_dir_name" && gcc -O3 -finline-functions -funroll-loops -Wall -o FastTree FastTree.c -lm)
+
+ # If compilation fails, try without SSE support
+ if [ $? -ne 0 ]; then
+ echo -e "${YELLOW}Compilation with SSE failed, trying without SSE...${NC}"
+ (cd "$TOOLS_DIR/$tool_dir_name" && gcc -DNO_SSE -O3 -finline-functions -funroll-loops -Wall -o FastTree FastTree.c -lm)
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to compile FastTree.${NC}"
+ return 1
+ fi
+ fi
+
+ # Create symlink
+ ln -sf "$TOOLS_DIR/$tool_dir_name/FastTree" "$TOOLS_DIR/bin/FastTree"
+
+ echo -e "${GREEN}FastTree installed successfully!${NC}"
+
+ # Test installation
+ if [ -f "$TOOLS_DIR/bin/FastTree" ]; then
+ echo -e "${GREEN}FastTree installed successfully!${NC}"
+ if [ -n "$version_cmd" ]; then
+ echo -e "${YELLOW}Running version command: $TOOLS_DIR/bin/FastTree $version_cmd | head -n 5${NC}"
+ "$TOOLS_DIR/bin/FastTree" $version_cmd | head -n 5
+ fi
+ else
+ echo -e "${RED}FastTree installation failed.${NC}"
+ echo -e "${YELLOW}Binary not found at: $TOOLS_DIR/bin/FastTree${NC}"
+ return 1
+ fi
+
+ return 0
+
+ # Special handling for BWA (requires compilation)
+ elif [ "$tool_name" = "BWA" ]; then
+ echo -e "${YELLOW}Installing BWA...${NC}"
+
+ # Check if git is installed
+ if ! command -v git &> /dev/null; then
+ echo -e "${RED}Git is not installed. Please install git to continue.${NC}"
+ return 1
+ fi
+
+ # Clone the repository
+ echo -e "${YELLOW}Cloning BWA repository from $download_url...${NC}"
+ mkdir -p "$TOOLS_DIR/$tool_dir_name"
+ git clone "$download_url" "$TOOLS_DIR/$tool_dir_name"
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to clone BWA repository from $download_url${NC}"
+ return 1
+ fi
+
+ # Compile BWA
+ echo -e "${YELLOW}Compiling BWA...${NC}"
+ (cd "$TOOLS_DIR/$tool_dir_name" && make)
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to compile BWA.${NC}"
+ return 1
+ fi
+
+ # Create symlink
+ ln -sf "$TOOLS_DIR/$tool_dir_name/bwa" "$TOOLS_DIR/bin/bwa"
+
+ # Test installation
+ if [ -f "$TOOLS_DIR/bin/bwa" ]; then
+ echo -e "${GREEN}BWA installed successfully!${NC}"
+ echo -e "${YELLOW}Running version check:${NC}"
+ "$TOOLS_DIR/bin/bwa" 2>&1 | head -n 3
+ else
+ echo -e "${RED}BWA installation failed.${NC}"
+ echo -e "${YELLOW}Binary not found at: $TOOLS_DIR/bin/bwa${NC}"
+ return 1
+ fi
+
+ return 0
+ fi
+
+ # Download the tool
+ echo -e "${YELLOW}Downloading $tool_name from: $download_url${NC}"
+
+ # Determine file extension
+ if [[ "$download_url" == *".zip" ]]; then
+ # Use verbose output to help diagnose issues
+ $DOWNLOADER "$TOOLS_DIR/$tool_dir_name.zip" "$download_url"
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to download $tool_name from $download_url${NC}"
+ echo -e "${YELLOW}Please check your internet connection and try again.${NC}"
+ echo -e "${YELLOW}If the problem persists, the download URL may be incorrect or the server may be down.${NC}"
+ return 1
+ fi
+
+ echo -e "${YELLOW}Extracting $tool_name...${NC}"
+ unzip -q -o "$TOOLS_DIR/$tool_dir_name.zip" -d "$TOOLS_DIR/$tool_dir_name"
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to extract $tool_name.${NC}"
+ return 1
+ fi
+
+ # Clean up
+ rm "$TOOLS_DIR/$tool_dir_name.zip"
+ elif [[ "$download_url" == *".tar.gz" ]]; then
+ # Use verbose output to help diagnose issues
+ $DOWNLOADER "$TOOLS_DIR/$tool_dir_name.tar.gz" "$download_url"
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to download $tool_name from $download_url${NC}"
+ echo -e "${YELLOW}Please check your internet connection and try again.${NC}"
+ echo -e "${YELLOW}If the problem persists, the download URL may be incorrect or the server may be down.${NC}"
+ return 1
+ fi
+
+ echo -e "${YELLOW}Extracting $tool_name...${NC}"
+ mkdir -p "$TOOLS_DIR/$tool_dir_name"
+ tar -xzf "$TOOLS_DIR/$tool_dir_name.tar.gz" -C "$TOOLS_DIR/$tool_dir_name" --strip-components=1
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to extract $tool_name.${NC}"
+ return 1
+ fi
+
+ # Clean up
+ rm "$TOOLS_DIR/$tool_dir_name.tar.gz"
+ # Handle executable files directly (for MUSCLE)
+ elif [[ "$tool_name" = "MUSCLE" ]]; then
+ echo -e "${YELLOW}Downloading $tool_name binary...${NC}"
+ $DOWNLOADER "$TOOLS_DIR/$tool_dir_name/$binary_name" "$download_url"
+
+ if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to download $tool_name from $download_url${NC}"
+ return 1
+ fi
+
+ # Make executable
+ chmod +x "$TOOLS_DIR/$tool_dir_name/$binary_name"
+
+ # Create symlink
+ ln -sf "$TOOLS_DIR/$tool_dir_name/$binary_name" "$TOOLS_DIR/bin/$binary_name"
+
+ # Test installation
+ if [ -f "$TOOLS_DIR/bin/$binary_name" ]; then
+ echo -e "${GREEN}$tool_name installed successfully!${NC}"
+ if [ -n "$version_cmd" ]; then
+ echo -e "${YELLOW}Running version command: $TOOLS_DIR/bin/$binary_name $version_cmd${NC}"
+ "$TOOLS_DIR/bin/$binary_name" $version_cmd
+ fi
+ else
+ echo -e "${RED}$tool_name installation failed.${NC}"
+ echo -e "${YELLOW}Binary not found at: $TOOLS_DIR/bin/$binary_name${NC}"
+ return 1
+ fi
+
+ return 0
+ else
+ echo -e "${RED}Unsupported file format for $tool_name.${NC}"
+ return 1
+ fi
+
+ # Find the binary path
+ local full_binary_path=$(find "$TOOLS_DIR/$tool_dir_name" -name "$(basename "$binary_path")" | head -n 1)
+
+ if [ -z "$full_binary_path" ]; then
+ echo -e "${RED}Could not find binary for $tool_name.${NC}"
+ echo -e "${YELLOW}Looking for binary at expected path: $TOOLS_DIR/$tool_dir_name/$binary_path${NC}"
+ full_binary_path="$TOOLS_DIR/$tool_dir_name/$binary_path"
+ fi
+
+ # Make the binary executable
+ chmod +x "$full_binary_path"
+
+ # Create symlink in bin directory
+ ln -sf "$full_binary_path" "$TOOLS_DIR/bin/$binary_name"
+
+ # Test installation
+ if [ -f "$TOOLS_DIR/bin/$binary_name" ]; then
+ echo -e "${GREEN}$tool_name installed successfully!${NC}"
+ if [ -n "$version_cmd" ]; then
+ echo -e "${YELLOW}Running version command: $TOOLS_DIR/bin/$binary_name $version_cmd${NC}"
+ "$TOOLS_DIR/bin/$binary_name" $version_cmd
+ fi
+ else
+ echo -e "${RED}$tool_name installation failed.${NC}"
+ echo -e "${YELLOW}Binary not found at: $TOOLS_DIR/bin/$binary_name${NC}"
+ return 1
+ fi
+
+ return 0
+}
+
+# Function to install a tool from the config
+install_tool_from_config() {
+ local tool_index=$1
+ local auto_install=${2:-0}
+
+ # Get tool information from config
+ local tool_name=$(jq -r ".tools[$tool_index].name" "$CONFIG_FILE")
+ local tool_desc=$(jq -r ".tools[$tool_index].description" "$CONFIG_FILE")
+
+ # Determine the appropriate download URL based on the system
+ local download_url=""
+ if [[ "$(uname)" == "Darwin" ]]; then
+ if [[ "$(uname -m)" == "arm64" ]]; then
+ # macOS M1
+ download_url=$(jq -r ".tools[$tool_index].downloads.macos_arm64" "$CONFIG_FILE")
+ else
+ # macOS Intel
+ download_url=$(jq -r ".tools[$tool_index].downloads.macos_intel" "$CONFIG_FILE")
+ fi
+ else
+ # Linux
+ download_url=$(jq -r ".tools[$tool_index].downloads.linux" "$CONFIG_FILE")
+ fi
+
+ local binary_path=$(jq -r ".tools[$tool_index].binary_path" "$CONFIG_FILE")
+ local version_cmd=$(jq -r ".tools[$tool_index].version_command" "$CONFIG_FILE")
+
+ # Install the tool
+ echo -e "\n${YELLOW}$tool_name: $tool_desc${NC}"
+
+ # If auto_install is enabled, install without asking
+ if [ "$auto_install" -eq 1 ]; then
+ install_tool "$tool_name" "$download_url" "$binary_path" "$version_cmd"
+ return $?
+ fi
+
+ # Otherwise, ask for confirmation
+ read -p "Install $tool_name? (y/n) " -n 1 -r
+ echo
+ if [[ $REPLY =~ ^[Yy]$ ]]; then
+ install_tool "$tool_name" "$download_url" "$binary_path" "$version_cmd"
+ return $?
+ fi
+
+ return 0
+}
+
+# Function to add a new tool to the config
+add_new_tool() {
+ echo -e "\n${BLUE}=== Add a New Tool ===${NC}"
+
+ read -p "Tool name: " tool_name
+ read -p "Tool description: " tool_desc
+ read -p "Tool website: " tool_website
+ read -p "Linux download URL: " linux_url
+ read -p "macOS Intel download URL: " macos_intel_url
+ read -p "macOS ARM64 download URL: " macos_arm64_url
+ read -p "Binary path (relative to extraction): " binary_path
+ read -p "Version command (e.g., --version): " version_cmd
+
+ # Generate function name
+ function_name="install_$(echo "$tool_name" | tr '[:upper:]' '[:lower:]' | tr ' .' '_')"
+
+ # Create new tool JSON
+ new_tool=$(cat < "$CONFIG_FILE.tmp" && mv "$CONFIG_FILE.tmp" "$CONFIG_FILE"
+
+ echo -e "${GREEN}Tool added to configuration!${NC}"
+
+ # Ask if user wants to install the tool now
+ read -p "Install $tool_name now? (y/n) " -n 1 -r
+ echo
+ if [[ $REPLY =~ ^[Yy]$ ]]; then
+ local tool_index=$(jq '.tools | length - 1' "$CONFIG_FILE")
+ install_tool_from_config "$tool_index"
+ fi
+}
+
+# Function to install all tools
+install_all_tools() {
+ local auto_install=${1:-0}
+ local num_tools=$(jq '.tools | length' "$CONFIG_FILE")
+
+ echo -e "\n${BLUE}Installing all command-line tools...${NC}"
+
+ for (( i=0; i<$num_tools; i++ )); do
+ install_tool_from_config "$i" "$auto_install"
+ done
+
+ return 0
+}
+
+# Function to add PATH to shell profile
+add_path_to_profile() {
+ local force_profile=${1:-""}
+
+ # Try to detect the shell profile file
+ local profile_file=""
+ local shell_name=$(basename "$SHELL")
+
+ # Create a sourceable file in the tools directory with PATH cleanup
+ echo "#!/bin/bash" > "$TOOLS_DIR/setup_path.sh"
+ echo "# Added by biomni setup" >> "$TOOLS_DIR/setup_path.sh"
+ echo "# Remove any old paths first to avoid duplicates" >> "$TOOLS_DIR/setup_path.sh"
+ echo "PATH=\$(echo \$PATH | tr ':' '\n' | grep -v \"biomni_tools/bin\" | tr '\n' ':' | sed 's/:$//')" >> "$TOOLS_DIR/setup_path.sh"
+ echo "export PATH=\"$TOOLS_DIR/bin:\$PATH\"" >> "$TOOLS_DIR/setup_path.sh"
+ echo "# Clear the shell's command hash table to force it to re-search the PATH" >> "$TOOLS_DIR/setup_path.sh"
+ echo "hash -r 2>/dev/null || rehash 2>/dev/null || true" >> "$TOOLS_DIR/setup_path.sh"
+ chmod +x "$TOOLS_DIR/setup_path.sh"
+ echo -e "${GREEN}Created sourceable file at $TOOLS_DIR/setup_path.sh${NC}"
+ echo -e "${YELLOW}You can add this to your PATH by running:${NC}"
+ echo -e "${GREEN}source $TOOLS_DIR/setup_path.sh${NC}"
+
+ # If a specific profile is forced, use that
+ if [ -n "$force_profile" ]; then
+ profile_file="$HOME/$force_profile"
+ echo -e "${YELLOW}Using specified profile file: $profile_file${NC}"
+ else
+ # Auto-detect based on current shell
+ case "$shell_name" in
+ bash)
+ if [ -f "$HOME/.bash_profile" ]; then
+ profile_file="$HOME/.bash_profile"
+ elif [ -f "$HOME/.profile" ]; then
+ profile_file="$HOME/.profile"
+ elif [ -f "$HOME/.bashrc" ]; then
+ profile_file="$HOME/.bashrc"
+ fi
+ ;;
+ zsh)
+ profile_file="$HOME/.zshrc"
+ ;;
+ fish)
+ # Fish has a different configuration structure
+ mkdir -p "$HOME/.config/fish"
+ profile_file="$HOME/.config/fish/config.fish"
+ ;;
+ *)
+ # For other shells, try common profile files
+ if [ -f "$HOME/.profile" ]; then
+ profile_file="$HOME/.profile"
+ elif [ -f "$HOME/.bashrc" ]; then
+ profile_file="$HOME/.bashrc"
+ elif [ -f "$HOME/.zshrc" ]; then
+ profile_file="$HOME/.zshrc"
+ fi
+ ;;
+ esac
+ fi
+
+ # If we found a profile file and it's writable, add the PATH
+ if [ -n "$profile_file" ]; then
+ # Create the file if it doesn't exist
+ if [ ! -f "$profile_file" ]; then
+ echo -e "${YELLOW}Creating new profile file: $profile_file${NC}"
+ touch "$profile_file"
+ fi
+
+ if [ -w "$profile_file" ]; then
+ # Check if the PATH is already in the profile
+ if ! grep -q "export PATH=\"$TOOLS_DIR/bin:\$PATH\"" "$profile_file"; then
+ # Remove any old biomni_tools paths first
+ if grep -q "biomni_tools/bin" "$profile_file"; then
+ echo -e "${YELLOW}Removing old biomni_tools paths from $profile_file...${NC}"
+ sed -i '/biomni_tools\/bin/d' "$profile_file"
+ fi
+
+ echo "" >> "$profile_file"
+ echo "# Added by biomni setup" >> "$profile_file"
+ echo "# Remove any old paths first to avoid duplicates" >> "$profile_file"
+ echo "PATH=\$(echo \$PATH | tr ':' '\n' | grep -v \"biomni_tools/bin\" | tr '\n' ':' | sed 's/:$//')" >> "$profile_file"
+
+ # Use the appropriate syntax for the shell
+ if [ "$shell_name" = "fish" ]; then
+ echo "set -gx PATH $TOOLS_DIR/bin \$PATH" >> "$profile_file"
+ else
+ echo "export PATH=\"$TOOLS_DIR/bin:\$PATH\"" >> "$profile_file"
+ fi
+
+ echo -e "${GREEN}Added tools directory to PATH in $profile_file${NC}"
+ echo -e "${YELLOW}Note: You may need to restart your shell or run 'source $profile_file' for changes to take effect.${NC}"
+ else
+ echo -e "${GREEN}PATH already configured in $profile_file${NC}"
+ fi
+ else
+ echo -e "${RED}Profile file $profile_file is not writable.${NC}"
+ echo -e "${YELLOW}Please add the following line to your shell profile manually:${NC}"
+
+ if [ "$shell_name" = "fish" ]; then
+ echo -e "${GREEN}set -gx PATH $TOOLS_DIR/bin \$PATH${NC}"
+ else
+ echo -e "${GREEN}export PATH=\"$TOOLS_DIR/bin:\$PATH\"${NC}"
+ fi
+
+ echo -e "${YELLOW}Or source the setup file we created:${NC}"
+ echo -e "${GREEN}source $TOOLS_DIR/setup_path.sh${NC}"
+ fi
+ else
+ # If we couldn't find a profile file, just print instructions
+ echo -e "${YELLOW}Could not determine appropriate shell profile file.${NC}"
+ echo -e "${YELLOW}Please add the following line to your shell profile manually:${NC}"
+
+ if [ "$shell_name" = "fish" ]; then
+ echo -e "${GREEN}set -gx PATH $TOOLS_DIR/bin \$PATH${NC}"
+ else
+ echo -e "${GREEN}export PATH=\"$TOOLS_DIR/bin:\$PATH\"${NC}"
+ fi
+
+ echo -e "${YELLOW}Or source the setup file we created:${NC}"
+ echo -e "${GREEN}source $TOOLS_DIR/setup_path.sh${NC}"
+ fi
+
+ # Always export PATH for the current session
+ # Remove any old paths first to avoid duplicates
+ PATH=$(echo $PATH | tr ':' '\n' | grep -v "biomni_tools/bin" | tr '\n' ':' | sed 's/:$//')
+ export PATH="$TOOLS_DIR/bin:$PATH"
+
+ # Clear the shell's command hash table to force it to re-search the PATH
+ hash -r 2>/dev/null || rehash 2>/dev/null || true
+
+ # Create a test script to verify the tools are in the PATH
+ echo "#!/bin/bash" > "$TOOLS_DIR/test_tools.sh"
+ echo "echo \"Testing if tools are in the PATH...\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo "echo \"Current PATH: \$PATH\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo "echo \"\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo "echo \"Looking for tools in: $TOOLS_DIR/bin\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo "ls -la \"$TOOLS_DIR/bin\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo "echo \"\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo "echo \"Checking for path caching issues...\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo "for tool in \$(ls \"$TOOLS_DIR/bin\"); do" >> "$TOOLS_DIR/test_tools.sh"
+ echo " which \$tool 2>/dev/null | grep -q \"/afs/cs.stanford.edu\" && {" >> "$TOOLS_DIR/test_tools.sh"
+ echo " echo \"WARNING: \$tool is still pointing to the old AFS location!\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo " echo \"Run 'hash -r' (bash) or 'rehash' (zsh) to clear the command cache.\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo " break" >> "$TOOLS_DIR/test_tools.sh"
+ echo " }" >> "$TOOLS_DIR/test_tools.sh"
+ echo "done" >> "$TOOLS_DIR/test_tools.sh"
+ echo "echo \"\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo "for tool in \$(ls \"$TOOLS_DIR/bin\"); do" >> "$TOOLS_DIR/test_tools.sh"
+ echo " if command -v \$tool &> /dev/null; then" >> "$TOOLS_DIR/test_tools.sh"
+ echo " echo \"\$tool: \$(which \$tool)\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo " else" >> "$TOOLS_DIR/test_tools.sh"
+ echo " echo \"\$tool: NOT FOUND IN PATH\"" >> "$TOOLS_DIR/test_tools.sh"
+ echo " fi" >> "$TOOLS_DIR/test_tools.sh"
+ echo "done" >> "$TOOLS_DIR/test_tools.sh"
+ chmod +x "$TOOLS_DIR/test_tools.sh"
+
+ echo -e "${YELLOW}Created test script at $TOOLS_DIR/test_tools.sh${NC}"
+ echo -e "${YELLOW}You can run it to verify the tools are in your PATH:${NC}"
+ echo -e "${GREEN}$TOOLS_DIR/test_tools.sh${NC}"
+
+ # Create a quick fix script for path caching issues
+ echo "#!/bin/bash" > "$TOOLS_DIR/fix_path.sh"
+ echo "# Script to fix path caching issues" >> "$TOOLS_DIR/fix_path.sh"
+ echo "echo \"Fixing path caching issues...\"" >> "$TOOLS_DIR/fix_path.sh"
+ echo "# Remove any old paths first to avoid duplicates" >> "$TOOLS_DIR/fix_path.sh"
+ echo "PATH=\$(echo \$PATH | tr ':' '\n' | grep -v \"biomni_tools/bin\" | tr '\n' ':' | sed 's/:$//')" >> "$TOOLS_DIR/fix_path.sh"
+ echo "export PATH=\"$TOOLS_DIR/bin:\$PATH\"" >> "$TOOLS_DIR/fix_path.sh"
+ echo "# Clear the shell's command hash table to force it to re-search the PATH" >> "$TOOLS_DIR/fix_path.sh"
+ echo "hash -r 2>/dev/null || rehash 2>/dev/null || true" >> "$TOOLS_DIR/fix_path.sh"
+ echo "echo \"Path fixed. Try running your command again.\"" >> "$TOOLS_DIR/fix_path.sh"
+ chmod +x "$TOOLS_DIR/fix_path.sh"
+
+ echo -e "${YELLOW}Created fix script at $TOOLS_DIR/fix_path.sh${NC}"
+ echo -e "${YELLOW}If you encounter 'No such file or directory' errors, run:${NC}"
+ echo -e "${GREEN}source $TOOLS_DIR/fix_path.sh${NC}"
+}
+
+# Function to verify installation
+verify_installation() {
+ echo -e "\n${BLUE}=== Verifying Installation ===${NC}"
+ echo -e "${YELLOW}Tools directory: $TOOLS_DIR${NC}"
+ echo -e "${YELLOW}Bin directory: $TOOLS_DIR/bin${NC}"
+
+ # Check if bin directory exists
+ if [ ! -d "$TOOLS_DIR/bin" ]; then
+ echo -e "${RED}Bin directory does not exist!${NC}"
+ return 1
+ fi
+
+ # Check if there are any tools in the bin directory
+ local tool_count=$(ls -1 "$TOOLS_DIR/bin" 2>/dev/null | wc -l)
+ if [ "$tool_count" -eq 0 ]; then
+ echo -e "${RED}No tools found in bin directory!${NC}"
+ return 1
+ fi
+
+ echo -e "${GREEN}Found $tool_count tools in bin directory.${NC}"
+
+ # List all tools
+ echo -e "${YELLOW}Installed tools:${NC}"
+ ls -la "$TOOLS_DIR/bin"
+
+ # Check if tools are in PATH
+ echo -e "\n${YELLOW}Checking if tools are in PATH...${NC}"
+ echo -e "${YELLOW}Current PATH: $PATH${NC}"
+
+ # Check if TOOLS_DIR/bin is in PATH
+ if [[ "$PATH" == *"$TOOLS_DIR/bin"* ]]; then
+ echo -e "${GREEN}Tools directory is in PATH.${NC}"
+ else
+ echo -e "${RED}Tools directory is NOT in PATH!${NC}"
+ echo -e "${YELLOW}Please run: source $TOOLS_DIR/setup_path.sh${NC}"
+ return 1
+ fi
+
+ # Check if each tool is accessible
+ echo -e "\n${YELLOW}Testing tool accessibility:${NC}"
+ for tool in $(ls "$TOOLS_DIR/bin"); do
+ if command -v "$tool" &> /dev/null; then
+ echo -e "${GREEN}$tool: $(which $tool)${NC}"
+ else
+ echo -e "${RED}$tool: NOT FOUND IN PATH${NC}"
+ fi
+ done
+
+ echo -e "\n${GREEN}Installation verification completed.${NC}"
+ echo -e "${YELLOW}If you encounter any issues, please run:${NC}"
+ echo -e "${GREEN}source $TOOLS_DIR/setup_path.sh${NC}"
+ echo -e "${YELLOW}And then run the test script:${NC}"
+ echo -e "${GREEN}$TOOLS_DIR/test_tools.sh${NC}"
+
+ echo -e "\n${YELLOW}IMPORTANT: If you see 'No such file or directory' errors when running tools,${NC}"
+ echo -e "${YELLOW}your shell may be using cached paths to old tool locations.${NC}"
+ echo -e "${YELLOW}To fix this, run:${NC}"
+ echo -e "${GREEN}source $TOOLS_DIR/fix_path.sh${NC}"
+ echo -e "${YELLOW}Or run one of these commands:${NC}"
+ echo -e "${GREEN}hash -r${NC} (for bash/sh)"
+ echo -e "${GREEN}rehash${NC} (for zsh/csh)"
+ echo -e "${YELLOW}Or simply start a new terminal session.${NC}"
+
+ return 0
+}
+
+# Main installation function
+install_cli_tools() {
+ echo -e "${YELLOW}=== Installing Command-Line Bioinformatics Tools ===${NC}"
+
+ # Try to add the tools bin directory to PATH
+ add_path_to_profile
+
+ # Check if auto-install mode is enabled
+ if [ -n "$BIOMNI_AUTO_INSTALL" ]; then
+ install_all_tools 1
+
+ echo -e "\n${GREEN}CLI tools installation completed!${NC}"
+ echo -e "The tools are installed in: ${YELLOW}$TOOLS_DIR${NC}"
+ echo -e "Binaries are symlinked in: ${YELLOW}$TOOLS_DIR/bin${NC}"
+ echo -e "Tools have been added to your PATH for the current session."
+
+ # Verify installation
+ verify_installation
+
+ return 0
+ fi
+
+ # Get the number of tools in the config
+ local num_tools=$(jq '.tools | length' "$CONFIG_FILE")
+
+ # Display menu
+ echo -e "\n${BLUE}Available tools:${NC}"
+ for (( i=0; i<$num_tools; i++ )); do
+ local tool_name=$(jq -r ".tools[$i].name" "$CONFIG_FILE")
+ local tool_desc=$(jq -r ".tools[$i].description" "$CONFIG_FILE")
+ echo -e "${YELLOW}$((i+1)). $tool_name${NC} - $tool_desc"
+ done
+ echo -e "${YELLOW}$((num_tools+1)). Add a new tool${NC}"
+ echo -e "${YELLOW}$((num_tools+2)). Install all tools${NC}"
+ echo -e "${YELLOW}$((num_tools+3)). Add tools directory to shell profile${NC}"
+ echo -e "${YELLOW}0. Exit${NC}"
+
+ # Get user choice
+ read -p "Enter your choice (0-$((num_tools+3))): " choice
+
+ if [[ "$choice" -eq 0 ]]; then
+ echo -e "${YELLOW}Exiting...${NC}"
+ return 0
+ elif [[ "$choice" -eq $((num_tools+1)) ]]; then
+ add_new_tool
+ elif [[ "$choice" -eq $((num_tools+2)) ]]; then
+ # Install all tools
+ install_all_tools
+ elif [[ "$choice" -eq $((num_tools+3)) ]]; then
+ # Add to shell profile
+ echo -e "\n${BLUE}=== Adding to Shell Profile ===${NC}"
+ echo -e "1. Auto-detect profile (recommended)"
+ echo -e "2. Specify profile file"
+ read -p "Enter your choice (1-2): " profile_choice
+
+ if [[ "$profile_choice" -eq 1 ]]; then
+ add_path_to_profile
+ elif [[ "$profile_choice" -eq 2 ]]; then
+ echo -e "\nCommon profile files:"
+ echo -e "- .bash_profile (for Bash on macOS/login shells)"
+ echo -e "- .bashrc (for Bash on Linux/non-login shells)"
+ echo -e "- .zshrc (for Zsh)"
+ echo -e "- .config/fish/config.fish (for Fish)"
+ echo -e "- .profile (generic)"
+ read -p "Enter profile filename (without $HOME/ prefix): " profile_file
+ add_path_to_profile "$profile_file"
+ else
+ echo -e "${RED}Invalid choice.${NC}"
+ fi
+ elif [[ "$choice" -ge 1 ]] && [[ "$choice" -le "$num_tools" ]]; then
+ # Install selected tool
+ install_tool_from_config "$((choice-1))"
+ else
+ echo -e "${RED}Invalid choice.${NC}"
+ return 1
+ fi
+
+ echo -e "\n${GREEN}CLI tools installation completed!${NC}"
+ echo -e "The tools are installed in: ${YELLOW}$TOOLS_DIR${NC}"
+ echo -e "Binaries are symlinked in: ${YELLOW}$TOOLS_DIR/bin${NC}"
+ echo -e "Tools have been added to your PATH for the current session."
+
+ # Ask if user wants to install more tools or configure PATH
+ read -p "Install more tools or configure PATH? (y/n) " -n 1 -r
+ echo
+ if [[ $REPLY =~ ^[Yy]$ ]]; then
+ install_cli_tools
+ fi
+}
+
+# Function to display help message
+show_help() {
+ echo "Usage: $0 [OPTION]"
+ echo "Install command-line bioinformatics tools for BioAgentOS."
+ echo
+ echo "Options:"
+ echo " --auto Automatically install all tools without prompting"
+ echo " --profile PROFILE Add tools directory to the specified shell profile file"
+ echo " Example: $0 --profile .zshrc"
+ echo " --help Display this help message and exit"
+ echo
+ echo "Without options, the script runs in interactive mode."
+}
+
+# Check command-line arguments
+if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
+ show_help
+ exit 0
+elif [ "$1" = "--auto" ]; then
+ # Set BIOMNI_AUTO_INSTALL if it's not already set
+ export BIOMNI_AUTO_INSTALL=1
+
+ # Run in auto-install mode without showing the menu
+ install_all_tools 1
+
+ # Add to profile automatically
+ add_path_to_profile
+
+ # Verify installation
+ verify_installation
+
+ echo -e "\n${GREEN}CLI tools installation completed!${NC}"
+ echo -e "The tools are installed in: ${YELLOW}$TOOLS_DIR${NC}"
+ echo -e "Binaries are symlinked in: ${YELLOW}$TOOLS_DIR/bin${NC}"
+ echo -e "Tools have been added to your PATH for the current session."
+
+ exit 0
+elif [ "$1" = "--profile" ] && [ -n "$2" ]; then
+ # Add to a specific profile file
+ add_path_to_profile "$2"
+ exit 0
+elif [ -n "$BIOMNI_AUTO_INSTALL" ]; then
+ # Run in auto-install mode without showing the menu
+ install_all_tools 1
+
+ # Add to profile automatically
+ add_path_to_profile
+
+ # Verify installation
+ verify_installation
+
+ echo -e "\n${GREEN}CLI tools installation completed!${NC}"
+ echo -e "The tools are installed in: ${YELLOW}$TOOLS_DIR${NC}"
+ echo -e "Binaries are symlinked in: ${YELLOW}$TOOLS_DIR/bin${NC}"
+ echo -e "Tools have been added to your PATH for the current session."
+
+ exit 0
+elif [ -n "$1" ]; then
+ echo -e "${RED}Unknown option: $1${NC}"
+ show_help
+ exit 1
+else
+ # Run the interactive installation
+ install_cli_tools
+fi
diff --git a/Biomanus/biomni_env/install_r_packages.R b/Biomanus/biomni_env/install_r_packages.R
new file mode 100644
index 0000000000000000000000000000000000000000..c5c13e159bdb75993f585c5ab855153cfa064768
--- /dev/null
+++ b/Biomanus/biomni_env/install_r_packages.R
@@ -0,0 +1,132 @@
+#!/usr/bin/env Rscript
+
+# Script to install R packages that might be missing from the conda environment
+# Run this script after creating the conda environment if you encounter issues with R packages
+
+# Set repository
+options(repos = c(CRAN = "https://cran.rstudio.com/"))
+
+# Function to install a package if it's not already installed
+install_if_missing <- function(package_name, bioconductor = FALSE) {
+ if (!require(package_name, character.only = TRUE, quietly = TRUE)) {
+ cat(sprintf("Installing package: %s\n", package_name))
+
+ if (bioconductor) {
+ if (!require("BiocManager", quietly = TRUE)) {
+ install.packages("BiocManager", dependencies = TRUE)
+ }
+ BiocManager::install(package_name, update = FALSE, ask = FALSE, dependencies = TRUE)
+ } else {
+ install.packages(package_name, dependencies = TRUE)
+ }
+
+ # Check if installation was successful
+ if (require(package_name, character.only = TRUE, quietly = TRUE)) {
+ cat(sprintf("✓ Successfully installed %s\n", package_name))
+ } else {
+ cat(sprintf("✗ Failed to install %s\n", package_name))
+ }
+ } else {
+ cat(sprintf("✓ Package %s is already installed\n", package_name))
+ }
+}
+
+# Install BiocManager first with dependencies
+cat("Installing BiocManager...\n")
+if (!require("BiocManager", quietly = TRUE)) {
+ install.packages("BiocManager", dependencies = TRUE)
+}
+
+# Make sure BiocManager is up to date
+BiocManager::install(version = BiocManager::version(), update = TRUE, ask = FALSE)
+
+# Install system dependencies for Bioconductor packages
+cat("\nInstalling system dependencies for Bioconductor packages...\n")
+
+# Install CRAN packages
+cran_packages <- c(
+ "ggplot2",
+ "lme4",
+ "dplyr",
+ "tidyr",
+ "readr",
+ "stringr",
+ "Matrix", # Required for Seurat
+ "Rcpp", # Required for many packages
+ "devtools", # Useful for package installation
+ "remotes", # Required for GitHub installations
+ "harmony"
+)
+
+# Install Bioconductor packages
+bioc_packages <- c(
+ "DESeq2",
+ "dada2",
+ "xcms",
+ "flowCore",
+ "edgeR",
+ "limma"
+)
+
+# Install CRAN packages
+cat("\nInstalling CRAN packages...\n")
+for (pkg in cran_packages) {
+ install_if_missing(pkg)
+}
+
+# Install Bioconductor packages one by one with specific handling
+cat("\nInstalling Bioconductor packages...\n")
+
+# Install DESeq2 with dependencies
+cat("\nInstalling DESeq2 and dependencies...\n")
+if (!require("DESeq2", quietly = TRUE)) {
+ BiocManager::install("DESeq2", dependencies = TRUE, update = FALSE, ask = FALSE)
+}
+
+# Install WGCNA (from CRAN, not Bioconductor)
+# Following official instructions from https://cran.r-project.org/web/packages/WGCNA/index.html
+cat("\nInstalling WGCNA and dependencies...\n")
+if (!require("WGCNA", quietly = TRUE)) {
+ # Install WGCNA dependencies first
+ wgcna_deps <- c("dynamicTreeCut", "fastcluster", "matrixStats", "Hmisc", "foreach", "doParallel")
+ for (dep in wgcna_deps) {
+ install_if_missing(dep)
+ }
+
+ # Install Bioconductor dependencies for WGCNA
+ bioc_deps <- c("impute", "preprocessCore", "GO.db", "AnnotationDbi")
+ for (dep in bioc_deps) {
+ if (!require(dep, character.only = TRUE, quietly = TRUE)) {
+ BiocManager::install(dep, update = FALSE, ask = FALSE)
+ }
+ }
+
+ # Install WGCNA from CRAN
+ install.packages("WGCNA", dependencies = TRUE)
+}
+
+# Install clusterProfiler
+cat("\nInstalling clusterProfiler and dependencies...\n")
+if (!require("clusterProfiler", quietly = TRUE)) {
+ BiocManager::install("clusterProfiler", dependencies = TRUE, update = FALSE, ask = FALSE)
+}
+
+# Install remaining Bioconductor packages
+remaining_bioc <- setdiff(bioc_packages, c("DESeq2", "clusterProfiler"))
+for (pkg in remaining_bioc) {
+ install_if_missing(pkg, bioconductor = TRUE)
+}
+
+# Verify installations
+cat("\nVerifying installations...\n")
+all_packages <- c(cran_packages, bioc_packages, "WGCNA")
+for (pkg in unique(all_packages)) {
+ if (require(pkg, character.only = TRUE, quietly = TRUE)) {
+ cat(sprintf("✓ Package %s is successfully installed\n", pkg))
+ } else {
+ cat(sprintf("✗ Package %s is NOT installed\n", pkg))
+ }
+}
+
+cat("\nPackage installation completed!\n")
+cat("If you still encounter issues with specific packages, please install them manually.\n")
diff --git a/Biomanus/biomni_env/new_software_v008.sh b/Biomanus/biomni_env/new_software_v008.sh
new file mode 100644
index 0000000000000000000000000000000000000000..306d68857fa6f21db868adb72fba0952ffd0a3f9
--- /dev/null
+++ b/Biomanus/biomni_env/new_software_v008.sh
@@ -0,0 +1,18 @@
+# Biomni v0.0.8 - Incremental Software Installation
+# Add any new packages/software introduced in version 0.0.8 below
+pip install transformers sentencepiece langchain-google-genai langchain_ollama mcp
+pip install lazyslide
+pip install "git+https://github.com/YosefLab/popV.git@refs/pull/100/head"
+pip install uv
+sudo apt-get install git-lfs # or brew install git-lfs if you are on macOS
+git lfs install
+pip install pybiomart
+pip install fair-esm
+pip install uv
+uv pip install transcriptformer
+pip install "zarr>=2.0,<3.0" #this resolved transcripformer download isses
+uv tool install arc-state
+pip install nnunet nibabel nilearn
+pip install mi-googlesearch-python
+pip install git+https://github.com/pylabrobot/pylabrobot.git
+conda install weasyprint
diff --git a/Biomanus/biomni_env/r_packages.yml b/Biomanus/biomni_env/r_packages.yml
new file mode 100644
index 0000000000000000000000000000000000000000..783bd949e7fe6cc598c7172a6b7507e9a877f117
--- /dev/null
+++ b/Biomanus/biomni_env/r_packages.yml
@@ -0,0 +1,7 @@
+name: biomni_e1
+channels:
+ - conda-forge
+ - defaults
+dependencies:
+ - r-essentials
+ - r-base>=4.4
diff --git a/Biomanus/biomni_env/setup.sh b/Biomanus/biomni_env/setup.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9b1796ac4298e045c7b483eafbb8b5b7323f71b5
--- /dev/null
+++ b/Biomanus/biomni_env/setup.sh
@@ -0,0 +1,232 @@
+#!/bin/bash
+
+# BioAgentOS - Biomni Environment Setup Script
+# This script sets up a comprehensive bioinformatics environment with various tools and packages
+
+# Set up colors for output
+GREEN='\033[0;32m'
+RED='\033[0;31m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+NC='\033[0m' # No Color
+
+# Default tools directory is the current directory
+DEFAULT_TOOLS_DIR="$(pwd)/biomni_tools"
+TOOLS_DIR=""
+
+echo -e "${YELLOW}=== Biomni Environment Setup ===${NC}"
+echo -e "${BLUE}This script will set up a comprehensive bioinformatics environment with various tools and packages.${NC}"
+
+# Check if conda is installed
+if ! command -v conda &> /dev/null && ! command -v micromamba &> /dev/null; then
+ echo -e "${RED}Error: Conda is not installed or not in PATH.${NC}"
+ echo "Please install Miniconda or Anaconda first."
+ echo "Visit: https://docs.conda.io/en/latest/miniconda.html"
+ exit 1
+fi
+
+# redirect to micromamba if needed
+if ! command -v conda &> /dev/null && command -v micromamba &> /dev/null; then
+ conda() {
+ micromamba "$@"
+ }
+ export -f conda
+fi
+
+# Function to handle errors
+handle_error() {
+ local exit_code=$1
+ local error_message=$2
+ local optional=${3:-false}
+
+ if [ $exit_code -ne 0 ]; then
+ echo -e "${RED}Error: $error_message${NC}"
+ if [ "$optional" = true ]; then
+ echo -e "${YELLOW}Continuing with setup as this component is optional.${NC}"
+ return 0
+ else
+ if [ -z "$NON_INTERACTIVE" ]; then
+ read -p "Continue with setup? (y/n) " -n 1 -r
+ echo
+ if [[ ! $REPLY =~ ^[Yy]$ ]]; then
+ echo -e "${RED}Setup aborted.${NC}"
+ exit 1
+ fi
+ else
+ echo -e "${YELLOW}Non-interactive mode: continuing despite error.${NC}"
+ fi
+ fi
+ fi
+ return $exit_code
+}
+
+# Function to install a specific environment file
+install_env_file() {
+ local env_file=$1
+ local description=$2
+ local optional=${3:-false}
+
+ echo -e "\n${BLUE}=== Installing $description ===${NC}"
+
+ if [ "$optional" = true ]; then
+ if [ -z "$NON_INTERACTIVE" ]; then
+ read -p "Do you want to install $description? (y/n) " -n 1 -r
+ echo
+ if [[ ! $REPLY =~ ^[Yy]$ ]]; then
+ echo -e "${YELLOW}Skipping $description installation.${NC}"
+ return 0
+ fi
+ else
+ echo -e "${YELLOW}Non-interactive mode: automatically installing $description.${NC}"
+ fi
+ fi
+
+ echo -e "${YELLOW}Installing $description from $env_file...${NC}"
+ conda env update -f $env_file
+ handle_error $? "Failed to install $description." $optional
+
+ if [ $? -eq 0 ]; then
+ echo -e "${GREEN}Successfully installed $description!${NC}"
+ fi
+}
+
+# Function to install CLI tools
+install_cli_tools() {
+ echo -e "\n${BLUE}=== Installing Command-Line Bioinformatics Tools ===${NC}"
+
+ # Ask user for the directory to install CLI tools
+ if [ -z "$NON_INTERACTIVE" ]; then
+ echo -e "${YELLOW}Where would you like to install the command-line tools?${NC}"
+ echo -e "${BLUE}Default: $DEFAULT_TOOLS_DIR${NC}"
+ read -p "Enter directory path (or press Enter for default): " user_tools_dir
+ else
+ user_tools_dir=""
+ echo -e "${YELLOW}Non-interactive mode: using default directory $DEFAULT_TOOLS_DIR for CLI tools.${NC}"
+ fi
+
+ if [ -z "$user_tools_dir" ]; then
+ TOOLS_DIR="$DEFAULT_TOOLS_DIR"
+ else
+ TOOLS_DIR="$user_tools_dir"
+ fi
+
+ # Export the tools directory for the CLI tools installer
+ export BIOMNI_TOOLS_DIR="$TOOLS_DIR"
+
+ echo -e "${YELLOW}Installing command-line tools (PLINK, IQ-TREE, GCTA, etc.) to $TOOLS_DIR...${NC}"
+
+ # Set environment variable to skip prompts in the CLI tools installer
+ export BIOMNI_AUTO_INSTALL=1
+
+ # Run the CLI tools installer
+ bash install_cli_tools.sh
+ handle_error $? "Failed to install CLI tools." true
+
+ if [ $? -eq 0 ]; then
+ echo -e "${GREEN}Successfully installed command-line tools!${NC}"
+
+ # Create a setup_path.sh file in the current directory
+ echo "#!/bin/bash" > setup_path.sh
+ echo "# Added by biomni setup" >> setup_path.sh
+ echo "# Remove any old paths first to avoid duplicates" >> setup_path.sh
+ echo "PATH=\$(echo \$PATH | tr ':' '\n' | grep -v \"biomni_tools/bin\" | tr '\n' ':' | sed 's/:$//')" >> setup_path.sh
+ echo "export PATH=\"$TOOLS_DIR/bin:\$PATH\"" >> setup_path.sh
+ chmod +x setup_path.sh
+
+ echo -e "${GREEN}Created setup_path.sh in the current directory.${NC}"
+ echo -e "${YELLOW}You can add the tools to your PATH by running:${NC}"
+ echo -e "${GREEN}source $(pwd)/setup_path.sh${NC}"
+
+ # Also add to the current session
+ # Remove any old paths first to avoid duplicates
+ PATH=$(echo $PATH | tr ':' '\n' | grep -v "biomni_tools/bin" | tr '\n' ':' | sed 's/:$//')
+ export PATH="$TOOLS_DIR/bin:$PATH"
+ fi
+
+ # Unset the environment variables
+ unset BIOMNI_AUTO_INSTALL
+ unset BIOMNI_TOOLS_DIR
+}
+
+# Main installation process
+main() {
+ # Step 1: Create base conda environment
+ echo -e "\n${YELLOW}Step 1: Creating base environment from environment.yml...${NC}"
+ conda env create -n biomni_e1 -f environment.yml
+ handle_error $? "Failed to create base conda environment."
+
+ # Step 2: Activate the environment
+ echo -e "\n${YELLOW}Step 2: Activating conda environment...${NC}"
+ if command -v micromamba &> /dev/null; then
+ eval "$("$MAMBA_EXE" shell hook --shell bash)"
+ micromamba activate biomni_e1
+ else
+ eval "$(conda shell.bash hook)"
+ conda activate biomni_e1
+ fi
+ handle_error $? "Failed to activate biomni_e1 environment."
+
+ # Step 3: Install core bioinformatics tools (including QIIME2)
+ echo -e "\n${YELLOW}Step 3: Installing core bioinformatics tools (including QIIME2)...${NC}"
+ install_env_file "bio_env.yml" "core bioinformatics tools"
+
+ # Step 4: Install R packages
+ echo -e "\n${YELLOW}Step 4: Installing R packages...${NC}"
+ install_env_file "r_packages.yml" "core R packages"
+
+ # Step 5: Install additional R packages through R's package manager
+ echo -e "\n${YELLOW}Step 5: Installing additional R packages through R's package manager...${NC}"
+ Rscript install_r_packages.R
+ handle_error $? "Failed to install additional R packages." true
+
+ # Step 6: Install CLI tools
+ echo -e "\n${YELLOW}Step 6: Installing command-line bioinformatics tools...${NC}"
+ install_cli_tools
+
+ # Setup completed
+ echo -e "\n${GREEN}=== Biomni Environment Setup Completed! ===${NC}"
+ echo -e "You can now run the example analysis with: ${YELLOW}python bio_analysis_example.py${NC}"
+ echo -e "To activate this environment in the future, run: ${YELLOW}conda activate biomni_e1${NC}"
+ echo -e "To use BioAgentOS, navigate to the BioAgentOS directory and follow the instructions in the README."
+
+ # Display CLI tools setup instructions
+ if [ -n "$TOOLS_DIR" ]; then
+ echo -e "\n${BLUE}=== Command-Line Tools Setup ===${NC}"
+ echo -e "The command-line tools are installed in: ${YELLOW}$TOOLS_DIR${NC}"
+ echo -e "To add these tools to your PATH, run: ${YELLOW}source $(pwd)/setup_path.sh${NC}"
+ echo -e "You can also add this line to your shell profile for permanent access:"
+ echo -e "${GREEN}export PATH=\"$TOOLS_DIR/bin:\$PATH\"${NC}"
+
+ # Test if tools are accessible
+ echo -e "\n${BLUE}=== Testing CLI Tools ===${NC}"
+ if command -v plink2 &> /dev/null; then
+ echo -e "${GREEN}PLINK2 is accessible in the current PATH${NC}"
+ echo -e "PLINK2 location: $(which plink2)"
+ else
+ echo -e "${RED}PLINK2 is not accessible in the current PATH${NC}"
+ echo -e "Please run: ${YELLOW}source $(pwd)/setup_path.sh${NC} to update your PATH"
+ fi
+
+ if command -v gcta64 &> /dev/null; then
+ echo -e "${GREEN}GCTA is accessible in the current PATH${NC}"
+ echo -e "GCTA location: $(which gcta64)"
+ else
+ echo -e "${RED}GCTA is not accessible in the current PATH${NC}"
+ echo -e "Please run: ${YELLOW}source $(pwd)/setup_path.sh${NC} to update your PATH"
+ fi
+
+ if command -v iqtree2 &> /dev/null; then
+ echo -e "${GREEN}IQ-TREE is accessible in the current PATH${NC}"
+ echo -e "IQ-TREE location: $(which iqtree2)"
+ else
+ echo -e "${RED}IQ-TREE is not accessible in the current PATH${NC}"
+ echo -e "Please run: ${YELLOW}source $(pwd)/setup_path.sh${NC} to update your PATH"
+ fi
+ fi
+
+ PATH=$(echo $PATH | tr ':' '\n' | grep -v "biomni_tools/bin" | tr '\n' ':' | sed 's/:$//')
+ export PATH="$(pwd)/biomni_tools/bin:$PATH"
+}
+
+# Run the main installation process
+main
diff --git a/Biomanus/biomni_predict.py b/Biomanus/biomni_predict.py
new file mode 100644
index 0000000000000000000000000000000000000000..d14c6c07118409794219d527371897b26edb84bc
--- /dev/null
+++ b/Biomanus/biomni_predict.py
@@ -0,0 +1,57 @@
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+
+sys.path.append("/225040511/project/Hypo_Bio_OS")
+
+from biomni.agent.a1 import A1
+
+
+def extract_answer(text: str) -> str:
+ text = str(text)
+ match = re.search(r"(.*?)", text, flags=re.S | re.I)
+ if match:
+ text = match.group(1)
+ text = re.sub(r"?[^>]+>", "", text)
+ text = text.strip()
+ marker = re.search(r"##\s*(.*)", text)
+ if marker:
+ text = marker.group(1).strip()
+ return text
+
+
+def load_payload(input_file: Path) -> dict:
+ return json.loads(input_file.read_text(encoding="utf-8"))
+
+
+def write_payload(output_file: Path, payload: dict) -> None:
+ output_file.write_text(json.dumps(payload, ensure_ascii=True), encoding="utf-8")
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--input-file", required=True)
+ parser.add_argument("--output-file", required=True)
+ args = parser.parse_args()
+
+ request = load_payload(Path(args.input_file))
+ prompt = request["prompt"]
+ agent_kwargs = request.get("agent_kwargs", {})
+
+ agent = A1(**agent_kwargs)
+ _, final_message = agent.go(prompt)
+ answer = extract_answer(final_message)
+
+ write_payload(
+ Path(args.output_file),
+ {
+ "answer": answer,
+ "final_message": str(final_message),
+ },
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Biomanus/biomni_web/ARCHITECTURE_SEQUENCE.md b/Biomanus/biomni_web/ARCHITECTURE_SEQUENCE.md
new file mode 100644
index 0000000000000000000000000000000000000000..419f12a1b8cd927bb9a1428c74f1f12caa423b3b
--- /dev/null
+++ b/Biomanus/biomni_web/ARCHITECTURE_SEQUENCE.md
@@ -0,0 +1,46 @@
+# Biomni Web 数据流时序图(当前实现)
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant U as 用户
+ participant FE as Frontend (ChatBox/api.js)
+ participant BE as FastAPI (/chat/stream)
+ participant SM as SessionManager
+ participant AG as V1ExecutorAgent
+ participant V1 as BioinfoV1Executor
+ participant RT as MCPToolRouter
+ participant MCP as MCP Tool / Docker or Python
+
+ U->>FE: 输入消息并点击 Run
+ FE->>BE: GET /chat/stream?message&session_id (SSE)
+ BE->>SM: get_agent(session_id)
+ SM-->>BE: 返回 V1ExecutorAgent
+ BE->>AG: go(message) (线程中执行)
+
+ AG->>AG: 解析会话上传文件并构建 manifest(r1/r2)
+ AG->>V1: execute_task(task, input_manifest, task_scope)
+ V1->>V1: 生成 plan(qc/trim/align/...)
+
+ loop 每个计划步骤
+ V1->>RT: 选择/解析可用 MCP route
+ RT-->>V1: 返回 tool function + server script
+ V1->>MCP: 调用工具(docker 或 python backend)
+ MCP-->>V1: step result / artifact / error
+ AG-->>BE: print Thought/Action/Observation
+ BE-->>FE: SSE 事件(thinking/tool_use/observation)
+ end
+
+ V1-->>AG: 返回 report(to_dict)
+ AG-->>BE: print 最终汇总
+ BE-->>FE: SSE 事件(result + done)
+ FE-->>U: 左侧展示最终结果,右侧展示推理步骤
+```
+
+## 关键逻辑说明
+
+- 前端协议保持不变:仍然是 `EventSource` 接收 SSE 结构化事件。
+- 后端执行引擎已切到 `BioClawMCP/agent_system/engines/v1_executor.py`。
+- 会话文件上传后,agent 依据会话内 FASTQ 文件生成 `input_manifest`,再触发 `execute_task`。
+- 步骤内的工具调用由 `MCPToolRouter` 决定具体 server script/function。
+- 后端通过 `StreamingCallback` 把打印输出映射为 SSE 事件并实时回推前端。
diff --git a/Biomanus/biomni_web/backend/analysis/pbmc/input/dataset_overview.json b/Biomanus/biomni_web/backend/analysis/pbmc/input/dataset_overview.json
new file mode 100644
index 0000000000000000000000000000000000000000..6a82efbc0f21fe31c85e0ed6aa711d1245118e83
--- /dev/null
+++ b/Biomanus/biomni_web/backend/analysis/pbmc/input/dataset_overview.json
@@ -0,0 +1,64 @@
+{
+ "dataset_name": "3k PBMCs from 10x Genomics (Healthy Donor)",
+ "species": "Homo sapiens",
+ "tissue": "Peripheral Blood Mononuclear Cells (PBMCs)",
+ "platform": "10x Genomics Chromium v1",
+ "source_url": "https://cf.10xgenomics.com/samples/cell-exp/1.1.0/pbmc3k/pbmc3k_filtered_gene_bc_matrices.tar.gz",
+ "reference": "Zheng et al. 2017, Nature Communications",
+ "download_date": "2026-05-06 15:12:56",
+ "processing_pipeline": "Scanpy 1.10.x",
+ "cell_count": 2700,
+ "gene_count": 32738,
+ "cells_passing_qc": 2698,
+ "qc_stats": {
+ "n_genes_by_counts": {
+ "min": 212.0,
+ "median": 817.0,
+ "max": 3422.0
+ },
+ "total_counts_umi": {
+ "min": 548.0,
+ "median": 2197.0,
+ "max": 15844.0
+ },
+ "pct_counts_mt": {
+ "min": 0.0,
+ "median": 2.02963924407959,
+ "max": 22.569026947021484
+ }
+ },
+ "cell_type_composition": {
+ "B cells": {
+ "count": 347,
+ "percentage": 12.86
+ },
+ "CD14+ Monocytes": {
+ "count": 451,
+ "percentage": 16.72
+ },
+ "CD16+ Monocytes": {
+ "count": 200,
+ "percentage": 7.41
+ },
+ "CD4+ T cells": {
+ "count": 1197,
+ "percentage": 44.37
+ },
+ "Dendritic cells": {
+ "count": 36,
+ "percentage": 1.33
+ },
+ "Megakaryocytes": {
+ "count": 13,
+ "percentage": 0.48
+ },
+ "NK cells": {
+ "count": 446,
+ "percentage": 16.53
+ },
+ "Proliferating cells": {
+ "count": 8,
+ "percentage": 0.3
+ }
+ }
+}
\ No newline at end of file
diff --git a/Biomanus/biomni_web/backend/analysis/pbmc/input/processing_log.json b/Biomanus/biomni_web/backend/analysis/pbmc/input/processing_log.json
new file mode 100644
index 0000000000000000000000000000000000000000..0374074361ab1e2c87f77557f346869150db275d
--- /dev/null
+++ b/Biomanus/biomni_web/backend/analysis/pbmc/input/processing_log.json
@@ -0,0 +1,136 @@
+{
+ "project": "PBMC 3k Single-Cell Dataset Curation",
+ "date": "2026-05-06 15:13:20",
+ "download_sources": [
+ {
+ "source": "10x Genomics Official Website",
+ "url": "https://cf.10xgenomics.com/samples/cell-exp/1.1.0/pbmc3k/pbmc3k_filtered_gene_bc_matrices.tar.gz",
+ "method": "scanpy.datasets.pbmc3k()",
+ "description": "3k PBMCs from a Healthy Donor, 10x Genomics v1 chemistry"
+ }
+ ],
+ "processing_steps": [
+ {
+ "step": 1,
+ "action": "Download raw filtered gene-barcode matrices",
+ "tool": "scanpy.datasets.pbmc3k()"
+ },
+ {
+ "step": 2,
+ "action": "Convert to AnnData (h5ad) format",
+ "tool": "scanpy + anndata"
+ },
+ {
+ "step": 3,
+ "action": "Compute QC metrics: n_genes_by_counts, total_counts, pct_counts_mt",
+ "tool": "sc.pp.calculate_qc_metrics"
+ },
+ {
+ "step": 4,
+ "action": "Filter cells (min_genes=200) and genes (min_cells=3)",
+ "tool": "sc.pp.filter_cells, sc.pp.filter_genes"
+ },
+ {
+ "step": 5,
+ "action": "Filter high mitochondrial content cells (pct_counts_mt < 20%)",
+ "tool": "manual filtering"
+ },
+ {
+ "step": 6,
+ "action": "Normalize (target_sum=1e4), log1p transform",
+ "tool": "sc.pp.normalize_total, sc.pp.log1p"
+ },
+ {
+ "step": 7,
+ "action": "Identify highly variable genes (1865 genes)",
+ "tool": "sc.pp.highly_variable_genes"
+ },
+ {
+ "step": 8,
+ "action": "Scale data, PCA (50 components)",
+ "tool": "sc.pp.scale, sc.tl.pca"
+ },
+ {
+ "step": 9,
+ "action": "Compute neighborhood graph and UMAP",
+ "tool": "sc.pp.neighbors, sc.tl.umap"
+ },
+ {
+ "step": 10,
+ "action": "Leiden clustering (resolution=0.5, 8 clusters)",
+ "tool": "sc.tl.leiden"
+ },
+ {
+ "step": 11,
+ "action": "Compute marker genes (Wilcoxon rank-sum test)",
+ "tool": "sc.tl.rank_genes_groups"
+ },
+ {
+ "step": 12,
+ "action": "Annotate cell types based on marker gene expression",
+ "tool": "Manual annotation using know-how document markers"
+ },
+ {
+ "step": 13,
+ "action": "Save output files",
+ "tool": "adata.write()"
+ }
+ ],
+ "output_files": [
+ {
+ "filename": "pbmc3k_annotated.h5ad",
+ "description": "Preprocessed and annotated AnnData with PCA, UMAP, clustering, cell types"
+ },
+ {
+ "filename": "pbmc3k_raw.h5ad",
+ "description": "Raw counts with QC metrics (no preprocessing)"
+ },
+ {
+ "filename": "dataset_overview.json",
+ "description": "JSON metadata with dataset statistics and cell type composition"
+ }
+ ],
+ "qc_summary": {
+ "total_cells_raw": 2700,
+ "total_genes_raw": 32738,
+ "cells_after_qc": 2698,
+ "genes_after_qc": 1865,
+ "median_umi_per_cell": 2197,
+ "median_genes_per_cell": 817,
+ "median_mitochondrial_pct": 2.03
+ },
+ "cell_type_composition": {
+ "B cells": {
+ "count": 347,
+ "percentage": 12.86
+ },
+ "CD14+ Monocytes": {
+ "count": 451,
+ "percentage": 16.72
+ },
+ "CD16+ Monocytes": {
+ "count": 200,
+ "percentage": 7.41
+ },
+ "CD4+ T cells": {
+ "count": 1197,
+ "percentage": 44.37
+ },
+ "Dendritic cells": {
+ "count": 36,
+ "percentage": 1.33
+ },
+ "Megakaryocytes": {
+ "count": 13,
+ "percentage": 0.48
+ },
+ "NK cells": {
+ "count": 446,
+ "percentage": 16.53
+ },
+ "Proliferating cells": {
+ "count": 8,
+ "percentage": 0.3
+ }
+ }
+}
\ No newline at end of file
diff --git a/Biomanus/biomni_web/backend/bioinfomcp_converter.py b/Biomanus/biomni_web/backend/bioinfomcp_converter.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e050e73abf16582605af0f0f016039afaa945d7
--- /dev/null
+++ b/Biomanus/biomni_web/backend/bioinfomcp_converter.py
@@ -0,0 +1,253 @@
+import ast
+import os
+import re
+import subprocess
+from pathlib import Path
+
+import pymupdf
+from dotenv import load_dotenv
+
+load_dotenv()
+
+
+'''
+# 0. Check whether that particular library is already installed (otherwise cannot run the help function)
+# 1. Run the --help function
+# 2. Let GPT-4 analyze the result from the help manual, attain the
+ a) What tools are there
+ i) For each tools, what is the input, output
+ ii) the CLI command, error handling
+ iii) capture output
+ iv) check output whether it is correct
+'''
+
+
+class BioinfoMCP():
+ def __init__(self, model="openai"):
+ prompt_path = Path(__file__).resolve().parent / "system_prompt.txt"
+ self.sys_prompt = prompt_path.read_text(encoding="utf-8")
+ self.provider = (model or "openai").strip().lower()
+ self.api_model_name = os.getenv("MODEL_NAME")
+
+ if self.provider == "azure":
+ from openai import AzureOpenAI
+ # Load Environment Keys
+ api_subscription_key = os.getenv('AZURE_OPENAI_KEY')
+ api_version = os.getenv('AZURE_OPENAI_API_VERSION')
+ api_endpoint = os.getenv('AZURE_OPENAI_ENDPOINT')
+ # initialize the Azure Client
+ self.client = AzureOpenAI(
+ api_version=api_version,
+ azure_endpoint=api_endpoint,
+ api_key=api_subscription_key,
+ )
+
+ elif self.provider == "openai":
+ from openai import OpenAI
+ # Load Environment Keys
+ openai_api_key = os.getenv('OPENAI_API_KEY')
+ if not self.api_model_name:
+ self.api_model_name = "gpt-4.1-mini"
+ # initialize the OpenAI Client
+ self.client = OpenAI(
+ api_key=openai_api_key
+ )
+ elif self.provider == "deepseek":
+ from openai import OpenAI
+ deepseek_api_key = os.getenv("DEEPSEEK_API_KEY", "").strip()
+ if not deepseek_api_key:
+ raise RuntimeError("Missing DEEPSEEK_API_KEY for DeepSeek backend.")
+ if not self.api_model_name:
+ self.api_model_name = "deepseek-chat"
+ self.client = OpenAI(
+ api_key=deepseek_api_key,
+ base_url=os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1").strip(),
+ )
+ elif self.provider == "claude":
+ from anthropic import Anthropic
+ anthropic_api_key = os.getenv("ANTHROPIC_API_KEY", "").strip()
+ if not anthropic_api_key:
+ raise RuntimeError("Missing ANTHROPIC_API_KEY for Claude backend.")
+ if not self.api_model_name:
+ self.api_model_name = "claude-3-5-sonnet-latest"
+ self.client = Anthropic(api_key=anthropic_api_key)
+ elif self.provider == "gemini":
+ from openai import OpenAI
+ gemini_api_key = os.getenv("GEMINI_API_KEY", "").strip()
+ if not gemini_api_key:
+ raise RuntimeError("Missing GEMINI_API_KEY for Gemini backend.")
+ if not self.api_model_name:
+ self.api_model_name = "gemini-2.5-flash"
+ self.client = OpenAI(
+ api_key=gemini_api_key,
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
+ )
+ else:
+ raise ValueError(f"Unsupported model provider: {self.provider}")
+ if self.provider == "azure" and not self.api_model_name:
+ raise RuntimeError("Missing MODEL_NAME for Azure backend (deployment/model name).")
+ print(f"Succesfully created backend={self.provider}, model={self.api_model_name}")
+
+
+
+ def is_tool_available(self, tool_name):
+ """Check whether that tool is installed or not"""
+ try:
+ vers_result = subprocess.run([tool_name, '--version'],
+ capture_output=True, timeout=20, text=True)
+ print(f"{tool_name} is installed")
+ return True
+ except:
+ print(f"{tool_name} is not installed!")
+ return False
+
+ def extract_help_document(self, tool_name, manual, run_help_command=False):
+ """Extract help text from tool"""
+ if not run_help_command: # document provided by user, no need to run the help command
+ manual_path = Path(str(manual)).expanduser().resolve()
+ if not manual_path.exists():
+ raise FileNotFoundError(f"Manual file not found: {manual_path}")
+
+ ext = manual_path.suffix.lower()
+ if ext == ".pdf":
+ pdf_doc = pymupdf.open(str(manual_path))
+ manual_content = ""
+ for page in pdf_doc:
+ text = page.get_text()
+ manual_content += text
+ return manual_content
+
+ if ext in {".md", ".markdown", ".txt"}:
+ return manual_path.read_text(encoding="utf-8", errors="ignore")
+
+ raise ValueError(
+ f"Unsupported manual file type: {ext}. "
+ "Supported file types are .pdf, .md, .markdown, .txt"
+ )
+
+ if self.is_tool_available(tool_name):
+ try:
+ result = subprocess.run([tool_name, manual],
+ capture_output=True, timeout=30, text=True)
+ return result.stdout + result.stderr
+ except:
+ return None
+
+ def generate_prompt(self, tool_name, help_docs):
+ """Generate the Prompt that later will be send to the OpenAI client"""
+ prompt = f"""
+ Convert the following bioinformatics tool into an MCP tool definition.
+
+ Tool Name: {tool_name}
+ Help Document:
+ {help_docs}
+
+ Parse the Input parameters correctly, follow the MCP best practices, and provide the complete python code with the @mcp.tool() decorator.
+ You MUST wrap final code in a fenced code block starting with ```python and ending with ```.
+ Do not output analysis text outside the code block.
+ """
+ return prompt
+
+ def _chat_completion(self, prompt: str) -> str:
+ if self.provider in {"openai", "azure", "deepseek", "gemini"}:
+ response = self.client.chat.completions.create(
+ messages=[
+ {
+ "role": "system",
+ "content": self.sys_prompt,
+ },
+ {
+ "role": "user",
+ "content": prompt,
+ },
+ ],
+ model=self.api_model_name,
+ temperature=0.1
+ )
+ return response.choices[0].message.content
+
+ if self.provider == "claude":
+ response = self.client.messages.create(
+ model=self.api_model_name,
+ max_tokens=4096,
+ temperature=0.1,
+ system=self.sys_prompt,
+ messages=[{"role": "user", "content": prompt}],
+ )
+ chunks = []
+ for block in response.content:
+ text = getattr(block, "text", "")
+ if text:
+ chunks.append(text)
+ return "\n".join(chunks)
+
+ raise ValueError(f"Unsupported model provider: {self.provider}")
+
+ def parse_mcpcode(self, gpt_response):
+ # 1) strict python fence
+ candidates = re.findall(r"```python\s*(.*?)\s*```", gpt_response, re.DOTALL | re.IGNORECASE)
+ # 2) py fence
+ if not candidates:
+ candidates = re.findall(r"```py\s*(.*?)\s*```", gpt_response, re.DOTALL | re.IGNORECASE)
+ # 3) generic fence
+ if not candidates:
+ candidates = re.findall(r"```\s*(.*?)\s*```", gpt_response, re.DOTALL)
+ # 4) fallback: raw content
+ if not candidates and "@mcp.tool" in gpt_response:
+ candidates = [gpt_response.strip()]
+ if not candidates:
+ snippet = (gpt_response or "")[:300].replace("\n", "\\n")
+ return (0, f"There is no python code found in the gpt_response. head={snippet}", None)
+
+ last_error = None
+ for code in candidates:
+ try:
+ ast.parse(code)
+ except SyntaxError as e:
+ last_error = f"Code is not working with the following SyntaxError: {e}"
+ continue
+
+ if '@mcp.tool' not in code:
+ last_error = "Code is missing the @mcp.tool() decorator"
+ continue
+
+ return (1, None, code)
+
+ return (0, last_error or "No valid MCP python code candidate found", candidates[0] if candidates else None)
+
+ def refine_after_feedback(self, tool_name, code, error_message):
+ prompt = f"""
+ The initial code block for {tool_name}:
+ ```python
+ {code}
+ ```
+ contains the following Error:
+ {error_message}
+
+ Please fix the code and ensure that
+ 1. Cover every internal functions of the tool
+ 2. Has proper error handling
+ 3. Validates input parameters
+ 4. Returns structured output
+ 5. Follows MCP best practices
+
+ Provide only the corrected python code.
+
+ """
+ response_content = self._chat_completion(prompt)
+ # output_file = open(f'./mcp_result/raw_{tool_name}', 'w')
+ # output_file.write(response_content)
+ return self.parse_mcpcode(response_content)
+
+ def autogenerate_mcp_tool(self, tool_name, manual, run_help_command):
+ """Autogenerate the MCP Tool using the extracted help documents"""
+ help_docs = self.extract_help_document(tool_name, manual, run_help_command)
+ # web_docs = self.fetch_web_docs(tool_name)
+ prompt = self.generate_prompt(tool_name, help_docs)
+ # Call the OpenAI Client to do Chat Completion
+ response_content = self._chat_completion(prompt)
+ #print(response_content)
+ # output_file = open(f'./mcp_result/raw_{tool_name}', 'w')
+ # output_file.write(response.choices[0].message.content)
+ print(response_content)
+ return self.parse_mcpcode(response_content)
diff --git a/Biomanus/biomni_web/backend/biomni_agent.py b/Biomanus/biomni_web/backend/biomni_agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..a48fc1a9df857d5829805dae1136193bfbdbb6f3
--- /dev/null
+++ b/Biomanus/biomni_web/backend/biomni_agent.py
@@ -0,0 +1,688 @@
+from __future__ import annotations
+
+import os
+import json
+import re
+import sys
+import inspect
+import traceback
+import zipfile
+from pathlib import Path
+from urllib.parse import quote
+from typing import Any, Generator
+from metabolomics_tools import (
+ generate_scmeta_mcp,
+ list_metabolomics_tools,
+ write_metabolomics_mcp_config,
+)
+
+
+def _ensure_biomni_importable(project_root: Path) -> None:
+ if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+
+class BiomniWebAgent:
+ """
+ Adapter that mounts biomni A1 agent into biomni_web backend.
+ It provides structured stream events and run artifacts for UI consumption.
+ """
+
+ def __init__(
+ self,
+ session_id: str,
+ expected_data_lake_files: list[str] | None = None,
+ llm_provider: str | None = None,
+ ):
+ self.session_id = session_id
+ self.uploaded_files: list[str] = []
+ self.metabolomics_enabled = False
+ self.metabolomics_tools: list[str] = []
+ self.paper_repro_enabled = False
+ self.paper_profile = "foxj1"
+ self._cancel_requested = False
+ self._loaded_mcp_signature: tuple[bool, tuple[str, ...]] | None = None
+ self.llm_provider = (llm_provider or os.getenv("BIOMNI_LLM_PROVIDER", "deepseek")).strip().lower()
+
+ self.project_root = Path(os.getenv("BIOMNI_PROJECT_ROOT", "/225040511/project/Biomni")).resolve()
+ if not self.project_root.exists():
+ raise RuntimeError(
+ f"BIOMNI project root not found: {self.project_root}. "
+ "Set BIOMNI_PROJECT_ROOT to your Biomni repository path."
+ )
+
+ _ensure_biomni_importable(self.project_root)
+ from biomni.agent import A1
+
+ # One workspace per session to isolate run artifacts.
+ self.session_workspace = (Path("./data") / "biomni_sessions" / session_id).resolve()
+ self.session_workspace.mkdir(parents=True, exist_ok=True)
+
+ source, api_key, model_name, base_url = self._resolve_llm_backend()
+
+ # Pass non-None value to skip large auto-download in web runtime.
+ self._agent = A1(
+ path=str(self.session_workspace),
+ llm=model_name,
+ source=source,
+ base_url=base_url,
+ api_key=api_key,
+ use_tool_retriever=True,
+ expected_data_lake_files=expected_data_lake_files if expected_data_lake_files is not None else [],
+ )
+ self._safe_configure_agent()
+
+ self.report_dir = (Path("./data") / "reports" / session_id).resolve()
+ self.report_dir.mkdir(parents=True, exist_ok=True)
+
+ def set_uploaded_files(self, files: list[str]) -> None:
+ self.uploaded_files = list(files)
+
+ def set_metabolomics_settings(self, enabled: bool, tools: list[str] | None = None) -> None:
+ self.metabolomics_enabled = bool(enabled)
+ self.metabolomics_tools = sorted(set(tools or []))
+
+ def set_paper_reproduction_settings(self, enabled: bool, profile: str = "foxj1") -> None:
+ self.paper_repro_enabled = bool(enabled)
+ self.paper_profile = (profile or "foxj1").strip().lower()
+
+ def request_cancel(self) -> None:
+ self._cancel_requested = True
+
+ def clear_cancel_request(self) -> None:
+ self._cancel_requested = False
+
+ def is_cancel_requested(self) -> bool:
+ return bool(self._cancel_requested)
+
+ def _resolve_llm_backend(self) -> tuple[str, str, str, str | None]:
+ if self.llm_provider == "claude":
+ api_key = os.getenv("ANTHROPIC_API_KEY", "").strip()
+ if not api_key:
+ raise RuntimeError(
+ "Missing ANTHROPIC_API_KEY in environment. "
+ "Please export ANTHROPIC_API_KEY before starting biomni_web backend."
+ )
+ os.environ["ANTHROPIC_API_KEY"] = api_key
+ return (
+ "Anthropic",
+ api_key,
+ os.getenv("ANTHROPIC_MODEL_NAME", "claude-3-5-sonnet-latest").strip(),
+ None,
+ )
+
+ if self.llm_provider == "openai":
+ api_key = os.getenv("OPENAI_API_KEY", "").strip()
+ if not api_key:
+ raise RuntimeError(
+ "Missing OPENAI_API_KEY in environment. "
+ "Please export OPENAI_API_KEY before starting biomni_web backend."
+ )
+ os.environ["OPENAI_API_KEY"] = api_key
+ return (
+ "OpenAI",
+ api_key,
+ os.getenv("OPENAI_MODEL_NAME", "gpt-4.1-mini").strip(),
+ None,
+ )
+
+ if self.llm_provider == "gemini":
+ api_key = os.getenv("GEMINI_API_KEY", "").strip()
+ if not api_key:
+ raise RuntimeError(
+ "Missing GEMINI_API_KEY in environment. "
+ "Please export GEMINI_API_KEY before starting biomni_web backend."
+ )
+ os.environ["GEMINI_API_KEY"] = api_key
+ return (
+ "Gemini",
+ api_key,
+ os.getenv("GEMINI_MODEL_NAME", "gemini-2.5-flash").strip(),
+ None,
+ )
+
+ if self.llm_provider == "deepseek":
+ api_key = os.getenv("DEEPSEEK_API_KEY", "").strip()
+ if not api_key:
+ raise RuntimeError(
+ "Missing DEEPSEEK_API_KEY in environment. "
+ "Please export DEEPSEEK_API_KEY before starting biomni_web backend."
+ )
+ base_url = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1").strip()
+ os.environ["DEEPSEEK_API_KEY"] = api_key
+ return (
+ "Custom",
+ api_key,
+ os.getenv("DEEPSEEK_MODEL_NAME", "deepseek-chat").strip(),
+ base_url,
+ )
+
+ raise RuntimeError(
+ f"Unsupported llm provider: {self.llm_provider}. "
+ "Supported providers for biomni_web chat are: claude, openai, gemini, deepseek."
+ )
+
+ def _safe_configure_agent(self) -> None:
+ """
+ Configure A1 with backward/forward compatible kwargs.
+ Different Biomni revisions expose different configure() signatures.
+ """
+ configure = getattr(self._agent, "configure", None)
+ if configure is None:
+ return
+
+ signature = inspect.signature(configure)
+ available_params = set(signature.parameters.keys())
+
+ preferred_kwargs = {
+ "self_critic": True,
+ "test_time_scale_round": 0,
+ "plan": True,
+ "reflect": True,
+ "data_lake": True,
+ "library_access": True,
+ }
+ safe_kwargs = {k: v for k, v in preferred_kwargs.items() if k in available_params}
+ configure(**safe_kwargs)
+
+ def stream_events(self, message: str) -> Generator[dict[str, Any], None, None]:
+ if self.paper_repro_enabled:
+ yield from self._stream_paper_reproduction(message)
+ return
+
+ self._ensure_metabolomics_tools_loaded()
+ prompt = self._build_prompt_with_uploaded_files(message)
+ yield {"type": "thinking", "content": "[Thinking] Biomni A1 is analyzing query and input data."}
+
+ for step in self._agent.go_stream(prompt):
+ if self.is_cancel_requested():
+ yield {"type": "error", "content": "Run cancelled by user."}
+ return
+ output = str(step.get("output", "")).strip()
+ if not output:
+ continue
+ yield self._classify_stream_event(output)
+
+ final_answer = self._extract_final_answer()
+ report_path, image_count = self._save_markdown_report()
+ artifacts = self._collect_downloadable_artifacts()
+
+ for idx, image_data_url in enumerate(self._extract_visualizations_from_markdown(), start=1):
+ yield {
+ "type": "visualization",
+ "title": f"Visualization {idx}",
+ "image_data_url": image_data_url,
+ }
+
+ summary = [
+ "## Biomni Agent Result",
+ "",
+ final_answer or "(No explicit final answer was generated.)",
+ "",
+ "## Run Artifacts",
+ f"- Report: {report_path}",
+ f"- Visualizations: {image_count}",
+ f"- Downloadable files: {len(artifacts)}",
+ ]
+ yield {"type": "result", "content": "\n".join(summary), "artifacts": artifacts}
+
+ def _load_paper_reproduction_helpers(self) -> dict[str, Any]:
+ from reproduce_foxj1_paper import ( # type: ignore
+ RunPaths,
+ build_or_load_mcp_graph,
+ build_prompt,
+ ensure_dirs,
+ extract_final_answer,
+ force_dynamic_mcp_selection,
+ persist_output_files_from_text,
+ resolve_selected_servers,
+ save_biomni_run_artifacts,
+ select_runtime_server_entries,
+ slugify,
+ write_execution_plan,
+ write_generic_alignment_report,
+ write_mcp_config,
+ write_paper_context_file,
+ write_query_file,
+ )
+
+ return {
+ "RunPaths": RunPaths,
+ "build_or_load_mcp_graph": build_or_load_mcp_graph,
+ "build_prompt": build_prompt,
+ "ensure_dirs": ensure_dirs,
+ "extract_final_answer": extract_final_answer,
+ "force_dynamic_mcp_selection": force_dynamic_mcp_selection,
+ "persist_output_files_from_text": persist_output_files_from_text,
+ "resolve_selected_servers": resolve_selected_servers,
+ "save_biomni_run_artifacts": save_biomni_run_artifacts,
+ "select_runtime_server_entries": select_runtime_server_entries,
+ "slugify": slugify,
+ "write_execution_plan": write_execution_plan,
+ "write_generic_alignment_report": write_generic_alignment_report,
+ "write_mcp_config": write_mcp_config,
+ "write_paper_context_file": write_paper_context_file,
+ "write_query_file": write_query_file,
+ }
+
+ def _build_web_run_paths(self, run_name: str, run_paths_cls: Any) -> Any:
+ run_root = (self.session_workspace / "paper_reproduction_runs" / run_name).resolve()
+ return run_paths_cls(
+ work_root=run_root,
+ data_dir=run_root / "data",
+ results_dir=run_root / "results",
+ graph_dir=run_root / "mcp_graph",
+ config_path=run_root / "mcp_config.yaml",
+ prompt_path=run_root / "reproduction_prompt.txt",
+ paper_context_path=run_root / "paper_context.md",
+ query_path=run_root / "reproduction_query.txt",
+ plan_path=run_root / "execution_plan.md",
+ )
+
+ def _stream_paper_reproduction(self, message: str) -> Generator[dict[str, Any], None, None]:
+ helpers = self._load_paper_reproduction_helpers()
+ query = message.strip()
+ if not query:
+ yield {
+ "type": "error",
+ "content": "Paper reproduction mode requires a non-empty query message.",
+ }
+ return
+
+ paper_title = "User-Provided Paper Reproduction Task"
+ paper_context = (
+ "Use the user query and uploaded files to reproduce requested paper findings. "
+ "The dataset location is not pre-declared and must be inferred from session uploads."
+ )
+ run_name = helpers["slugify"](paper_title)
+ paths = self._build_web_run_paths(run_name, helpers["RunPaths"])
+ helpers["ensure_dirs"](paths)
+
+ input_files: list[Path] = []
+ for relative_path in self.uploaded_files:
+ absolute_path = (Path("./data") / relative_path).resolve()
+ if absolute_path.exists() and absolute_path.is_file():
+ input_files.append(absolute_path)
+
+ if not input_files:
+ yield {
+ "type": "error",
+ "content": (
+ "No uploaded input files were found for this session. "
+ "Please upload data files first, then submit your reproduction query again."
+ ),
+ }
+ return
+
+ if self.is_cancel_requested():
+ yield {"type": "error", "content": "Run cancelled by user."}
+ return
+
+ requested_servers = helpers["resolve_selected_servers"]([])
+ graph_dir, graph_server_entries = helpers["build_or_load_mcp_graph"](
+ paths,
+ os.getenv("BIOMNI_MCP_GRAPH_DIR", ""),
+ )
+ runtime_server_entries = helpers["select_runtime_server_entries"](graph_server_entries, requested_servers)
+ selected_servers = [entry["name"] for entry in runtime_server_entries]
+
+ config_path = helpers["write_mcp_config"](selected_servers, paths.config_path, paper_title)
+ helpers["write_paper_context_file"](paper_title, paper_context, input_files, paths)
+ helpers["write_query_file"](query, paths)
+ helpers["write_execution_plan"](
+ query=query,
+ selected_servers=selected_servers,
+ input_files=input_files,
+ graph_dir=graph_dir,
+ graph_server_count=len(graph_server_entries),
+ paths=paths,
+ )
+ prompt = helpers["build_prompt"](
+ paper_title=paper_title,
+ paper_context=paper_context,
+ query=query,
+ input_files=input_files,
+ selected_servers=selected_servers,
+ graph_dir=graph_dir,
+ graph_server_count=len(graph_server_entries),
+ paths=paths,
+ )
+
+ yield {
+ "type": "thinking",
+ "content": (
+ "Paper reproduction mode enabled. Building MCP graph routing context and forcing "
+ "dynamic MCP selection before execution."
+ ),
+ }
+ yield {
+ "type": "observation",
+ "content": (
+ f"Run root: {paths.work_root}\n"
+ f"MCP graph: {graph_dir}\n"
+ f"Graph servers: {len(graph_server_entries)}\n"
+ f"Runtime candidates: {len(runtime_server_entries)}"
+ ),
+ }
+
+ try:
+ if self.is_cancel_requested():
+ yield {"type": "error", "content": "Run cancelled by user."}
+ return
+
+ attached_entries = self._agent.attach_mcp_server_entries(runtime_server_entries)
+ yield {
+ "type": "tool_use",
+ "tool": "attach_mcp_server_entries",
+ "content": f"Attached {len(attached_entries)} MCP catalog entries.",
+ }
+
+ selected_dynamic_servers = helpers["force_dynamic_mcp_selection"](self._agent, prompt)
+ yield {
+ "type": "observation",
+ "content": (
+ "Dynamic MCP selection: "
+ + ", ".join(server["name"] for server in selected_dynamic_servers)
+ ),
+ }
+
+ log_entries: list[str] = []
+ captured_output_files: dict[str, str] = {}
+ seen_visualizations: set[str] = set()
+ for step in self._agent.go_stream(prompt):
+ if self.is_cancel_requested():
+ yield {"type": "error", "content": "Run cancelled by user."}
+ return
+ output = str(step.get("output", "")).strip()
+ log_entries.append(str(step))
+ if output:
+ copied = helpers["persist_output_files_from_text"](
+ output,
+ paths.results_dir,
+ captured_output_files,
+ )
+ if copied:
+ persisted_lines = [
+ f"{label}: {saved_path}" for label, saved_path in copied.items()
+ ]
+ yield {
+ "type": "observation",
+ "content": "Persisted MCP result files:\n" + "\n".join(persisted_lines),
+ }
+ yield self._classify_stream_event(output)
+ for event in self._collect_new_visualization_events(paths.results_dir, seen_visualizations):
+ yield event
+
+ final_answer = helpers["extract_final_answer"](self._agent)
+ artifacts = helpers["save_biomni_run_artifacts"](
+ agent=self._agent,
+ prompt=prompt,
+ log_entries=log_entries,
+ final_answer=final_answer,
+ config_path=config_path,
+ paths=paths,
+ paper_title=paper_title,
+ query=query,
+ selected_servers=[server["name"] for server in selected_dynamic_servers],
+ input_files=input_files,
+ graph_dir=graph_dir,
+ graph_server_count=len(graph_server_entries),
+ captured_output_files=captured_output_files,
+ )
+ report_path = helpers["write_generic_alignment_report"](
+ paper_title=paper_title,
+ query=query,
+ final_answer=final_answer,
+ selected_servers=[server["name"] for server in selected_dynamic_servers],
+ input_files=input_files,
+ graph_dir=graph_dir,
+ graph_server_count=len(graph_server_entries),
+ paths=paths,
+ )
+
+ report_md_path, image_count = self._save_markdown_report()
+ curated_bundle_path = self._build_curated_results_bundle(paths.results_dir)
+ downloadable_artifacts = []
+ if curated_bundle_path is not None:
+ downloadable_artifacts.append(
+ self._build_artifact_entry("session", self.session_workspace, curated_bundle_path)
+ )
+
+ summary = [
+ "## Paper Reproduction Result",
+ "",
+ final_answer or "(No explicit final answer was generated.)",
+ "",
+ "## Reproduction Artifacts",
+ f"- Report markdown: {report_md_path}",
+ f"- Alignment report: {report_path}",
+ f"- Saved artifacts: {json.dumps(artifacts, ensure_ascii=False)}",
+ f"- Persisted MCP outputs: {len(captured_output_files)}",
+ f"- Visualizations: {image_count}",
+ f"- Download bundle: {curated_bundle_path if curated_bundle_path else 'Not generated'}",
+ f"- Downloadable files: {len(downloadable_artifacts)}",
+ ]
+ yield {"type": "result", "content": "\n".join(summary), "artifacts": downloadable_artifacts}
+ except Exception:
+ yield {
+ "type": "error",
+ "content": "Paper reproduction run failed:\n" + traceback.format_exc(),
+ }
+
+ def _ensure_metabolomics_tools_loaded(self) -> None:
+ current_signature = (self.metabolomics_enabled, tuple(self.metabolomics_tools))
+ if self._loaded_mcp_signature == current_signature:
+ return
+ if not self.metabolomics_enabled:
+ self._loaded_mcp_signature = current_signature
+ return
+
+ all_tools = {tool["name"]: tool for tool in list_metabolomics_tools()}
+ requested = [t for t in self.metabolomics_tools if t in all_tools]
+ if not requested:
+ self._loaded_mcp_signature = current_signature
+ return
+
+ # Auto-generate scmeta MCP server if user selected it and it is not generated yet.
+ if "scmeta" in requested and not all_tools.get("scmeta", {}).get("available"):
+ result = generate_scmeta_mcp()
+ if not result.get("ok"):
+ raise RuntimeError(
+ "Failed to generate scmeta MCP server. "
+ f"stderr: {result.get('stderr', '')}"
+ )
+
+ config_path = write_metabolomics_mcp_config(requested)
+ self._agent.add_mcp(config_path=str(config_path))
+ self._loaded_mcp_signature = current_signature
+
+ def _build_prompt_with_uploaded_files(self, user_message: str) -> str:
+ if not self.uploaded_files:
+ return user_message
+
+ absolute_paths: list[str] = []
+ for relative_path in self.uploaded_files:
+ absolute_paths.append(str((Path("./data") / relative_path).resolve()))
+
+ context = [
+ "User uploaded files for this session:",
+ *[f"- {path}" for path in absolute_paths],
+ "",
+ "Please analyze user query with these files, plan tasks, execute analysis, and provide a final report.",
+ "",
+ "User query:",
+ user_message,
+ ]
+ return "\n".join(context)
+
+ def _classify_stream_event(self, output: str) -> dict[str, Any]:
+ lowered_head = output.lower()[:120]
+ if "tool message" in lowered_head or "tool:" in lowered_head:
+ tool_name_match = re.search(r"Name:\s*([^\n]+)", output)
+ tool_name = tool_name_match.group(1).strip() if tool_name_match else "tool"
+ return {"type": "tool_use", "tool": tool_name, "content": output}
+
+ code_match = re.search(r"```(\w+)?\n([\s\S]*?)```", output)
+ if code_match:
+ lang = (code_match.group(1) or "text").strip()
+ code = code_match.group(2).strip()
+ return {"type": "code", "lang": lang, "content": code}
+
+ if "observation" in lowered_head:
+ return {"type": "observation", "content": output}
+
+ return {"type": "thinking", "content": output}
+
+ def _extract_final_answer(self) -> str:
+ state = getattr(self._agent, "_conversation_state", None)
+ if not state or "messages" not in state:
+ return ""
+
+ for message in reversed(state["messages"]):
+ content = str(getattr(message, "content", "")).strip()
+ msg_type = str(getattr(message, "type", "")).lower()
+ if content and msg_type == "ai":
+ return content
+ return ""
+
+ def _save_markdown_report(self) -> tuple[str, int]:
+ markdown = self._agent._generate_markdown_content(include_images=True)
+ report_path = self.report_dir / "report.md"
+ report_path.write_text(markdown, encoding="utf-8")
+ image_count = len(re.findall(r"!\[Plot\]\((data:image[^)]+)\)", markdown))
+ return str(report_path), image_count
+
+ def _extract_visualizations_from_markdown(self) -> list[str]:
+ markdown = self._agent._generate_markdown_content(include_images=True)
+ return re.findall(r"!\[Plot\]\((data:image[^)]+)\)", markdown)
+
+ def _should_include_in_curated_bundle(self, file_path: Path) -> bool:
+ name = file_path.name.lower()
+ suffix = file_path.suffix.lower()
+
+ if suffix not in {".csv", ".tsv", ".md", ".txt"}:
+ return False
+ if name.endswith(".log") or name.endswith(".json"):
+ return False
+ if "execution_log" in name or "run_metadata" in name or "conversation" in name:
+ return False
+ if "prompt" in name or "query" in name or "plan" in name or "config" in name:
+ return False
+ if name in {"run_fgsea_analysis.r", "run_fgsea_plots.r"}:
+ return False
+ if any(token in name for token in ("summary", "report", "final_answer")):
+ return True
+ if suffix in {".csv", ".tsv"}:
+ return True
+ return False
+
+ def _build_curated_results_bundle(self, results_dir: Path) -> Path | None:
+ if not results_dir.exists():
+ return None
+
+ selected_files = [
+ file_path
+ for file_path in sorted(results_dir.rglob("*"))
+ if file_path.is_file() and self._should_include_in_curated_bundle(file_path)
+ ]
+ if not selected_files:
+ return None
+
+ bundle_path = results_dir / "paper_reproduction_key_results.zip"
+ with zipfile.ZipFile(bundle_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
+ for file_path in selected_files:
+ zf.write(file_path, arcname=file_path.relative_to(results_dir).as_posix())
+ return bundle_path
+
+ def _build_artifact_entry(self, root_name: str, root_dir: Path, file_path: Path) -> dict[str, Any]:
+ relative_path = file_path.relative_to(root_dir).as_posix()
+ return {
+ "name": file_path.name,
+ "root": root_name,
+ "relative_path": relative_path,
+ "size_bytes": file_path.stat().st_size,
+ "download_path": (
+ f"/session/{self.session_id}/artifacts/download"
+ f"?root={root_name}&path={quote(relative_path, safe='/')}"
+ ),
+ }
+
+ def _collect_new_visualization_events(
+ self,
+ results_dir: Path,
+ seen_relative_paths: set[str],
+ ) -> list[dict[str, Any]]:
+ if not results_dir.exists():
+ return []
+
+ events: list[dict[str, Any]] = []
+ image_suffixes = {".png", ".jpg", ".jpeg", ".gif", ".webp"}
+
+ for file_path in sorted(results_dir.rglob("*")):
+ if not file_path.is_file() or file_path.suffix.lower() not in image_suffixes:
+ continue
+ if not str(file_path.resolve()).startswith(str(self.session_workspace)):
+ continue
+
+ artifact = self._build_artifact_entry("session", self.session_workspace, file_path)
+ relative_path = artifact["relative_path"]
+ if relative_path in seen_relative_paths:
+ continue
+
+ seen_relative_paths.add(relative_path)
+ events.append(
+ {
+ "type": "visualization",
+ "title": file_path.stem.replace("_", " "),
+ "content": f"Generated figure: {file_path.name}",
+ "relative_path": relative_path,
+ "download_path": artifact["download_path"],
+ }
+ )
+
+ return events
+
+ def _collect_downloadable_artifacts(self) -> list[dict[str, Any]]:
+ artifacts: list[dict[str, Any]] = []
+ seen: set[tuple[str, str]] = set()
+
+ def should_skip(relative_path: str) -> bool:
+ normalized = relative_path.replace("\\", "/")
+ if normalized.startswith("biomni_data/data_lake/"):
+ return True
+ if normalized.startswith("biomni_data/benchmark/"):
+ return True
+ if "/__pycache__/" in f"/{normalized}/":
+ return True
+ return False
+
+ def register_file(root_name: str, root_dir: Path, file_path: Path) -> None:
+ relative_path = file_path.relative_to(root_dir).as_posix()
+ if should_skip(relative_path):
+ return
+ key = (root_name, relative_path)
+ if key in seen:
+ return
+ seen.add(key)
+ artifacts.append(self._build_artifact_entry(root_name, root_dir, file_path))
+
+ if self.report_dir.exists():
+ for file_path in sorted(self.report_dir.rglob("*")):
+ if file_path.is_file():
+ register_file("report", self.report_dir, file_path)
+
+ if self.session_workspace.exists():
+ for file_path in sorted(self.session_workspace.rglob("*")):
+ if file_path.is_file():
+ register_file("session", self.session_workspace, file_path)
+
+ def sort_key(item: dict[str, Any]) -> tuple[int, str]:
+ relative_path = item["relative_path"]
+ if relative_path.startswith("analysis/"):
+ return (0, relative_path)
+ if item["root"] == "report":
+ return (1, relative_path)
+ return (2, relative_path)
+
+ artifacts.sort(key=sort_key)
+ return artifacts
diff --git a/Biomanus/biomni_web/backend/lentiCRISPR_v2_B2M_sg1_final_map.png b/Biomanus/biomni_web/backend/lentiCRISPR_v2_B2M_sg1_final_map.png
new file mode 100644
index 0000000000000000000000000000000000000000..9c071e29ad37bf27a2de01df71f61bab4540491f
--- /dev/null
+++ b/Biomanus/biomni_web/backend/lentiCRISPR_v2_B2M_sg1_final_map.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d7aec50494de30b3e3b2a90ea7d9f93b4ff985301d6e427061541cc1faeadf72
+size 638812
diff --git a/Biomanus/biomni_web/backend/lentiCRISPR_v2_B2M_sg1_map.png b/Biomanus/biomni_web/backend/lentiCRISPR_v2_B2M_sg1_map.png
new file mode 100644
index 0000000000000000000000000000000000000000..d06cd60dada4f44057722d07b6ee311d49a710fd
--- /dev/null
+++ b/Biomanus/biomni_web/backend/lentiCRISPR_v2_B2M_sg1_map.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:5d313b8eda7956226e8f9d5dea6b3f0630dbff3e242f6300fbd196fc7ad1d688
+size 432465
diff --git a/Biomanus/biomni_web/backend/main.py b/Biomanus/biomni_web/backend/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcdc36b177b6872656a2e280dd89b41944381de3
--- /dev/null
+++ b/Biomanus/biomni_web/backend/main.py
@@ -0,0 +1,424 @@
+"""
+FastAPI backend for Biomni Web UI.
+核心:把 Biomni agent 的执行过程包装成 SSE 流式响应。
+"""
+import asyncio
+import json
+import os
+import queue
+import re
+import threading
+import traceback
+import uuid
+from datetime import datetime, timezone
+from contextlib import asynccontextmanager
+from pathlib import Path
+from typing import Any, AsyncGenerator
+
+from fastapi import FastAPI, File, Form, HTTPException, UploadFile
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import FileResponse
+from fastapi.responses import StreamingResponse
+from pydantic import BaseModel
+
+from mcp_registry import discover_mcp_servers, load_latest_graph_server_count
+from session import SessionManager
+from streaming import StreamingCallback
+from metabolomics_tools import generate_scmeta_mcp, list_metabolomics_tools
+from tool2mcp import (
+ build_docker_image,
+ claude_addition,
+ convert_mcptool,
+ generate_environment_yaml,
+ generate_requirements_with_pipreqs,
+)
+
+DEFAULT_LLM_PROVIDER = os.getenv("BIOMNI_LLM_PROVIDER", "deepseek").strip().lower()
+
+# ── 全局 session 管理器(启动时初始化一次)────────────────────────
+session_manager = SessionManager()
+
+
+def _artifact_root_dir(session_id: str, root: str) -> Path:
+ if root == "session":
+ return (Path("./data") / "biomni_sessions" / session_id).resolve()
+ if root == "report":
+ return (Path("./data") / "reports" / session_id).resolve()
+ raise HTTPException(status_code=400, detail=f"Unsupported artifact root: {root}")
+
+
+def _resolve_artifact_file(session_id: str, root: str, relative_path: str) -> Path:
+ root_dir = _artifact_root_dir(session_id, root)
+ candidate = (root_dir / relative_path).resolve()
+ if not str(candidate).startswith(str(root_dir)):
+ raise HTTPException(status_code=400, detail="Invalid artifact path")
+ if not candidate.exists() or not candidate.is_file():
+ raise HTTPException(status_code=404, detail="Artifact not found")
+ return candidate
+
+@asynccontextmanager
+async def lifespan(_: FastAPI):
+ print("Biomni backend starting...")
+ yield
+ session_manager.cleanup_all()
+
+app = FastAPI(lifespan=lifespan)
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"], # 开发阶段先放开所有来源
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+# ── 数据模型 ─────────────────────────────────────────────────────
+class ChatRequest(BaseModel):
+ message: str
+ session_id: str | None = None # None = 新建 session
+
+class CreateSessionRequest(BaseModel):
+ llm_provider: str = DEFAULT_LLM_PROVIDER
+
+class NewSessionResponse(BaseModel):
+ session_id: str
+
+class UploadResponse(BaseModel):
+ files: list[dict[str, str]]
+ uploaded_count: int
+
+class MetabolomicsToolListResponse(BaseModel):
+ tools: list[dict[str, Any]]
+
+
+class McpServerListResponse(BaseModel):
+ servers: list[dict[str, Any]]
+ catalog_server_count: int | None = None
+
+
+class ConverterGenerateResponse(BaseModel):
+ ok: bool
+ tool_name: str
+ llm_provider: str
+ run_help_command: bool
+ server_path: str
+ files: dict[str, str]
+ warnings: list[str] = []
+
+# ── 接口 ─────────────────────────────────────────────────────────
+@app.post("/session/new", response_model=NewSessionResponse)
+async def new_session(payload: CreateSessionRequest | None = None):
+ """创建新的 session,返回 session_id"""
+ sid = session_manager.create_session(
+ llm_provider=(payload.llm_provider if payload else DEFAULT_LLM_PROVIDER)
+ )
+ return NewSessionResponse(session_id=sid)
+
+@app.post("/session/{session_id}/upload", response_model=UploadResponse)
+async def upload_file_to_session(
+ session_id: str,
+ file: UploadFile | None = File(default=None),
+ files: list[UploadFile] | None = File(default=None),
+):
+ """上传单个或多个文件并挂到 session,对话时将基于上传文件处理。"""
+ if not session_manager.has_session(session_id):
+ raise HTTPException(status_code=404, detail="Session not found")
+
+ incoming_files: list[UploadFile] = []
+ if files:
+ incoming_files.extend(files)
+ if file is not None:
+ incoming_files.append(file)
+ if not incoming_files:
+ raise HTTPException(status_code=400, detail="No file is provided")
+
+ session_dir = Path("./data/uploads") / session_id
+ session_dir.mkdir(parents=True, exist_ok=True)
+
+ uploaded_items: list[dict[str, str]] = []
+ for upload in incoming_files:
+ if not upload.filename:
+ raise HTTPException(status_code=400, detail="Filename is empty")
+
+ safe_name = Path(upload.filename).name
+ stored_name = f"{uuid.uuid4()}_{safe_name}"
+ save_path = session_dir / stored_name
+ content = await upload.read()
+ with open(save_path, "wb") as f:
+ f.write(content)
+
+ relative_path = os.path.relpath(save_path, start="./data")
+ session_manager.add_uploaded_file(session_id, relative_path)
+ uploaded_items.append({
+ "filename": safe_name,
+ "relative_path": relative_path,
+ })
+
+ return UploadResponse(files=uploaded_items, uploaded_count=len(uploaded_items))
+
+@app.get("/metabolomics/tools", response_model=MetabolomicsToolListResponse)
+async def get_metabolomics_tools():
+ return MetabolomicsToolListResponse(tools=list_metabolomics_tools())
+
+
+@app.get("/mcp/servers", response_model=McpServerListResponse)
+async def get_mcp_servers():
+ return McpServerListResponse(
+ servers=discover_mcp_servers(),
+ catalog_server_count=load_latest_graph_server_count(),
+ )
+
+@app.post("/metabolomics/scmeta/generate")
+async def generate_scmeta():
+ result = generate_scmeta_mcp()
+ if not result.get("ok"):
+ raise HTTPException(
+ status_code=500,
+ detail={
+ "message": "Failed to generate scmeta MCP server",
+ "stderr": result.get("stderr", ""),
+ "stdout": result.get("stdout", ""),
+ },
+ )
+ return result
+
+
+@app.post("/mcp/converter/generate", response_model=ConverterGenerateResponse)
+async def converter_generate(
+ tool_name: str = Form(...),
+ llm_provider: str = Form("claude"),
+ manual_pdf: UploadFile | None = File(default=None),
+):
+ safe_tool_name = re.sub(r"[^a-zA-Z0-9_\-]", "", tool_name).strip()
+ if not safe_tool_name:
+ raise HTTPException(status_code=400, detail="Invalid tool name")
+
+ output_root = Path("./data/mcp_generated").resolve()
+ output_root.mkdir(parents=True, exist_ok=True)
+ server_path = output_root / f"mcp_{safe_tool_name}"
+ app_path = server_path / "app"
+ app_path.mkdir(parents=True, exist_ok=True)
+
+ run_help_command = manual_pdf is None
+ manual = "--help"
+
+ if manual_pdf is not None:
+ if not manual_pdf.filename:
+ raise HTTPException(status_code=400, detail="manual_pdf filename is empty")
+ allowed_exts = (".pdf", ".md", ".markdown", ".txt")
+ lower_name = manual_pdf.filename.lower()
+ if not lower_name.endswith(allowed_exts):
+ raise HTTPException(
+ status_code=400,
+ detail="manual_pdf must be one of: .pdf, .md, .markdown, .txt",
+ )
+ manual_dir = Path("./data/uploads/converter_manuals").resolve()
+ manual_dir.mkdir(parents=True, exist_ok=True)
+ manual_path = manual_dir / f"{uuid.uuid4()}_{Path(manual_pdf.filename).name}"
+ content = await manual_pdf.read()
+ manual_path.write_bytes(content)
+ manual = str(manual_path)
+
+ warnings: list[str] = []
+ try:
+ convert_mcptool(
+ safe_tool_name,
+ manual=manual,
+ run_help_command=run_help_command,
+ server_path=server_path,
+ llm_provider=llm_provider,
+ )
+ except Exception as exc:
+ raise HTTPException(
+ status_code=500,
+ detail=f"convert_mcptool failed: {exc}",
+ ) from exc
+
+ req_path = server_path / "requirements.txt"
+ try:
+ req_path = generate_requirements_with_pipreqs(safe_tool_name, server_path)
+ except Exception as exc:
+ warnings.append(f"generate requirements.txt failed: {exc}")
+
+ env_path = generate_environment_yaml(safe_tool_name, server_path)
+ try:
+ build_status = build_docker_image(safe_tool_name, server_path, output_root, is_pipeline=False)
+ if not build_status:
+ warnings.append("build_docker_image returned failed status")
+ except Exception as exc:
+ warnings.append(f"build_docker_image failed: {exc}")
+
+ return ConverterGenerateResponse(
+ ok=True,
+ tool_name=safe_tool_name,
+ llm_provider=llm_provider,
+ run_help_command=run_help_command,
+ server_path=str(server_path),
+ files={
+ "server": str(app_path / f"{safe_tool_name}_server.py"),
+ "requirements": str(req_path),
+ "environment": str(env_path),
+ "dockerfile": str(server_path / "Dockerfile"),
+ "docker_compose": str(server_path / "docker-compose.yml"),
+ "claude_config_hint": claude_addition(safe_tool_name),
+ },
+ warnings=warnings,
+ )
+
+@app.get("/chat/stream")
+async def chat_stream(
+ message: str,
+ session_id: str,
+ metabolomics_enabled: bool = False,
+ metabolomics_tools: str = "",
+ paper_repro_enabled: bool = False,
+ paper_profile: str = "foxj1",
+ llm_provider: str = DEFAULT_LLM_PROVIDER,
+):
+ """
+ 主接口:接收用户消息,返回 SSE 流
+
+ SSE 事件格式:
+ data: {"type": "thinking", "content": "..."}
+ data: {"type": "code", "lang": "python", "content": "..."}
+ data: {"type": "tool_use", "tool": "admet_prediction", "content": "..."}
+ data: {"type": "result", "content": "..."}
+ data: {"type": "error", "content": "..."}
+ data: {"type": "done"}
+ """
+ if not session_manager.has_session(session_id):
+ raise HTTPException(status_code=404, detail="Session not found")
+ session_manager.set_llm_provider(session_id, llm_provider)
+ selected_tools = [x.strip() for x in metabolomics_tools.split(",") if x.strip()]
+ session_manager.set_metabolomics_settings(session_id, metabolomics_enabled, selected_tools)
+ session_manager.set_paper_reproduction_settings(session_id, paper_repro_enabled, paper_profile)
+
+ return StreamingResponse(
+ _stream_agent_response(message, session_id),
+ media_type="text/event-stream",
+ headers={
+ "Cache-Control": "no-cache",
+ "X-Accel-Buffering": "no", # 关闭 nginx 缓冲
+ },
+ )
+
+@app.delete("/session/{session_id}")
+async def delete_session(session_id: str):
+ session_manager.delete_session(session_id)
+ return {"ok": True}
+
+@app.post("/session/{session_id}/stop")
+async def stop_session_run(session_id: str):
+ if not session_manager.has_session(session_id):
+ raise HTTPException(status_code=404, detail="Session not found")
+ session_manager.request_stop(session_id)
+ return {"ok": True}
+
+
+@app.get("/session/{session_id}/artifacts/download")
+async def download_session_artifact(session_id: str, root: str, path: str):
+ if not session_manager.has_session(session_id):
+ raise HTTPException(status_code=404, detail="Session not found")
+ artifact_path = _resolve_artifact_file(session_id, root, path)
+ return FileResponse(path=artifact_path, filename=artifact_path.name)
+
+# ── 核心:同步 agent 转异步 SSE ───────────────────────────────────
+def _create_run_log_file(session_id: str) -> tuple[Path, Any]:
+ log_dir = Path("./data/logs") / session_id
+ log_dir.mkdir(parents=True, exist_ok=True)
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S_%fZ")
+ log_path = log_dir / f"run_{ts}.log"
+ return log_path, open(log_path, "a", encoding="utf-8")
+
+
+def _append_run_log(log_file: Any, record_type: str, payload: dict):
+ row = {
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ "type": record_type,
+ "payload": payload,
+ }
+ log_file.write(json.dumps(row, ensure_ascii=False) + "\n")
+ log_file.flush()
+
+
+async def _stream_agent_response(
+ message: str, session_id: str
+) -> AsyncGenerator[str, None]:
+ """
+ 关键流程:
+ 1. 从 session 取出 agent 实例
+ 2. 创建一个线程安全的 Queue
+ 3. 在子线程中运行 agent(优先走 stream_events)
+ 并把中间步骤放进 Queue
+ 4. 主线程(asyncio event loop)从 Queue 取数据 yield 给客户端
+ """
+ agent = session_manager.get_agent(session_id)
+ session_manager.clear_stop(session_id)
+ event_queue: queue.Queue = queue.Queue()
+ callback = StreamingCallback(event_queue)
+ log_path, log_file = _create_run_log_file(session_id)
+ _append_run_log(log_file, "run_start", {"session_id": session_id, "message": message})
+
+ def run_agent():
+ """在独立线程运行,防止阻塞 event loop"""
+ try:
+ if hasattr(agent, "clear_cancel_request"):
+ agent.clear_cancel_request()
+ if hasattr(agent, "stream_events"):
+ for event in agent.stream_events(message):
+ if session_manager.is_stop_requested(session_id):
+ if hasattr(agent, "request_cancel"):
+ agent.request_cancel()
+ event_queue.put({"type": "error", "content": "Run cancelled by user."})
+ break
+ event_queue.put(event)
+ else:
+ # 兼容旧实现:通过 stdout 拦截转事件
+ callback.attach(agent)
+ agent.go(message)
+ event_queue.put({"type": "done"})
+ except Exception:
+ _append_run_log(
+ log_file,
+ "agent_exception",
+ {"traceback": traceback.format_exc()},
+ )
+ event_queue.put({
+ "type": "error",
+ "content": traceback.format_exc()
+ })
+ event_queue.put({"type": "done"})
+ finally:
+ if not hasattr(agent, "stream_events"):
+ callback.detach(agent)
+
+ # 在线程池运行 agent(不阻塞 asyncio)
+ loop = asyncio.get_event_loop()
+ thread = threading.Thread(target=run_agent, daemon=True)
+ thread.start()
+
+ # 持续从 Queue 取事件并 yield
+ try:
+ while True:
+ if session_manager.is_stop_requested(session_id):
+ yield f"data: {json.dumps({'type': 'error', 'content': 'Run cancelled by user.'}, ensure_ascii=False)}\n\n"
+ yield "data: {\"type\": \"done\"}\n\n"
+ break
+ try:
+ # 非阻塞轮询,让出控制权给 event loop
+ event = await loop.run_in_executor(
+ None, lambda: event_queue.get(timeout=0.1)
+ )
+ except queue.Empty:
+ # 心跳,防止连接超时
+ yield "data: {\"type\": \"heartbeat\"}\n\n"
+ continue
+
+ _append_run_log(log_file, "event", event)
+ yield f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
+
+ if event.get("type") == "done":
+ break
+ finally:
+ session_manager.clear_stop(session_id)
+ _append_run_log(log_file, "run_end", {"log_path": str(log_path)})
+ log_file.close()
diff --git a/Biomanus/biomni_web/backend/mcp_registry.py b/Biomanus/biomni_web/backend/mcp_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..03dc2101a916d93c076b10639a8023f145c5aad2
--- /dev/null
+++ b/Biomanus/biomni_web/backend/mcp_registry.py
@@ -0,0 +1,503 @@
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+from typing import Any
+
+
+BACKEND_ROOT = Path(__file__).resolve().parent
+BIOMNI_ROOT = BACKEND_ROOT.parents[1]
+PROJECTS_ROOT = BACKEND_ROOT.parents[2]
+GENERATED_ROOT = (BACKEND_ROOT / "data" / "mcp_generated").resolve()
+GRAPH_OUTPUTS_ROOT = (BIOMNI_ROOT / "graph_outputs").resolve()
+HELP_DOCS_ROOT = (
+ PROJECTS_ROOT
+ / "BioScientist"
+ / "agent_system"
+ / "toolbase"
+ / "output"
+ / "help_docs"
+ / "merged_prefer_help_txt"
+).resolve()
+HELP_BATCH_ROOT = (
+ PROJECTS_ROOT
+ / "BioScientist"
+ / "agent_system"
+ / "toolbase"
+ / "mcp_batch_from_help_txt"
+).resolve()
+MANUAL_BATCH_ROOT = (
+ PROJECTS_ROOT
+ / "BioScientist"
+ / "agent_system"
+ / "toolbase"
+ / "mcp_batch_from_manual_txt"
+).resolve()
+
+DISCOVERY_ROOTS = [
+ {
+ "id": "generated",
+ "label": "Strata Bio Generated",
+ "path": GENERATED_ROOT,
+ "priority": 0,
+ },
+ {
+ "id": "help_batch",
+ "label": "BioScientist Help Batch",
+ "path": HELP_BATCH_ROOT,
+ "priority": 1,
+ },
+ {
+ "id": "manual_batch",
+ "label": "BioScientist Manual Batch",
+ "path": MANUAL_BATCH_ROOT,
+ "priority": 2,
+ },
+]
+
+CATEGORY_SPECS = [
+ (
+ "featured-metabolomics",
+ "Featured",
+ "Metabolomics",
+ True,
+ [
+ "metabol",
+ "lipid",
+ "scmeta",
+ "escher",
+ "metaphlan",
+ "metabolomicsworkbenchr",
+ ],
+ ),
+ (
+ "single-cell-spatial",
+ "Single Cell",
+ "Single Cell & Spatial",
+ False,
+ [
+ "singlecell",
+ "scanpy",
+ "scvelo",
+ "scvis",
+ "scarches",
+ "sccaf",
+ "scelvis",
+ "scpred",
+ "sccell",
+ "scrna",
+ "seurat",
+ "signac",
+ "cellrank",
+ "celltypist",
+ "cellid",
+ "cellmigration",
+ "infercnv",
+ "spatial",
+ "visium",
+ "xenium",
+ "decontx",
+ "tenx",
+ "echidna",
+ "seacells",
+ "talon",
+ "spapros",
+ "sopa",
+ "standr",
+ "ggspavis",
+ "lisaclust",
+ "hoodscanr",
+ "cardspa",
+ "concordexr",
+ "scmageck",
+ "spaniel",
+ "nebulosa",
+ "clustifyr",
+ "mosim",
+ "scrnaseq",
+ "singlecellmultimodal",
+ ],
+ ),
+ (
+ "sequencing-alignment",
+ "Sequencing",
+ "Sequencing, Alignment & Assembly",
+ False,
+ [
+ "fastq",
+ "fastp",
+ "fastani",
+ "fasttree",
+ "fastdtw",
+ "trimmomatic",
+ "seqtk",
+ "seqfu",
+ "sortmerna",
+ "bwa",
+ "bowtie",
+ "hisat",
+ "minimap",
+ "blast",
+ "flye",
+ "abyss",
+ "mummer",
+ "ngmlr",
+ "gmap",
+ "gffread",
+ "gffutils",
+ "samtools",
+ "sambamba",
+ "samblaster",
+ "subread",
+ "kallisto",
+ "rsem",
+ "portcullis",
+ "muscle",
+ "clustal",
+ "famsa",
+ "parasail",
+ "checkm",
+ "assembly",
+ "f5c",
+ "medaka",
+ "stacks",
+ "tabix",
+ "bbmap",
+ "bamtools",
+ "bedtools",
+ "bedops",
+ "circos",
+ "augustus",
+ "aragorn",
+ "barrnap",
+ "abundancebin",
+ "abricate",
+ "dnaio",
+ "ucsc-",
+ "ena-webin",
+ "eva-sub",
+ "ncbi-vdb",
+ "csvtk",
+ "bioawk",
+ "coreutils",
+ ],
+ ),
+ (
+ "variants-genomics",
+ "Genomics",
+ "Variants, Genomics & Annotation",
+ False,
+ [
+ "vcf",
+ "bcf",
+ "variant",
+ "delly",
+ "whatshap",
+ "snpsift",
+ "picard",
+ "gatk",
+ "sentieon",
+ "crispresso",
+ "dnacopy",
+ "genome",
+ "annotation",
+ "biomart",
+ "ensembldb",
+ "go.db",
+ "org.",
+ "kegg",
+ "geneplotter",
+ "genefilter",
+ "iranges",
+ "rtracklayer",
+ "rsamtools",
+ "rhtslib",
+ "rhdf5",
+ "rhdf5filters",
+ "genomicalignments",
+ "genomicfeatures",
+ "genomeinfodb",
+ "bsgenome",
+ "xvector",
+ "zlibbioc",
+ "shortread",
+ "variantannotation",
+ ],
+ ),
+ (
+ "transcriptomics-expression",
+ "Transcriptomics",
+ "Transcriptomics & Expression",
+ False,
+ [
+ "deseq",
+ "edger",
+ "limma",
+ "gsva",
+ "tximport",
+ "scran",
+ "glmgampoi",
+ "ancombc",
+ "speckle",
+ "mia",
+ "poem",
+ "summarizedexperiment",
+ "scaledmatrix",
+ "matrixgenerics",
+ "statial",
+ "scrnasim",
+ "deblur",
+ "doubletdetection",
+ "deconvobuddies",
+ "decipher",
+ "decoupler",
+ ],
+ ),
+ (
+ "proteomics",
+ "Proteomics",
+ "Proteomics",
+ False,
+ [
+ "proteom",
+ "peptide",
+ "maxquant",
+ "sage-proteomics",
+ "msproteomicstools",
+ "searchgui",
+ "peptide-shaker",
+ "proteomicsannotationhubdata",
+ "rforproteomics",
+ "protgenerics",
+ ],
+ ),
+ (
+ "phylogeny-comparative",
+ "Comparative",
+ "Phylogeny, Comparative & Taxonomy",
+ False,
+ [
+ "tree",
+ "phylo",
+ "ortho",
+ "rscape",
+ "viennarna",
+ "anarci",
+ "pangolearn",
+ "unifrac",
+ "dendro",
+ "mash",
+ "paml",
+ "last",
+ "diamond",
+ "orthofinder",
+ "opticlust",
+ "constellations",
+ ],
+ ),
+]
+
+
+def _humanize_tool_name(tool_name: str) -> str:
+ chunks = re.split(r"[-_.]+", tool_name)
+ return " ".join(chunk.upper() if len(chunk) <= 4 else chunk.capitalize() for chunk in chunks if chunk)
+
+
+def _compact_text(value: str, limit: int = 480) -> str:
+ compacted = re.sub(r"\s+", " ", value or "").strip()
+ if len(compacted) <= limit:
+ return compacted
+ return f"{compacted[: limit - 3].rstrip()}..."
+
+
+def _extract_help_metadata(lines: list[str], key: str) -> str:
+ prefix = f"{key}:"
+ for line in lines:
+ if line.startswith(prefix):
+ return line[len(prefix) :].strip()
+ return ""
+
+
+def _extract_help_excerpt(lines: list[str], command_index: int) -> str:
+ excerpt_lines: list[str] = []
+ for line in lines[command_index + 1 :]:
+ stripped = line.strip()
+ if not stripped or stripped.startswith("[rc="):
+ continue
+ if stripped.startswith("## "):
+ break
+ excerpt_lines.append(stripped)
+ if len(excerpt_lines) >= 6:
+ break
+ return "\n".join(excerpt_lines)
+
+
+def _read_help_doc(tool_name: str) -> dict[str, str]:
+ help_doc_path = HELP_DOCS_ROOT / f"{tool_name}.txt"
+ if not help_doc_path.exists():
+ return {
+ "help_doc_path": "",
+ "help_summary": "",
+ "help_description": "",
+ "help_command": "",
+ "help_excerpt": "",
+ }
+
+ text = help_doc_path.read_text(encoding="utf-8", errors="ignore")
+ lines = [line.rstrip() for line in text.splitlines()]
+ summary = _compact_text(_extract_help_metadata(lines, "summary"), limit=220)
+ description = _compact_text(_extract_help_metadata(lines, "description"))
+
+ command_index = next((idx for idx, line in enumerate(lines) if line.startswith("$ ")), -1)
+ help_command = lines[command_index].strip() if command_index >= 0 else ""
+ help_excerpt = _extract_help_excerpt(lines, command_index) if command_index >= 0 else ""
+
+ return {
+ "help_doc_path": str(help_doc_path),
+ "help_summary": summary,
+ "help_description": description,
+ "help_command": help_command,
+ "help_excerpt": help_excerpt,
+ }
+
+
+def _classify_tool(tool_name: str) -> tuple[str, str, str, bool]:
+ lowered = tool_name.lower()
+ for slug, section, label, featured, keywords in CATEGORY_SPECS:
+ if any(keyword in lowered for keyword in keywords):
+ return slug, section, label, featured
+ return ("utilities-ecosystem", "Utilities", "Utilities & Libraries", False)
+
+
+def _should_exclude_tool(directory_name: str, tool_name: str, has_server_file: bool) -> bool:
+ lowered = f"{directory_name} {tool_name}".lower()
+ if not has_server_file:
+ return True
+ if "copy" in lowered:
+ return True
+ return False
+
+
+def _scan_root(root_info: dict[str, Any]) -> list[dict[str, Any]]:
+ root_path = Path(root_info["path"])
+ if not root_path.exists():
+ return []
+
+ items: list[dict[str, Any]] = []
+ for server_dir in sorted(root_path.glob("mcp_*")):
+ if not server_dir.is_dir():
+ continue
+
+ tool_name = server_dir.name.removeprefix("mcp_")
+ help_meta = _read_help_doc(tool_name)
+ app_dir = server_dir / "app"
+ server_candidates = sorted(app_dir.glob("*_server.py")) if app_dir.exists() else []
+ shim_candidates = sorted(app_dir.glob("*_shim_server.py")) if app_dir.exists() else []
+ has_server_file = bool(server_candidates)
+ if _should_exclude_tool(server_dir.name, tool_name, has_server_file):
+ continue
+ category_slug, category_section, category_label, featured = _classify_tool(tool_name)
+ description = help_meta["help_summary"] or f"{category_label} MCP server for {tool_name}."
+
+ items.append(
+ {
+ "id": server_dir.name,
+ "name": tool_name,
+ "display_name": _humanize_tool_name(tool_name),
+ "directory_name": server_dir.name,
+ "category_slug": category_slug,
+ "category_section": category_section,
+ "category_label": category_label,
+ "is_featured": featured,
+ "description": description,
+ "source_id": root_info["id"],
+ "source_label": root_info["label"],
+ "root_path": str(root_path),
+ "server_dir": str(server_dir),
+ "app_dir": str(app_dir) if app_dir.exists() else "",
+ "server_file": str(server_candidates[0]) if server_candidates else "",
+ "shim_file": str(shim_candidates[0]) if shim_candidates else "",
+ "has_server_file": has_server_file,
+ "has_shim_file": bool(shim_candidates),
+ "has_dockerfile": (server_dir / "Dockerfile").exists(),
+ "has_docker_compose": (server_dir / "docker-compose.yml").exists(),
+ "has_environment": (server_dir / "environment.yaml").exists(),
+ "has_requirements": (server_dir / "requirements.txt").exists()
+ or (app_dir / "requirements.txt").exists(),
+ "status": "ready",
+ "_priority": int(root_info["priority"]),
+ **help_meta,
+ }
+ )
+ return items
+
+
+def load_latest_graph_server_count() -> int | None:
+ if not GRAPH_OUTPUTS_ROOT.exists():
+ return None
+
+ graph_dirs = sorted(
+ path
+ for path in GRAPH_OUTPUTS_ROOT.glob("mcp_generated_graph_*")
+ if path.is_dir() and (path / "graph_summary.json").exists()
+ )
+ if not graph_dirs:
+ return None
+
+ latest_graph_dir = graph_dirs[-1]
+ try:
+ payload = json.loads((latest_graph_dir / "graph_summary.json").read_text(encoding="utf-8"))
+ except Exception:
+ return None
+
+ server_count = payload.get("server_count")
+ return int(server_count) if isinstance(server_count, int) else None
+
+
+def discover_mcp_servers() -> list[dict[str, Any]]:
+ merged: dict[str, dict[str, Any]] = {}
+
+ for root_info in DISCOVERY_ROOTS:
+ for item in _scan_root(root_info):
+ key = item["directory_name"]
+ existing = merged.get(key)
+ summary = {
+ "source_id": item["source_id"],
+ "source_label": item["source_label"],
+ "server_dir": item["server_dir"],
+ "status": item["status"],
+ }
+
+ if existing is None:
+ item["alternate_sources"] = []
+ merged[key] = item
+ continue
+
+ if item["_priority"] < existing["_priority"]:
+ item["alternate_sources"] = [summary, *existing.get("alternate_sources", [])]
+ merged[key] = item
+ continue
+
+ existing.setdefault("alternate_sources", []).append(summary)
+
+ servers = list(merged.values())
+ for server in servers:
+ server.pop("_priority", None)
+ server["alternate_sources"] = sorted(
+ server.get("alternate_sources", []),
+ key=lambda source: (source["source_label"], source["server_dir"]),
+ )
+
+ return sorted(
+ servers,
+ key=lambda item: (
+ not item["is_featured"],
+ item["category_section"].lower(),
+ item["display_name"].lower(),
+ ),
+ )
+
+
+def list_metabolomics_servers() -> list[dict[str, Any]]:
+ return [item for item in discover_mcp_servers() if item["category_slug"] == "featured-metabolomics"]
diff --git a/Biomanus/biomni_web/backend/metabolomics_tools.py b/Biomanus/biomni_web/backend/metabolomics_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..692205efc5429a291b174f43da5333c9b3e872f3
--- /dev/null
+++ b/Biomanus/biomni_web/backend/metabolomics_tools.py
@@ -0,0 +1,111 @@
+from __future__ import annotations
+
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any
+
+from mcp_registry import GENERATED_ROOT, list_metabolomics_servers
+
+
+BACKEND_ROOT = Path(__file__).resolve().parent
+TOOL2MCP_SCRIPT = (BACKEND_ROOT / "tool2mcp.py").resolve()
+
+
+def _scmeta_config_file() -> Path:
+ return GENERATED_ROOT / "metabolomics_mcp.yaml"
+
+
+def _find_generated_server(tool_name: str) -> Path | None:
+ app_dir = GENERATED_ROOT / f"mcp_{tool_name}" / "app"
+ if not app_dir.exists():
+ return None
+
+ exact = app_dir / f"{tool_name}_server.py"
+ if exact.exists():
+ return exact
+
+ for candidate in sorted(app_dir.glob("*_server.py")):
+ if candidate.is_file():
+ return candidate
+ return None
+
+
+def list_metabolomics_tools() -> list[dict[str, Any]]:
+ tools: list[dict[str, Any]] = []
+ for server in list_metabolomics_servers():
+ tools.append(
+ {
+ "name": server["name"],
+ "label": server["display_name"],
+ "category": "metabolomics",
+ "description": server["description"],
+ "available": server["has_server_file"],
+ "server_path": server["server_file"],
+ "source_label": server["source_label"],
+ "featured": server["is_featured"],
+ }
+ )
+ return tools
+
+
+def generate_scmeta_mcp() -> dict[str, Any]:
+ GENERATED_ROOT.mkdir(parents=True, exist_ok=True)
+
+ cmd = [
+ sys.executable,
+ str(TOOL2MCP_SCRIPT),
+ "--name",
+ "scmeta",
+ "--manual",
+ "--help",
+ "--run_help_command",
+ "True",
+ "--output_location",
+ str(GENERATED_ROOT),
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+ generated_server = _find_generated_server("scmeta")
+ success = result.returncode == 0 and generated_server is not None
+
+ if success:
+ write_metabolomics_mcp_config(["scmeta"])
+
+ return {
+ "ok": success,
+ "returncode": result.returncode,
+ "stdout": result.stdout[-4000:],
+ "stderr": result.stderr[-4000:],
+ "server_path": str(generated_server) if generated_server else "",
+ "config_path": str(_scmeta_config_file()) if _scmeta_config_file().exists() else "",
+ }
+
+
+def write_metabolomics_mcp_config(selected_tools: list[str] | None = None) -> Path:
+ available_tools = [
+ tool for tool in list_metabolomics_servers() if tool.get("has_server_file")
+ ]
+ if selected_tools:
+ selected = set(selected_tools)
+ available_tools = [tool for tool in available_tools if tool["name"] in selected]
+
+ if not available_tools:
+ raise FileNotFoundError("Cannot write metabolomics config: no metabolomics server file found.")
+
+ config_path = _scmeta_config_file()
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+
+ lines = ["mcp_servers:"]
+ for tool in available_tools:
+ lines.extend(
+ [
+ f" {tool['name']}:",
+ " enabled: true",
+ f" command: [\"{sys.executable}\", \"{tool['server_file']}\"]",
+ f" description: \"{tool['display_name']} MCP server for metabolomics tasks\"",
+ ]
+ )
+
+ config_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ return config_path
diff --git a/Biomanus/biomni_web/backend/pLentiCRISPR_v2_B2M_sgRNA_map.png b/Biomanus/biomni_web/backend/pLentiCRISPR_v2_B2M_sgRNA_map.png
new file mode 100644
index 0000000000000000000000000000000000000000..88c2fb9852a46cb612c82cfd3883865dd360e63d
--- /dev/null
+++ b/Biomanus/biomni_web/backend/pLentiCRISPR_v2_B2M_sgRNA_map.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:64b945d66fa162651a8731f67d80f431321803f656f50379fca35c6dffdbdb65
+size 636379
diff --git a/Biomanus/biomni_web/backend/rawtools_log.txt b/Biomanus/biomni_web/backend/rawtools_log.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0e02c668d2b19454466c9dda30a74ced524a6778
--- /dev/null
+++ b/Biomanus/biomni_web/backend/rawtools_log.txt
@@ -0,0 +1,8 @@
+2026-04-28 02:13:23.287 +00:00 [INF] Program started with arguments: -version
+2026-04-28 02:13:23.441 +00:00 [INF] Program started with arguments: -f /225040511/project/Biomni/biomni_web/backend/data/uploads/4eddae61-3893-487a-85ec-f800ff65468a/7bff3a3d-759f-4fc3-b0cf-e3f16b49c96a_HepG2.RAW -o /tmp/tmp21i4jzof/tmpd1m2xezd -asd
+2026-04-28 02:13:23.681 +00:00 [INF] Files to be processed, provided as list: /225040511/project/Biomni/biomni_web/backend/data/uploads/4eddae61-3893-487a-85ec-f800ff65468a/7bff3a3d-759f-4fc3-b0cf-e3f16b49c96a_HepG2.RAW
+2026-04-28 02:13:23.722 +00:00 [INF] Extracting scan indices
+2026-04-28 02:13:29.039 +00:00 [INF] Extracting method/instrument information
+2026-04-28 02:13:29.704 +00:00 [INF] Extracting trailer extras
+2026-04-28 02:13:29.718 +00:00 [INF] Extracting precursor masses
+2026-04-28 02:13:29.719 +00:00 [INF] Extracting retention times
diff --git a/Biomanus/biomni_web/backend/requirements.txt b/Biomanus/biomni_web/backend/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f863b80c56927e4fb583e1d09a9a0afaea7a2c9b
--- /dev/null
+++ b/Biomanus/biomni_web/backend/requirements.txt
@@ -0,0 +1,13 @@
+# Core runtime
+requests>=2.31.0
+beautifulsoup4>=4.12.0
+python-dotenv>=1.0.0
+PyMuPDF>=1.24.0
+
+# LLM backends
+openai>=1.30.0
+anthropic>=0.34.0
+google-generativeai>=0.8.0
+
+# MCP server/runtime helpers used by generated servers
+fastmcp>=2.0.0
diff --git a/Biomanus/biomni_web/backend/scema_readme.md b/Biomanus/biomni_web/backend/scema_readme.md
new file mode 100644
index 0000000000000000000000000000000000000000..d7e67cb4148a333c735e030049ef13a93c1720a3
--- /dev/null
+++ b/Biomanus/biomni_web/backend/scema_readme.md
@@ -0,0 +1,47 @@
+# SCMeTA
+
+SCMeTA is a python library of single-cell meta-analysis tools. It provides a set of functions for single-cell meta-analysis, including data integration, batch effect correction, cell type annotation, cell clustering, cell trajectory inference, and cell type marker identification. It also provides a set of functions for single-cell data visualization, including dimension reduction, cell clustering, cell trajectory inference, and cell type marker identification.
+
+## Installation
+
+SCMeTA is available on PyPI and can be installed with pip:
+
+```bash
+pip install scmeta
+```
+
+## Usage
+
+### Data integration
+
+```python
+
+from SCMeTA import Process
+
+sc = Process()
+
+# Load data
+
+sc.load("data/example.RAW")
+
+# Data process
+
+sc.pre_process()
+sc.process()
+sc.post_process()
+
+```
+
+## Documentation
+
+The official documentation is hosted on Read the Docs: https://sc-meta.com/
+
+## Sample data
+
+You can find the sample data on [Google Dirve](https://drive.google.com/drive/folders/1tRQEPa7eX8Q_VkAIBnKieim6gIPfVJsM?usp=share_link).
+
+## License
+
+SCMeTA is licensed under the GPLv3 license. See the LICENSE file for more details.
+
+
diff --git a/Biomanus/biomni_web/backend/session.py b/Biomanus/biomni_web/backend/session.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3fbd25d20b9760c48f9e72bf544583529b60c0b
--- /dev/null
+++ b/Biomanus/biomni_web/backend/session.py
@@ -0,0 +1,145 @@
+import os
+import uuid
+from dataclasses import dataclass, field
+from threading import Lock
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+from biomni_agent import BiomniWebAgent
+
+DEFAULT_LLM_PROVIDER = os.getenv("BIOMNI_LLM_PROVIDER", "deepseek").strip().lower()
+
+
+@dataclass
+class SessionState:
+ agent: BiomniWebAgent | None = None
+ uploaded_files: list[str] = field(default_factory=list)
+ metabolomics_enabled: bool = False
+ metabolomics_tools: list[str] = field(default_factory=list)
+ paper_repro_enabled: bool = False
+ paper_profile: str = "foxj1"
+ stop_requested: bool = False
+ llm_provider: str = field(default_factory=lambda: DEFAULT_LLM_PROVIDER)
+
+
+def _create_agent(
+ session_id: str,
+ expected_files: list[str] | None = None,
+ llm_provider: str = DEFAULT_LLM_PROVIDER,
+) -> BiomniWebAgent:
+ return BiomniWebAgent(
+ session_id=session_id,
+ expected_data_lake_files=expected_files or [],
+ llm_provider=llm_provider,
+ )
+
+
+class SessionManager:
+ def __init__(self):
+ self._sessions: dict[str, SessionState] = {}
+ self._lock = Lock()
+
+ def create_session(self, llm_provider: str = DEFAULT_LLM_PROVIDER) -> str:
+ sid = str(uuid.uuid4())
+ with self._lock:
+ # Lazy init agent to avoid blocking /session/new.
+ self._sessions[sid] = SessionState(
+ llm_provider=(llm_provider or DEFAULT_LLM_PROVIDER).strip().lower()
+ )
+ return sid
+
+ def has_session(self, sid: str) -> bool:
+ return sid in self._sessions
+
+ def get_agent(self, sid: str) -> BiomniWebAgent:
+ # Fast path: already initialized
+ with self._lock:
+ state = self._sessions[sid]
+ if state.agent is not None:
+ return state.agent
+ expected_files = list(state.uploaded_files)
+ llm_provider = state.llm_provider
+
+ # Slow path: initialize outside lock
+ new_agent = _create_agent(sid, expected_files=expected_files, llm_provider=llm_provider)
+ if expected_files:
+ new_agent.set_uploaded_files(expected_files)
+ new_agent.set_metabolomics_settings(state.metabolomics_enabled, state.metabolomics_tools)
+ new_agent.set_paper_reproduction_settings(state.paper_repro_enabled, state.paper_profile)
+
+ # Publish initialized agent
+ with self._lock:
+ state = self._sessions.get(sid)
+ if state is None:
+ raise KeyError(f"Session not found: {sid}")
+ if state.agent is None:
+ state.agent = new_agent
+ return state.agent
+
+ def add_uploaded_file(self, sid: str, relative_path: str):
+ with self._lock:
+ state = self._sessions[sid]
+ if relative_path not in state.uploaded_files:
+ state.uploaded_files.append(relative_path)
+ if state.agent is not None:
+ state.agent.set_uploaded_files(state.uploaded_files)
+
+ def set_metabolomics_settings(self, sid: str, enabled: bool, tools: list[str]):
+ with self._lock:
+ state = self._sessions[sid]
+ state.metabolomics_enabled = bool(enabled)
+ state.metabolomics_tools = sorted(set(tools))
+ if state.agent is not None:
+ state.agent.set_metabolomics_settings(state.metabolomics_enabled, state.metabolomics_tools)
+
+ def set_llm_provider(self, sid: str, llm_provider: str):
+ normalized = (llm_provider or DEFAULT_LLM_PROVIDER).strip().lower()
+ with self._lock:
+ state = self._sessions[sid]
+ if state.llm_provider == normalized:
+ return
+ state.llm_provider = normalized
+ # Recreate the agent on next access so the new backend takes effect.
+ state.agent = None
+
+ def request_stop(self, sid: str) -> None:
+ with self._lock:
+ state = self._sessions[sid]
+ state.stop_requested = True
+ if state.agent is not None:
+ state.agent.request_cancel()
+
+ def clear_stop(self, sid: str) -> None:
+ with self._lock:
+ state = self._sessions[sid]
+ state.stop_requested = False
+ if state.agent is not None:
+ state.agent.clear_cancel_request()
+
+ def is_stop_requested(self, sid: str) -> bool:
+ with self._lock:
+ state = self._sessions[sid]
+ return bool(state.stop_requested)
+
+ def set_paper_reproduction_settings(self, sid: str, enabled: bool, profile: str = "foxj1"):
+ normalized_profile = (profile or "foxj1").strip().lower()
+ with self._lock:
+ state = self._sessions[sid]
+ state.paper_repro_enabled = bool(enabled)
+ state.paper_profile = normalized_profile
+ if state.agent is not None:
+ state.agent.set_paper_reproduction_settings(state.paper_repro_enabled, state.paper_profile)
+
+ def get_uploaded_files(self, sid: str) -> list[str]:
+ with self._lock:
+ return list(self._sessions[sid].uploaded_files)
+
+ def delete_session(self, sid: str):
+ with self._lock:
+ self._sessions.pop(sid, None)
+
+ def cleanup_all(self):
+ with self._lock:
+ self._sessions.clear()
diff --git a/Biomanus/biomni_web/backend/streaming.py b/Biomanus/biomni_web/backend/streaming.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7de56fdd7bd73755f7167ea36c2b91b4c6c5282
--- /dev/null
+++ b/Biomanus/biomni_web/backend/streaming.py
@@ -0,0 +1,144 @@
+"""
+StreamingCallback:拦截 agent 的输出,转成结构化 SSE 事件
+
+后端通过 patch agent 的 print 输出方法捕获步骤事件,并转成 SSE。
+"""
+import io
+import queue
+import re
+import sys
+
+
+class StreamingCallback:
+ """
+ 拦截 agent.go() 的 stdout 输出,解析成结构化事件。
+
+ Biomni 的 agent 通过 print() 输出中间步骤:
+ - "Thought: ..." → thinking 事件
+ - "```python\n...\n```" → code 事件
+ - "Observation: ..." → observation 事件
+ - 最终答案 → result 事件
+ """
+
+ def __init__(self, event_queue: queue.Queue):
+ self.q = event_queue
+ self._original_stdout = None
+ self._buf = io.StringIO()
+ self._in_solution = False
+ self._solution_lines: list[str] = []
+
+ def attach(self, _agent):
+ """patch sys.stdout 来捕获 agent 的 print 输出"""
+ self._original_stdout = sys.stdout
+ sys.stdout = _InterceptWriter(self._parse_and_emit, self._original_stdout)
+
+ def detach(self, _agent):
+ # 兜底:若流结束时仍在 solution 块内,仍然输出 result
+ self._flush_solution_if_any()
+ if self._original_stdout:
+ sys.stdout = self._original_stdout
+
+ def _parse_and_emit(self, text: str):
+ """解析 agent 输出文本,转成结构化事件"""
+ raw_text = text.rstrip("\n")
+ if self._handle_solution_markup(raw_text):
+ return
+
+ text = raw_text.strip()
+ if not text:
+ return
+
+ # 匹配 Biomni A1 的输出格式
+ if text.startswith("Thought:") or text.startswith("[Thinking]"):
+ self.q.put({"type": "thinking", "content": text})
+
+ elif "```python" in text or "```r" in text or "```bash" in text:
+ # 提取代码块
+ match = re.search(r"```(\w+)\n(.*?)```", text, re.DOTALL)
+ if match:
+ lang, code = match.group(1), match.group(2)
+ self.q.put({"type": "code", "lang": lang, "content": code})
+ else:
+ self.q.put({"type": "thinking", "content": text})
+
+ elif text.startswith("Observation:") or text.startswith("[Output]"):
+ self.q.put({"type": "observation", "content": text})
+
+ elif text.startswith("Action:") or "tool" in text.lower()[:30]:
+ # 尝试提取工具名
+ tool_match = re.search(r"(\w+)\(", text)
+ tool_name = tool_match.group(1) if tool_match else "tool"
+ self.q.put({"type": "tool_use", "tool": tool_name, "content": text})
+
+ elif text.startswith("Final Answer:") or text.startswith("Answer:"):
+ self.q.put({"type": "result", "content": text})
+
+ else:
+ # 其他输出作为 thinking
+ self.q.put({"type": "thinking", "content": text})
+
+ def _handle_solution_markup(self, raw_text: str) -> bool:
+ """
+ 解析 ... 多行块。
+ 命中时输出 type=result,并返回 True 表示该行已被消费。
+ """
+ if self._in_solution:
+ if "" in raw_text:
+ before_end, _after_end = raw_text.split("", 1)
+ if before_end:
+ self._solution_lines.append(before_end)
+ self._flush_solution_if_any()
+ self._in_solution = False
+ else:
+ self._solution_lines.append(raw_text)
+ return True
+
+ if "
+ {artifacts.length > 0 &&
}
+ {blocks.map((block, idx) => {
+ if (block.type === "table") {
+ return
;
+ }
+ return
;
+ })}
+
+ );
+}
+
+function ArtifactDownloads({ artifacts }) {
+ return (
+
+ {sections.map((section, idx) => {
+ if (section.type === "heading") {
+ return (
+
+ {renderInlineMarkdown(section.text)}
+
+ );
+ }
+ if (section.type === "list") {
+ return (
+
+ {section.items.map((item, i) => (
+ - {renderInlineMarkdown(item)}
+ ))}
+
+ );
+ }
+ if (section.type === "quote") {
+ return
{renderInlineMarkdown(section.text)}
;
+ }
+ if (section.type === "sequence") {
+ return (
+
+
Sequence
+
{section.text}
+
+ );
+ }
+ return
{renderInlineMarkdown(section.text)}
;
+ })}
+
+ );
+}
+
+function ResultTable({ headers, rows }) {
+ return (
+