Skip to content
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 134 additions & 0 deletions GITHUB_COPILOT_INTEGRATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# GitHub Copilot Integration
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know if I like adding random markdown files to the Root of the repo. Delete this file

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Deleted the GITHUB_COPILOT_INTEGRATION.md file in commit 6bac6af.


This document describes the GitHub Copilot integration added to TreeAgent.

## Features

### GitHub Copilot Model Accessor

A new model accessor `github_copilot` has been added that interfaces with GitHub Copilot via the `gh copilot` CLI command. This accessor:

- Uses the GitHub CLI (`gh`) to interact with GitHub Copilot
- Automatically includes GitHub issue tracking tools
- Supports tool usage for enhanced functionality

### GitHub Tools

New tools have been added for GitHub issue tracking:

- `get_github_issue` - Get details of a specific issue
- `create_github_issue` - Create a new issue
- `update_github_issue` - Update an existing issue
- `comment_github_issue` - Add comments to issues
- `list_github_issues` - List issues in a repository
- `close_github_issue` - Close an issue

### Command Line Interface

A new CLI command `gh-copilot-agent-task` provides GitHub Copilot style interface:

#### Create a new task
```bash
gh-copilot-agent-task create "Create a basic Flask app with one GET /hello endpoint returning JSON {'message': 'Hello'}" --repo owner/repo --follow
```

#### Follow an existing task
```bash
gh-copilot-agent-task follow 123 --repo owner/repo
```

#### List tasks
```bash
gh-copilot-agent-task list --repo owner/repo --state open --limit 10
```

## Prerequisites

1. **GitHub CLI**: Install and authenticate with GitHub CLI
```bash
# Install gh CLI (see https://github.com/cli/cli#installation)
gh auth login
```

2. **GitHub Copilot**: Ensure you have GitHub Copilot access and the CLI extension installed
```bash
gh extension install github/gh-copilot
```

## Usage Examples

### Using GitHub Copilot accessor programmatically

```python
from src.orchestrator import AgentOrchestrator
from src.dataModel.model import AccessorType

orchestrator = AgentOrchestrator(default_accessor_type=AccessorType.GITHUB_COPILOT)
project = orchestrator.implement_project("Create a REST API server")
```

### Using the CLI with GitHub integration

```bash
# Create a task and track it in a GitHub issue
gh-copilot-agent-task create "Build a React todo app" --repo myorg/myrepo --follow

# Follow up on an existing task
gh-copilot-agent-task follow 42 --repo myorg/myrepo

# List all open tasks
gh-copilot-agent-task list --repo myorg/myrepo --state open
```

### Using GitHub tools directly

```python
from src.tools.github_tools import create_issue, comment_on_issue

# Create an issue
result = create_issue("owner/repo", "New Feature Request", "Description of the feature")

# Add a comment
comment_on_issue("owner/repo", 123, "Implementation completed!")
```

## Architecture

The GitHub Copilot integration consists of:

1. **GitHubCopilotAccessor** (`src/modelAccessors/github_copilot_accessor.py`)
- Interfaces with `gh copilot` CLI
- Automatically includes GitHub tools
- Handles JSON response parsing

2. **GitHub Tools** (`src/tools/github_tools.py`)
- Complete issue management functionality
- Uses `gh` CLI for all operations
- Provides both functions and tool definitions

3. **Copilot CLI** (`src/cli/copilot_cli.py`)
- GitHub Copilot style command interface
- Integrates with GitHub issues for task tracking
- Supports follow-up workflows

## Error Handling

The integration includes robust error handling:

- Checks for `gh` CLI availability
- Validates GitHub authentication
- Provides clear error messages
- Graceful fallbacks for optional GitHub features

## Testing

Comprehensive tests are included:

- `tests/modelAccessors/test_github_copilot_accessor.py` - Accessor tests
- `tests/tools/test_github_tools.py` - GitHub tools tests
- `tests/cli/test_copilot_cli.py` - CLI tests

Run tests with:
```bash
pytest tests/ -v
```
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,23 @@ processing the remaining tasks.
5. Metrics & logging – capture token counts, wall-clock time, and per-node error traces.

6. Extensible UI – optional graph-viz or web dashboard to visualise task trees.

---

## GitHub Copilot Integration

TreeAgent now includes GitHub Copilot integration for enhanced AI-assisted development:

- **GitHub Copilot Accessor**: Use GitHub Copilot as a model accessor via `gh copilot` CLI
- **GitHub Issue Tools**: Complete issue management (create, update, comment, track)
- **Copilot-style CLI**: GitHub Copilot inspired command interface

```bash
# Create and track a task in GitHub
gh-copilot-agent-task create "Build a REST API" --repo owner/repo --follow

# Follow existing tasks
gh-copilot-agent-task follow 123 --repo owner/repo
```

See [GITHUB_COPILOT_INTEGRATION.md](GITHUB_COPILOT_INTEGRATION.md) for detailed usage instructions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ dev = [
[project.scripts]
treeagent = "src.cli:main"
treeagent-swebench = "src.cli.bench.swebench_cli:main"
gh-copilot-agent-task = "src.cli.copilot_cli:main"

[tool.hatch.build.targets.wheel]
packages = ["src"]
Expand Down
212 changes: 212 additions & 0 deletions src/cli/copilot_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
"""GitHub Copilot style CLI interface for TreeAgent."""

from __future__ import annotations

import argparse
import sys
from typing import Optional

from ..orchestrator import AgentOrchestrator
from ..dataModel.model import AccessorType
from ..tools.github_tools import create_issue, get_issue, comment_on_issue, list_issues


def parse_copilot_args() -> argparse.Namespace:
"""Parse gh copilot agent-task style arguments."""
parser = argparse.ArgumentParser(
prog="gh copilot agent-task",
description="GitHub Copilot style interface for TreeAgent tasks",
)

subparsers = parser.add_subparsers(dest="command", help="Available commands")

# create subcommand
create_parser = subparsers.add_parser("create", help="Create a new agent task")
create_parser.add_argument(
"prompt",
help="Description of the task to create",
)
create_parser.add_argument(
"--follow",
action="store_true",
help="Follow the task progress",
)
create_parser.add_argument(
"--model-type",
choices=[t.value for t in AccessorType],
default="github_copilot",
help="Model accessor to use for the task",
)
create_parser.add_argument(
"--repo",
help="GitHub repository to create issue in (format: owner/repo)",
)
create_parser.add_argument(
"--checkpoint-dir",
default="checkpoints",
help="Directory to store project checkpoints",
)

# follow subcommand for existing tasks
follow_parser = subparsers.add_parser("follow", help="Follow an existing task")
follow_parser.add_argument(
"task_id",
help="Task/Issue ID to follow",
)
follow_parser.add_argument(
"--repo",
help="GitHub repository (format: owner/repo)",
)

# list subcommand
list_parser = subparsers.add_parser("list", help="List agent tasks")
list_parser.add_argument(
"--repo",
help="GitHub repository to list issues from (format: owner/repo)",
)
list_parser.add_argument(
"--state",
choices=["open", "closed", "all"],
default="open",
help="Filter by issue state",
)
list_parser.add_argument(
"--limit",
type=int,
default=10,
help="Maximum number of tasks to list",
)

return parser.parse_args()


def create_agent_task(prompt: str, model_type: str, repo: Optional[str] = None,
checkpoint_dir: str = "checkpoints", follow: bool = False) -> None:
"""Create a new agent task."""
print(f"Creating agent task: {prompt}")

# Create GitHub issue if repo is provided
issue_url = None
issue_number = None
if repo:
try:
result = create_issue(repo, f"Agent Task: {prompt[:50]}...", prompt)
issue_url = result.get("url")
# Extract issue number from URL
if issue_url:
issue_number = issue_url.split("/")[-1]
print(f"Created GitHub issue: {issue_url}")
except Exception as e:
print(f"Warning: Could not create GitHub issue: {e}")

# Set up orchestrator
accessor_type = AccessorType(model_type)
orchestrator = AgentOrchestrator(default_accessor_type=accessor_type)

# Run the task
try:
project = orchestrator.implement_project(prompt, checkpoint_dir=checkpoint_dir)

# Update GitHub issue with results
if repo and issue_number:
try:
summary = f"""Task completed!

**Project Summary:**
- Completed Tasks: {len(project.completedTasks)}
- In Progress Tasks: {len(project.inProgressTasks)}
- Failed Tasks: {len(project.failedTasks)}
- Queued Tasks: {len(project.queuedTasks)}

Latest response type: {project.latestResponse.type if project.latestResponse else "None"}
"""
comment_on_issue(repo, int(issue_number), summary)
print(f"Updated GitHub issue with results: {issue_url}")
except Exception as e:
print(f"Warning: Could not update GitHub issue: {e}")

# Print summary
print("\nProject Summary:")
print(f"Completed Tasks: {len(project.completedTasks)}")
print(f"In Progress Tasks: {len(project.inProgressTasks)}")
print(f"Failed Tasks: {len(project.failedTasks)}")
print(f"Queued Tasks: {len(project.queuedTasks)}")

if follow and repo and issue_number:
follow_task(issue_number, repo)

except Exception as e:
print(f"Error executing task: {e}")
if repo and issue_number:
try:
comment_on_issue(repo, int(issue_number), f"Task failed with error: {e}")
except Exception:
pass # Ignore secondary errors
sys.exit(1)


def follow_task(task_id: str, repo: Optional[str] = None) -> None:
"""Follow an existing task."""
if not repo:
print("Error: --repo is required for following tasks")
sys.exit(1)

try:
issue = get_issue(repo, int(task_id))
print(f"Task {task_id}: {issue['title']}")
print(f"State: {issue['state']}")
print(f"Author: {issue['author']['login']}")
if issue.get('labels'):
labels = [label['name'] for label in issue['labels']]
print(f"Labels: {', '.join(labels)}")
print(f"\nDescription:\n{issue['body']}")
except Exception as e:
print(f"Error following task {task_id}: {e}")
sys.exit(1)


def list_tasks(repo: Optional[str] = None, state: str = "open", limit: int = 10) -> None:
"""List agent tasks."""
if not repo:
print("Error: --repo is required for listing tasks")
sys.exit(1)

try:
issues = list_issues(repo, state, limit)
print(f"Tasks in {repo} (state: {state}):")
for issue in issues:
labels = [label['name'] for label in issue.get('labels', [])]
label_str = f" [{', '.join(labels)}]" if labels else ""
print(f"#{issue['number']}: {issue['title']} ({issue['state']}){label_str}")
except Exception as e:
print(f"Error listing tasks: {e}")
sys.exit(1)


def main() -> None:
"""Entry point for the GitHub Copilot style CLI."""
args = parse_copilot_args()

if not args.command:
print("Error: No command specified. Use --help for usage information.")
sys.exit(1)

if args.command == "create":
create_agent_task(
args.prompt,
args.model_type,
args.repo,
args.checkpoint_dir,
args.follow
)
elif args.command == "follow":
follow_task(args.task_id, args.repo)
elif args.command == "list":
list_tasks(args.repo, args.state, args.limit)
else:
print(f"Error: Unknown command '{args.command}'")
sys.exit(1)


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions src/dataModel/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
class AccessorType(str, Enum):
OPENAI = "openai"
ANTHROPIC = "anthropic"
GITHUB_COPILOT = "github_copilot"
MOCK = "mock"

class Model(BaseModel):
Expand Down
Loading