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.4.1 — agent context enrichment, github co-author fix, loop detection

Salman Qureshi057bc2a2ac73
diff --git a/RELEASE.md b/RELEASE.md
index d42ea4cb..eaf6e4f5 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -1,46 +1,27 @@
-# Release v0.4.0
+# Release v0.4.1
-## ☿ Mercury Agent v0.4.0
+## ☿ Mercury Agent v0.4.1
-**Persistent working directory, Ollama support, Telegram messaging, and more.**
+**Smarter agent context, co-author fix, and loop detection.**
-### Highlights
+### What's Changed
-- **`cd` tool** — Change directories persistently. All subsequent file, shell, and git operations use the new working directory. No more lost `cd` between commands.
-- **Relative path support** — All 8 filesystem tools and all 6 git tools now resolve relative paths against the current working directory instead of `process.cwd()`.
-- **`run_command` learns `cd`** — Running `cd /some/path` or `cd /some/path && ls` in `run_command` automatically updates the persistent working directory.
-- **Ollama provider** — Run Mercury fully locally with Ollama. Added during onboarding with model selection.
-- **Telegram paired messaging** — New `send_message` tool lets the agent proactively send messages to the paired Telegram chat.
-- **Improved onboarding** — Relaxed provider setup, better Telegram guidance, Ollama configuration flow.
+- **Agent context enrichment** — Every request now includes `Platform` and `Working directory` in the system prompt, so the LLM knows what OS it's on and where it's working. Prevents the "trying `/home/zayd` on Windows" confusion.
+- **GitHub companion awareness** — When GitHub tools are active, the system prompt now explains when to use `git_commit` + `git_push` vs. `github_api` Contents API, so the agent doesn't fumble between approaches.
+- **Co-author injection for GitHub API** — `github_api` now automatically injects `Co-authored-by: Mercury <[email protected]>` into all content creation/update operations (`PUT /repos/:owner/:repo/contents/:path`). Previously, only `git_commit` had the co-author trailer — API-created files were missing it.
+- **Loop detection circuit breaker** — New `ToolCallLoopDetector` tracks consecutive tool calls. If the same tool+params is called 3+ times in a row, a system warning is injected telling the LLM to try a different approach. Prevents the infinite `approve_scope` / `list_dir` death spirals that burned through token budgets.
+- **`github_api` description overhaul** — The tool description now explicitly documents Contents API operations (push files, delete files) and when to use the API vs. git CLI, so the LLM makes smarter choices from the start.
-### What's New
+### Bug Fixes
-- `cd` tool — persistent directory changes across all tool calls
-- `currentCwd` state in `CapabilityRegistry` with `getCwd()`/`setCwd()`
-- `send_message` capability for paired Telegram chats
-- Ollama provider (`ollama-ai-provider`) with onboarding setup
-- Enhanced Telegram channel with paired messaging support
+- LLM no longer blind to the current working directory or platform when making tool calls
+- GitHub API file pushes now correctly show Mercury as co-author in GitHub's commit history
+- Agent no longer loops on failing permission/approval calls until token budget exhaustion
-### Fixes & Improvements
+### Migration from v0.4.0
-- All filesystem tools (`read_file`, `write_file`, `create_file`, `list_dir`, `delete_file`, `edit_file`, `send_file`, `approve_scope`) now resolve relative paths against current working directory
-- All git tools (`git_status`, `git_diff`, `git_log`, `git_add`, `git_commit`, `git_push`) now use `cwd: getCwd()` in `execSync`
-- `run_command` uses persistent `cwd` and auto-detects directory changes
-- Improved provider onboarding flow with Ollama support
-- Enhanced `.env.example` with all available configuration options
-- Updated documentation with new tools and provider setup
-
-### Migration from v0.3.x
-
-No configuration changes required. The `cd` tool is automatically registered. Existing relative paths in tool calls will now resolve against the persistent working directory (defaults to `process.cwd()` on startup, same as before).
-
-### Credits
-
-- Persistent working directory implementation — @salmanqureshi
-- Ollama provider & onboarding improvements — @salmanqureshi
-- Telegram paired messaging — @salmanqureshi
-- Social media & documentation updates — reviewed by PR #3 contributors
+No configuration changes required. All improvements are in agent behavior and tool descriptions.
---
-**Full Changelog**: https://github.com/cosmicstack-labs/mercury-agent/compare/v0.3.4...v0.4.0
\ No newline at end of file
+**Full Changelog**: https://github.com/cosmicstack-labs/mercury-agent/compare/v0.4.0...v0.4.1
\ No newline at end of file
diff --git a/package.json b/package.json
index 837dc617..a803901b 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@cosmicstack/mercury-agent",
- "version": "0.4.0",
+ "version": "0.4.1",
"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/github-api.ts b/src/capabilities/github/github-api.ts
index c3bbc0e5..e8014644 100644
--- a/src/capabilities/github/github-api.ts
+++ b/src/capabilities/github/github-api.ts
@@ -2,11 +2,47 @@ import { tool } from 'ai';
import { z } from 'zod';
import { githubRequest } from '../../utils/github.js';
+const CO_AUTHOR_NAME = 'Mercury';
+const CO_AUTHOR_EMAIL = '[email protected]';
+const CO_AUTHOR_TRAILER = `Co-authored-by: ${CO_AUTHOR_NAME} <${CO_AUTHOR_EMAIL}>`;
+
+function isContentCreatePath(path: string): boolean {
+ return /^\/repos\/[^/]+\/[^/]+\/contents\//.test(path);
+}
+
+function injectCoAuthor(body: any): any {
+ const result = { ...body };
+
+ if (typeof result.message === 'string' && !result.message.includes(CO_AUTHOR_TRAILER)) {
+ result.message += `\n\n${CO_AUTHOR_TRAILER}`;
+ }
+
+ if (!result.committer || typeof result.committer !== 'object') {
+ result.committer = { name: CO_AUTHOR_NAME, email: CO_AUTHOR_EMAIL };
+ }
+
+ if (!result.author || typeof result.author !== 'object') {
+ result.author = { name: CO_AUTHOR_NAME, email: CO_AUTHOR_EMAIL };
+ }
+
+ return result;
+}
+
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 (read-only) are always allowed. Write operations (POST, PUT, PATCH, DELETE) will ask the user for approval via the permission system.',
+ description: `Make a raw request to the GitHub API. GET requests (read-only) are always allowed. Write operations (POST, PUT, PATCH, DELETE) may require user approval.
+
+Common operations you can perform:
+- Push a file: PUT /repos/{owner}/{repo}/contents/{path} — body must include "message" (commit message) and "content" (base64-encoded file). For updates, also include "sha" from the current file. Co-authored-by Mercury is automatically included.
+- Delete a file: DELETE /repos/{owner}/{repo}/contents/{path} — body must include "message" and "sha".
+- List branches: GET /repos/{owner}/{repo}/branches
+- Get file contents: GET /repos/{owner}/{repo}/contents/{path}
+- Search code: GET /search/code?q={query}
+- Any other GitHub API v3 endpoint.
+
+IMPORTANT: When the user wants to push code or files to GitHub and git push fails (auth issues, no SSH key, etc.), use PUT /repos/{owner}/{repo}/contents/{path} to create or update files directly through the API. This bypasses local git and creates a commit with Mercury as co-author.`,
parameters: z.object({
- path: z.string().describe('Full API path (e.g., /repos/owner/repo/issues or /user)'),
+ path: z.string().describe('Full API path (e.g., /repos/owner/repo/issues or /repos/owner/repo/contents/path/to/file)'),
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(),
}),
@@ -21,6 +57,10 @@ export function createGithubApiTool() {
}
}
+ if (parsedBody && isContentCreatePath(path) && (method === 'PUT' || method === 'POST' || method === 'PATCH')) {
+ parsedBody = injectCoAuthor(parsedBody);
+ }
+
const result = await githubRequest(path, {
method,
body: parsedBody,
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 08a37be2..714ed1b3 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -12,6 +12,56 @@ import { Lifecycle } from './lifecycle.js';
import { Scheduler } from './scheduler.js';
import { logger } from '../utils/logger.js';
+class ToolCallLoopDetector {
+ private recentCalls: Array<{ tool: string; params: string }> = [];
+ private maxEntries = 10;
+
+ record(toolName: string, params: Record<string, any>): void {
+ const paramsKey = JSON.stringify(params).slice(0, 100);
+ this.recentCalls.push({ tool: toolName, params: paramsKey });
+ if (this.recentCalls.length > this.maxEntries) {
+ this.recentCalls.shift();
+ }
+ }
+
+ detect(): { tool: string; count: number } | null {
+ if (this.recentCalls.length < 3) return null;
+
+ const last = this.recentCalls[this.recentCalls.length - 1];
+ let consecutiveCount = 0;
+ for (let i = this.recentCalls.length - 1; i >= 0; i--) {
+ if (this.recentCalls[i].tool === last.tool && this.recentCalls[i].params === last.params) {
+ consecutiveCount++;
+ } else {
+ break;
+ }
+ }
+
+ if (consecutiveCount >= 3) {
+ return { tool: last.tool, count: consecutiveCount };
+ }
+
+ const lastTool = last.tool;
+ let toolCount = 0;
+ for (let i = this.recentCalls.length - 1; i >= 0; i--) {
+ if (this.recentCalls[i].tool === lastTool) {
+ toolCount++;
+ } else {
+ break;
+ }
+ }
+ if (toolCount >= 4) {
+ return { tool: lastTool, count: toolCount };
+ }
+
+ return null;
+ }
+
+ reset(): void {
+ this.recentCalls = [];
+ }
+}
+
const MAX_STEPS = 10;
export class Agent {
@@ -188,6 +238,32 @@ export class Agent {
const messages: any[] = [];
+ const recentSteps = this.shortTerm.getRecent(msg.channelId, 4);
+ let loopWarning: string | null = null;
+ if (recentSteps.length >= 3) {
+ const toolCallPattern = /\[Using: (.+?)\]/g;
+ const toolCalls: string[] = [];
+ for (const m of recentSteps) {
+ if (m.role === 'assistant') {
+ let match;
+ while ((match = toolCallPattern.exec(m.content)) !== null) {
+ toolCalls.push(match[1]);
+ }
+ }
+ }
+ if (toolCalls.length >= 3) {
+ const last3 = toolCalls.slice(-3);
+ if (last3[0] === last3[1] && last3[1] === last3[2]) {
+ loopWarning = `[SYSTEM WARNING] You have called ${last3[0]} 3+ times in a row with the same result. Stop repeating this call. Try a different approach — if you're failing on permissions, try a different path. If you're failing on git push auth, use github_api with PUT /repos/{owner}/{repo}/contents/{path} to push files directly through the API.`;
+ }
+ }
+ }
+
+ if (loopWarning) {
+ messages.push({ role: 'user', content: loopWarning });
+ messages.push({ role: 'assistant', content: 'Understood. I will try a different approach.' });
+ }
+
if (relevantFacts.length > 0) {
messages.push({
role: 'user',
@@ -222,6 +298,7 @@ export class Agent {
let usedProvider: { name: string; model: string } | null = null;
let lastError: any = null;
let streamedText = '';
+ const loopDetector = new ToolCallLoopDetector();
const canStream = msg.channelType === 'cli' || (msg.channelType === 'telegram' && this.telegramStreaming);
@@ -240,6 +317,13 @@ export class Agent {
if (toolCalls && toolCalls.length > 0) {
const names = toolCalls.map((tc: any) => tc.toolName).join(', ');
logger.info({ tools: names }, 'Tool call step');
+ for (const tc of toolCalls) {
+ loopDetector.record(tc.toolName, tc.args as Record<string, any>);
+ }
+ const loop = loopDetector.detect();
+ if (loop) {
+ logger.warn({ tool: loop.tool, count: loop.count }, 'Tool call loop detected');
+ }
await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});
}
},
@@ -282,6 +366,13 @@ export class Agent {
if (toolCalls && toolCalls.length > 0) {
const names = toolCalls.map((tc: any) => tc.toolName).join(', ');
logger.info({ tools: names }, 'Tool call step');
+ for (const tc of toolCalls) {
+ loopDetector.record(tc.toolName, tc.args as Record<string, any>);
+ }
+ const loop = loopDetector.detect();
+ if (loop) {
+ logger.warn({ tool: loop.tool, count: loop.count }, 'Tool call loop detected');
+ }
if (channel && msg.channelType !== 'internal') {
await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});
}
@@ -385,16 +476,35 @@ export class Agent {
if (this.tokenBudget.getUsagePercentage() > 70) {
prompt += '\nBe concise to conserve tokens.';
}
+
+ prompt += `\n\nEnvironment:\n- Platform: ${process.platform}\n- Working directory: ${this.capabilities.getCwd()}`;
+
const toolNames = this.capabilities.getToolNames();
const githubTools = ['create_pr', 'review_pr', 'list_issues', 'create_issue', 'github_api'];
const hasGitHub = githubTools.some(t => toolNames.includes(t));
if (hasGitHub) {
- let githubHint = '\n\nGitHub companion is active. You can create pull requests, review PRs, manage issues, and use the GitHub API.';
+ let githubHint = '\n\nGitHub companion is active.';
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.';
+
+ githubHint += `
+
+Available GitHub tools and when to use them:
+- git_add, git_commit, git_push: LOCAL git operations (stage, commit, push to a remote you have SSH/auth access to). All commits include "Co-authored-by: Mercury <[email protected]>".
+- create_pr: Create a pull request on GitHub. The head branch must already exist on the remote.
+- review_pr: Get PR details and optionally post a review comment.
+- list_issues, create_issue: Browse and file issues.
+- github_api: Raw GitHub API access. IMPORTANT USE CASES:
+ - Push files directly to GitHub via PUT /repos/{owner}/{repo}/contents/{path} when git push fails due to auth. The body must include "message" and "content" (base64-encoded file content). This creates a commit on GitHub with Mercury as co-author.
+ - Delete files via DELETE /repos/{owner}/{repo}/contents/{path} with a "message" and "sha" in the body.
+ - Any other GitHub API operation not covered by the other tools.
+
+When the user asks to "push to GitHub" or "upload files" and git push fails, use github_api with PUT /repos/{owner}/{repo}/contents/{path} to push content directly through the API. This bypasses local git entirely.
+
+Always specify owner and repo parameters on GitHub tools. The user's GitHub username is ${this.config.github.username || 'not set'}.'`;
+
prompt += githubHint;
}
return prompt;