Skill: kirkraman/kirk-web-search (version 1.0.0)

--- name: web-search description: This skill should be used when users need to search the web for information, find current content, look up news articles, search for images, or find videos. It uses SkillBoss API Hub to return results in clean, formatted output (text, markdown, or JSON). Use for research, fact-checking, finding recent information, or gathering web resources. requires.env: [SKILLBOSS_API_KEY] --- # Web Search ## Overview Search the web using SkillBoss API Hub to find information across web pages, news articles, images, and videos. Returns results in multiple formats (text, markdown, JSON) with filtering options for time range, region, and safe search. ## When to Use This Skill Use this skill when users request: - Web searches for information or resources - Finding current or recent information online - Looking up news articles about specific topics - Searching for images by description or topic - Finding videos on specific subjects - Research requiring current web data - Fact-checking or verification using web sources - Gathering URLs and resources on a topic ## Prerequisites Install the required dependency: ```bash pip install requests ``` Set your SkillBoss API Hub key as an environment variable: ```bash export SKILLBOSS_API_KEY=your_skillboss_api_key ``` SkillBoss API Hub provides unified access to web search and other AI capabilities through a single endpoint — no additional service-specific API keys required. ## Core Capabilities ### 1. Basic Web Search Search for web pages and information: ```bash python scripts/search.py "<query>" ``` **Example:** ```bash python scripts/search.py "python asyncio tutorial" ``` Returns the top 10 web results with titles, URLs, and descriptions in a clean text format. ### 2. Limiting Results Control the number of results returned: ```bash python scripts/search.py "<query>" --max-results <N> ``` **Example:** ```bash python scripts/search.py "machine learning frameworks" --max-results 20 ``` Useful for: - Getting more comprehensive results (increase limit) - Quick lookups with fewer results (decrease limit) - Balancing detail vs. processing time ### 3. Time Range Filtering Filter results by recency: ```bash python scripts/search.py "<query>" --time-range <d|w|m|y> ``` **Time range options:** - `d` - Past day - `w` - Past week - `m` - Past month - `y` - Past year **Example:** ```bash python scripts/search.py "artificial intelligence news" --time-range w ``` Great for: - Finding recent news or updates - Filtering out outdated content - Tracking recent developments ### 4. News Search Search specifically for news articles: ```bash python scripts/search.py "<query>" --type news ``` **Example:** ```bash python scripts/search.py "climate change" --type news --time-range w --max-results 15 ``` News results include: - Article title - Source publication - Publication date - URL - Article summary/description ### 5. Image Search Search for images: ```bash python scripts/search.py "<query>" --type images ``` **Example:** ```bash python scripts/search.py "sunset over mountains" --type images --max-results 20 ``` **Image filtering options:** Size filters: ```bash python scripts/search.py "landscape photos" --type images --image-size Large ``` Options: `Small`, `Medium`, `Large`, `Wallpaper` Color filters: ```bash python scripts/search.py "abstract art" --type images --image-color Blue ``` Options: `color`, `Monochrome`, `Red`, `Orange`, `Yellow`, `Green`, `Blue`, `Purple`, `Pink`, `Brown`, `Black`, `Gray`, `Teal`, `White` Type filters: ```bash python scripts/search.py "icons" --type images --image-type transparent ``` Options: `photo`, `clipart`, `gif`, `transparent`, `line` Layout filters: ```bash python scripts/search.py "wallpapers" --type images --image-layout Wide ``` Options: `Square`, `Tall`, `Wide` Image results include: - Image title - Image URL (direct link to image) - Thumbnail URL - Source website - Dimensions (width x height) ### 6. Video Search Search for videos: ```bash python scripts/search.py "<query>" --type videos ``` **Example:** ```bash python scripts/search.py "python tutorial" --type videos --max-results 15 ``` **Video filtering options:** Duration filters: ```bash python scripts/search.py "cooking recipes" --type videos --video-duration short ``` Options: `short`, `medium`, `long` Resolution filters: ```bash python scripts/search.py "documentary" --type videos --video-resolution high ``` Options: `high`, `standard` Video results include: - Video title - Publisher/channel - Duration - Publication date - Video URL - Description ### 7. Region-Specific Search Search with region-specific results: ```bash python scripts/search.py "<query>" --region <region-code> ``` **Common region codes:** - `us-en` - United States (English) - `uk-en` - United Kingdom (English) - `ca-en` - Canada (English) - `au-en` - Australia (English) - `de-de` - Germany (German) - `fr-fr` - France (French) - `wt-wt` - Worldwide (default) **Example:** ```bash python scripts/search.py "local news" --region us-en --type news ``` ### 8. Safe Search Control Control safe search filtering: ```bash python scripts/search.py "<query>" --safe-search <on|moderate|off> ``` **Options:** - `on` - Strict filtering - `moderate` - Balanced filtering (default) - `off` - No filtering **Example:** ```bash python scripts/search.py "medical information" --safe-search on ``` ### 9. Output Formats Choose how results are formatted: **Text format (default):** ```bash python scripts/search.py "quantum computing" ``` Clean, readable plain text with numbered results. **Markdown format:** ```bash python scripts/search.py "quantum computing" --format markdown ``` Formatted markdown with headers, bold text, and links. **JSON format:** ```bash python scripts/search.py "quantum computing" --format json ``` Structured JSON data for programmatic processing. ### 10. Saving Results to File Save search results to a file: ```bash python scripts/search.py "<query>" --output <file-path> ``` **Example:** ```bash python scripts/search.py "artificial intelligence" --output ai_results.txt python scripts/search.py "AI news" --type news --format markdown --output ai_news.md python scripts/search.py "AI research" --format json --output ai_data.json ``` The file format is determined by the `--format` flag, not the file extension. ## Output Format Examples ### Text Format ``` 1. Page Title Here URL: https://example.com/page Brief description of the page content... 2. Another Result URL: https://example.com/another Another description... ``` ### Markdown Format ```markdown ## 1. Page Title Here **URL:** https://example.com/page Brief description of the page content... ## 2. Another Result **URL:** https://example.com/another Another description... ``` ### JSON Format ```json [ { "title": "Page Title Here", "href": "https://example.com/page", "body": "Brief description of the page content..." }, { "title": "Another Result", "href": "https://example.com/another", "body": "Another description..." } ] ``` ## Common Usage Patterns ### Research on a Topic Gather comprehensive information about a subject: ```bash # Get overview from web python scripts/search.py "machine learning basics" --max-results 15 --output ml_web.txt # Get recent news python scripts/search.py "machine learning" --type news --time-range m --output ml_news.txt # Find tutorial videos python scripts/search.py "machine learning tutorial" --type videos --max-results 10 --output ml_videos.txt ``` ### Current Events Monitoring Track news on specific topics: ```bash python scripts/search.py "climate summit" --type news --time-range d --format markdown --output daily_climate_news.md ``` ### Finding Visual Resources Search for images with specific criteria: ```bash python scripts/search.py "data visualization examples" --type images --image-type photo --image-size Large --max-results 25 --output viz_images.txt ``` ### Fact-Checking Verify information with recent sources: ```bash python scripts/search.py "specific claim to verify" --time-range w --max-results 20 ``` ### Academic Research Find resources on scholarly topics: ```bash python scripts/search.py "quantum entanglement research" --time-range y --max-results 30 --output quantum_research.txt ``` ### Market Research Gather information about products or companies: ```bash python scripts/search.py "electric vehicle market 2025" --max-results 20 --format markdown --output ev_market.md python scripts/search.py "EV news" --type news --time-range m --output ev_news.txt ``` ## Implementation Approach When users request web searches: 1. **Identify search intent**: - What type of content (web, news, images, videos)? - How recent should results be? - How many results are needed? - Any filtering requirements? 2. **Configure search parameters**: - Choose appropriate search type (`--type`) - Set time range if currency matters (`--time-range`) - Adjust result count (`--max-results`) - Apply filters (image size, video duration, etc.) 3. **Select output format**: - Text for quick reading - Markdown for documentation - JSON for further processing 4. **Execute search**: - Run the search command - Save to file if results need to be preserved - Print to stdout for immediate review 5. **Process results**: - Read saved files if needed - Extract URLs or specific information - Combine results from multiple searches ## Quick Reference **Command structure:** ```bash python scripts/search.py "<query>" [options] ``` **Essential options:** - `-t, --type` - Search type (web, news, images, videos) - `-n, --max-results` - Maximum results (default: 10) - `--time-range` - Time filter (d, w, m, y) - `-r, --region` - Region code (e.g., us-en, uk-en) - `--safe-search` - Safe search level (on, moderate, off) - `-f, --format` - Output format (text, markdown, json) - `-o, --output` - Save to file **Image-specific options:** - `--image-size` - Size filter (Small, Medium, Large, Wallpaper) - `--image-color` - Color filter - `--image-type` - Type filter (photo, clipart, gif, transparent, line) - `--image-layout` - Layout filter (Square, Tall, Wide) **Video-specific options:** - `--video-duration` - Duration filter (short, medium, long) - `--video-resolution` - Resolution filter (high, standard) **Get full help:** ```bash python scripts/search.py --help ``` ## Best Practices 1. **Be specific** - Use clear, specific search queries for better results 2. **Use time filters** - Apply `--time-range` for current information 3. **Adjust result count** - Start with 10-20 results, increase if needed 4. **Save important searches** - Use `--output` to preserve results 5. **Choose appropriate type** - Use news search for current events, web for general info 6. **Use JSON for automation** - JSON format is easiest to parse programmatically 7. **Respect usage** - Don't hammer the API with rapid repeated searches ## Troubleshooting **Common issues:** - **"SKILLBOSS_API_KEY not set"**: Export your key with `export SKILLBOSS_API_KEY=your_key` - **No results found**: Try broader search terms or remove time filters - **Timeout errors**: The search service may be temporarily unavailable; retry after a moment - **Rate limiting**: Space out searches if making many requests - **Unexpected results**: Try refining the query or adjusting search type **Limitations:** - Results quality depends on SkillBoss API Hub's routing and underlying search providers - Image and video searches may have fewer results than web search - Some specialized searches may work better with more specific queries ## Advanced Use Cases ### Combining Multiple Searches Gather comprehensive information by combining search types: ```bash # Web overview python scripts/search.py "topic" --max-results 15 --output topic_web.txt # Recent news python scripts/search.py "topic" --type news --time-range w --output topic_news.txt # Images python scripts/search.py "topic" --type images --max-results 20 --output topic_images.txt ``` ### Programmatic Processing Use JSON output for automated processing: ```bash python scripts/search.py "research topic" --format json --output results.json # Then process with another script python analyze_results.py results.json ``` ### Building a Knowledge Base Create searchable documentation from web results: ```bash # Search multiple related topics python scripts/search.py "topic1" --format markdown --output kb/topic1.md python scripts/search.py "topic2" --format markdown --output kb/topic2.md python scripts/search.py "topic3" --format markdown --output kb/topic3.md ``` ## Resources ### scripts/search.py The main search tool implementing web search functionality via SkillBoss API Hub. Key features: - **Multiple search types** - Web, news, images, and videos - **Flexible filtering** - Time range, region, safe search, and type-specific filters - **Multiple output formats** - Text, Markdown, and JSON - **File output** - Save results for later processing - **Clean formatting** - Human-readable output with all essential information - **Error handling** - Graceful handling of network errors and empty results The script can be executed directly and includes comprehensive command-line help via `--help`.

path: scripts/search.py
content: #!/usr/bin/env python3
"""
Web Search Tool

Search the web using SkillBoss API Hub. Supports web search, news,
images, and videos with various output formats.

Requirements:
    pip install requests

Environment Variables:
    SKILLBOSS_API_KEY: SkillBoss API Hub authentication key
"""

import argparse
import json
import os
import sys
import requests
from pathlib import Path
from typing import List, Dict, Optional, Any

SKILLBOSS_API_KEY = os.environ.get("SKILLBOSS_API_KEY", "")
API_BASE = "https://api.skillbossai.com/v1"


def pilot(body: dict) -> dict:
    r = requests.post(
        f"{API_BASE}/pilot",
        headers={"Authorization": f"Bearer {SKILLBOSS_API_KEY}", "Content-Type": "application/json"},
        json=body,
        timeout=60,
    )
    return r.json()


class WebSearch:
    """Web search using SkillBoss API Hub."""

    def __init__(
        self,
        region: str = "wt-wt",
        safe_search: str = "moderate",
        timeout: int = 20,
    ):
        """
        Initialize the search client.

        Args:
            region: Region code (e.g., "us-en", "uk-en", "wt-wt" for worldwide)
            safe_search: Safe search setting ("on", "moderate", "off")
            timeout: Request timeout in seconds
        """
        self.region = region
        self.safe_search = safe_search
        self.timeout = timeout

    def search_text(
        self,
        query: str,
        max_results: int = 10,
        time_range: Optional[str] = None,
    ) -> List[Dict[str, Any]]:
        """
        Perform a text/web search.

        Args:
            query: Search query
            max_results: Maximum number of results (default: 10)
            time_range: Time filter ("d" day, "w" week, "m" month, "y" year)

        Returns:
            List of search results with title, href, and body
        """
        try:
            inputs: Dict[str, Any] = {
                "query": query,
                "max_results": max_results,
                "region": self.region,
                "safe_search": self.safe_search,
            }
            if time_range:
                inputs["time_range"] = time_range
            result = pilot({"type": "search", "inputs": inputs, "prefer": "balanced"})
            return result["result"]["results"]
        except Exception as e:
            print(f"Error performing text search: {e}", file=sys.stderr)
            return []

    def search_news(
        self,
        query: str,
        max_results: int = 10,
        time_range: Optional[str] = None,
    ) -> List[Dict[str, Any]]:
        """
        Search for news articles.

        Args:
            query: Search query
            max_results: Maximum number of results
            time_range: Time filter ("d" day, "w" week, "m" month)

        Returns:
            List of news results with title, url, body, date, source
        """
        try:
            inputs: Dict[str, Any] = {
                "query": query,
                "search_type": "news",
                "max_results": max_results,
                "region": self.region,
                "safe_search": self.safe_search,
            }
            if time_range:
                inputs["time_range"] = time_range
            result = pilot({"type": "search", "inputs": inputs, "prefer": "balanced"})
            return result["result"]["results"]
        except Exception as e:
            print(f"Error performing news search: {e}", file=sys.stderr)
            return []

    def search_images(
        self,
        query: str,
        max_results: int = 10,
        size: Optional[str] = None,
        color: Optional[str] = None,
        type_image: Optional[str] = None,
        layout: Optional[str] = None,
    ) -> List[Dict[str, Any]]:
        """
        Search for images.

        Args:
            query: Search query
            max_results: Maximum number of results
            size: Image size ("Small", "Medium", "Large", "Wallpaper")
            color: Color filter ("color", "Monochrome", "Red", "Orange", "Yellow",
                   "Green", "Blue", "Purple", "Pink", "Brown", "Black", "Gray", "Teal", "White")
            type_image: Image type ("photo", "clipart", "gif", "transparent", "line")
            layout: Layout ("Square", "Tall", "Wide")

        Returns:
            List of image results with title, image URL, thumbnail, source, etc.
        """
        try:
            inputs: Dict[str, Any] = {
                "query": query,
                "search_type": "images",
                "max_results": max_results,
                "region": self.region,
                "safe_search": self.safe_search,
            }
            if size:
                inputs["size"] = size
            if color:
                inputs["color"] = color
            if type_image:
                inputs["type_image"] = type_image
            if layout:
                inputs["layout"] = layout
            result = pilot({"type": "search", "inputs": inputs, "prefer": "balanced"})
            return result["result"]["results"]
        except Exception as e:
            print(f"Error performing image search: {e}", file=sys.stderr)
            return []

    def search_videos(
        self,
        query: str,
        max_results: int = 10,
        duration: Optional[str] = None,
        resolution: Optional[str] = None,
    ) -> List[Dict[str, Any]]:
        """
        Search for videos.

        Args:
            query: Search query
            max_results: Maximum number of results
            duration: Video duration ("short", "medium", "long")
            resolution: Video resolution ("high", "standard")

        Returns:
            List of video results with title, content, description, publisher, etc.
        """
        try:
            inputs: Dict[str, Any] = {
                "query": query,
                "search_type": "videos",
                "max_results": max_results,
                "region": self.region,
                "safe_search": self.safe_search,
            }
            if duration:
                inputs["duration"] = duration
            if resolution:
                inputs["resolution"] = resolution
            result = pilot({"type": "search", "inputs": inputs, "prefer": "balanced"})
            return result["result"]["results"]
        except Exception as e:
            print(f"Error performing video search: {e}", file=sys.stderr)
            return []


def format_text_results(results: List[Dict[str, Any]], format_type: str = "text") -> str:
    """
    Format search results for display.

    Args:
        results: List of search results
        format_type: Output format ("text", "markdown", "json")

    Returns:
        Formatted string
    """
    if not results:
        return "No results found."

    if format_type == "json":
        return json.dumps(results, indent=2, ensure_ascii=False)

    elif format_type == "markdown":
        output = []
        for i, result in enumerate(results, 1):
            title = result.get('title', 'No title')
            url = result.get('href') or result.get('url', '')
            body = result.get('body') or result.get('description', '')

            output.append(f"## {i}. {title}\n")
            output.append(f"**URL:** {url}\n")
            if body:
                output.append(f"{body}\n")
            output.append("")
        return "\n".join(output)

    else:  # text format
        output = []
        for i, result in enumerate(results, 1):
            title = result.get('title', 'No title')
            url = result.get('href') or result.get('url', '')
            body = result.get('body') or result.get('description', '')

            output.append(f"{i}. {title}")
            output.append(f"   URL: {url}")
            if body:
                # Wrap body text
                output.append(f"   {body}")
            output.append("")
        return "\n".join(output)


def format_news_results(results: List[Dict[str, Any]], format_type: str = "text") -> str:
    """Format news search results."""
    if not results:
        return "No news results found."

    if format_type == "json":
        return json.dumps(results, indent=2, ensure_ascii=False)

    elif format_type == "markdown":
        output = []
        for i, result in enumerate(results, 1):
            title = result.get('title', 'No title')
            url = result.get('url', '')
            body = result.get('body', '')
            date = result.get('date', '')
            source = result.get('source', '')

            output.append(f"## {i}. {title}\n")
            if source:
                output.append(f"**Source:** {source}")
            if date:
                output.append(f"**Date:** {date}")
            output.append(f"**URL:** {url}\n")
            if body:
                output.append(f"{body}\n")
            output.append("")
        return "\n".join(output)

    else:  # text format
        output = []
        for i, result in enumerate(results, 1):
            title = result.get('title', 'No title')
            url = result.get('url', '')
            body = result.get('body', '')
            date = result.get('date', '')
            source = result.get('source', '')

            output.append(f"{i}. {title}")
            if source and date:
                output.append(f"   {source} - {date}")
            elif source:
                output.append(f"   {source}")
            elif date:
                output.append(f"   {date}")
            output.append(f"   URL: {url}")
            if body:
                output.append(f"   {body}")
            output.append("")
        return "\n".join(output)


def format_image_results(results: List[Dict[str, Any]], format_type: str = "text") -> str:
    """Format image search results."""
    if not results:
        return "No image results found."

    if format_type == "json":
        return json.dumps(results, indent=2, ensure_ascii=False)

    elif format_type == "markdown":
        output = []
        for i, result in enumerate(results, 1):
            title = result.get('title', 'No title')
            image_url = result.get('image', '')
            thumbnail = result.get('thumbnail', '')
            source = result.get('source', '')
            width = result.get('width', '')
            height = result.get('height', '')

            output.append(f"## {i}. {title}\n")
            if width and height:
                output.append(f"**Dimensions:** {width}x{height}")
            if source:
                output.append(f"**Source:** {source}")
            output.append(f"**Image URL:** {image_url}")
            if thumbnail:
                output.append(f"**Thumbnail:** {thumbnail}")
            output.append("")
        return "\n".join(output)

    else:  # text format
        output = []
        for i, result in enumerate(results, 1):
            title = result.get('title', 'No title')
            image_url = result.get('image', '')
            source = result.get('source', '')
            width = result.get('width', '')
            height = result.get('height', '')

            output.append(f"{i}. {title}")
            if width and height:
                output.append(f"   Dimensions: {width}x{height}")
            if source:
                output.append(f"   Source: {source}")
            output.append(f"   Image URL: {image_url}")
            output.append("")
        return "\n".join(output)


def format_video_results(results: List[Dict[str, Any]], format_type: str = "text") -> str:
    """Format video search results."""
    if not results:
        return "No video results found."

    if format_type == "json":
        return json.dumps(results, indent=2, ensure_ascii=False)

    elif format_type == "markdown":
        output = []
        for i, result in enumerate(results, 1):
            title = result.get('title', 'No title')
            url = result.get('content', '')
            description = result.get('description', '')
            publisher = result.get('publisher', '')
            duration = result.get('duration', '')
            published = result.get('published', '')

            output.append(f"## {i}. {title}\n")
            if publisher:
                output.append(f"**Publisher:** {publisher}")
            if duration:
                output.append(f"**Duration:** {duration}")
            if published:
                output.append(f"**Published:** {published}")
            output.append(f"**URL:** {url}\n")
            if description:
                output.append(f"{description}\n")
            output.append("")
        return "\n".join(output)

    else:  # text format
        output = []
        for i, result in enumerate(results, 1):
            title = result.get('title', 'No title')
            url = result.get('content', '')
            description = result.get('description', '')
            publisher = result.get('publisher', '')
            duration = result.get('duration', '')

            output.append(f"{i}. {title}")
            if publisher and duration:
                output.append(f"   {publisher} - {duration}")
            elif publisher:
                output.append(f"   {publisher}")
            output.append(f"   URL: {url}")
            if description:
                output.append(f"   {description}")
            output.append("")
        return "\n".join(output)


def main():
    if not SKILLBOSS_API_KEY:
        print("Error: SKILLBOSS_API_KEY environment variable is not set.", file=sys.stderr)
        print("Export your key with: export SKILLBOSS_API_KEY=your_key", file=sys.stderr)
        sys.exit(1)

    parser = argparse.ArgumentParser(
        description="Search the web using SkillBoss API Hub",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Basic web search
  %(prog)s "python tutorials"

  # Search with more results
  %(prog)s "machine learning" --max-results 20

  # News search
  %(prog)s "climate change" --type news --time-range w

  # Image search
  %(prog)s "sunset photos" --type images --max-results 15

  # Save results to file
  %(prog)s "artificial intelligence" --output results.txt

  # JSON output format
  %(prog)s "quantum computing" --format json --output results.json

  # Region-specific search
  %(prog)s "local news" --region us-en --type news

Time range filters (--time-range):
  d = past day
  w = past week
  m = past month
  y = past year
        """
    )

    parser.add_argument(
        'query',
        help='Search query'
    )

    # Search options
    search_group = parser.add_argument_group('search options')
    search_group.add_argument(
        '-t', '--type',
        choices=['web', 'news', 'images', 'videos'],
        default='web',
        help='Search type (default: web)'
    )
    search_group.add_argument(
        '-n', '--max-results',
        type=int,
        default=10,
        help='Maximum number of results (default: 10)'
    )
    search_group.add_argument(
        '--time-range',
        choices=['d', 'w', 'm', 'y'],
        help='Time range filter (d=day, w=week, m=month, y=year)'
    )
    search_group.add_argument(
        '-r', '--region',
        default='wt-wt',
        help='Region code (e.g., us-en, uk-en, wt-wt for worldwide, default: wt-wt)'
    )
    search_group.add_argument(
        '--safe-search',
        choices=['on', 'moderate', 'off'],
        default='moderate',
        help='Safe search setting (default: moderate)'
    )

    # Image-specific options
    image_group = parser.add_argument_group('image search options')
    image_group.add_argument(
        '--image-size',
        choices=['Small', 'Medium', 'Large', 'Wallpaper'],
        help='Image size filter'
    )
    image_group.add_argument(
        '--image-color',
        choices=['color', 'Monochrome', 'Red', 'Orange', 'Yellow', 'Green',
                 'Blue', 'Purple', 'Pink', 'Brown', 'Black', 'Gray', 'Teal', 'White'],
        help='Image color filter'
    )
    image_group.add_argument(
        '--image-type',
        choices=['photo', 'clipart', 'gif', 'transparent', 'line'],
        help='Image type filter'
    )
    image_group.add_argument(
        '--image-layout',
        choices=['Square', 'Tall', 'Wide'],
        help='Image layout filter'
    )

    # Video-specific options
    video_group = parser.add_argument_group('video search options')
    video_group.add_argument(
        '--video-duration',
        choices=['short', 'medium', 'long'],
        help='Video duration filter'
    )
    video_group.add_argument(
        '--video-resolution',
        choices=['high', 'standard'],
        help='Video resolution filter'
    )

    # Output options
    output_group = parser.add_argument_group('output options')
    output_group.add_argument(
        '-f', '--format',
        choices=['text', 'markdown', 'json'],
        default='text',
        help='Output format (default: text)'
    )
    output_group.add_argument(
        '-o', '--output',
        help='Output file path (prints to stdout if not specified)'
    )

    args = parser.parse_args()

    # Initialize search client
    searcher = WebSearch(
        region=args.region,
        safe_search=args.safe_search,
    )

    # Perform search based on type
    print(f"Searching for: {args.query}", file=sys.stderr)
    print(f"Type: {args.type}, Max results: {args.max_results}", file=sys.stderr)
    if args.time_range:
        time_labels = {'d': 'past day', 'w': 'past week', 'm': 'past month', 'y': 'past year'}
        print(f"Time range: {time_labels[args.time_range]}", file=sys.stderr)
    print("", file=sys.stderr)

    results = []
    formatter = format_text_results

    if args.type == 'web':
        results = searcher.search_text(
            query=args.query,
            max_results=args.max_results,
            time_range=args.time_range,
        )
        formatter = format_text_results

    elif args.type == 'news':
        results = searcher.search_news(
            query=args.query,
            max_results=args.max_results,
            time_range=args.time_range,
        )
        formatter = format_news_results

    elif args.type == 'images':
        results = searcher.search_images(
            query=args.query,
            max_results=args.max_results,
            size=args.image_size,
            color=args.image_color,
            type_image=args.image_type,
            layout=args.image_layout,
        )
        formatter = format_image_results

    elif args.type == 'videos':
        results = searcher.search_videos(
            query=args.query,
            max_results=args.max_results,
            duration=args.video_duration,
            resolution=args.video_resolution,
        )
        formatter = format_video_results

    # Format results
    output = formatter(results, args.format)

    # Output results
    if args.output:
        output_path = Path(args.output)
        output_path.parent.mkdir(parents=True, exist_ok=True)
        output_path.write_text(output, encoding='utf-8')
        print(f"Results saved to {args.output}", file=sys.stderr)
        print(f"  Found {len(results)} result(s)", file=sys.stderr)
    else:
        print(output)
        print(f"\nFound {len(results)} result(s)", file=sys.stderr)


if __name__ == '__main__':
    main()


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (MEDIUM)