open-agent-skills
We are dedicated to building a set of open agent skills that deliver superior performance, higher determinism, and greater consistency on targeted tasks, while operating at a lower cost and with reduced context usage.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/masslab-sii--open-agent-skills)HTML
<a href="/listings/masslab-sii--open-agent-skills"><img src="/api/listings/masslab-sii--open-agent-skills/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Prerequisites
- Python 3.11+ - [uv](https://github.com/astral-sh/uv) package manager (recommended, for faster installs)
Quick Install
# Clone the repository git clone https://github.com/zjtco-yr/open-agent-skills.git cd open-agent-skills # install with uv (faster) uv pip install -e .
Environment Configuration
Create a `.mcp_env` file with your API credentials:
# Example: OpenAI OPENAI_BASE_URL="https://api.openai.com/v1" OPENAI_API_KEY="sk-..." # Optional: Notion (only for Notion tasks) # SOURCE_NOTION_API_KEY="your-source-notion-api-key" # EVAL_NOTION_API_KEY="your-eval-notion-api-key" # EVAL_PARENT_PAGE_TITLE="MCPMark Eval Hub" # Optional: Playwright (only for Playwright tasks) PLAYWRIGHT_BROWSER="chromium" # chromium | firefox PLAYWRIGHT_HEADLESS="True" # Optional: GitHub (only for GitHub tasks) GITHUB_TOKENS="token1,token2" # token pooling for rate limits GITHUB_EVAL_ORG="your-eval-org"
For more detailed environment configuration, service setup, and authentication instructions, please refer to [MCPMark](https://github.com/mcpmark/mcpmark).
---
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
README.md · README · 327 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <div align="center">
- <img src="assets/logo.png" alt="Open Agent Skills" width="400">
- **Enhancing AI Agent Efficiency Through Domain-Specific Skills**
- 
- </div>
- ---
- > **"Model Context Protocol (MCP) connects Claude to third-party tools, and skills teach Claude how to use them well."**
- > — *[Extending Claude's capabilities with skills and MCP servers](https://claude.com/blog/extending-claude-capabilities-with-skills-mcp-servers)*, Anthropic
- ## 📖 Introduction
- As AI agents evolve, there is a growing need for modular, reusable approaches to equip them with domain-specific expertise while mitigating issues like excessive MCP context consumption. To address this, Anthropic introduced **[Agent Skills](https://agentskills.io/home)** as an open standard on December 18, 2025, allowing agents to dynamically load structured instructions and resources for more effective task execution. Although platforms such as **[OpenAI Codex](https://developers.openai.com/codex/skills/)** have adopted this standard, native support remains limited to specific ecosystems.
- However, many LLM providers have not yet adopted the Agent Skills standard, leaving this efficient approach temporarily inaccessible to a broader audience. We, **the Project Q team at SII**, bridge this gap by providing a lightweight, efficient open-source framework fully compatible with the Agent Skills standard, extending these capabilities to any LLM provider. Our implementation focuses on the synergy between **Model Context Protocol (MCP)** and **Skills**: MCP provides access to external tools and systems, while Skills provide the procedural knowledge to utilize tools (including MCP) effectively. With our skill-based implementation, we achieved up to **~20x context reduction** compared to pure MCP approaches.
- This project builds upon [MCPMark](https://github.com/mcpmark/mcpmark), a comprehensive evaluation suite for assessing the agentic capabilities of frontier models. We extend MCPMark's benchmark capabilities by introducing a **skill-based Implementation**.
- ### Key Features
- - ⚡ **Lightweight Skill Implementation**: Built with a minimal framework approach, making skills implementation easy to read and quick to understand
- - 🔗 **Skill + MCP Integration**: See how skills leverage MCP's external knowledge capabilities and organize multiple MCP services to collaboratively complete tasks
- - 🔌 **Claude Agent Standard Compatible**: Skills can be directly executed in Claude and other compatible agent environments
- - 🔀 **LLM provider Agnostic**: Not limited to Claude or Codex, any LLM can leverage skills to enhance efficiency
- ---
- ## 🛠️ Installation
- ### Prerequisites
- - Python 3.11+
- - [uv](https://github.com/astral-sh/uv) package manager (recommended, for faster installs)
- ### Quick Install
- ```bash
- # Clone the repository
- git clone https://github.com/zjtco-yr/open-agent-skills.git
- cd open-agent-skills
- # install with uv (faster)
- uv pip install -e .
- ```
- ### Environment Configuration
- Create a `.mcp_env` file with your API credentials:
- ```bash
- # Example: OpenAI
- OPENAI_BASE_URL="https://api.openai.com/v1"
- OPENAI_API_KEY="sk-..."
- # Optional: Notion (only for Notion tasks)
- # SOURCE_NOTION_API_KEY="your-source-notion-api-key"
- # EVAL_NOTION_API_KEY="your-eval-notion-api-key"
- # EVAL_PARENT_PAGE_TITLE="MCPMark Eval Hub"
- # Optional: Playwright (only for Playwright tasks)
- PLAYWRIGHT_BROWSER="chromium" # chromium | firefox
- PLAYWRIGHT_HEADLESS="True"
- # Optional: GitHub (only for GitHub tasks)
- GITHUB_TOKENS="token1,token2" # token pooling for rate limits
- GITHUB_EVAL_ORG="your-eval-org"
- ```
- For more detailed environment configuration, service setup, and authentication instructions, please refer to [MCPMark](https://github.com/mcpmark/mcpmark).
- ---
- ## 📊 Performance Results
- We conducted preliminary benchmark evaluations comparing MCP with Open-Agent-Skills **(Skill with MCP)** using the Claude-Sonnet-4.5 model. Results demonstrate that **Skill with MCP** achieves significant advantages in both **task performance** and **token efficiency**.
- ### Overall Pass@1 Accuracy
- <div align="center">
- | Benchmark | MCP | Skills |
- |:----------|:---:|:------:|
- | **GitHub** | 29.35% | **43.48%** |
- | **Filesystem** | 32.5% | **53.3%** |
- | **Playwright WebArena** | 32.14% | **52.38%** |
- </div>
- ### Token Efficiency (Successful Tasks Only)
- <div align="center">
- | Benchmark | MCP Tokens | Skills Tokens | Reduction |
- |:----------|:----------:|:-------------:|:---------:|
- | **GitHub** | 7.36M | 4.47M | **39.25%** |
- | **Filesystem** | 2.27M | 1.55M | **31.55%** |
- | **Playwright WebArena** | 10.25M | 8.27M | **19.30%** |
- </div>
- ### Extreme Cases
- <div align="center">
- | Task | MCP Tokens | Skills Tokens | Reduction |
- |:-----|:----------:|:-------------:|:---------:|
- | `english_talent` (Filesystem) | 1.05M | 0.053M | **95.00%** (~20x) |
- | `find_commit_date` (GitHub) | 1.21M | 0.23M | **80.84%** |
- | `marketing_customer_analysis`<br>(Playwright_webarena) | 1.45M | 0.67M | **54.00%** |
- </div>
- ### Key Insights
- 1. **Significant Accuracy Improvement**: Average Pass@1 accuracy increased by ~**18 percentage points** across all three benchmarks
- 2. **Excellent Token Efficiency**: Token consumption for successful tasks reduced by **20-40%**, with extreme cases reaching **80-95%**
- ---
- ## 🎬 Demo: How Skills Work
- ### Example: budget_europe_travel in reddit
- **Task**: This task involves multiple operations including account registration, creating posts, and setting up forums. For the complete task description, see `tasks/playwright_webarena/standard/reddit/budget_europe_travel`.
- <table style="table-layout: fixed; width: 100%;">
- <tr>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <strong>Sign Up - Skill with MCP</strong>
- </td>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <strong>Sign Up - MCP</strong>
- </td>
- </tr>
- <tr>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <img src="assets/gifs/sign_up_skill.gif" width="100%">
- </td>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <img src="assets/gifs/sign_up_mcp.gif" width="100%">
- </td>
- </tr>
- <tr>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <strong>Create Forum - Skill with MCP</strong>
- </td>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <strong>Create Forum - MCP</strong>
- </td>
- </tr>
- <tr>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <img src="assets/gifs/create_forum_skill.gif" width="100%">
- </td>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <img src="assets/gifs/create_forum_mcp.gif" width="100%">
- </td>
- </tr>
- <tr>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <strong>Create Page - Skill with MCP</strong>
- </td>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <strong>Create Page - MCP</strong>
- </td>
- </tr>
- <tr>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <img src="assets/gifs/create_page_skill.gif" width="100%">
- </td>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <img src="assets/gifs/create_page_mcp.gif" width="100%">
- </td>
- </tr>
- <tr>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <strong>Create Submission - Skill with MCP</strong>
- </td>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <strong>Create Submission - MCP</strong>
- </td>
- </tr>
- <tr>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <img src="assets/gifs/create_submission_skill.gif" width="100%">
- </td>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <img src="assets/gifs/create_submission_mcp.gif" width="100%">
- </td>
- </tr>
- <tr>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <strong>Full Demo - Skill with MCP</strong>
- </td>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <strong>Full Demo - MCP</strong>
- </td>
- </tr>
- <tr>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <video src="https://github.com/user-attachments/assets/15664a10-0cce-4241-9448-cf57ef9eade3" controls muted preload="metadata" width="100%" style="border-radius: 8px;"></video>
- </td>
- <td style="padding: 10px; width: 50%; vertical-align: top;">
- <video src="https://github.com/user-attachments/assets/b7db7bbb-dafd-42e5-8a98-75786d4640cb" controls muted preload="metadata" width="100%" style="border-radius: 8px;"></video>
- </td>
- </tr>
- </table>
- **Result**: Using 4 skills, achieved 2x context reduction.
- ### Running the Demo
- ```bash
- # Start the browser server
- uv run skills/scripts/reddit/browser_server.py &
- # Execute a reddit task with skills
- python -m pipeline \
- --mcp playwright_webarena \
- --models claude-sonnet-4.5 \
- --tasks reddit/budget_europe_travel \
- --exp-name skill-demo \
- --k 1
- ```
- ---
- ## 🚀 Future Plans
- We acknowledge that the current implementation has room for improvement. This project is intended as a **starting point** to demonstrate the potential of combining MCP with domain-specific skills.
- ### Planned Improvements
- 1. **Balancing Specificity and Generalization**: While some of our skills are designed with broad applicability (e.g., Playwright-based skills for registration, posting, forum creation), others remain highly task-specific (e.g., time-based file classification in filesystem skills). We will focus on improving skill design patterns to strike a better balance between task-specific performance and cross-domain generalization.
- 2. **Skill-MCP Integration**: We plan to:
- - Develop better coordination patterns between skills and MCP tools
- - Enable smoother handoffs between skill scripts and MCP operations
- 3. **Extended Domain Coverage**:
- - Advanced database operations and Notion workspace automation
- - Common daily life use cases (productivity, personal automation, etc.)
- ---
- ## 🔒 Security
- Security is a primary consideration in our skill execution framework. It inherits and leverages several security features from [MCPMark](https://github.com/eval-sys/mcpmark/), including:
- - **Directory Isolation**: MCP/Skill file operations are confined to specific directories
- - **Docker Containerization**: Tasks run in isolated containers
- However, we strongly recommend that you **always review skill scripts** before execution in production, whether creating new skills or using existing ones.
- ---
- ## 📚 References & Resources
- ### Open Standards
- - **[Model Context Protocol (MCP)](https://modelcontextprotocol.io/)** - Anthropic's protocol for connecting AI assistants to external tools
- - **[Agent Skills Standard](https://agentskills.io/home)** - A simple, open format for giving agents new capabilities and expertise.
- ### Documentation
- - **[Agent Skills Overview](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview)** - Anthropic's official guide for Claude agent skills
- - **[Skills Docs](https://code.claude.com/docs/en/skills)** - Skills integration in Claude Code
- - **[Skills in Codex](https://developers.openai.com/codex/skills/)** - Give Codex new capabilities with support for explicit and implicit invocation
- ---
- ## ▶️ Quick Start
- After configuring the relevant APIs and Docker environment (if needed), you can run the following commands:
- ### Run a Playwright WebArena Task
- ```bash
- python -m pipeline --mcp playwright_webarena \
- --models claude-sonnet-4.5 \
- --tasks reddit/marketing_customer_analysis \
- --exp-name webarena-test \
- --k 1
- ```
- ### Run a Filesystem Task
- ```bash
- python -m pipeline --mcp filesystem \
- --models claude-sonnet-4.5 \
- --tasks student_database/english_talent \
- --exp-name filesystem-test \
- --k 1
- ```
- ### Run a Github Task
- ```bash
- python -m pipeline --mcp github \
- --models claude-sonnet-4.5 \
- --tasks build_your_own_x/find_commit_date \
- --exp-name github-test \
- --k 1
- ```
- ## 📄 License
- This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
- ---
- <div align="center">
- **Open-Agent-Skills** - Making AI agents more effective through domain expertise skill
- [Report Bug](https://github.com/zjtco-yr/open-agent-skills/issues) · [Request Feature](https://github.com/zjtco-yr/open-agent-skills/issues)
- </div>
portable-skills/github/scripts/file_editor.py · Bundled script · 430 lines · 1 finding marked
- """
- File Editor Script (Using utils.py)
- ===================================
- General purpose file editor for GitHub repositories.
- This script allows for modifying existing files, applying specific fixes,
- or pushing multiple files in a single atomic commit.
- Usage:
- python file_editor.py <command> <owner> <repo> [options]
- Commands:
- edit Edit/Overwrite a file
- apply_fix Apply a search and replace fix to a single file
- batch Push multiple files in a single commit
- Content Input Methods (for edit and batch commands):
- --content Direct content string (may have shell escaping issues with quotes)
- --content-base64 Base64 encoded content (recommended for code with special chars)
- --content-file Read content from a local file
- --stdin Read content from stdin (for piping)
- Examples:
- # Edit/Overwrite a configuration file
- python file_editor.py edit mcpmark-source build-your-own-x --path "src/config.py" --content "DEBUG = False" --message "Disable debug mode"
- # Edit with base64 encoded content (recommended for code)
- python file_editor.py edit owner repo --path "src/app.js" --content-base64 "Y29uc3QgbXNnID0gJ2hlbGxvJzs=" --message "Add app.js"
- # Apply a specific fix (search and replace in a single file)
- python file_editor.py apply_fix mcpmark-source build-your-own-x --path "src/buggy.py" --pattern "if x = y:" --replacement "if x == y:" --message "Fix syntax error"
- # Batch push multiple files in a single commit
- python file_editor.py batch mcpmark-source build-your-own-x --files '[{"path": ".github/workflows/lint.yml", "content": "..."}, {"path": "eslint.config.js", "content": "..."}]' --message "Add linting workflow and config"
- # Batch push with base64 encoded files (recommended)
- python file_editor.py batch owner repo --files-base64 "W3sicGF0aCI6ICJzcmMvYXBwLmpzIiwgImNvbnRlbnQiOiAiY29uc3QgeCA9IDE7In1d" --message "Add files"
- Dismissed after review: Contains a long base64-looking blob — not necessarily malicious, but worth inspecting what it decodes to
- Line 37 on GitHub
- """
- import argparse
- import asyncio
- import sys
- import os
- import traceback
- import base64
- from utils import (
- GitHubTools,
- extract_sha_from_result,
- extract_file_content,
- check_api_success,
- )
- class FileEditor:
- """Editor class for modifying files in GitHub repositories"""
- def __init__(self):
- """Initialize the editor with GitHubTools"""
- self.github = GitHubTools()
- def _check_api_success(self, result: any) -> bool:
- """Check if API result indicates success."""
- return check_api_success(result)
- def _extract_sha(self, result) -> str:
- """Extract SHA from get_file_contents result."""
- return extract_sha_from_result(result)
- async def edit_file(
- self,
- owner: str,
- repo: str,
- path: str,
- content: str,
- message: str,
- branch: str = "main",
- ) -> bool:
- """Edit an existing file or create if it doesn't exist."""
- async with self.github:
- print(f"Fetching current state of {path} in {owner}/{repo} on {branch}...")
- existing_file = await self.github.get_file_contents(
- owner, repo, path, ref=branch
- )
- sha = None
- if isinstance(existing_file, dict) and "sha" in existing_file:
- sha = existing_file["sha"]
- print(f"Found existing file (SHA: {sha}), updating...")
- else:
- print("File not found, creating new file...")
- # Note: For now, we simply overwrite the content.
- # In a more advanced version, we could support 'replace' logic (read -> str replace -> write).
- result = await self.github.create_or_update_file(
- owner=owner,
- repo=repo,
- path=path,
- content=content,
- message=message,
- branch=branch,
- sha=sha,
- )
- # Check for actual success: result should contain GitHub API success indicators
- success = self._check_api_success(result)
- if success:
- print(f"Successfully edited {path}")
- return True
- else:
- print(f"Failed to edit {path}: {result}")
- return False
- def _extract_file_content(self, result) -> str:
- """Extract actual file content from MCP get_file_contents result."""
- return extract_file_content(result) or ""
- async def apply_fix(
- self,
- owner: str,
- repo: str,
- path: str,
- pattern: str,
- replacement: str,
- message: str,
- branch: str = "main",
- ) -> bool:
- """Apply a fix by replacing a specific pattern in a file.
- Args:
- owner: Repository owner
- repo: Repository name
- path: File path in repository
- pattern: Text pattern to find and replace
- replacement: Replacement text
- message: Commit message
- branch: Target branch
- Returns:
- True if fix was applied successfully, False otherwise
- Note:
- This method does NOT assume a fix was already applied just because
- the replacement text exists. It requires the exact pattern to be present.
- """
- async with self.github:
- print(f"Fetching current state of {path} in {owner}/{repo} on {branch}...")
- existing_file = await self.github.get_file_contents(
- owner, repo, path, ref=branch
- )
- if not existing_file:
- print(f"Error: Could not fetch file {path}")
- return False
- # Extract file content properly from MCP result
- file_content = self._extract_file_content(existing_file)
- sha = self._extract_sha(existing_file)
- if not file_content:
- print(f"Error: Could not extract content from {path}")
- return False
- if pattern not in file_content:
- # Pattern not found - check if this might be an idempotent case
- # Only consider it "already applied" if:
- # 1. The replacement text exists in the file
- # 2. The pattern and replacement are different (not a no-op)
- # 3. The replacement appears in a context that suggests it replaced the pattern
- # (e.g., similar line structure)
- if replacement in file_content and pattern != replacement:
- # More careful check: see if the replacement is on a line by itself
- # or in a similar context where the pattern would have been
- pattern_lines = pattern.strip().split('\n')
- replacement_lines = replacement.strip().split('\n')
- # If both are single-line and replacement exists, it's likely already applied
- if len(pattern_lines) == 1 and len(replacement_lines) == 1:
- print(f"Pattern not found, but replacement text exists in file.")
- print(f"Note: Cannot confirm if fix was previously applied or if pattern never existed.")
- print(f"Returning success (idempotent behavior).")
- return True
- # For multi-line patterns, be more conservative
- print(f"Pattern not found in file.")
- print(f"Replacement text exists but cannot confirm prior application.")
- print(f"Pattern '{pattern[:100]}{'...' if len(pattern) > 100 else ''}' not found in file.")
- print(f"File content preview (first 500 chars):")
- print(file_content[:500])
- return False
- new_content = file_content.replace(pattern, replacement)
- # Verify the replacement actually changed something
- if new_content == file_content:
- print(f"Warning: Replacement did not change file content")
- return False
- result = await self.github.create_or_update_file(
- owner=owner,
- repo=repo,
- path=path,
- content=new_content,
- message=message,
- branch=branch,
- sha=sha,
- )
- # Check for actual success
- success = self._check_api_success(result)
- if success:
- print(f"Successfully applied fix to {path}")
- return True
- else:
- print(f"Failed to apply fix: {result}")
- return False
- async def batch_push(
- self,
- owner: str,
- repo: str,
- files: list,
- message: str,
- branch: str = "main",
- ) -> bool:
- """
- Push multiple files to a repository in a single commit.
- This is useful when you need to create/update multiple files atomically,
- ensuring all changes are in one commit (e.g., adding workflow + config files).
- Args:
- owner: Repository owner
- repo: Repository name
- files: List of file dicts with 'path' and 'content' keys
- message: Commit message
- branch: Target branch (default: main)
- Returns:
- True if successful, False otherwise
- Example:
- files = [
- {"path": ".github/workflows/lint.yml", "content": "name: Lint..."},
- {"path": "eslint.config.js", "content": "module.exports = {...}"}
- ]
- await editor.batch_push(owner, repo, files, "Add linting", "main")
- """
- async with self.github:
- print(f"Pushing {len(files)} files to {owner}/{repo} on {branch} in a single commit...")
- # Validate files format
- for i, f in enumerate(files):
- if not isinstance(f, dict) or 'path' not in f or 'content' not in f:
- print(f"Error: File at index {i} must have 'path' and 'content' keys")
- return False
- result = await self.github.push_files(
- owner=owner,
- repo=repo,
- branch=branch,
- files=files,
- message=message,
- )
- # Check for success
- success = self._check_api_success(result)
- if success:
- print(f"Successfully pushed {len(files)} files in a single commit")
- for f in files:
- print(f" - {f['path']}")
- return True
- else:
- print(f"Failed to push files: {result}")
- return False
- async def main():
- """Main entry point"""
- parser = argparse.ArgumentParser(
- description="Edit files in GitHub repository.",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
- Examples:
- # Edit/Overwrite a file
- python file_editor.py edit owner repo --path "src/config.py" --content "data" --message "upd"
- # Apply a fix
- python file_editor.py apply_fix owner repo --path "src/bug.py" --pattern "bad" --replacement "good" --message "fix"
- """
- )
- subparsers = parser.add_subparsers(dest="command", help="Command to execute")
- # Command: edit
- edit_parser = subparsers.add_parser("edit", help="Edit/Overwrite a file")
- edit_parser.add_argument("owner", help="Repository owner")
- edit_parser.add_argument("repo", help="Repository name")
- edit_parser.add_argument("--path", required=True, help="Path to the file")
- # Content input options (mutually exclusive)
- content_group = edit_parser.add_mutually_exclusive_group(required=True)
- content_group.add_argument("--content", help="New content of the file (direct string)")
- content_group.add_argument("--content-base64", help="Base64 encoded content (recommended for code)")
- content_group.add_argument("--content-file", help="Read content from local file")
- content_group.add_argument("--stdin", action="store_true", help="Read content from stdin")
- edit_parser.add_argument("--message", required=True, help="Commit message")
- edit_parser.add_argument("--branch", default="main", help="Target branch")
- # Command: apply_fix
- fix_parser = subparsers.add_parser("apply_fix", help="Apply a search and replace fix")
- fix_parser.add_argument("owner", help="Repository owner")
- fix_parser.add_argument("repo", help="Repository name")
- fix_parser.add_argument("--path", required=True, help="Path to the file")
- fix_parser.add_argument("--pattern", required=True, help="Text pattern to find")
- fix_parser.add_argument("--replacement", required=True, help="Replacement text")
- fix_parser.add_argument("--message", required=True, help="Commit message")
- fix_parser.add_argument("--branch", default="main", help="Target branch")
- # Command: batch
- batch_parser = subparsers.add_parser("batch", help="Push multiple files in a single commit")
- batch_parser.add_argument("owner", help="Repository owner")
- batch_parser.add_argument("repo", help="Repository name")
- # Files input options (mutually exclusive)
- files_group = batch_parser.add_mutually_exclusive_group(required=True)
- files_group.add_argument("--files", help='JSON array of files: [{"path": "...", "content": "..."}]')
- files_group.add_argument("--files-base64", help="Base64 encoded JSON array of files (recommended)")
- files_group.add_argument("--files-file", help="Read files JSON from local file")
- batch_parser.add_argument("--message", required=True, help="Commit message")
- batch_parser.add_argument("--branch", default="main", help="Target branch")
- args = parser.parse_args()
- editor = FileEditor()
- try:
- if args.command == "edit":
- # Resolve content from various input methods
- content = None
- if args.content:
- content = args.content
- elif args.content_base64:
- try:
- content = base64.b64decode(args.content_base64).decode('utf-8')
- except Exception as e:
- print(f"Error: Failed to decode base64 content: {e}")
- sys.exit(1)
- elif args.content_file:
- try:
- with open(args.content_file, 'r', encoding='utf-8') as f:
- content = f.read()
- except Exception as e:
- print(f"Error: Failed to read content file: {e}")
- sys.exit(1)
- elif args.stdin:
- content = sys.stdin.read()
- if content is None:
- print("Error: No content provided")
- sys.exit(1)
- success = await editor.edit_file(
- args.owner, args.repo, args.path, content, args.message, args.branch
- )
- if not success: sys.exit(1)
- elif args.command == "apply_fix":
- success = await editor.apply_fix(
- args.owner, args.repo, args.path, args.pattern, args.replacement, args.message, args.branch
- )
- if not success: sys.exit(1)
- elif args.command == "batch":
- import json
- files_json = None
- # Resolve files from various input methods
- if args.files:
- files_json = args.files
- elif args.files_base64:
- try:
- files_json = base64.b64decode(args.files_base64).decode('utf-8')
- except Exception as e:
- print(f"Error: Failed to decode base64 files: {e}")
- sys.exit(1)
- elif args.files_file:
- try:
- with open(args.files_file, 'r', encoding='utf-8') as f:
- files_json = f.read()
- except Exception as e:
- print(f"Error: Failed to read files file: {e}")
- sys.exit(1)
- if files_json is None:
- print("Error: No files provided")
- sys.exit(1)
- try:
- files = json.loads(files_json)
- if not isinstance(files, list):
- print("Error: files must be a JSON array")
- sys.exit(1)
- except json.JSONDecodeError as e:
- print(f"Error: Invalid JSON in files: {e}")
- sys.exit(1)
- success = await editor.batch_push(
- args.owner, args.repo, files, args.message, args.branch
- )
- if not success: sys.exit(1)
- else:
- parser.print_help()
- sys.exit(1)
- except Exception as e:
- print(f"\nError during execution: {e}")
- import traceback
- traceback.print_exc()
- sys.exit(1)
- if __name__ == "__main__":
- asyncio.run(main())
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.