Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

v0.3.0 — GitHub Companion: co-authored commits, PRs, issues, GitHub API tools

Salman Qureshi65a402f628f9
diff --git a/.env.example b/.env.example
index 33a060ee..415648a2 100644
--- a/.env.example
+++ b/.env.example
@@ -37,4 +37,11 @@ MEMORY_DIR=./memory
HEARTBEAT_INTERVAL_MINUTES=60
# ── Token Budget ──
-DAILY_TOKEN_BUDGET=50000
\ No newline at end of file
+DAILY_TOKEN_BUDGET=50000
+
+# ── GitHub (optional) ──
+# Fine-grained personal access token with repo scope
+# Create at: https://github.com/settings/tokens?type=beta
+GITHUB_TOKEN=
+GITHUB_USERNAME=
+GITHUB_EMAIL=
\ No newline at end of file
diff --git a/docs/index.html b/docs/index.html
index fd3b6f49..6dd61a20 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mercury — Soul-Driven AI Agent with Permission Guardrails | Cosmic Stack</title>
<meta name="description"
- content="The AI agent that asks before it acts. Permission guardrails, token efficiency, and full control. Runs 24/7 from CLI or Telegram. 21 built-in tools, skill system, scheduling.">
+ content="The AI agent that asks before it acts. Permission guardrails, token efficiency, full control, and GitHub companion. Runs 24/7 from CLI or Telegram. 26 built-in tools, skill system, scheduling.">
<meta name="author" content="Cosmic Stack">
<meta name="robots" content="index, follow">
<meta name="keywords"
@@ -46,7 +46,7 @@
"@type": "SoftwareApplication",
"name": "Mercury",
"applicationCategory": "DeveloperApplication",
- "operatingSystem": "Node.js 20+",
+ "operatingSystem": "Node.js 18+",
"description": "Soul-driven AI agent with permission guardrails, token budgets, and multi-channel access. Runs 24/7 from CLI or Telegram.",
"url": "https://mercury.cosmicstack.org",
"offers": {
@@ -80,6 +80,7 @@
<a href="#how-it-works">Install</a>
<a href="#demo">Demo</a>
<a href="#capabilities">Capabilities</a>
+ <a href="#github">GitHub</a>
<a href="#compare">Compare</a>
<a href="docs.html">Docs</a>
<a href="https://github.com/cosmicstack-labs/mercury-agent" class="github-btn" target="_blank" rel="noopener">
@@ -103,7 +104,7 @@
/_/ /_/_____/_/ |_|\____/\____/_/ |_| /_/
</pre>
<p class="hero-tagline">Soul-driven. Token-efficient. Always on.</p>
- <p class="hero-sub">Your personal AI agent with 21 built-in tools, skill system, multi-channel access, and
+ <p class="hero-sub">Your personal AI agent with 26 built-in tools, skill system, multi-channel access, GitHub companion, and
hardened permissions. Runs 24/7 from your terminal or Telegram.</p>
<div class="hero-actions">
<a href="#how-it-works" class="btn btn-primary">Get Started</a>
@@ -216,7 +217,7 @@
<section id="capabilities" class="section section-dark">
<div class="container">
- <h2 class="section-title">21 Built-In Tools</h2>
+ <h2 class="section-title">26 Built-In Tools</h2>
<p class="section-sub">Plus extensible skills, scheduling, and memory.</p>
<div class="caps-grid">
<div class="cap-group" data-reveal>
@@ -229,6 +230,7 @@
<li><code>list_dir</code> — List directory contents</li>
<li><code>delete_file</code> — Delete a file</li>
<li><code>send_file</code> — Send file to user (Telegram upload)</li>
+ <li><code>approve_scope</code> — Request directory access</li>
</ul>
</div>
<div class="cap-group" data-reveal>
@@ -255,6 +257,17 @@
<li><code>fetch_url</code> — Fetch &amp; strip HTML to text</li>
</ul>
</div>
+ <div class="cap-group" data-reveal>
+ <h3>🐙 GitHub</h3>
+ <ul>
+ <li><code>create_pr</code> — Create pull requests</li>
+ <li><code>review_pr</code> — Review PRs + post comments</li>
+ <li><code>list_issues</code> — List &amp; filter issues</li>
+ <li><code>create_issue</code> — Create new issues</li>
+ <li><code>github_api</code> — Raw API access (escape hatch)</li>
+ <li>Co-authored-by on every commit</li>
+ </ul>
+ </div>
<div class="cap-group" data-reveal>
<h3>🧩 Skills</h3>
<ul>
@@ -340,6 +353,12 @@
<td class="partial">Confirmation prompts</td>
<td class="partial">Permission prompts</td>
</tr>
+ <tr>
+ <td>GitHub Companion</td>
+ <td class="highlight">PRs, issues, co-authored commits</td>
+ <td class="no">—</td>
+ <td class="no">—</td>
+ </tr>
<tr>
<td>Proactive Notifications</td>
<td class="highlight">Heartbeat + task alerts</td>
@@ -440,6 +459,50 @@
</div>
</section>
+ <section id="github" class="section">
+ <div class="container">
+ <h2 class="section-title">GitHub Companion</h2>
+ <p class="section-sub">Your agent, your commits, your repos.</p>
+ <div class="features-grid" style="max-width: 900px; margin: 0 auto;">
+ <div class="feature-card" data-reveal>
+ <div class="feature-icon">🐙</div>
+ <h3>Co-Authored Commits</h3>
+ <p>Every Mercury-assisted commit gets a <code>Co-authored-by: Mercury</code> trailer. Mercury's avatar appears alongside yours in GitHub's commit history.</p>
+ </div>
+ <div class="feature-card" data-reveal>
+ <div class="feature-icon">🔀</div>
+ <h3>Pull Requests</h3>
+ <p>Create PRs, review diffs, and post review comments — all through Mercury's tools. Just say "create a PR" or "review the open PRs".</p>
+ </div>
+ <div class="feature-card" data-reveal>
+ <div class="feature-icon">📋</div>
+ <h3>Issue Management</h3>
+ <p>List, filter, and create issues. Schedule daily issue checks. Mercury keeps your backlog moving without you touching the browser.</p>
+ </div>
+ <div class="feature-card" data-reveal>
+ <div class="feature-icon">🔑</div>
+ <h3>Self-Hosted Auth</h3>
+ <p>Uses a fine-grained Personal Access Token stored on your machine. No accounts, no OAuth servers, no cloud dependencies. Your token, your repos, your control.</p>
+ </div>
+ </div>
+ <div class="terminal-window" style="max-width: 680px; margin: 48px auto 0;">
+ <div class="terminal-bar">
+ <span class="terminal-dot red"></span>
+ <span class="terminal-dot yellow"></span>
+ <span class="terminal-dot green"></span>
+ <span class="terminal-title">terminal</span>
+ </div>
+ <div class="terminal-body" style="min-height: auto; padding: 16px 24px;">
+ <p style="margin:0;color:var(--gray);">$ <span style="color:var(--cyan);">mercury doctor</span></p>
+ <p style="margin:0;color:var(--gray-dim);">GitHub username: salmanqureshi</p>
+ <p style="margin:0;color:var(--gray-dim);">GitHub email: [email protected]</p>
+ <p style="margin:0;color:var(--gray-dim);">GitHub PAT (repo scope): ••••••••</p>
+ <p style="margin:0;color:var(--green);">✓ GitHub tools registered (5)</p>
+ </div>
+ </div>
+ </div>
+ </section>
+
<section id="architecture" class="section section-dark">
<div class="container">
<h2 class="section-title">Under the Hood</h2>
@@ -447,7 +510,7 @@
<div class="arch-grid">
<div class="arch-card" data-reveal>
<div class="arch-label">Core</div>
- <div class="arch-value">TypeScript + Node.js 20+</div>
+ <div class="arch-value">TypeScript + Node.js 18+</div>
<div class="arch-desc">ESM, tsup build, zero native deps</div>
</div>
<div class="arch-card" data-reveal>
@@ -485,7 +548,7 @@
<div class="cta-terminal">
<code>npm i -g @cosmicstack/mercury-agent && mercury</code>
</div>
- <p class="cta-sub">That's it. 60 seconds to your own AI agent.</p>
+ <p class="cta-sub">That's it. 60 seconds to your own AI agent with GitHub companion.</p>
<div class="cta-links">
<a href="https://github.com/cosmicstack-labs/mercury-agent" target="_blank" rel="noopener">GitHub →</a>
<a href="https://github.com/cosmicstack-labs/mercury-agent/issues" target="_blank" rel="noopener">Report an
diff --git a/package.json b/package.json
index 50a6cd49..12c0aa90 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@cosmicstack/mercury-agent",
- "version": "0.2.7",
+ "version": "0.3.0",
"description": "Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI or Telegram.",
"type": "module",
"main": "dist/index.js",
diff --git a/src/capabilities/git/git-commit.ts b/src/capabilities/git/git-commit.ts
index a4cc5bff..c49f0bd4 100644
--- a/src/capabilities/git/git-commit.ts
+++ b/src/capabilities/git/git-commit.ts
@@ -2,15 +2,18 @@ import { tool } from 'ai';
import { z } from 'zod';
import { execSync } from 'node:child_process';
+const CO_AUTHOR = 'Mercury <[email protected]>';
+
export function createGitCommitTool() {
return tool({
- description: 'Record changes to the repository. Creates a new commit with staged changes.',
+ description: 'Record changes to the repository. Creates a new commit with staged changes. Automatically includes a Co-authored-by trailer for attribution.',
parameters: z.object({
message: z.string().describe('Commit message'),
}),
execute: async ({ message }) => {
try {
- const escapedMsg = message.replace(/"/g, '\\"');
+ const fullMessage = `${message}\n\nCo-authored-by: ${CO_AUTHOR}`;
+ const escapedMsg = fullMessage.replace(/"/g, '\\"');
const result = execSync(`git commit -m "${escapedMsg}"`, { encoding: 'utf-8', timeout: 10000 });
return result.trim() || 'Committed successfully.';
} catch (err: any) {
diff --git a/src/capabilities/github/create-issue.ts b/src/capabilities/github/create-issue.ts
new file mode 100644
index 00000000..0fa94a93
--- /dev/null
+++ b/src/capabilities/github/create-issue.ts
@@ -0,0 +1,32 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { githubRequest, getCurrentRepo } from '../../utils/github.js';
+
+export function createCreateIssueTool() {
+ return tool({
+ description: 'Create a new GitHub issue in the current repository. Requires GITHUB_TOKEN.',
+ parameters: z.object({
+ title: z.string().describe('Issue title'),
+ body: z.string().describe('Issue description (markdown supported)').default(''),
+ labels: z.array(z.string()).describe('Label names to apply').optional(),
+ }),
+ execute: async ({ title, body, labels }) => {
+ try {
+ const repo = await getCurrentRepo();
+ if (!repo) return 'Error: Could not detect GitHub repository.';
+
+ const payload: any = { title, body };
+ if (labels && labels.length > 0) payload.labels = labels;
+
+ const result = await githubRequest(`/repos/${repo.owner}/${repo.repo}/issues`, {
+ method: 'POST',
+ body: payload,
+ });
+
+ return `Issue created: ${result.html_url}\n#${result.number}: ${result.title}`;
+ } catch (err: any) {
+ return `Error creating issue: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/github/create-pr.ts b/src/capabilities/github/create-pr.ts
new file mode 100644
index 00000000..30e3da25
--- /dev/null
+++ b/src/capabilities/github/create-pr.ts
@@ -0,0 +1,37 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { githubRequest, getCurrentRepo } from '../../utils/github.js';
+
+export function createCreatePrTool() {
+ return tool({
+ description: 'Create a pull request on GitHub. Requires GITHUB_TOKEN to be configured.',
+ parameters: z.object({
+ title: z.string().describe('PR title'),
+ body: z.string().describe('PR description (markdown supported)').default(''),
+ head: z.string().describe('The branch containing the changes'),
+ base: z.string().describe('The branch to merge into').default('main'),
+ draft: z.boolean().describe('Create as draft PR').default(false),
+ }),
+ execute: async ({ title, body, head, base, draft }) => {
+ try {
+ const repo = await getCurrentRepo();
+ if (!repo) return 'Error: Could not detect GitHub repository. Make sure you are in a git repo with a GitHub remote.';
+
+ const result = await githubRequest(`/repos/${repo.owner}/${repo.repo}/pulls`, {
+ method: 'POST',
+ body: {
+ title,
+ body,
+ head,
+ base,
+ draft,
+ },
+ });
+
+ return `PR created: ${result.html_url}\n#${result.number}: ${result.title}\n${draft ? '(draft)' : ''} ${result.state}`;
+ } catch (err: any) {
+ return `Error creating PR: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/github/github-api.ts b/src/capabilities/github/github-api.ts
new file mode 100644
index 00000000..25192cf1
--- /dev/null
+++ b/src/capabilities/github/github-api.ts
@@ -0,0 +1,52 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { githubRequest } from '../../utils/github.js';
+import type { PermissionManager } from '../permissions.js';
+
+export function createGithubApiTool(permissions: PermissionManager) {
+ return tool({
+ description: 'Make a raw request to the GitHub API. Use this for any GitHub operation not covered by other tools. GET requests are auto-approved; write operations (POST, PUT, PATCH, DELETE) require approval.',
+ parameters: z.object({
+ path: z.string().describe('API path (e.g., /repos/owner/repo/releases)'),
+ method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method').default('GET'),
+ body: z.string().describe('JSON body for write requests (as a JSON string)').optional(),
+ }),
+ execute: async ({ path, method, body }) => {
+ const isWrite = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(method);
+
+ if (isWrite) {
+ const check = await permissions.checkShellCommand(`github-api ${method} ${path}`);
+ if (!check.allowed) {
+ if (check.needsApproval) {
+ return `This GitHub API write operation requires approval: ${method} ${path}\n\nTell the user what this does and ask for confirmation. If approved, try again.`;
+ }
+ return `Error: ${check.reason}`;
+ }
+ }
+
+ try {
+ let parsedBody: any;
+ if (body) {
+ try {
+ parsedBody = JSON.parse(body);
+ } catch {
+ return 'Error: body must be valid JSON.';
+ }
+ }
+
+ const result = await githubRequest(path, {
+ method,
+ body: parsedBody,
+ });
+
+ if (result === null) return 'Request completed (204 No Content).';
+
+ if (typeof result === 'string') return result;
+
+ return JSON.stringify(result, null, 2);
+ } catch (err: any) {
+ return `Error: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/github/list-issues.ts b/src/capabilities/github/list-issues.ts
new file mode 100644
index 00000000..0b5c7a4e
--- /dev/null
+++ b/src/capabilities/github/list-issues.ts
@@ -0,0 +1,42 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { githubRequest, getCurrentRepo } from '../../utils/github.js';
+
+export function createListIssuesTool() {
+ return tool({
+ description: 'List open GitHub issues for the current repository. Requires GITHUB_TOKEN.',
+ parameters: z.object({
+ state: z.enum(['open', 'closed', 'all']).describe('Filter by issue state').default('open'),
+ labels: z.string().describe('Comma-separated label names to filter by (optional)').optional(),
+ limit: z.number().describe('Maximum number of issues to return').default(10),
+ }),
+ execute: async ({ state, labels, limit }) => {
+ try {
+ const repo = await getCurrentRepo();
+ if (!repo) return 'Error: Could not detect GitHub repository.';
+
+ const params = new URLSearchParams();
+ params.set('state', state);
+ params.set('per_page', String(Math.min(limit, 100)));
+ params.set('sort', 'updated');
+ params.set('direction', 'desc');
+ if (labels) params.set('labels', labels);
+
+ const issues = await githubRequest(`/repos/${repo.owner}/${repo.repo}/issues?${params}`);
+
+ if (!Array.isArray(issues) || issues.length === 0) {
+ return `No ${state} issues found.`;
+ }
+
+ const lines = issues.map((issue: any) => {
+ const labelStr = issue.labels?.map((l: any) => `[${l.name}]`).join(' ') || '';
+ return `#${issue.number} ${issue.title} ${labelStr} (${issue.state}, by ${issue.user?.login})`;
+ });
+
+ return `Issues in ${repo.owner}/${repo.repo} (${state}):\n${lines.join('\n')}`;
+ } catch (err: any) {
+ return `Error listing issues: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/github/review-pr.ts b/src/capabilities/github/review-pr.ts
new file mode 100644
index 00000000..87f7f051
--- /dev/null
+++ b/src/capabilities/github/review-pr.ts
@@ -0,0 +1,67 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { githubRequest, getCurrentRepo } from '../../utils/github.js';
+
+export function createReviewPrTool() {
+ return tool({
+ description: 'Get details of a pull request including the diff. Reviews the PR and returns the title, body, changed files, and diff. Optionally post a review comment.',
+ parameters: z.object({
+ number: z.number().describe('PR number'),
+ comment: z.string().describe('Review comment to post on the PR (optional)').optional(),
+ }),
+ execute: async ({ number, comment }) => {
+ try {
+ const repo = await getCurrentRepo();
+ if (!repo) return 'Error: Could not detect GitHub repository.';
+
+ const pr = await githubRequest(`/repos/${repo.owner}/${repo.repo}/pulls/${number}`);
+ if (!pr) return `Error: PR #${number} not found.`;
+
+ const diff = await githubRequest(`/repos/${repo.owner}/${repo.repo}/pulls/${number}`, {
+ headers: { 'Accept': 'application/vnd.github.v3.diff' },
+ });
+
+ let summary = `PR #${pr.number}: ${pr.title}\n`;
+ summary += `Author: ${pr.user?.login}\n`;
+ summary += `State: ${pr.state} (${pr.merged ? 'merged' : pr.mergeable_state || 'unknown'})\n`;
+ summary += `Branch: ${pr.head.ref} → ${pr.base.ref}\n`;
+ summary += `Changed files: ${pr.changed_files} | Additions: +${pr.additions} | Deletions: -${pr.deletions}\n\n`;
+
+ if (pr.body) {
+ summary += `Description:\n${pr.body.slice(0, 2000)}\n\n`;
+ }
+
+ if (typeof diff === 'string') {
+ const diffLines = diff.split('\n');
+ const maxDiffLines = 200;
+ summary += `Diff (first ${Math.min(diffLines.length, maxDiffLines)} of ${diffLines.length} lines):\n`;
+ summary += diffLines.slice(0, maxDiffLines).join('\n');
+ if (diffLines.length > maxDiffLines) {
+ summary += `\n\n... (${diffLines.length - maxDiffLines} more lines)`;
+ }
+ } else {
+ summary += `(Diff not available in text format)`;
+ }
+
+ if (comment) {
+ try {
+ await githubRequest(`/repos/${repo.owner}/${repo.repo}/pulls/${number}/reviews`, {
+ method: 'POST',
+ body: {
+ body: comment,
+ event: 'COMMENT',
+ },
+ });
+ summary += `\n\nReview comment posted.`;
+ } catch (err: any) {
+ summary += `\n\nFailed to post review comment: ${err.message}`;
+ }
+ }
+
+ return summary;
+ } catch (err: any) {
+ return `Error reviewing PR: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index 8582890a..53699df7 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -23,7 +23,13 @@ import { createGitLogTool } from './git/git-log.js';
import { createGitAddTool } from './git/git-add.js';
import { createGitCommitTool } from './git/git-commit.js';
import { createGitPushTool } from './git/git-push.js';
+import { createCreatePrTool } from './github/create-pr.js';
+import { createReviewPrTool } from './github/review-pr.js';
+import { createListIssuesTool } from './github/list-issues.js';
+import { createCreateIssueTool } from './github/create-issue.js';
+import { createGithubApiTool } from './github/github-api.js';
import { createFetchUrlTool } from './web/fetch-url.js';
+import { isGitHubConfigured, setGitHubToken } from '../utils/github.js';
import type { SkillLoader } from '../skills/loader.js';
import type { Scheduler } from '../core/scheduler.js';
import type { TokenBudget } from '../utils/tokens.js';
@@ -131,6 +137,15 @@ export class CapabilityRegistry {
logger.info('Git tools registered');
}
+ if (isGitHubConfigured()) {
+ this.tools.create_pr = createCreatePrTool();
+ this.tools.review_pr = createReviewPrTool();
+ this.tools.list_issues = createListIssuesTool();
+ this.tools.create_issue = createCreateIssueTool();
+ this.tools.github_api = createGithubApiTool(this.permissions);
+ logger.info('GitHub tools registered');
+ }
+
this.tools.fetch_url = createFetchUrlTool();
logger.info('Web fetch tool registered');
}
diff --git a/src/index.ts b/src/index.ts
index c7717245..3cef1351 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,4 +1,4 @@
-import { readFileSync } from 'node:fs';
+import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { Command } from 'commander';
@@ -22,6 +22,7 @@ import { getManual } from './utils/manual.js';
import { startBackground, stopDaemon, showLogs, getDaemonStatus, restartDaemon, tryAutoDaemonize } from './cli/daemon.js';
import { installService, uninstallService, showServiceStatus, isServiceInstalled } from './cli/service.js';
import { runWithWatchdog } from './cli/watchdog.js';
+import { setGitHubToken } from './utils/github.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const pkgVersion = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf8')).version;
@@ -77,6 +78,18 @@ function maskKey(key: string): string {
return key.slice(0, 4) + '••••' + key.slice(-4);
}
+function appendToEnv(key: string, value: string): void {
+ const envPath = join(getMercuryHome(), '.env');
+ let envContent = '';
+ if (existsSync(envPath)) {
+ envContent = readFileSync(envPath, 'utf-8');
+ }
+ const lines = envContent.split('\n').filter((l: string) => !l.startsWith(`${key}=`) && l.trim() !== '');
+ lines.push(`${key}=${value}`);
+ writeFileSync(envPath, lines.join('\n') + '\n', 'utf-8');
+ process.env[key] = value;
+}
+
async function configure(existingConfig?: MercuryConfig): Promise<void> {
const isReconfig = !!existingConfig;
const config = existingConfig ?? loadConfig();
@@ -189,6 +202,27 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {
config.channels.telegram.enabled = true;
}
+ hr();
+ console.log('');
+ console.log(chalk.bold.white(' GitHub (optional)'));
+ console.log(chalk.dim(' Connect Mercury to GitHub for PRs, issues, and co-authored commits.'));
+ console.log(chalk.dim(' Leave empty to skip. You can add it later with mercury doctor.'));
+ console.log('');
+
+ const ghUserCurrent = isReconfig && config.github.username ? ` [${config.github.username}]` : '';
+ const ghUsername = await ask(chalk.white(` GitHub username${ghUserCurrent}: `));
+ if (ghUsername) config.github.username = ghUsername;
+
+ const ghEmailCurrent = isReconfig && config.github.email ? ` [${config.github.email}]` : '';
+ const ghEmail = await ask(chalk.white(` GitHub email${ghEmailCurrent}: `));
+ if (ghEmail) config.github.email = ghEmail;
+
+ const ghTokenCurrent = process.env.GITHUB_TOKEN ? ` [${maskKey(process.env.GITHUB_TOKEN)}]` : '';
+ const ghToken = await ask(chalk.white(` GitHub PAT (repo scope)${ghTokenCurrent}: `));
+ if (ghToken) {
+ appendToEnv('GITHUB_TOKEN', ghToken);
+ }
+
hr();
console.log('');
console.log(chalk.bold.white(' Token Budget'));
@@ -314,6 +348,10 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
}
});
+ if (process.env.GITHUB_TOKEN) {
+ setGitHubToken(process.env.GITHUB_TOKEN);
+ }
+
capabilities.registerAll();
const agent = new Agent(
diff --git a/src/utils/config.ts b/src/utils/config.ts
index 16a5af40..4df422b3 100644
--- a/src/utils/config.ts
+++ b/src/utils/config.ts
@@ -41,6 +41,10 @@ export interface MercuryConfig {
streaming?: boolean;
};
};
+ github: {
+ username: string;
+ email: string;
+ };
memory: {
dir: string;
shortTermMaxMessages: number;
@@ -113,6 +117,10 @@ export function getDefaultConfig(): MercuryConfig {
streaming: getEnvBool('TELEGRAM_STREAMING', true),
},
},
+ github: {
+ username: getEnv('GITHUB_USERNAME', ''),
+ email: getEnv('GITHUB_EMAIL', ''),
+ },
memory: {
dir: getEnv('MEMORY_DIR', join(home, 'memory')),
shortTermMaxMessages: getEnvNum('SHORT_TERM_MAX_MESSAGES', 20),
diff --git a/src/utils/github.ts b/src/utils/github.ts
new file mode 100644
index 00000000..d66ecbca
--- /dev/null
+++ b/src/utils/github.ts
@@ -0,0 +1,87 @@
+import { logger } from './logger.js';
+
+const GITHUB_API = 'https://api.github.com';
+
+let cachedToken: string | null = null;
+
+export function setGitHubToken(token: string): void {
+ cachedToken = token;
+}
+
+export function getGitHubToken(): string | null {
+ if (cachedToken) return cachedToken;
+ return process.env.GITHUB_TOKEN || null;
+}
+
+export function isGitHubConfigured(): boolean {
+ return !!getGitHubToken();
+}
+
+interface GitHubRequestOptions {
+ method?: string;
+ body?: any;
+ headers?: Record<string, string>;
+}
+
+export async function githubRequest(path: string, options: GitHubRequestOptions = {}): Promise<any> {
+ const token = getGitHubToken();
+ if (!token) {
+ throw new Error('GITHUB_TOKEN not configured. Run mercury doctor to set it up.');
+ }
+
+ const url = path.startsWith('http') ? path : `${GITHUB_API}${path}`;
+ const headers: Record<string, string> = {
+ 'Authorization': `Bearer ${token}`,
+ 'Accept': 'application/vnd.github.v3+json',
+ 'User-Agent': 'Mercury-Agent',
+ ...options.headers,
+ };
+
+ const fetchOptions: any = {
+ method: options.method || 'GET',
+ headers,
+ };
+
+ if (options.body) {
+ fetchOptions.body = JSON.stringify(options.body);
+ headers['Content-Type'] = 'application/json';
+ }
+
+ logger.info({ method: fetchOptions.method, path }, 'GitHub API request');
+
+ const response = await fetch(url, fetchOptions);
+
+ const remaining = response.headers.get('x-ratelimit-remaining');
+ if (remaining && parseInt(remaining, 10) < 100) {
+ logger.warn({ remaining }, 'GitHub API rate limit running low');
+ }
+
+ if (!response.ok) {
+ const body = await response.text();
+ throw new Error(`GitHub API ${response.status}: ${body.slice(0, 500)}`);
+ }
+
+ if (response.status === 204) return null;
+
+ return response.json();
+}
+
+export function parseRepo(remoteUrl: string): { owner: string; repo: string } | null {
+ const sshMatch = remoteUrl.match(/git@github\.com:([^/]+)\/([^.\s]+)(?:\.git)?$/);
+ if (sshMatch) return { owner: sshMatch[1], repo: sshMatch[2] };
+
+ const httpsMatch = remoteUrl.match(/https:\/\/github\.com\/([^/]+)\/([^.\s]+)(?:\.git)?$/);
+ if (httpsMatch) return { owner: httpsMatch[1], repo: httpsMatch[2] };
+
+ return null;
+}
+
+export async function getCurrentRepo(): Promise<{ owner: string; repo: string } | null> {
+ try {
+ const { execSync } = await import('node:child_process');
+ const remoteUrl = execSync('git remote get-url origin', { encoding: 'utf-8', timeout: 5000 }).trim();
+ return parseRepo(remoteUrl);
+ } catch {
+ return null;
+ }
+}
\ No newline at end of file