Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
v0.3.2 — fix GitHub tools: explicit owner/repo params, no more getCurrentRepo guessing, remove broken permission check
Salman Qureshi20c9b4489b90
diff --git a/.env.example b/.env.exampleindex 415648a2..419cd0da 100644--- a/.env.example+++ b/.env.example@@ -44,4 +44,7 @@ DAILY_TOKEN_BUDGET=50000# Create at: https://github.com/settings/tokens?type=betaGITHUB_TOKEN=GITHUB_USERNAME=-GITHUB_EMAIL=\ No newline at end of file+GITHUB_EMAIL=+# Default repo for GitHub tools (optional — you can also specify per-call)+GITHUB_DEFAULT_OWNER=+GITHUB_DEFAULT_REPO=\ No newline at end of filediff --git a/package.json b/package.jsonindex 1a8aa914..52c11ecd 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@cosmicstack/mercury-agent",- "version": "0.3.1",+ "version": "0.3.2","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/github/create-issue.ts b/src/capabilities/github/create-issue.tsindex 0fa94a93..c8b5102d 100644--- a/src/capabilities/github/create-issue.ts+++ b/src/capabilities/github/create-issue.ts@@ -1,24 +1,23 @@import { tool } from 'ai';import { z } from 'zod';-import { githubRequest, getCurrentRepo } from '../../utils/github.js';+import { githubRequest } from '../../utils/github.js';export function createCreateIssueTool() {return tool({- description: 'Create a new GitHub issue in the current repository. Requires GITHUB_TOKEN.',+ description: 'Create a new GitHub issue in a repository. Requires GITHUB_TOKEN.',parameters: z.object({+ owner: z.string().describe('Repository owner (username or org)'),+ repo: z.string().describe('Repository name'),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 }) => {+ execute: async ({ owner, repo, 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`, {+ const result = await githubRequest(`/repos/${owner}/${repo}/issues`, {method: 'POST',body: payload,});diff --git a/src/capabilities/github/create-pr.ts b/src/capabilities/github/create-pr.tsindex 30e3da25..f920cd77 100644--- a/src/capabilities/github/create-pr.ts+++ b/src/capabilities/github/create-pr.ts@@ -1,31 +1,24 @@import { tool } from 'ai';import { z } from 'zod';-import { githubRequest, getCurrentRepo } from '../../utils/github.js';+import { githubRequest } 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({+ owner: z.string().describe('Repository owner (username or org)'),+ repo: z.string().describe('Repository name'),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 }) => {+ execute: async ({ owner, repo, 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`, {+ const result = await githubRequest(`/repos/${owner}/${repo}/pulls`, {method: 'POST',- body: {- title,- body,- head,- base,- draft,- },+ body: { title, body, head, base, draft },});return `PR created: ${result.html_url}\n#${result.number}: ${result.title}\n${draft ? '(draft)' : ''} ${result.state}`;diff --git a/src/capabilities/github/github-api.ts b/src/capabilities/github/github-api.tsindex 25192cf1..c3bbc0e5 100644--- a/src/capabilities/github/github-api.ts+++ b/src/capabilities/github/github-api.ts@@ -1,29 +1,16 @@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) {+export function createGithubApiTool() {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.',+ description: 'Make a raw request to the GitHub API. Use this for any GitHub operation not covered by other tools. GET requests (read-only) are always allowed. Write operations (POST, PUT, PATCH, DELETE) will ask the user for approval via the permission system.',parameters: z.object({- path: z.string().describe('API path (e.g., /repos/owner/repo/releases)'),+ path: z.string().describe('Full API path (e.g., /repos/owner/repo/issues or /user)'),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) {diff --git a/src/capabilities/github/list-issues.ts b/src/capabilities/github/list-issues.tsindex 0b5c7a4e..18dc18e6 100644--- a/src/capabilities/github/list-issues.ts+++ b/src/capabilities/github/list-issues.ts@@ -1,20 +1,19 @@import { tool } from 'ai';import { z } from 'zod';-import { githubRequest, getCurrentRepo } from '../../utils/github.js';+import { githubRequest } from '../../utils/github.js';export function createListIssuesTool() {return tool({- description: 'List open GitHub issues for the current repository. Requires GITHUB_TOKEN.',+ description: 'List GitHub issues for a repository. Requires GITHUB_TOKEN.',parameters: z.object({+ owner: z.string().describe('Repository owner (username or org)'),+ repo: z.string().describe('Repository name'),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 }) => {+ execute: async ({ owner, repo, 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)));@@ -22,10 +21,10 @@ export function createListIssuesTool() {params.set('direction', 'desc');if (labels) params.set('labels', labels);- const issues = await githubRequest(`/repos/${repo.owner}/${repo.repo}/issues?${params}`);+ const issues = await githubRequest(`/repos/${owner}/${repo}/issues?${params}`);if (!Array.isArray(issues) || issues.length === 0) {- return `No ${state} issues found.`;+ return `No ${state} issues found in ${owner}/${repo}.`;}const lines = issues.map((issue: any) => {@@ -33,7 +32,7 @@ export function createListIssuesTool() {return `#${issue.number} ${issue.title} ${labelStr} (${issue.state}, by ${issue.user?.login})`;});- return `Issues in ${repo.owner}/${repo.repo} (${state}):\n${lines.join('\n')}`;+ return `Issues in ${owner}/${repo} (${state}):\n${lines.join('\n')}`;} catch (err: any) {return `Error listing issues: ${err.message}`;}diff --git a/src/capabilities/github/review-pr.ts b/src/capabilities/github/review-pr.tsindex 87f7f051..7a7fa263 100644--- a/src/capabilities/github/review-pr.ts+++ b/src/capabilities/github/review-pr.ts@@ -1,26 +1,21 @@import { tool } from 'ai';import { z } from 'zod';-import { githubRequest, getCurrentRepo } from '../../utils/github.js';+import { githubRequest } 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({+ owner: z.string().describe('Repository owner (username or org)'),+ repo: z.string().describe('Repository name'),number: z.number().describe('PR number'),comment: z.string().describe('Review comment to post on the PR (optional)').optional(),}),- execute: async ({ number, comment }) => {+ execute: async ({ owner, repo, 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}`);+ const pr = await githubRequest(`/repos/${owner}/${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`;@@ -31,26 +26,29 @@ export function createReviewPrTool() {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)`;+ try {+ const diff = await githubRequest(`/repos/${owner}/${repo}/pulls/${number}`, {+ headers: { 'Accept': 'application/vnd.github.v3.diff' },+ });++ 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)`;+ } catch {+ summary += `(Diff not available)`;}if (comment) {try {- await githubRequest(`/repos/${repo.owner}/${repo.repo}/pulls/${number}/reviews`, {+ await githubRequest(`/repos/${owner}/${repo}/pulls/${number}/reviews`, {method: 'POST',- body: {- body: comment,- event: 'COMMENT',- },+ body: { body: comment, event: 'COMMENT' },});summary += `\n\nReview comment posted.`;} catch (err: any) {diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.tsindex 53699df7..0b7e139a 100644--- a/src/capabilities/registry.ts+++ b/src/capabilities/registry.ts@@ -142,7 +142,7 @@ export class CapabilityRegistry {this.tools.review_pr = createReviewPrTool();this.tools.list_issues = createListIssuesTool();this.tools.create_issue = createCreateIssueTool();- this.tools.github_api = createGithubApiTool(this.permissions);+ this.tools.github_api = createGithubApiTool();logger.info('GitHub tools registered');}diff --git a/src/core/agent.ts b/src/core/agent.tsindex 5dd12e36..9395a985 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -389,7 +389,13 @@ export class Agent {const githubTools = ['create_pr', 'review_pr', 'list_issues', 'create_issue', 'github_api'];const hasGitHub = githubTools.some(t => toolNames.includes(t));if (hasGitHub) {- prompt += '\n\nGitHub companion is active. You can create pull requests, review PRs, manage issues, and use the GitHub API. When the user asks to create a PR, use create_pr. When they ask about issues, use list_issues or create_issue. When they ask to review a PR, use review_pr.';+ let githubHint = '\n\nGitHub companion is active. You can create pull requests, review PRs, manage issues, and use the GitHub API.';+ const { defaultOwner, defaultRepo } = this.config.github;+ if (defaultOwner && defaultRepo) {+ githubHint += ` Default repo: ${defaultOwner}/${defaultRepo}. Use this when the user doesn't specify a repo.`;+ }+ githubHint += ' When the user says "create a PR", use create_pr. When they ask about issues, use list_issues or create_issue. When they ask to review a PR, use review_pr. Always specify owner and repo parameters.';+ prompt += githubHint;}return prompt;}diff --git a/src/index.ts b/src/index.tsindex 3cef1351..46d13c1f 100644--- a/src/index.ts+++ b/src/index.ts@@ -223,6 +223,16 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {appendToEnv('GITHUB_TOKEN', ghToken);}+ if (config.github.username || process.env.GITHUB_TOKEN) {+ const ghOwnerCurrent = isReconfig && config.github.defaultOwner ? ` [${config.github.defaultOwner}]` : '';+ const ghOwner = await ask(chalk.white(` Default GitHub owner/org${ghOwnerCurrent}: `));+ if (ghOwner) config.github.defaultOwner = ghOwner;++ const ghRepoCurrent = isReconfig && config.github.defaultRepo ? ` [${config.github.defaultRepo}]` : '';+ const ghRepo = await ask(chalk.white(` Default repo name${ghRepoCurrent}: `));+ if (ghRepo) config.github.defaultRepo = ghRepo;+ }+hr();console.log('');console.log(chalk.bold.white(' Token Budget'));diff --git a/src/utils/config.ts b/src/utils/config.tsindex 6c029bc9..5d58f9d3 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -48,6 +48,8 @@ export interface MercuryConfig {github: {username: string;email: string;+ defaultOwner: string;+ defaultRepo: string;};memory: {dir: string;@@ -124,6 +126,8 @@ export function getDefaultConfig(): MercuryConfig {github: {username: getEnv('GITHUB_USERNAME', ''),email: getEnv('GITHUB_EMAIL', ''),+ defaultOwner: getEnv('GITHUB_DEFAULT_OWNER', ''),+ defaultRepo: getEnv('GITHUB_DEFAULT_REPO', ''),},memory: {dir: getEnv('MEMORY_DIR', join(home, 'memory')),diff --git a/src/utils/github.ts b/src/utils/github.tsindex d66ecbca..43bc4e90 100644--- a/src/utils/github.ts+++ b/src/utils/github.ts@@ -63,25 +63,10 @@ export async function githubRequest(path: string, options: GitHubRequestOptionsif (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;+ const contentType = response.headers.get('content-type') || '';+ if (contentType.includes('application/json')) {+ return response.json();}++ return response.text();}\ No newline at end of file