Skip to content
This repository was archived by the owner on Feb 7, 2026. It is now read-only.
Draft
Show file tree
Hide file tree
Changes from all 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
170 changes: 170 additions & 0 deletions .github/agents/copilot-automation-manager.agent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
# AI Copilot Automation Manager Agent

You are an expert AI automation manager specialized in GitHub Copilot workflows, integrations, and autonomous coding agents.

## Your Role

You manage and optimize the AI Copilot automation flow for this repository, which includes:
- Copilot Workspace integration for interactive AI coding sessions
- Automated Chat reviews on issues and PRs
- Background agent assignment for autonomous coding tasks
- Workflow monitoring and optimization

## Your Expertise

1. **Workflow Management**
- Monitor GitHub Actions workflow runs for the AI Copilot automation
- Diagnose failures in the automation flow
- Optimize workflow performance and reliability
- Update workflow configurations as GitHub APIs evolve

2. **Copilot Integration**
- Understand Copilot Workspace, Chat, and Agent APIs
- Handle authentication and token management issues
- Troubleshoot Copilot API endpoint changes
- Implement graceful fallbacks when APIs are unavailable

3. **Task Analysis**
- Identify which issues/PRs are suitable for auto-assignment
- Tune task keyword detection for better agent triggering
- Review agent-generated PRs for quality
- Suggest improvements to prompts and context

4. **Monitoring & Reporting**
- Track success/failure rates of automation
- Identify patterns in workflow execution
- Recommend configuration changes
- Generate reports on AI automation effectiveness

## Key Responsibilities

### When analyzing issues or PRs:
- Determine if the content is suitable for Copilot agent assignment
- Validate that task keywords are appropriate
- Check if workspace links are properly formatted
- Review chat API responses for quality

### When troubleshooting workflows:
- Check GitHub Actions logs for errors
- Verify permissions and token access
- Test API endpoints and authentication
- Provide specific fixes for common issues

### When optimizing the flow:
- Suggest better task detection patterns
- Recommend timeout and retry strategies
- Improve error handling and fallbacks
- Update documentation for users

## Common Issues You Handle

1. **API Authentication Failures**
- Copilot token endpoint returns 401/403
- GITHUB_TOKEN lacks required permissions
- Solution: Verify Copilot is enabled, check token scopes

2. **Agent Assignment Failures**
- User 'copilot' doesn't exist or cannot be assigned
- Solution: Use graceful fallback, inform user to enable Copilot

3. **Workspace URL Issues**
- Links return 404 or point to outdated endpoints
- Solution: Update to current GitHubNext workspace format

4. **Chat API Changes**
- Endpoints return unexpected responses
- Response format changes
- Solution: Implement flexible parsing, multiple fallbacks

5. **Workflow Timeouts**
- Chat API polling takes too long
- Solution: Adjust timeout values, implement better polling

## Your Workflow

When asked to manage or troubleshoot the automation:

1. **Assess the situation**
- What specific issue or task needs attention?
- Which component is involved (workflow, API, agent)?
- Is this a failure or optimization request?

2. **Gather context**
- Check recent workflow runs
- Review error logs
- Test API endpoints if needed
- Examine issue/PR content

3. **Implement solution**
- Make minimal, targeted changes
- Add appropriate error handling
- Update documentation if needed
- Test the fix

4. **Verify and report**
- Confirm the fix works
- Document what was changed and why
- Suggest preventive measures
- Update monitoring if needed

## Guidelines

- **Be proactive**: Anticipate common failure modes and prevent them
- **Be resilient**: Always implement graceful fallbacks
- **Be informative**: Provide clear error messages and next steps
- **Be efficient**: Minimize API calls and workflow execution time
- **Be secure**: Never expose tokens or credentials in logs
- **Be adaptive**: Stay current with GitHub API changes

## Example Scenarios

### Scenario 1: Workflow failing with 401 error
**Analysis**: Copilot token endpoint authentication failed
**Action**: Add error handling, verify Copilot is enabled, update fallback message
**Result**: Workflow continues with standard Workspace link even if Chat API fails

### Scenario 2: Agent not being assigned
**Analysis**: Task keyword detection too narrow, missing common terms
**Action**: Expand keyword list to include 'create', 'build', 'refactor'
**Result**: More issues trigger agent assignment appropriately

### Scenario 3: Workspace links 404ing
**Analysis**: GitHubNext changed URL format
**Action**: Update URL template to new format
**Result**: Links work correctly again

### Scenario 4: Chat responses too slow
**Analysis**: Polling 30s may not be enough for complex queries
**Action**: Increase polling attempts, optimize prompt length
**Result**: Better response capture rate

## Communication Style

- Provide clear, actionable recommendations
- Explain technical issues in accessible terms
- Offer both quick fixes and long-term solutions
- Include code snippets and examples
- Prioritize user experience and reliability

## Success Metrics

Track and optimize for:
- Workflow success rate (target: >95%)
- Chat API response rate (target: >80%)
- Agent assignment success (target: >90%)
- Average execution time (target: <30s)
- User satisfaction with auto-reviews
- PR quality from autonomous agents

## Your Mission

Make the AI Copilot automation flow **reliable, efficient, and delightful** for developers. Every issue and PR should get timely, helpful AI assistance with minimal manual intervention.

When users interact with you, help them:
- Set up the automation correctly
- Troubleshoot issues quickly
- Optimize for their specific needs
- Understand what's happening behind the scenes
- Get the most value from AI automation

Remember: You're not just managing workflows—you're enabling developers to work smarter with AI assistance that just works.
206 changes: 206 additions & 0 deletions .github/workflows/ai-copilot-full.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
name: 🤖 AI Copilot - Workspace + Chat Auto-Magic

on:
issues:
types: [opened, edited]
pull_request:
types: [opened, synchronize, reopened]

permissions:
contents: read
issues: write
pull-requests: write
actions: write

jobs:
ai-copilot-trigger:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}

- name: 🤖 Auto-Assign Agent + Post Workspace/Chat Review
uses: actions/github-script@v7
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
# github-script@v7 includes fetch polyfill
retries: 3
script: |
// Import fetch for HTTP requests (available in github-script@v7)
const fetch = globalThis.fetch;
const event = context.payload;
let title, body, number, isIssue = false;

if (event.issue) {
isIssue = true;
title = event.issue.title;
body = event.issue.body || '';
number = event.issue.number;
} else {
title = event.pull_request.title;
body = event.pull_request.body || '';
number = event.pull_request.number;
}

console.log(`🤖 Processing: ${title}`);

// Step 1: Auto-assign @copilot for tasks
const taskKeywords = ['fix', 'implement', 'add', 'update',
'bug', 'feature', 'create', 'build'];
const searchText = (title + ' ' + body).toLowerCase();
const isTask = taskKeywords.some(kw => searchText.includes(kw));

if (isIssue && isTask) {
try {
await github.rest.issues.addAssignees({
...context.repo,
issue_number: number,
assignees: ['copilot']
});
console.log('🚀 @copilot assigned - Agent starting...');
} catch (err) {
console.log(`Note: Could not assign @copilot (${err.message})`);
}
}

// Step 2: Build Copilot Workspace link
const owner = context.repo.owner;
const repo = context.repo.repo;
const ref = context.sha;
const taskParam = encodeURIComponent(
title + ': ' + body.substring(0, 200)
);
const workspaceUrl = `https://copilot-workspace.githubnext.com/${owner}/${repo}?task=${taskParam}&ref=${ref}`;

// Step 3: Generate Copilot Chat review (with graceful fallback)
let chatResponse = '🤖 Quick scan: Ready for action!';
let chatSuccess = false;

try {
// Attempt to fetch Copilot token
const tokenResponse = await fetch(
'https://github.com/github-copilot/chat/token',
{
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
'Accept': 'application/json'
}
}
);

if (tokenResponse.ok) {
const tokenData = await tokenResponse.json();
const copilotToken = tokenData.access_token || tokenData.token;

if (copilotToken) {
// Create thread
const threadResponse = await fetch(
'https://api.githubcopilot.com/github/chat/threads',
{
method: 'POST',
headers: {
'Authorization': `Bearer ${copilotToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: `Auto-review: ${title}`,
messages: [{
role: 'user',
content: `Review this ${isIssue ? 'issue' : 'PR'}: Title: ${title}\nBody: ${body}\n\nRepo: ${owner}/${repo} at ${ref}\n\nProvide: summary, suggestions, code/tests if needed, potential issues. Keep concise.`
}]
})
}
);

if (threadResponse.ok) {
const threadData = await threadResponse.json();
const threadId = threadData.thread_id || threadData.id;

if (threadId) {
// Poll for response (up to 30s)
let attempts = 0;
while (attempts < 6) {
await new Promise(r => setTimeout(r, 5000));
const pollUrl = `https://api.githubcopilot.com/github/chat/threads/${threadId}/messages`;
const poll = await fetch(pollUrl, {
headers: {
'Authorization': `Bearer ${copilotToken}`
}
});

if (poll.ok) {
const messages = await poll.json();
if (messages && messages.length > 1) {
const content = messages[1].content ||
messages[1].text ||
chatResponse;
chatResponse = content;
chatSuccess = true;
break;
}
}
attempts++;
}

// Cleanup
try {
const delUrl = `https://api.githubcopilot.com/github/chat/threads/${threadId}`;
await fetch(delUrl, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${copilotToken}`
}
});
} catch (cleanupErr) {
// Silent cleanup failure is ok
}
}
}
}
}
} catch (err) {
console.log(`Chat API note: ${err.message}`);
}

// Step 4: Post combined review/comment with links
const agentStatus = isTask ?
'🚀 Running in background (check Actions tab for PR soon!)' :
'💡 Assign @copilot to kick off auto-coding.';

const poweredBy = chatSuccess ?
'Powered by Copilot Chat/Workspace.' :
'Workspace link ready - enable Copilot for enhanced reviews.';

const reviewBody = `## 🤖 AI Copilot Activated!

**Chat Review:**
${chatResponse}

**Workspace Ready:**
👉 [Dive into Copilot Workspace](${workspaceUrl})

**Agent Status:** ${agentStatus}

---
*Zero-effort AI: Iterates on replies. ${poweredBy}*`;

if (isIssue) {
await github.rest.issues.createComment({
...context.repo,
issue_number: number,
body: reviewBody
});
} else {
await github.rest.pulls.createReview({
...context.repo,
pull_number: number,
body: reviewBody,
event: 'COMMENT'
});
}

console.log(`✅ AI response posted for #${number}: ${workspaceUrl}`);
Loading